Search in sources :

Example 51 with Channel

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

the class SSLEngineTest method setupHandlers.

protected void setupHandlers(SslContext serverCtx, SslContext clientCtx) throws InterruptedException, SSLException, CertificateException {
    serverSslCtx = serverCtx;
    clientSslCtx = clientCtx;
    serverConnectedChannel = null;
    sb = new ServerBootstrap();
    cb = new Bootstrap();
    sb.group(new NioEventLoopGroup(), new NioEventLoopGroup());
    sb.channel(NioServerSocketChannel.class);
    sb.childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.config().setAllocator(new TestByteBufAllocator(ch.config().getAllocator(), type));
            ChannelPipeline p = ch.pipeline();
            p.addLast(serverSslCtx.newHandler(ch.alloc()));
            p.addLast(new MessageDelegatorChannelHandler(serverReceiver, serverLatch));
            p.addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    if (cause.getCause() instanceof SSLHandshakeException) {
                        serverException = cause.getCause();
                        serverLatch.countDown();
                    } else {
                        ctx.fireExceptionCaught(cause);
                    }
                }
            });
            serverConnectedChannel = ch;
        }
    });
    cb.group(new NioEventLoopGroup());
    cb.channel(NioSocketChannel.class);
    cb.handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.config().setAllocator(new TestByteBufAllocator(ch.config().getAllocator(), type));
            ChannelPipeline p = ch.pipeline();
            p.addLast(clientSslCtx.newHandler(ch.alloc()));
            p.addLast(new MessageDelegatorChannelHandler(clientReceiver, clientLatch));
            p.addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    if (cause.getCause() instanceof SSLHandshakeException) {
                        clientException = cause.getCause();
                        clientLatch.countDown();
                    } else {
                        ctx.fireExceptionCaught(cause);
                    }
                }
            });
        }
    });
    serverChannel = sb.bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
    ChannelFuture ccf = cb.connect(serverChannel.localAddress());
    assertTrue(ccf.syncUninterruptibly().isSuccess());
    clientChannel = ccf.channel();
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) InetSocketAddress(java.net.InetSocketAddress) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) SSLException(javax.net.ssl.SSLException) ClosedChannelException(java.nio.channels.ClosedChannelException) CertificateException(java.security.cert.CertificateException) ExecutionException(java.util.concurrent.ExecutionException) ChannelPipeline(io.netty.channel.ChannelPipeline) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 52 with Channel

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

the class SniHandlerTest method testSniWithApnHandler.

@Test
public void testSniWithApnHandler() throws Exception {
    SslContext nettyContext = makeSslContext(provider, true);
    SslContext sniContext = makeSslContext(provider, true);
    final SslContext clientContext = makeSslClientContext(provider, true);
    try {
        final CountDownLatch serverApnDoneLatch = new CountDownLatch(1);
        final CountDownLatch clientApnDoneLatch = new CountDownLatch(1);
        final DomainNameMapping<SslContext> mapping = new DomainNameMappingBuilder<SslContext>(nettyContext).add("*.netty.io", nettyContext).add("sni.fake.site", sniContext).build();
        final SniHandler handler = new SniHandler(mapping);
        EventLoopGroup group = new NioEventLoopGroup(2);
        Channel serverChannel = null;
        Channel clientChannel = null;
        try {
            ServerBootstrap sb = new ServerBootstrap();
            sb.group(group);
            sb.channel(NioServerSocketChannel.class);
            sb.childHandler(new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    // Server side SNI.
                    p.addLast(handler);
                    // Catch the notification event that APN has completed successfully.
                    p.addLast(new ApplicationProtocolNegotiationHandler("foo") {

                        @Override
                        protected void configurePipeline(ChannelHandlerContext ctx, String protocol) {
                            serverApnDoneLatch.countDown();
                        }
                    });
                }
            });
            Bootstrap cb = new Bootstrap();
            cb.group(group);
            cb.channel(NioSocketChannel.class);
            cb.handler(new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ch.pipeline().addLast(new SslHandler(clientContext.newEngine(ch.alloc(), "sni.fake.site", -1)));
                    // Catch the notification event that APN has completed successfully.
                    ch.pipeline().addLast(new ApplicationProtocolNegotiationHandler("foo") {

                        @Override
                        protected void configurePipeline(ChannelHandlerContext ctx, String protocol) {
                            clientApnDoneLatch.countDown();
                        }
                    });
                }
            });
            serverChannel = sb.bind(new InetSocketAddress(0)).sync().channel();
            ChannelFuture ccf = cb.connect(serverChannel.localAddress());
            assertTrue(ccf.awaitUninterruptibly().isSuccess());
            clientChannel = ccf.channel();
            assertTrue(serverApnDoneLatch.await(5, TimeUnit.SECONDS));
            assertTrue(clientApnDoneLatch.await(5, TimeUnit.SECONDS));
            assertThat(handler.hostname(), is("sni.fake.site"));
            assertThat(handler.sslContext(), is(sniContext));
        } finally {
            if (serverChannel != null) {
                serverChannel.close().sync();
            }
            if (clientChannel != null) {
                clientChannel.close().sync();
            }
            group.shutdownGracefully(0, 0, TimeUnit.MICROSECONDS);
        }
    } finally {
        releaseAll(clientContext, nettyContext, sniContext);
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) InetSocketAddress(java.net.InetSocketAddress) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) DecoderException(io.netty.handler.codec.DecoderException) ChannelPipeline(io.netty.channel.ChannelPipeline) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Test(org.junit.Test)

Example 53 with Channel

use of org.apache.flink.shaded.netty4.io.netty.channel.Channel in project okhttp by square.

the class NettyHttpClient method enqueue.

