Search in sources :

Example 41 with EventLoopGroup

use of org.apache.flink.shaded.netty4.io.netty.channel.EventLoopGroup in project BRFS by zhangnianli.

the class NettyMessageServer method bind.

public void bind(int port) throws Exception {
    // 配置服务端的NIO线程组
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) {
                ch.pipeline().addLast("http-decoder", new HttpRequestDecoder());
                ch.pipeline().addLast("http-servercodec", new HttpServerCodec());
                // 定义缓冲数据量
                ch.pipeline().addLast("http-aggegator", new HttpObjectAggregator(1024 * 1024 * 64));
                // ch.pipeline().addLast(new ProtobufVarint32FrameDecoder());
                // ch.pipeline().addLast(
                // new ProtobufDecoder(NettyMessageProto.NettyMessageReqRes.getDefaultInstance()));
                // ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
                // ch.pipeline().addLast(new ProtobufEncoder());
                // ch.pipeline().addLast("http-chunked",new ChunkedWriteHandler());
                ch.pipeline().addLast(new NettyMessageServerHandler());
                ch.pipeline().addLast("http-responseencoder", new HttpResponseEncoder());
            }
        });
        // 绑定端口,同步等待成功
        ChannelFuture f = b.bind(port).sync();
        System.out.println("init start");
        // 等待服务端监听端口关闭
        f.channel().closeFuture().sync();
    } finally {
        // 优雅退出,释放线程池资源
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) LoggingHandler(io.netty.handler.logging.LoggingHandler) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) HttpRequestDecoder(io.netty.handler.codec.http.HttpRequestDecoder) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 42 with EventLoopGroup

use of org.apache.flink.shaded.netty4.io.netty.channel.EventLoopGroup in project java by wavefrontHQ.

the class StreamIngester method run.

public void run() {
    activeListeners.inc();
    // Configure the server.
    ServerBootstrap b = new ServerBootstrap();
    EventLoopGroup parentGroup;
    EventLoopGroup childGroup;
    Class<? extends ServerChannel> socketChannelClass;
    if (Epoll.isAvailable()) {
        logger.fine("Using native socket transport for port " + listeningPort);
        parentGroup = new EpollEventLoopGroup(1);
        childGroup = new EpollEventLoopGroup();
        socketChannelClass = EpollServerSocketChannel.class;
    } else {
        logger.fine("Using NIO socket transport for port " + listeningPort);
        parentGroup = new NioEventLoopGroup(1);
        childGroup = new NioEventLoopGroup();
        socketChannelClass = NioServerSocketChannel.class;
    }
    try {
        b.group(parentGroup, childGroup).channel(socketChannelClass).option(ChannelOption.SO_BACKLOG, 1024).localAddress(listeningPort).childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("frame decoder", frameDecoderFactory.getDecoder());
                pipeline.addLast("byte array decoder", new ByteArrayDecoder());
                pipeline.addLast(commandHandler);
            }
        });
        if (parentChannelOptions != null) {
            for (Map.Entry<ChannelOption<?>, ?> entry : parentChannelOptions.entrySet()) {
                b.option((ChannelOption<Object>) entry.getKey(), entry.getValue());
            }
        }
        if (childChannelOptions != null) {
            for (Map.Entry<ChannelOption<?>, ?> entry : childChannelOptions.entrySet()) {
                b.childOption((ChannelOption<Object>) entry.getKey(), entry.getValue());
            }
        }
        // Start the server.
        ChannelFuture f = b.bind().sync();
        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } catch (final InterruptedException e) {
        logger.log(Level.WARNING, "Interrupted");
        parentGroup.shutdownGracefully();
        childGroup.shutdownGracefully();
        logger.info("Listener on port " + String.valueOf(listeningPort) + " shut down");
    } catch (Exception e) {
        // ChannelFuture throws undeclared checked exceptions, so we need to handle it
        if (e instanceof BindException) {
            logger.severe("Unable to start listener - port " + String.valueOf(listeningPort) + " is already in use!");
        } else {
            logger.log(Level.SEVERE, "StreamIngester exception: ", e);
        }
    } finally {
        activeListeners.dec();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) ChannelOption(io.netty.channel.ChannelOption) BindException(java.net.BindException) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) BindException(java.net.BindException) ChannelPipeline(io.netty.channel.ChannelPipeline) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) Map(java.util.Map) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ByteArrayDecoder(io.netty.handler.codec.bytes.ByteArrayDecoder)

Example 43 with EventLoopGroup

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

the class TestPerChannelBookieClient method testConnectCloseRace.

/**
 * Test that a race does not exist between connection completion
 * and client closure. If a race does exist, this test will simply
 * hang at releaseExternalResources() as it is uninterruptible.
 * This specific race was found in
 * {@link https://issues.apache.org/jira/browse/BOOKKEEPER-485}.
 */
@Test
public void testConnectCloseRace() throws Exception {
    EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    OrderedExecutor executor = getOrderedSafeExecutor();
    BookieSocketAddress addr = getBookie(0);
    for (int i = 0; i < 1000; i++) {
        PerChannelBookieClient client = new PerChannelBookieClient(executor, eventLoopGroup, addr, authProvider, extRegistry);
        client.connectIfNeededAndDoOp(new GenericCallback<PerChannelBookieClient>() {

            @Override
            public void operationComplete(int rc, PerChannelBookieClient client) {
            // do nothing, we don't care about doing anything with the connection,
            // we just want to trigger it connecting.
            }
        });
        client.close();
    }
    eventLoopGroup.shutdownGracefully();
    executor.shutdown();
}
Also used : EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) BookieSocketAddress(org.apache.bookkeeper.net.BookieSocketAddress) OrderedExecutor(org.apache.bookkeeper.common.util.OrderedExecutor) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Test(org.junit.Test)

