Search in sources :

Example 51 with ChannelFutureListener

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

the class SslHandlerTest method testHandshakeFailBeforeWritePromise.

@Test
@Timeout(value = 5000, unit = TimeUnit.MILLISECONDS)
public void testHandshakeFailBeforeWritePromise() throws Exception {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    final SslContext sslServerCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    final CountDownLatch latch = new CountDownLatch(2);
    final CountDownLatch latch2 = new CountDownLatch(2);
    final BlockingQueue<Object> events = new LinkedBlockingQueue<Object>();
    Channel serverChannel = null;
    Channel clientChannel = null;
    EventLoopGroup group = new DefaultEventLoopGroup();
    try {
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(group).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<Channel>() {

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

                    @Override
                    public void channelActive(ChannelHandlerContext ctx) {
                        ByteBuf buf = ctx.alloc().buffer(10);
                        buf.writeZero(buf.capacity());
                        ctx.writeAndFlush(buf).addListener(new ChannelFutureListener() {

                            @Override
                            public void operationComplete(ChannelFuture future) {
                                events.add(future);
                                latch.countDown();
                            }
                        });
                    }

                    @Override
                    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
                        if (evt instanceof SslCompletionEvent) {
                            events.add(evt);
                            latch.countDown();
                            latch2.countDown();
                        }
                    }
                });
            }
        });
        Bootstrap cb = new Bootstrap();
        cb.group(group).channel(LocalChannel.class).handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) {
                ch.pipeline().addFirst(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void channelActive(ChannelHandlerContext ctx) {
                        ByteBuf buf = ctx.alloc().buffer(1000);
                        buf.writeZero(buf.capacity());
                        ctx.writeAndFlush(buf);
                    }
                });
            }
        });
        serverChannel = sb.bind(new LocalAddress("SslHandlerTest")).sync().channel();
        clientChannel = cb.connect(serverChannel.localAddress()).sync().channel();
        latch.await();
        SslCompletionEvent evt = (SslCompletionEvent) events.take();
        assertTrue(evt instanceof SslHandshakeCompletionEvent);
        assertThat(evt.cause(), is(instanceOf(SSLException.class)));
        ChannelFuture future = (ChannelFuture) events.take();
        assertThat(future.cause(), is(instanceOf(SSLException.class)));
        serverChannel.close().sync();
        serverChannel = null;
        clientChannel.close().sync();
        clientChannel = null;
        latch2.await();
        evt = (SslCompletionEvent) events.take();
        assertTrue(evt instanceof SslCloseCompletionEvent);
        assertThat(evt.cause(), is(instanceOf(ClosedChannelException.class)));
        assertTrue(events.isEmpty());
    } finally {
        if (serverChannel != null) {
            serverChannel.close();
        }
        if (clientChannel != null) {
            clientChannel.close();
        }
        group.shutdownGracefully();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) LocalAddress(io.netty.channel.local.LocalAddress) LocalChannel(io.netty.channel.local.LocalChannel) 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) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) ByteBuf(io.netty.buffer.ByteBuf) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test) Timeout(org.junit.jupiter.api.Timeout)

Example 52 with ChannelFutureListener

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

the class SslHandlerTest method testNonApplicationDataFailureFailsQueuedWrites.

@Test
@Timeout(value = 5000, unit = TimeUnit.MILLISECONDS)
public void testNonApplicationDataFailureFailsQueuedWrites() throws NoSuchAlgorithmException, InterruptedException {
    final CountDownLatch writeLatch = new CountDownLatch(1);
    final Queue<ChannelPromise> writesToFail = new ConcurrentLinkedQueue<ChannelPromise>();
    SSLEngine engine = newClientModeSSLEngine();
    SslHandler handler = new SslHandler(engine) {

        @Override
        public void write(final ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            super.write(ctx, msg, promise);
            writeLatch.countDown();
        }
    };
    EmbeddedChannel ch = new EmbeddedChannel(new ChannelDuplexHandler() {

        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
            if (msg instanceof ByteBuf) {
                if (((ByteBuf) msg).isReadable()) {
                    writesToFail.add(promise);
                } else {
                    promise.setSuccess();
                }
            }
            ReferenceCountUtil.release(msg);
        }
    }, handler);
    try {
        final CountDownLatch writeCauseLatch = new CountDownLatch(1);
        final AtomicReference<Throwable> failureRef = new AtomicReference<Throwable>();
        ch.write(Unpooled.wrappedBuffer(new byte[] { 1 })).addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) {
                failureRef.compareAndSet(null, future.cause());
                writeCauseLatch.countDown();
            }
        });
        writeLatch.await();
        // Simulate failing the SslHandler non-application writes after there are applications writes queued.
        ChannelPromise promiseToFail;
        while ((promiseToFail = writesToFail.poll()) != null) {
            promiseToFail.setFailure(new RuntimeException("fake exception"));
        }
        writeCauseLatch.await();
        Throwable writeCause = failureRef.get();
        assertNotNull(writeCause);
        assertThat(writeCause, is(CoreMatchers.<Throwable>instanceOf(SSLException.class)));
        Throwable cause = handler.handshakeFuture().cause();
        assertNotNull(cause);
        assertThat(cause, is(CoreMatchers.<Throwable>instanceOf(SSLException.class)));
    } finally {
        assertFalse(ch.finishAndReleaseAll());
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) SSLEngine(javax.net.ssl.SSLEngine) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ChannelPromise(io.netty.channel.ChannelPromise) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuf(io.netty.buffer.ByteBuf) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) Test(org.junit.jupiter.api.Test) Timeout(org.junit.jupiter.api.Timeout)

