Search in sources :

Example 46 with ChannelInitializer

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInitializer in project vert.x by eclipse.

the class NetServerBase method listen.

public synchronized void listen(Handler<? super C> handler, int port, String host, Handler<AsyncResult<Void>> listenHandler) {
    if (handler == null) {
        throw new IllegalStateException("Set connect handler first");
    }
    if (listening) {
        throw new IllegalStateException("Listen already called");
    }
    listening = true;
    listenContext = vertx.getOrCreateContext();
    registeredHandler = handler;
    synchronized (vertx.sharedNetServers()) {
        // Will be updated on bind for a wildcard port
        this.actualPort = port;
        id = new ServerID(port, host);
        NetServerBase shared = vertx.sharedNetServers().get(id);
        if (shared == null || port == 0) {
            // Wildcard port will imply a new actual server each time
            serverChannelGroup = new DefaultChannelGroup("vertx-acceptor-channels", GlobalEventExecutor.INSTANCE);
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(availableWorkers);
            bootstrap.channel(NioServerSocketChannel.class);
            sslHelper.validate(vertx);
            bootstrap.childHandler(new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    if (isPaused()) {
                        ch.close();
                        return;
                    }
                    ChannelPipeline pipeline = ch.pipeline();
                    NetServerBase.this.initChannel(ch.pipeline());
                    pipeline.addLast("handler", new ServerHandler(ch));
                }
            });
            applyConnectionOptions(bootstrap);
            handlerManager.addHandler(handler, listenContext);
            try {
                bindFuture = AsyncResolveConnectHelper.doBind(vertx, port, host, bootstrap);
                bindFuture.addListener(res -> {
                    if (res.succeeded()) {
                        Channel ch = res.result();
                        log.trace("Net server listening on " + host + ":" + ch.localAddress());
                        NetServerBase.this.actualPort = ((InetSocketAddress) ch.localAddress()).getPort();
                        NetServerBase.this.id = new ServerID(NetServerBase.this.actualPort, id.host);
                        serverChannelGroup.add(ch);
                        vertx.sharedNetServers().put(id, NetServerBase.this);
                        metrics = vertx.metricsSPI().createMetrics(new SocketAddressImpl(id.port, id.host), options);
                    } else {
                        vertx.sharedNetServers().remove(id);
                    }
                });
            } catch (Throwable t) {
                // Make sure we send the exception back through the handler (if any)
                if (listenHandler != null) {
                    vertx.runOnContext(v -> listenHandler.handle(Future.failedFuture(t)));
                } else {
                    // No handler - log so user can see failure
                    log.error(t);
                }
                listening = false;
                return;
            }
            if (port != 0) {
                vertx.sharedNetServers().put(id, this);
            }
            actualServer = this;
        } else {
            // Server already exists with that host/port - we will use that
            actualServer = shared;
            this.actualPort = shared.actualPort();
            metrics = vertx.metricsSPI().createMetrics(new SocketAddressImpl(id.port, id.host), options);
            actualServer.handlerManager.addHandler(handler, listenContext);
        }
        // just add it to the future so it gets notified once the bind is complete
        actualServer.bindFuture.addListener(res -> {
            if (listenHandler != null) {
                AsyncResult<Void> ares;
                if (res.succeeded()) {
                    ares = Future.succeededFuture();
                } else {
                    listening = false;
                    ares = Future.failedFuture(res.cause());
                }
                listenContext.runOnContext(v -> listenHandler.handle(ares));
            } else if (res.failed()) {
                log.error("Failed to listen", res.cause());
                listening = false;
            }
        });
    }
    return;
}
Also used : DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) ChannelOption(io.netty.channel.ChannelOption) ContextImpl(io.vertx.core.impl.ContextImpl) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) TCPMetrics(io.vertx.core.spi.metrics.TCPMetrics) LoggerFactory(io.vertx.core.logging.LoggerFactory) GlobalEventExecutor(io.netty.util.concurrent.GlobalEventExecutor) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) FixedRecvByteBufAllocator(io.netty.channel.FixedRecvByteBufAllocator) Map(java.util.Map) AsyncResult(io.vertx.core.AsyncResult) Logger(io.vertx.core.logging.Logger) Metrics(io.vertx.core.spi.metrics.Metrics) Closeable(io.vertx.core.Closeable) ChannelGroup(io.netty.channel.group.ChannelGroup) VertxInternal(io.vertx.core.impl.VertxInternal) ChannelInitializer(io.netty.channel.ChannelInitializer) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) MetricsProvider(io.vertx.core.spi.metrics.MetricsProvider) ChannelPipeline(io.netty.channel.ChannelPipeline) EventLoop(io.netty.channel.EventLoop) Future(io.vertx.core.Future) InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) NetServerOptions(io.vertx.core.net.NetServerOptions) SslHandler(io.netty.handler.ssl.SslHandler) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelGroupFuture(io.netty.channel.group.ChannelGroupFuture) Handler(io.vertx.core.Handler) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline)