Example 44 with EventLoopGroup

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

the class TestPerChannelBookieClient method testDisconnectRace.

/**
 * Test that all resources are freed if connections and disconnections
 * are interleaved randomly.
 *
 * {@link https://issues.apache.org/jira/browse/BOOKKEEPER-620}
 */
@Test
public void testDisconnectRace() throws Exception {
    final GenericCallback<PerChannelBookieClient> nullop = new GenericCallback<PerChannelBookieClient>() {

        @Override
        public void operationComplete(int rc, PerChannelBookieClient client) {
        // do nothing, we don't care about doing anything with the connection,
        // we just want to trigger it connecting.
        }
    };
    final int iterations = 100000;
    EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    OrderedExecutor executor = getOrderedSafeExecutor();
    BookieSocketAddress addr = getBookie(0);
    final PerChannelBookieClient client = new PerChannelBookieClient(executor, eventLoopGroup, addr, authProvider, extRegistry);
    final AtomicBoolean shouldFail = new AtomicBoolean(false);
    final AtomicBoolean running = new AtomicBoolean(true);
    final CountDownLatch disconnectRunning = new CountDownLatch(1);
    Thread connectThread = new Thread() {

        public void run() {
            try {
                if (!disconnectRunning.await(10, TimeUnit.SECONDS)) {
                    LOG.error("Disconnect thread never started");
                    shouldFail.set(true);
                }
            } catch (InterruptedException ie) {
                LOG.error("Connect thread interrupted", ie);
                Thread.currentThread().interrupt();
                running.set(false);
            }
            for (int i = 0; i < iterations && running.get(); i++) {
                client.connectIfNeededAndDoOp(nullop);
            }
            running.set(false);
        }
    };
    Thread disconnectThread = new Thread() {

        public void run() {
            disconnectRunning.countDown();
            while (running.get()) {
                client.disconnect();
            }
        }
    };
    Thread checkThread = new Thread() {

        public void run() {
            ConnectionState state;
            Channel channel;
            while (running.get()) {
                synchronized (client) {
                    state = client.state;
                    channel = client.channel;
                    if ((state == ConnectionState.CONNECTED && (channel == null || !channel.isActive())) || (state != ConnectionState.CONNECTED && channel != null && channel.isActive())) {
                        LOG.error("State({}) and channel({}) inconsistent " + channel, state, channel == null ? null : channel.isActive());
                        shouldFail.set(true);
                        running.set(false);
                    }
                }
            }
        }
    };
    connectThread.start();
    disconnectThread.start();
    checkThread.start();
    connectThread.join();
    disconnectThread.join();
    checkThread.join();
    assertFalse("Failure in threads, check logs", shouldFail.get());
    client.close();
    eventLoopGroup.shutdownGracefully();
    executor.shutdown();
}
Also used : Channel(io.netty.channel.Channel) OrderedExecutor(org.apache.bookkeeper.common.util.OrderedExecutor) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) BookieSocketAddress(org.apache.bookkeeper.net.BookieSocketAddress) ConnectionState(org.apache.bookkeeper.proto.PerChannelBookieClient.ConnectionState) GenericCallback(org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.GenericCallback) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Test(org.junit.Test)

Example 45 with EventLoopGroup

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

the class TestPerChannelBookieClient method testConnectRace.

/**
 * Test race scenario found in {@link https://issues.apache.org/jira/browse/BOOKKEEPER-5}
 * where multiple clients try to connect a channel simultaneously. If not synchronised
 * correctly, this causes the netty channel to get orphaned.
 */
@Test
public void testConnectRace() throws Exception {
    GenericCallback<PerChannelBookieClient> nullop = new GenericCallback<PerChannelBookieClient>() {

        @Override
        public void operationComplete(int rc, PerChannelBookieClient pcbc) {
        // do nothing, we don't care about doing anything with the connection,
        // we just want to trigger it connecting.
        }
    };
    EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    OrderedExecutor executor = getOrderedSafeExecutor();
    BookieSocketAddress addr = getBookie(0);
    for (int i = 0; i < 100; i++) {
        PerChannelBookieClient client = new PerChannelBookieClient(executor, eventLoopGroup, addr, authProvider, extRegistry);
        for (int j = i; j < 10; j++) {
            client.connectIfNeededAndDoOp(nullop);
        }
        client.close();
    }
    eventLoopGroup.shutdownGracefully();
    executor.shutdown();
}
Also used : EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) BookieSocketAddress(org.apache.bookkeeper.net.BookieSocketAddress) OrderedExecutor(org.apache.bookkeeper.common.util.OrderedExecutor) GenericCallback(org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.GenericCallback) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Test(org.junit.Test)

Aggregations

EventLoopGroup (io.netty.channel.EventLoopGroup)352 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)259 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)155 Bootstrap (io.netty.bootstrap.Bootstrap)131 Channel (io.netty.channel.Channel)127 ChannelFuture (io.netty.channel.ChannelFuture)117 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)103 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)88 SocketChannel (io.netty.channel.socket.SocketChannel)82 InetSocketAddress (java.net.InetSocketAddress)69 Test (org.junit.jupiter.api.Test)67 DefaultEventLoopGroup (io.netty.channel.DefaultEventLoopGroup)60 LoggingHandler (io.netty.handler.logging.LoggingHandler)53 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)50 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)49 SslContext (io.netty.handler.ssl.SslContext)48 ChannelPipeline (io.netty.channel.ChannelPipeline)47 SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)45 LocalServerChannel (io.netty.channel.local.LocalServerChannel)42 LocalChannel (io.netty.channel.local.LocalChannel)40