Example usage for io.netty.channel ChannelOption WRITE_BUFFER_WATER_MARK

List of usage examples for io.netty.channel ChannelOption WRITE_BUFFER_WATER_MARK

Introduction

In this page you can find the example usage for io.netty.channel ChannelOption WRITE_BUFFER_WATER_MARK.

Prototype

ChannelOption WRITE_BUFFER_WATER_MARK

To view the source code for io.netty.channel ChannelOption WRITE_BUFFER_WATER_MARK.

Click Source Link

Usage

From source file:io.atomix.cluster.messaging.impl.NettyMessagingService.java

License:Apache License

private CompletableFuture<Void> startAcceptingConnections() {
    CompletableFuture<Void> future = new CompletableFuture<>();
    ServerBootstrap b = new ServerBootstrap();
    b.option(ChannelOption.SO_REUSEADDR, true);
    b.option(ChannelOption.SO_BACKLOG, 128);
    b.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(8 * 1024, 32 * 1024));
    b.childOption(ChannelOption.SO_RCVBUF, 1024 * 1024);
    b.childOption(ChannelOption.SO_SNDBUF, 1024 * 1024);
    b.childOption(ChannelOption.SO_KEEPALIVE, true);
    b.childOption(ChannelOption.TCP_NODELAY, true);
    b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.group(serverGroup, clientGroup);// ww w .  j a va2 s  .  co m
    b.channel(serverChannelClass);
    if (enableNettyTls) {
        b.childHandler(new SslServerCommunicationChannelInitializer());
    } else {
        b.childHandler(new BasicChannelInitializer());
    }

    // Bind and start to accept incoming connections.
    b.bind(localAddress.port()).addListener((ChannelFutureListener) f -> {
        if (f.isSuccess()) {
            log.info("{} accepting incoming connections on port {}", localAddress.address(true),
                    localAddress.port());
            serverChannel = f.channel();
            future.complete(null);
        } else {
            log.warn("{} failed to bind to port {} due to {}", localAddress.address(true), localAddress.port(),
                    f.cause());
            future.completeExceptionally(f.cause());
        }
    });
    return future;
}

From source file:io.grpc.netty.NettyServerTest.java

License:Apache License

@Test(timeout = 60000)
public void childChannelOptions() throws Exception {
    final int originalLowWaterMark = 2097169;
    final int originalHighWaterMark = 2097211;

    Map<ChannelOption<?>, Object> channelOptions = new HashMap<>();

    channelOptions.put(ChannelOption.WRITE_BUFFER_WATER_MARK,
            new WriteBufferWaterMark(originalLowWaterMark, originalHighWaterMark));

    final AtomicInteger lowWaterMark = new AtomicInteger(0);
    final AtomicInteger highWaterMark = new AtomicInteger(0);

    final CountDownLatch countDownLatch = new CountDownLatch(1);

    InetSocketAddress addr = new InetSocketAddress(0);
    NettyServer ns = new NettyServer(addr, Utils.DEFAULT_SERVER_CHANNEL_FACTORY, channelOptions,
            SharedResourcePool.forResource(Utils.DEFAULT_BOSS_EVENT_LOOP_GROUP),
            SharedResourcePool.forResource(Utils.DEFAULT_WORKER_EVENT_LOOP_GROUP),
            ProtocolNegotiators.plaintext(), Collections.<ServerStreamTracer.Factory>emptyList(),
            TransportTracer.getDefaultFactory(), 1, // ignore
            1, // ignore
            1, // ignore
            1, // ignore
            1, // ignore
            1, 1, // ignore
            1, 1, // ignore
            true, 0, // ignore
            channelz);//from   w ww.j a  v  a 2 s. co m
    ns.start(new ServerListener() {
        @Override
        public ServerTransportListener transportCreated(ServerTransport transport) {
            Channel channel = ((NettyServerTransport) transport).channel();
            WriteBufferWaterMark writeBufferWaterMark = channel.config()
                    .getOption(ChannelOption.WRITE_BUFFER_WATER_MARK);
            lowWaterMark.set(writeBufferWaterMark.low());
            highWaterMark.set(writeBufferWaterMark.high());

            countDownLatch.countDown();

            return new NoopServerTransportListener();
        }

        @Override
        public void serverShutdown() {
        }
    });

    Socket socket = new Socket();
    socket.connect(ns.getListenSocketAddress(), /* timeout= */ 8000);
    countDownLatch.await();
    socket.close();

    assertThat(lowWaterMark.get()).isEqualTo(originalLowWaterMark);
    assertThat(highWaterMark.get()).isEqualTo(originalHighWaterMark);

    ns.shutdown();
}