Example 53 with ChannelFutureListener

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

the class SslHandlerTest method testHandshakeFailedByWriteBeforeChannelActive.

@Test
@Timeout(value = 10000, unit = TimeUnit.MILLISECONDS)
public void testHandshakeFailedByWriteBeforeChannelActive() throws Exception {
    final SslContext sslClientCtx = SslContextBuilder.forClient().protocols(SslProtocols.SSL_v3).trustManager(InsecureTrustManagerFactory.INSTANCE).sslProvider(SslProvider.JDK).build();
    EventLoopGroup group = new NioEventLoopGroup();
    Channel sc = null;
    Channel cc = null;
    final CountDownLatch activeLatch = new CountDownLatch(1);
    final AtomicReference<AssertionError> errorRef = new AtomicReference<AssertionError>();
    final SslHandler sslHandler = sslClientCtx.newHandler(UnpooledByteBufAllocator.DEFAULT);
    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) throws Exception {
                ch.pipeline().addLast(sslHandler);
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                        if (cause instanceof AssertionError) {
                            errorRef.set((AssertionError) cause);
                        }
                    }

                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        activeLatch.countDown();
                    }
                });
            }
        }).connect(sc.localAddress()).addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                // Write something to trigger the handshake before fireChannelActive is called.
                future.channel().writeAndFlush(wrappedBuffer(new byte[] { 1, 2, 3, 4 }));
            }
        }).syncUninterruptibly().channel();
        // Ensure there is no AssertionError thrown by having the handshake failed by the writeAndFlush(...) before
        // channelActive(...) was called. Let's first wait for the activeLatch countdown to happen and after this
        // check if we saw and AssertionError (even if we timed out waiting).
        activeLatch.await(5, TimeUnit.SECONDS);
        AssertionError error = errorRef.get();
        if (error != null) {
            throw error;
        }
        assertThat(sslHandler.handshakeFuture().await().cause(), CoreMatchers.<Throwable>instanceOf(SSLException.class));
    } finally {
        if (cc != null) {
            cc.close().syncUninterruptibly();
        }
        if (sc != null) {
            sc.close().syncUninterruptibly();
        }
        group.shutdownGracefully();
        ReferenceCountUtil.release(sslClientCtx);
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) InetSocketAddress(java.net.InetSocketAddress) 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) AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ChannelFutureListener(io.netty.channel.ChannelFutureListener) SSLException(javax.net.ssl.SSLException) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) IllegalReferenceCountException(io.netty.util.IllegalReferenceCountException) CodecException(io.netty.handler.codec.CodecException) DecoderException(io.netty.handler.codec.DecoderException) SSLProtocolException(javax.net.ssl.SSLProtocolException) SSLException(javax.net.ssl.SSLException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ClosedChannelException(java.nio.channels.ClosedChannelException) CertificateException(java.security.cert.CertificateException) ExecutionException(java.util.concurrent.ExecutionException) UnsupportedMessageTypeException(io.netty.handler.codec.UnsupportedMessageTypeException) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test) Timeout(org.junit.jupiter.api.Timeout)

Example 54 with ChannelFutureListener

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

the class ChunkedWriteHandlerTest method testWriteListenerInvokedAfterSuccessfulChunkedInputClosed.

@Test
public void testWriteListenerInvokedAfterSuccessfulChunkedInputClosed() throws Exception {
    final TestChunkedInput input = new TestChunkedInput(2);
    EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler());
    final AtomicBoolean inputClosedWhenListenerInvoked = new AtomicBoolean();
    final CountDownLatch listenerInvoked = new CountDownLatch(1);
    ChannelFuture writeFuture = ch.write(input);
    writeFuture.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) {
            inputClosedWhenListenerInvoked.set(input.isClosed());
            listenerInvoked.countDown();
        }
    });
    ch.flush();
    assertTrue(listenerInvoked.await(10, SECONDS));
    assertTrue(writeFuture.isSuccess());
    assertTrue(inputClosedWhenListenerInvoked.get());
    assertTrue(ch.finishAndReleaseAll());
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) CountDownLatch(java.util.concurrent.CountDownLatch) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Test(org.junit.jupiter.api.Test)

Example 55 with ChannelFutureListener

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

the class WriteTimeoutHandlerTest method testPromiseUseDifferentExecutor.

@Test
public void testPromiseUseDifferentExecutor() throws Exception {
    EventExecutorGroup group1 = new DefaultEventExecutorGroup(1);
    EventExecutorGroup group2 = new DefaultEventExecutorGroup(1);
    EmbeddedChannel channel = new EmbeddedChannel(false, false);
    try {
        channel.pipeline().addLast(group1, new WriteTimeoutHandler(10000));
        final CountDownLatch latch = new CountDownLatch(1);
        channel.pipeline().addLast(group2, new ChannelInboundHandlerAdapter() {

            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                ctx.writeAndFlush("something").addListener(new ChannelFutureListener() {

                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        latch.countDown();
                    }
                });
            }
        });
        channel.register();
        latch.await();
        assertTrue(channel.finishAndReleaseAll());
    } finally {
        group1.shutdownGracefully();
        group2.shutdownGracefully();
    }
}
Also used : DefaultEventExecutorGroup(io.netty.util.concurrent.DefaultEventExecutorGroup) EventExecutorGroup(io.netty.util.concurrent.EventExecutorGroup) ChannelFuture(io.netty.channel.ChannelFuture) DefaultEventExecutorGroup(io.netty.util.concurrent.DefaultEventExecutorGroup) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ChannelFutureListener(io.netty.channel.ChannelFutureListener) 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