Example 47 with ChannelInitializer

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

the class NettyHttpClient method prepare.

@Override
public void prepare(final Benchmark benchmark) {
    this.concurrencyLevel = benchmark.concurrencyLevel;
    this.targetBacklog = benchmark.targetBacklog;
    ChannelInitializer<SocketChannel> channelInitializer = new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            if (benchmark.tls) {
                SslClient sslClient = SslClient.localhost();
                SSLEngine engine = sslClient.sslContext.createSSLEngine();
                engine.setUseClientMode(true);
                pipeline.addLast("ssl", new SslHandler(engine));
            }
            pipeline.addLast("codec", new HttpClientCodec());
            pipeline.addLast("inflater", new HttpContentDecompressor());
            pipeline.addLast("handler", new HttpChannel(channel));
        }
    };
    bootstrap = new Bootstrap();
    bootstrap.group(new NioEventLoopGroup(concurrencyLevel)).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).channel(NioSocketChannel.class).handler(channelInitializer);
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) SSLEngine(javax.net.ssl.SSLEngine) SslClient(okhttp3.internal.tls.SslClient) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 48 with ChannelInitializer

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

the class SSLEngineTest method clientInitiatedRenegotiationWithFatalAlertDoesNotInfiniteLoopServer.

@Test(timeout = 30000)
public void clientInitiatedRenegotiationWithFatalAlertDoesNotInfiniteLoopServer() throws CertificateException, SSLException, InterruptedException, ExecutionException {
    final SelfSignedCertificate ssc = new SelfSignedCertificate();
    serverSslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(sslServerProvider()).build();
    sb = new ServerBootstrap().group(new NioEventLoopGroup(1)).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) {
            ch.config().setAllocator(new TestByteBufAllocator(ch.config().getAllocator(), type));
            ChannelPipeline p = ch.pipeline();
            p.addLast(serverSslCtx.newHandler(ch.alloc()));
            p.addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
                    if (evt instanceof SslHandshakeCompletionEvent && ((SslHandshakeCompletionEvent) evt).isSuccess()) {
                        // This data will be sent to the client before any of the re-negotiation data can be
                        // sent. The client will read this, detect that it is not the response to
                        // renegotiation which was expected, and respond with a fatal alert.
                        ctx.writeAndFlush(ctx.alloc().buffer(1).writeByte(100));
                    }
                    ctx.fireUserEventTriggered(evt);
                }

                @Override
                public void channelRead(final ChannelHandlerContext ctx, Object msg) {
                    ReferenceCountUtil.release(msg);
                    // The server then attempts to trigger a flush operation once the application data is
                    // received from the client. The flush will encrypt all data and should not result in
                    // deadlock.
                    ctx.channel().eventLoop().schedule(new Runnable() {

                        @Override
                        public void run() {
                            ctx.writeAndFlush(ctx.alloc().buffer(1).writeByte(101));
                        }
                    }, 500, TimeUnit.MILLISECONDS);
                }

                @Override
                public void channelInactive(ChannelHandlerContext ctx) {
                    serverLatch.countDown();
                }
            });
            serverConnectedChannel = ch;
        }
    });
    serverChannel = sb.bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
    clientSslCtx = SslContextBuilder.forClient().sslProvider(// OpenSslEngine doesn't support renegotiation on client side
    SslProvider.JDK).trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    cb = new Bootstrap();
    cb.group(new NioEventLoopGroup(1)).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) {
            ch.config().setAllocator(new TestByteBufAllocator(ch.config().getAllocator(), type));
            ChannelPipeline p = ch.pipeline();
            SslHandler sslHandler = clientSslCtx.newHandler(ch.alloc());
            // The renegotiate is not expected to succeed, so we should stop trying in a timely manner so
            // the unit test can terminate relativley quicly.
            sslHandler.setHandshakeTimeout(1, TimeUnit.SECONDS);
            p.addLast(sslHandler);
            p.addLast(new ChannelInboundHandlerAdapter() {

                private int handshakeCount;

                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
                    // completed the first renegotiation handshake (which is the second handshake).
                    if (evt instanceof SslHandshakeCompletionEvent && ++handshakeCount == 2) {
                        ctx.close();
                        return;
                    }
                    ctx.fireUserEventTriggered(evt);
                }

                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) {
                    ReferenceCountUtil.release(msg);
                    // Simulate a request that the server's application logic will think is invalid.
                    ctx.writeAndFlush(ctx.alloc().buffer(1).writeByte(102));
                    ctx.pipeline().get(SslHandler.class).renegotiate();
                }
            });
        }
    });
    ChannelFuture ccf = cb.connect(serverChannel.localAddress());
    assertTrue(ccf.syncUninterruptibly().isSuccess());
    clientChannel = ccf.channel();
    serverLatch.await();
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) InetSocketAddress(java.net.InetSocketAddress) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) 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.Test)