From source file:io.grpc.netty.UtilsTest.java

License:Apache License

private static InternalChannelz.SocketOptions setAndValidateGeneric(Channel channel) {
    channel.config().setOption(ChannelOption.SO_LINGER, 3);
    // only applicable for OIO channels:
    channel.config().setOption(ChannelOption.SO_TIMEOUT, 250);
    // Test some arbitrarily chosen options with a non numeric values
    channel.config().setOption(ChannelOption.SO_KEEPALIVE, true);
    WriteBufferWaterMark writeBufWaterMark = new WriteBufferWaterMark(10, 20);
    channel.config().setOption(ChannelOption.WRITE_BUFFER_WATER_MARK, writeBufWaterMark);

    InternalChannelz.SocketOptions socketOptions = Utils.getSocketOptions(channel);
    assertEquals(3, (int) socketOptions.lingerSeconds);
    assertEquals("true", socketOptions.others.get("SO_KEEPALIVE"));
    assertEquals(writeBufWaterMark.toString(),
            socketOptions.others.get(ChannelOption.WRITE_BUFFER_WATER_MARK.toString()));
    return socketOptions;
}

From source file:org.apache.bookkeeper.proto.BookieNettyServer.java

License:Apache License

private void listenOn(InetSocketAddress address, BookieSocketAddress bookieAddress)
        throws InterruptedException {
    if (!conf.isDisableServerSocketBind()) {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.option(ChannelOption.ALLOCATOR, allocator);
        bootstrap.childOption(ChannelOption.ALLOCATOR, allocator);
        bootstrap.group(eventLoopGroup, eventLoopGroup);
        bootstrap.childOption(ChannelOption.TCP_NODELAY, conf.getServerTcpNoDelay());
        bootstrap.childOption(ChannelOption.SO_LINGER, conf.getServerSockLinger());
        bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR,
                new AdaptiveRecvByteBufAllocator(conf.getRecvByteBufAllocatorSizeMin(),
                        conf.getRecvByteBufAllocatorSizeInitial(), conf.getRecvByteBufAllocatorSizeMax()));
        bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(
                conf.getServerWriteBufferLowWaterMark(), conf.getServerWriteBufferHighWaterMark()));

        if (eventLoopGroup instanceof EpollEventLoopGroup) {
            bootstrap.channel(EpollServerSocketChannel.class);
        } else {/*w ww.  ja va 2s  .c o  m*/
            bootstrap.channel(NioServerSocketChannel.class);
        }

        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                synchronized (suspensionLock) {
                    while (suspended) {
                        suspensionLock.wait();
                    }
                }

                BookieSideConnectionPeerContextHandler contextHandler = new BookieSideConnectionPeerContextHandler();
                ChannelPipeline pipeline = ch.pipeline();

                // For ByteBufList, skip the usual LengthFieldPrepender and have the encoder itself to add it
                pipeline.addLast("bytebufList", ByteBufList.ENCODER_WITH_SIZE);

                pipeline.addLast("lengthbaseddecoder",
                        new LengthFieldBasedFrameDecoder(maxFrameSize, 0, 4, 0, 4));
                pipeline.addLast("lengthprepender", new LengthFieldPrepender(4));

                pipeline.addLast("bookieProtoDecoder", new BookieProtoEncoding.RequestDecoder(registry));
                pipeline.addLast("bookieProtoEncoder", new BookieProtoEncoding.ResponseEncoder(registry));
                pipeline.addLast("bookieAuthHandler", new AuthHandler.ServerSideHandler(
                        contextHandler.getConnectionPeer(), authProviderFactory));

                ChannelInboundHandler requestHandler = isRunning.get()
                        ? new BookieRequestHandler(conf, requestProcessor, allChannels)
                        : new RejectRequestHandler();
                pipeline.addLast("bookieRequestHandler", requestHandler);

                pipeline.addLast("contextHandler", contextHandler);
            }
        });

        // Bind and start to accept incoming connections
        Channel listen = bootstrap.bind(address.getAddress(), address.getPort()).sync().channel();
        if (listen.localAddress() instanceof InetSocketAddress) {
            if (conf.getBookiePort() == 0) {
                conf.setBookiePort(((InetSocketAddress) listen.localAddress()).getPort());
            }
        }
    }

    if (conf.isEnableLocalTransport()) {
        ServerBootstrap jvmBootstrap = new ServerBootstrap();
        jvmBootstrap.childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true));
        jvmBootstrap.group(jvmEventLoopGroup, jvmEventLoopGroup);
        jvmBootstrap.childOption(ChannelOption.TCP_NODELAY, conf.getServerTcpNoDelay());
        jvmBootstrap.childOption(ChannelOption.SO_KEEPALIVE, conf.getServerSockKeepalive());
        jvmBootstrap.childOption(ChannelOption.SO_LINGER, conf.getServerSockLinger());
        jvmBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR,
                new AdaptiveRecvByteBufAllocator(conf.getRecvByteBufAllocatorSizeMin(),
                        conf.getRecvByteBufAllocatorSizeInitial(), conf.getRecvByteBufAllocatorSizeMax()));
        jvmBootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(
                conf.getServerWriteBufferLowWaterMark(), conf.getServerWriteBufferHighWaterMark()));

        if (jvmEventLoopGroup instanceof DefaultEventLoopGroup) {
            jvmBootstrap.channel(LocalServerChannel.class);
        } else if (jvmEventLoopGroup instanceof EpollEventLoopGroup) {
            jvmBootstrap.channel(EpollServerSocketChannel.class);
        } else {
            jvmBootstrap.channel(NioServerSocketChannel.class);
        }

        jvmBootstrap.childHandler(new ChannelInitializer<LocalChannel>() {
            @Override
            protected void initChannel(LocalChannel ch) throws Exception {
                synchronized (suspensionLock) {
                    while (suspended) {
                        suspensionLock.wait();
                    }
                }

                BookieSideConnectionPeerContextHandler contextHandler = new BookieSideConnectionPeerContextHandler();
                ChannelPipeline pipeline = ch.pipeline();

                pipeline.addLast("lengthbaseddecoder",
                        new LengthFieldBasedFrameDecoder(maxFrameSize, 0, 4, 0, 4));
                pipeline.addLast("lengthprepender", new LengthFieldPrepender(4));

                pipeline.addLast("bookieProtoDecoder", new BookieProtoEncoding.RequestDecoder(registry));
                pipeline.addLast("bookieProtoEncoder", new BookieProtoEncoding.ResponseEncoder(registry));
                pipeline.addLast("bookieAuthHandler", new AuthHandler.ServerSideHandler(
                        contextHandler.getConnectionPeer(), authProviderFactory));

                ChannelInboundHandler requestHandler = isRunning.get()
                        ? new BookieRequestHandler(conf, requestProcessor, allChannels)
                        : new RejectRequestHandler();
                pipeline.addLast("bookieRequestHandler", requestHandler);

                pipeline.addLast("contextHandler", contextHandler);
            }
        });

        // use the same address 'name', so clients can find local Bookie still discovering them using ZK
        jvmBootstrap.bind(bookieAddress.getLocalAddress()).sync();
        LocalBookiesRegistry.registerLocalBookieAddress(bookieAddress);
    }
}

