Search in sources :

Example 81 with ChannelFutureListener

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

the class LocalChannelTest method testWriteWhilePeerIsClosedReleaseObjectAndFailPromise.

@Test
public void testWriteWhilePeerIsClosedReleaseObjectAndFailPromise() throws InterruptedException {
    Bootstrap cb = new Bootstrap();
    ServerBootstrap sb = new ServerBootstrap();
    final CountDownLatch serverMessageLatch = new CountDownLatch(1);
    final LatchChannelFutureListener serverChannelCloseLatch = new LatchChannelFutureListener(1);
    final LatchChannelFutureListener clientChannelCloseLatch = new LatchChannelFutureListener(1);
    final CountDownLatch writeFailLatch = new CountDownLatch(1);
    final ByteBuf data = Unpooled.wrappedBuffer(new byte[1024]);
    final ByteBuf data2 = Unpooled.wrappedBuffer(new byte[512]);
    final CountDownLatch serverChannelLatch = new CountDownLatch(1);
    final AtomicReference<Channel> serverChannelRef = new AtomicReference<Channel>();
    try {
        cb.group(group1).channel(LocalChannel.class).handler(new TestHandler());
        sb.group(group2).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<LocalChannel>() {

            @Override
            public void initChannel(LocalChannel ch) throws Exception {
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        if (data.equals(msg)) {
                            ReferenceCountUtil.safeRelease(msg);
                            serverMessageLatch.countDown();
                        } else {
                            super.channelRead(ctx, msg);
                        }
                    }
                });
                serverChannelRef.set(ch);
                serverChannelLatch.countDown();
            }
        });
        Channel sc = null;
        Channel cc = null;
        try {
            // Start server
            sc = sb.bind(TEST_ADDRESS).syncUninterruptibly().channel();
            // Connect to the server
            cc = cb.connect(sc.localAddress()).syncUninterruptibly().channel();
            assertTrue(serverChannelLatch.await(5, SECONDS));
            final Channel ccCpy = cc;
            final Channel serverChannelCpy = serverChannelRef.get();
            serverChannelCpy.closeFuture().addListener(serverChannelCloseLatch);
            ccCpy.closeFuture().addListener(clientChannelCloseLatch);
            // Make sure a write operation is executed in the eventloop
            cc.pipeline().lastContext().executor().execute(new Runnable() {

                @Override
                public void run() {
                    ccCpy.writeAndFlush(data.retainedDuplicate(), ccCpy.newPromise()).addListener(new ChannelFutureListener() {

                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            serverChannelCpy.eventLoop().execute(new Runnable() {

                                @Override
                                public void run() {
                                    // The point of this test is to write while the peer is closed, so we should
                                    // ensure the peer is actually closed before we write.
                                    int waitCount = 0;
                                    while (ccCpy.isOpen()) {
                                        try {
                                            Thread.sleep(50);
                                        } catch (InterruptedException ignored) {
                                        // ignored
                                        }
                                        if (++waitCount > 5) {
                                            fail();
                                        }
                                    }
                                    serverChannelCpy.writeAndFlush(data2.retainedDuplicate(), serverChannelCpy.newPromise()).addListener(new ChannelFutureListener() {

                                        @Override
                                        public void operationComplete(ChannelFuture future) throws Exception {
                                            if (!future.isSuccess() && future.cause() instanceof ClosedChannelException) {
                                                writeFailLatch.countDown();
                                            }
                                        }
                                    });
                                }
                            });
                            ccCpy.close();
                        }
                    });
                }
            });
            assertTrue(serverMessageLatch.await(5, SECONDS));
            assertTrue(writeFailLatch.await(5, SECONDS));
            assertTrue(serverChannelCloseLatch.await(5, SECONDS));
            assertTrue(clientChannelCloseLatch.await(5, SECONDS));
            assertFalse(ccCpy.isOpen());
            assertFalse(serverChannelCpy.isOpen());
        } finally {
            closeChannel(cc);
            closeChannel(sc);
        }
    } finally {
        data.release();
        data2.release();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ClosedChannelException(java.nio.channels.ClosedChannelException) AbstractChannel(io.netty.channel.AbstractChannel) Channel(io.netty.channel.Channel) 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) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ConnectException(java.net.ConnectException) ClosedChannelException(java.nio.channels.ClosedChannelException) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

Example 82 with ChannelFutureListener

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

the class BootstrapTest method testLateRegisterSuccessBindFailed.

@Test
public void testLateRegisterSuccessBindFailed() throws Exception {
    TestEventLoopGroup group = new TestEventLoopGroup();
    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(group);
        bootstrap.channelFactory(new ChannelFactory<ServerChannel>() {

            @Override
            public ServerChannel newChannel() {
                return new LocalServerChannel() {

                    @Override
                    public ChannelFuture bind(SocketAddress localAddress) {
                        // Close the Channel to emulate what NIO and others impl do on bind failure
                        // See https://github.com/netty/netty/issues/2586
                        close();
                        return newFailedFuture(new SocketException());
                    }

                    @Override
                    public ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) {
                        // Close the Channel to emulate what NIO and others impl do on bind failure
                        // See https://github.com/netty/netty/issues/2586
                        close();
                        return promise.setFailure(new SocketException());
                    }
                };
            }
        });
        bootstrap.childHandler(new DummyHandler());
        bootstrap.localAddress(new LocalAddress("1"));
        ChannelFuture future = bootstrap.bind();
        assertFalse(future.isDone());
        group.promise.setSuccess();
        final BlockingQueue<Boolean> queue = new LinkedBlockingQueue<Boolean>();
        future.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                queue.add(future.channel().eventLoop().inEventLoop(Thread.currentThread()));
                queue.add(future.isSuccess());
            }
        });
        assertTrue(queue.take());
        assertFalse(queue.take());
    } finally {
        group.shutdownGracefully();
        group.terminationFuture().sync();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) SocketException(java.net.SocketException) LocalAddress(io.netty.channel.local.LocalAddress) ChannelPromise(io.netty.channel.ChannelPromise) LocalServerChannel(io.netty.channel.local.LocalServerChannel) ServerChannel(io.netty.channel.ServerChannel) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) ChannelFutureListener(io.netty.channel.ChannelFutureListener) SocketException(java.net.SocketException) ConnectException(java.net.ConnectException) UnknownHostException(java.net.UnknownHostException) LocalServerChannel(io.netty.channel.local.LocalServerChannel) SocketAddress(java.net.SocketAddress) Test(org.junit.jupiter.api.Test)