Example 49 with ChannelInitializer

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

the class NettyUdpConnectionlessSendTest method createNettyUdpReceiver.

public void createNettyUdpReceiver() {
    group = new NioEventLoopGroup();
    bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioDatagramChannel.class).handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel channel) throws Exception {
            channel.pipeline().addLast(new UdpHandler());
            channel.pipeline().addLast(new ContentHandler());
        }
    }).localAddress(new InetSocketAddress(getPort()));
}
Also used : InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 50 with ChannelInitializer

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInitializer in project ambry by linkedin.

the class NettyServerFactoryTest method doGetNettyServerTest.

/**
 * Test that a {@link NettyServer} can be constructed by the factory.
 * @param properties the {@link Properties} to use.
 * @param sslFactory the {@link SSLFactory} to use.
 */
private void doGetNettyServerTest(Properties properties, SSLFactory sslFactory) {
    VerifiableProperties verifiableProperties = new VerifiableProperties(properties);
    NettyConfig nettyConfig = new NettyConfig(verifiableProperties);
    NettyServerFactory nettyServerFactory = new NettyServerFactory(verifiableProperties, new MetricRegistry(), REST_REQUEST_HANDLER, PUBLIC_ACCESS_LOGGER, REST_SERVER_STATE, sslFactory);
    NioServer nioServer = nettyServerFactory.getNioServer();
    assertNotNull("No NioServer returned", nioServer);
    assertEquals("Did not receive a NettyServer instance", NettyServer.class.getCanonicalName(), nioServer.getClass().getCanonicalName());
    Map<Integer, ChannelInitializer<SocketChannel>> channelInitializers = nettyServerFactory.channelInitializers;
    if (nettyConfig.nettyServerEnableSSL && sslFactory != null) {
        assertEquals("Expected two ChannelInitializers when SSLFactory is not null", 2, channelInitializers.size());
        assertNotNull("No ChannelInitializer for SSL port", channelInitializers.get(nettyConfig.nettyServerSSLPort));
    } else {
        assertEquals("Expected one ChannelInitializer when SSLFactory is null", 1, channelInitializers.size());
    }
    assertNotNull("No ChannelInitializer for plaintext port", channelInitializers.get(nettyConfig.nettyServerPort));
}
Also used : VerifiableProperties(com.github.ambry.config.VerifiableProperties) MetricRegistry(com.codahale.metrics.MetricRegistry) ChannelInitializer(io.netty.channel.ChannelInitializer) NettyConfig(com.github.ambry.config.NettyConfig)

Aggregations

ChannelInitializer (io.netty.channel.ChannelInitializer)83 Channel (io.netty.channel.Channel)58 Bootstrap (io.netty.bootstrap.Bootstrap)42 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)39 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)36 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)32 InetSocketAddress (java.net.InetSocketAddress)32 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)31 ChannelFuture (io.netty.channel.ChannelFuture)29 EventLoopGroup (io.netty.channel.EventLoopGroup)26 ChannelPipeline (io.netty.channel.ChannelPipeline)25 LocalServerChannel (io.netty.channel.local.LocalServerChannel)22 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)21 LocalChannel (io.netty.channel.local.LocalChannel)20 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)17 SslHandler (io.netty.handler.ssl.SslHandler)17 SocketChannel (io.netty.channel.socket.SocketChannel)16 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)14 DefaultEventLoopGroup (io.netty.channel.DefaultEventLoopGroup)12 CountDownLatch (java.util.concurrent.CountDownLatch)12