From source file:org.apache.bookkeeper.proto.PerChannelBookieClient.java

License:Apache License

protected ChannelFuture connect() {
    final long startTime = MathUtils.nowInNano();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Connecting to bookie: {}", addr);
    }//from  www  . j av  a 2s  .  c  om

    // Set up the ClientBootStrap so we can create a new Channel connection to the bookie.
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(eventLoopGroup);
    if (eventLoopGroup instanceof EpollEventLoopGroup) {
        bootstrap.channel(EpollSocketChannel.class);
    } else if (eventLoopGroup instanceof DefaultEventLoopGroup) {
        bootstrap.channel(LocalChannel.class);
    } else {
        bootstrap.channel(NioSocketChannel.class);
    }

    bootstrap.option(ChannelOption.ALLOCATOR, this.allocator);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, conf.getClientConnectTimeoutMillis());
    bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(
            conf.getClientWriteBufferLowWaterMark(), conf.getClientWriteBufferHighWaterMark()));

    if (!(eventLoopGroup instanceof DefaultEventLoopGroup)) {
        bootstrap.option(ChannelOption.TCP_NODELAY, conf.getClientTcpNoDelay());
        bootstrap.option(ChannelOption.SO_KEEPALIVE, conf.getClientSockKeepalive());

        // if buffer sizes are 0, let OS auto-tune it
        if (conf.getClientSendBufferSize() > 0) {
            bootstrap.option(ChannelOption.SO_SNDBUF, conf.getClientSendBufferSize());
        }

        if (conf.getClientReceiveBufferSize() > 0) {
            bootstrap.option(ChannelOption.SO_RCVBUF, conf.getClientReceiveBufferSize());
        }
    }

    // In the netty pipeline, we need to split packets based on length, so we
    // use the {@link LengthFieldBasedFramDecoder}. Other than that all actions
    // are carried out in this class, e.g., making sense of received messages,
    // prepending the length to outgoing packets etc.
    bootstrap.handler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();

            pipeline.addLast("bytebufList", ByteBufList.ENCODER_WITH_SIZE);
            pipeline.addLast("lengthbasedframedecoder",
                    new LengthFieldBasedFrameDecoder(maxFrameSize, 0, 4, 0, 4));
            pipeline.addLast("lengthprepender", new LengthFieldPrepender(4));
            pipeline.addLast("bookieProtoEncoder", new BookieProtoEncoding.RequestEncoder(extRegistry));
            pipeline.addLast("bookieProtoDecoder",
                    new BookieProtoEncoding.ResponseDecoder(extRegistry, useV2WireProtocol));
            pipeline.addLast("authHandler", new AuthHandler.ClientSideHandler(authProviderFactory,
                    txnIdGenerator, connectionPeer, useV2WireProtocol));
            pipeline.addLast("mainhandler", PerChannelBookieClient.this);
        }
    });

    SocketAddress bookieAddr = addr.getSocketAddress();
    if (eventLoopGroup instanceof DefaultEventLoopGroup) {
        bookieAddr = addr.getLocalAddress();
    }

    ChannelFuture future = bootstrap.connect(bookieAddr);
    future.addListener(contextPreservingListener(new ConnectionFutureListener(startTime)));
    future.addListener(x -> makeWritable());
    return future;
}