Example 83 with ChannelFutureListener

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

the class EmbeddedChannelTest method promiseDoesNotInfiniteLoop.

@Test
@Timeout(value = 2000, unit = TimeUnit.MILLISECONDS)
public void promiseDoesNotInfiniteLoop() throws InterruptedException {
    EmbeddedChannel channel = new EmbeddedChannel();
    channel.closeFuture().addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            future.channel().close();
        }
    });
    channel.close().syncUninterruptibly();
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ClosedChannelException(java.nio.channels.ClosedChannelException) Test(org.junit.jupiter.api.Test) Timeout(org.junit.jupiter.api.Timeout)

Example 84 with ChannelFutureListener

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

the class KQueueDomainSocketFdTest method testSendRecvFd.

public void testSendRecvFd(ServerBootstrap sb, Bootstrap cb) throws Throwable {
    final BlockingQueue<Object> queue = new LinkedBlockingQueue<Object>(1);
    sb.childHandler(new ChannelInboundHandlerAdapter() {

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            // Create new channel and obtain a file descriptor from it.
            final KQueueDomainSocketChannel ch = new KQueueDomainSocketChannel();
            ctx.writeAndFlush(ch.fd()).addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        Throwable cause = future.cause();
                        queue.offer(cause);
                    }
                }
            });
        }
    });
    cb.handler(new ChannelInboundHandlerAdapter() {

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            FileDescriptor fd = (FileDescriptor) msg;
            queue.offer(fd);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            queue.add(cause);
            ctx.close();
        }
    });
    cb.option(KQueueChannelOption.DOMAIN_SOCKET_READ_MODE, DomainSocketReadMode.FILE_DESCRIPTORS);
    Channel sc = sb.bind().sync().channel();
    Channel cc = cb.connect(sc.localAddress()).sync().channel();
    Object received = queue.take();
    cc.close().sync();
    sc.close().sync();
    if (received instanceof FileDescriptor) {
        FileDescriptor fd = (FileDescriptor) received;
        assertTrue(fd.isOpen());
        fd.close();
        assertFalse(fd.isOpen());
        assertNull(queue.poll());
    } else {
        throw (Throwable) received;
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) ChannelFutureListener(io.netty.channel.ChannelFutureListener) FileDescriptor(io.netty.channel.unix.FileDescriptor) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 85 with ChannelFutureListener

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

the class WebSocketServerProtocolHandshakeHandler method channelRead.

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
    final HttpObject httpObject = (HttpObject) msg;
    if (httpObject instanceof HttpRequest) {
        final HttpRequest req = (HttpRequest) httpObject;
        isWebSocketPath = isWebSocketPath(req);
        if (!isWebSocketPath) {
            ctx.fireChannelRead(msg);
            return;
        }
        try {
            if (!GET.equals(req.method())) {
                sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN, ctx.alloc().buffer(0)));
                return;
            }
            final WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(ctx.pipeline(), req, serverConfig.websocketPath()), serverConfig.subprotocols(), serverConfig.decoderConfig());
            final WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);
            final ChannelPromise localHandshakePromise = handshakePromise;
            if (handshaker == null) {
                WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
            } else {
                // Ensure we set the handshaker and replace this handler before we
                // trigger the actual handshake. Otherwise we may receive websocket bytes in this handler
                // before we had a chance to replace it.
                // 
                // See https://github.com/netty/netty/issues/9471.
                WebSocketServerProtocolHandler.setHandshaker(ctx.channel(), handshaker);
                ctx.pipeline().remove(this);
                final ChannelFuture handshakeFuture = handshaker.handshake(ctx.channel(), req);
                handshakeFuture.addListener(new ChannelFutureListener() {

                    @Override
                    public void operationComplete(ChannelFuture future) {
                        if (!future.isSuccess()) {
                            localHandshakePromise.tryFailure(future.cause());
                            ctx.fireExceptionCaught(future.cause());
                        } else {
                            localHandshakePromise.trySuccess();
                            // Kept for compatibility
                            ctx.fireUserEventTriggered(WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE);
                            ctx.fireUserEventTriggered(new WebSocketServerProtocolHandler.HandshakeComplete(req.uri(), req.headers(), handshaker.selectedSubprotocol()));
                        }
                    }
                });
                applyHandshakeTimeout();
            }
        } finally {
            ReferenceCountUtil.release(req);
        }
    } else if (!isWebSocketPath) {
        ctx.fireChannelRead(msg);
    } else {
        ReferenceCountUtil.release(msg);
    }
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) ChannelFuture(io.netty.channel.ChannelFuture) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpObject(io.netty.handler.codec.http.HttpObject) ChannelPromise(io.netty.channel.ChannelPromise) ChannelFutureListener(io.netty.channel.ChannelFutureListener)

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