@Override
public void enqueue(HttpUrl url) throws Exception {
    HttpChannel httpChannel = null;
    synchronized (this) {
        if (!freeChannels.isEmpty()) {
            httpChannel = freeChannels.pop();
        } else if (totalChannels < concurrencyLevel) {
            // Create a new channel. (outside of the synchronized block).
            totalChannels++;
        } else {
            // Enqueue this for later, to be picked up when another request completes.
            backlog.add(url);
            return;
        }
    }
    if (httpChannel == null) {
        Channel channel = bootstrap.connect(url.host(), url.port()).sync().channel();
        httpChannel = (HttpChannel) channel.pipeline().last();
    }
    httpChannel.sendRequest(url);
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel)

Example 54 with Channel

use of org.apache.flink.shaded.netty4.io.netty.channel.Channel in project rest.li by linkedin.

the class HttpNettyClient method shutdown.

@Override
public void shutdown(final Callback<None> callback) {
    LOG.info("Shutdown requested");
    if (_state.compareAndSet(State.RUNNING, State.SHUTTING_DOWN)) {
        LOG.info("Shutting down");
        final long deadline = System.currentTimeMillis() + _shutdownTimeout;
        TimeoutCallback<None> closeChannels = new TimeoutCallback<None>(_scheduler, _shutdownTimeout, TimeUnit.MILLISECONDS, new Callback<None>() {

            private void finishShutdown() {
                _state.set(State.REQUESTS_STOPPING);
                // Timeout any waiters which haven't received a Channel yet
                for (Callback<Channel> callback : _channelPoolManager.cancelWaiters()) {
                    callback.onError(new TimeoutException("Operation did not complete before shutdown"));
                }
                // Timeout any requests still pending response
                for (Channel c : _allChannels) {
                    TransportCallback<RestResponse> callback = c.attr(RAPResponseHandler.CALLBACK_ATTR_KEY).getAndRemove();
                    if (callback != null) {
                        errorResponse(callback, new TimeoutException("Operation did not complete before shutdown"));
                    }
                }
                // Close all active and idle Channels
                final TimeoutRunnable afterClose = new TimeoutRunnable(_scheduler, deadline - System.currentTimeMillis(), TimeUnit.MILLISECONDS, new Runnable() {

                    @Override
                    public void run() {
                        _state.set(State.SHUTDOWN);
                        LOG.info("Shutdown complete");
                        callback.onSuccess(None.none());
                    }
                }, "Timed out waiting for channels to close, continuing shutdown");
                _allChannels.close().addListener(new ChannelGroupFutureListener() {

                    @Override
                    public void operationComplete(ChannelGroupFuture channelGroupFuture) throws Exception {
                        if (!channelGroupFuture.isSuccess()) {
                            LOG.warn("Failed to close some connections, ignoring");
                        }
                        afterClose.run();
                    }
                });
            }

            @Override
            public void onSuccess(None none) {
                LOG.info("All connection pools shut down, closing all channels");
                finishShutdown();
            }

            @Override
            public void onError(Throwable e) {
                LOG.warn("Error shutting down HTTP connection pools, ignoring and continuing shutdown", e);
                finishShutdown();
            }
        }, "Connection pool shutdown timeout exceeded (" + _shutdownTimeout + "ms)");
        _channelPoolManager.shutdown(closeChannels);
        _jmxManager.onProviderShutdown(_channelPoolManager);
    } else {
        callback.onError(new IllegalStateException("Shutdown has already been requested."));
    }
}
Also used : TransportCallback(com.linkedin.r2.transport.common.bridge.common.TransportCallback) TimeoutRunnable(com.linkedin.r2.util.TimeoutRunnable) ChannelGroupFuture(io.netty.channel.group.ChannelGroupFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) ChannelGroupFutureListener(io.netty.channel.group.ChannelGroupFutureListener) TransportCallback(com.linkedin.r2.transport.common.bridge.common.TransportCallback) Callback(com.linkedin.common.callback.Callback) TimeoutRunnable(com.linkedin.r2.util.TimeoutRunnable) None(com.linkedin.common.util.None) TimeoutException(java.util.concurrent.TimeoutException)

Example 55 with Channel

use of org.apache.flink.shaded.netty4.io.netty.channel.Channel in project rest.li by linkedin.

the class ChannelPoolHandler method channelRead.

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    AsyncPool<Channel> pool = ctx.channel().attr(CHANNEL_POOL_ATTR_KEY).getAndRemove();
    if (pool != null) {
        RestResponse restResponse = (RestResponse) msg;
        List<String> connectionTokens = restResponse.getHeaderValues("connection");
        if (connectionTokens != null) {
            for (String token : connectionTokens) {
                if ("close".equalsIgnoreCase(token)) {
                    pool.dispose(ctx.channel());
                    return;
                }
            }
        }
        pool.put(ctx.channel());
    }
}
Also used : RestResponse(com.linkedin.r2.message.rest.RestResponse) Channel(io.netty.channel.Channel)

Aggregations

Channel (io.netty.channel.Channel)889 Test (org.junit.Test)242 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)227 ChannelFuture (io.netty.channel.ChannelFuture)204 Bootstrap (io.netty.bootstrap.Bootstrap)201 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)193 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)176 InetSocketAddress (java.net.InetSocketAddress)169 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)152 IOException (java.io.IOException)143 EventLoopGroup (io.netty.channel.EventLoopGroup)142 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)138 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)131 ByteBuf (io.netty.buffer.ByteBuf)112 SocketChannel (io.netty.channel.socket.SocketChannel)105 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)99 ChannelPipeline (io.netty.channel.ChannelPipeline)98 CountDownLatch (java.util.concurrent.CountDownLatch)97 LocalChannel (io.netty.channel.local.LocalChannel)93 LocalServerChannel (io.netty.channel.local.LocalServerChannel)88