From source file:org.apache.hyracks.http.server.HttpServer.java

License:Apache License

protected void doStart() throws InterruptedException {
    /*/* w ww .  j  a  v a2 s.  com*/
     * This is a hacky way to ensure that IServlets with more specific paths are checked first.
     * For example:
     * "/path/to/resource/"
     * is checked before
     * "/path/to/"
     * which in turn is checked before
     * "/path/"
     * Note that it doesn't work for the case where multiple paths map to a single IServlet
     */
    Collections.sort(servlets, (l1, l2) -> l2.getPaths()[0].length() - l1.getPaths()[0].length());
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(RECEIVE_BUFFER_SIZE))
            .childOption(ChannelOption.AUTO_READ, Boolean.FALSE)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, WRITE_BUFFER_WATER_MARK)
            .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new HttpServerInitializer(this));
    channel = b.bind(port).sync().channel();
}

From source file:org.jupiter.transport.netty.NettyTcpAcceptor.java

License:Apache License

@Override
protected void setOptions() {
    super.setOptions();

    ServerBootstrap boot = bootstrap();/*www .jav  a2  s.com*/

    // parent options
    NettyConfig.NettyTcpConfigGroup.ParentConfig parent = configGroup.parent();
    boot.option(ChannelOption.SO_BACKLOG, parent.getBacklog());
    boot.option(ChannelOption.SO_REUSEADDR, parent.isReuseAddress());
    if (parent.getRcvBuf() > 0) {
        boot.option(ChannelOption.SO_RCVBUF, parent.getRcvBuf());
    }

    // child options
    NettyConfig.NettyTcpConfigGroup.ChildConfig child = configGroup.child();
    boot.childOption(ChannelOption.SO_REUSEADDR, child.isReuseAddress())
            .childOption(ChannelOption.SO_KEEPALIVE, child.isKeepAlive())
            .childOption(ChannelOption.TCP_NODELAY, child.isTcpNoDelay())
            .childOption(ChannelOption.ALLOW_HALF_CLOSURE, child.isAllowHalfClosure());
    if (child.getRcvBuf() > 0) {
        boot.childOption(ChannelOption.SO_RCVBUF, child.getRcvBuf());
    }
    if (child.getSndBuf() > 0) {
        boot.childOption(ChannelOption.SO_SNDBUF, child.getSndBuf());
    }
    if (child.getLinger() > 0) {
        boot.childOption(ChannelOption.SO_LINGER, child.getLinger());
    }
    if (child.getIpTos() > 0) {
        boot.childOption(ChannelOption.IP_TOS, child.getIpTos());
    }
    int bufLowWaterMark = child.getWriteBufferLowWaterMark();
    int bufHighWaterMark = child.getWriteBufferHighWaterMark();
    if (bufLowWaterMark >= 0 && bufHighWaterMark > 0) {
        WriteBufferWaterMark waterMark = new WriteBufferWaterMark(bufLowWaterMark, bufHighWaterMark);
        boot.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, waterMark);
    }
}

From source file:org.jupiter.transport.netty.NettyTcpConnector.java

License:Apache License

@Override
protected void setOptions() {
    super.setOptions();

    Bootstrap boot = bootstrap();/*from  w  w  w .j  ava2s .c  om*/

    NettyConfig.NettyTcpConfigGroup.ChildConfig child = childConfig;

    // child options
    boot.option(ChannelOption.SO_REUSEADDR, child.isReuseAddress())
            .option(ChannelOption.SO_KEEPALIVE, child.isKeepAlive())
            .option(ChannelOption.TCP_NODELAY, child.isTcpNoDelay())
            .option(ChannelOption.ALLOW_HALF_CLOSURE, child.isAllowHalfClosure());
    if (child.getRcvBuf() > 0) {
        boot.option(ChannelOption.SO_RCVBUF, child.getRcvBuf());
    }
    if (child.getSndBuf() > 0) {
        boot.option(ChannelOption.SO_SNDBUF, child.getSndBuf());
    }
    if (child.getLinger() > 0) {
        boot.option(ChannelOption.SO_LINGER, child.getLinger());
    }
    if (child.getIpTos() > 0) {
        boot.option(ChannelOption.IP_TOS, child.getIpTos());
    }
    if (child.getConnectTimeoutMillis() > 0) {
        boot.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, child.getConnectTimeoutMillis());
    }
    int bufLowWaterMark = child.getWriteBufferLowWaterMark();
    int bufHighWaterMark = child.getWriteBufferHighWaterMark();
    if (bufLowWaterMark >= 0 && bufHighWaterMark > 0) {
        WriteBufferWaterMark waterMark = new WriteBufferWaterMark(bufLowWaterMark, bufHighWaterMark);
        boot.option(ChannelOption.WRITE_BUFFER_WATER_MARK, waterMark);
    }
}

From source file:org.jupiter.transport.netty.NettyUdtAcceptor.java

License:Apache License

@Override
protected void setOptions() {
    super.setOptions();

    ServerBootstrap boot = bootstrap();/*from   w  w w  . j  a v a  2  s  . co  m*/

    // parent options
    NettyUdtConfigGroup.ParentConfig parent = configGroup.parent();
    boot.option(ChannelOption.SO_BACKLOG, parent.getBacklog());

    // child options
    NettyUdtConfigGroup.ChildConfig child = configGroup.child();
    boot.childOption(ChannelOption.SO_REUSEADDR, child.isReuseAddress());
    if (child.getRcvBuf() > 0) {
        boot.childOption(ChannelOption.SO_RCVBUF, child.getRcvBuf());
    }
    if (child.getSndBuf() > 0) {
        boot.childOption(ChannelOption.SO_SNDBUF, child.getSndBuf());
    }
    if (child.getLinger() > 0) {
        boot.childOption(ChannelOption.SO_LINGER, child.getLinger());
    }
    int bufLowWaterMark = child.getWriteBufferLowWaterMark();
    int bufHighWaterMark = child.getWriteBufferHighWaterMark();
    if (bufLowWaterMark >= 0 && bufHighWaterMark > 0) {
        WriteBufferWaterMark waterMark = new WriteBufferWaterMark(bufLowWaterMark, bufHighWaterMark);
        boot.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, waterMark);
    }
}

From source file:org.jupiter.transport.netty.NettyUdtConnector.java

License:Apache License

@Override
protected void setOptions() {
    super.setOptions();

    Bootstrap boot = bootstrap();/*from ww  w  . j a va 2 s  .  c o  m*/

    NettyUdtConfigGroup.ChildConfig child = childConfig;

    // child options
    boot.option(ChannelOption.SO_REUSEADDR, child.isReuseAddress());
    if (child.getRcvBuf() > 0) {
        boot.option(ChannelOption.SO_RCVBUF, child.getRcvBuf());
    }
    if (child.getSndBuf() > 0) {
        boot.option(ChannelOption.SO_SNDBUF, child.getSndBuf());
    }
    if (child.getLinger() > 0) {
        boot.option(ChannelOption.SO_LINGER, child.getLinger());
    }
    if (child.getConnectTimeoutMillis() > 0) {
        boot.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, child.getConnectTimeoutMillis());
    }
    int bufLowWaterMark = child.getWriteBufferLowWaterMark();
    int bufHighWaterMark = child.getWriteBufferHighWaterMark();
    if (bufLowWaterMark >= 0 && bufHighWaterMark > 0) {
        WriteBufferWaterMark waterMark = new WriteBufferWaterMark(bufLowWaterMark, bufHighWaterMark);
        boot.option(ChannelOption.WRITE_BUFFER_WATER_MARK, waterMark);
    }
}