Search in sources :

Example 91 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project elasticsearch by elastic.

the class Netty4Transport method connectToChannels.

@Override
protected NodeChannels connectToChannels(DiscoveryNode node, ConnectionProfile profile) {
    final Channel[] channels = new Channel[profile.getNumConnections()];
    final NodeChannels nodeChannels = new NodeChannels(node, channels, profile);
    boolean success = false;
    try {
        final TimeValue connectTimeout;
        final Bootstrap bootstrap;
        final TimeValue defaultConnectTimeout = defaultConnectionProfile.getConnectTimeout();
        if (profile.getConnectTimeout() != null && profile.getConnectTimeout().equals(defaultConnectTimeout) == false) {
            bootstrap = this.bootstrap.clone(this.bootstrap.config().group());
            bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Math.toIntExact(profile.getConnectTimeout().millis()));
            connectTimeout = profile.getConnectTimeout();
        } else {
            connectTimeout = defaultConnectTimeout;
            bootstrap = this.bootstrap;
        }
        final ArrayList<ChannelFuture> connections = new ArrayList<>(channels.length);
        final InetSocketAddress address = node.getAddress().address();
        for (int i = 0; i < channels.length; i++) {
            connections.add(bootstrap.connect(address));
        }
        final Iterator<ChannelFuture> iterator = connections.iterator();
        try {
            for (int i = 0; i < channels.length; i++) {
                assert iterator.hasNext();
                ChannelFuture future = iterator.next();
                future.awaitUninterruptibly((long) (connectTimeout.millis() * 1.5));
                if (!future.isSuccess()) {
                    throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", future.cause());
                }
                channels[i] = future.channel();
                channels[i].closeFuture().addListener(new ChannelCloseListener(node));
            }
            assert iterator.hasNext() == false : "not all created connection have been consumed";
        } catch (final RuntimeException e) {
            for (final ChannelFuture future : Collections.unmodifiableList(connections)) {
                FutureUtils.cancel(future);
                if (future.channel() != null && future.channel().isOpen()) {
                    try {
                        future.channel().close();
                    } catch (Exception inner) {
                        e.addSuppressed(inner);
                    }
                }
            }
            throw e;
        }
        success = true;
    } finally {
        if (success == false) {
            try {
                nodeChannels.close();
            } catch (IOException e) {
                logger.trace("exception while closing channels", e);
            }
        }
    }
    return nodeChannels;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) InetSocketAddress(java.net.InetSocketAddress) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) ArrayList(java.util.ArrayList) IOException(java.io.IOException) ElasticsearchException(org.elasticsearch.ElasticsearchException) ConnectTransportException(org.elasticsearch.transport.ConnectTransportException) IOException(java.io.IOException) ConnectTransportException(org.elasticsearch.transport.ConnectTransportException) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) TimeValue(org.elasticsearch.common.unit.TimeValue)

Example 92 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project elasticsearch by elastic.

the class Netty4Transport method createBootstrap.

private Bootstrap createBootstrap() {
    final Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(new NioEventLoopGroup(workerCount, daemonThreadFactory(settings, TRANSPORT_CLIENT_BOSS_THREAD_NAME_PREFIX)));
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.handler(getClientChannelInitializer());
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Math.toIntExact(defaultConnectionProfile.getConnectTimeout().millis()));
    bootstrap.option(ChannelOption.TCP_NODELAY, TCP_NO_DELAY.get(settings));
    bootstrap.option(ChannelOption.SO_KEEPALIVE, TCP_KEEP_ALIVE.get(settings));
    final ByteSizeValue tcpSendBufferSize = TCP_SEND_BUFFER_SIZE.get(settings);
    if (tcpSendBufferSize.getBytes() > 0) {
        bootstrap.option(ChannelOption.SO_SNDBUF, Math.toIntExact(tcpSendBufferSize.getBytes()));
    }
    final ByteSizeValue tcpReceiveBufferSize = TCP_RECEIVE_BUFFER_SIZE.get(settings);
    if (tcpReceiveBufferSize.getBytes() > 0) {
        bootstrap.option(ChannelOption.SO_RCVBUF, Math.toIntExact(tcpReceiveBufferSize.getBytes()));
    }
    bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator);
    final boolean reuseAddress = TCP_REUSE_ADDRESS.get(settings);
    bootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress);
    bootstrap.validate();
    return bootstrap;
}
Also used : ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 93 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project grpc-java by grpc.

the class ProtocolNegotiatorsTest method httpProxy_completes.

@Test(timeout = 5000)
public void httpProxy_completes() throws Exception {
    DefaultEventLoopGroup elg = new DefaultEventLoopGroup(1);
    // ProxyHandler is incompatible with EmbeddedChannel because when channelRegistered() is called
    // the channel is already active.
    LocalAddress proxy = new LocalAddress("httpProxy_completes");
    SocketAddress host = InetSocketAddress.createUnresolved("specialHost", 314);
    ChannelInboundHandler mockHandler = mock(ChannelInboundHandler.class);
    Channel serverChannel = new ServerBootstrap().group(elg).channel(LocalServerChannel.class).childHandler(mockHandler).bind(proxy).sync().channel();
    ProtocolNegotiator nego = ProtocolNegotiators.httpProxy(proxy, null, null, ProtocolNegotiators.plaintext());
    ChannelHandler handler = nego.newHandler(grpcHandler);
    Channel channel = new Bootstrap().group(elg).channel(LocalChannel.class).handler(handler).register().sync().channel();
    pipeline = channel.pipeline();
    // Wait for initialization to complete
    channel.eventLoop().submit(NOOP_RUNNABLE).sync();
    // The grpcHandler must be in the pipeline, but we don't actually want it during our test
    // because it will consume all events since it is a mock. We only use it because it is required
    // to construct the Handler.
    pipeline.remove(grpcHandler);
    channel.connect(host).sync();
    serverChannel.close();
    ArgumentCaptor<ChannelHandlerContext> contextCaptor = ArgumentCaptor.forClass(ChannelHandlerContext.class);
    Mockito.verify(mockHandler).channelActive(contextCaptor.capture());
    ChannelHandlerContext serverContext = contextCaptor.getValue();
    final String golden = "isThisThingOn?";
    ChannelFuture negotiationFuture = channel.writeAndFlush(bb(golden, channel));
    // Wait for sending initial request to complete
    channel.eventLoop().submit(NOOP_RUNNABLE).sync();
    ArgumentCaptor<Object> objectCaptor = ArgumentCaptor.forClass(Object.class);
    Mockito.verify(mockHandler).channelRead(any(ChannelHandlerContext.class), objectCaptor.capture());
    ByteBuf b = (ByteBuf) objectCaptor.getValue();
    String request = b.toString(UTF_8);
    b.release();
    assertTrue("No trailing newline: " + request, request.endsWith("\r\n\r\n"));
    assertTrue("No CONNECT: " + request, request.startsWith("CONNECT specialHost:314 "));
    assertTrue("No host header: " + request, request.contains("host: specialHost:314"));
    assertFalse(negotiationFuture.isDone());
    serverContext.writeAndFlush(bb("HTTP/1.1 200 OK\r\n\r\n", serverContext.channel())).sync();
    negotiationFuture.sync();
    channel.eventLoop().submit(NOOP_RUNNABLE).sync();
    objectCaptor.getAllValues().clear();
    Mockito.verify(mockHandler, times(2)).channelRead(any(ChannelHandlerContext.class), objectCaptor.capture());
    b = (ByteBuf) objectCaptor.getAllValues().get(1);
    // If we were using the real grpcHandler, this would have been the HTTP/2 preface
    String preface = b.toString(UTF_8);
    b.release();
    assertEquals(golden, preface);
    channel.close();
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) LocalAddress(io.netty.channel.local.LocalAddress) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelHandler(io.netty.channel.ChannelHandler) ByteBuf(io.netty.buffer.ByteBuf) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) ChannelInboundHandler(io.netty.channel.ChannelInboundHandler) Test(org.junit.Test)

Example 94 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project failsafe by jhalterman.

the class NettyExample method main.

public static void main(String... args) throws Throwable {
    EventLoopGroup group = new NioEventLoopGroup();
    Bootstrap bootstrap = createBootstrap(group);
    RetryPolicy retryPolicy = new RetryPolicy().withDelay(1, TimeUnit.SECONDS);
    Failsafe.with(retryPolicy).with(group).runAsync(execution -> bootstrap.connect(HOST, PORT).addListener((ChannelFutureListener) channelFuture -> {
        if (channelFuture.isSuccess()) {
            System.out.println("Connected!");
            try {
                channelFuture.sync();
                channelFuture.channel().closeFuture().sync();
            } catch (Exception ignore) {
                group.shutdownGracefully();
            }
        } else if (!execution.retryOn(channelFuture.cause()))
            System.out.println("Connection attempts failed");
    }));
    Thread.sleep(5000);
}
Also used : EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) RetryPolicy(net.jodah.failsafe.RetryPolicy) ChannelFutureListener(io.netty.channel.ChannelFutureListener) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 95 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project pinot by linkedin.

the class NettyTCPClientConnection method init.

private void init() {
    _bootstrap = new Bootstrap();
    _bootstrap.group(_eventGroup).channel(NioSocketChannel.class).handler(new ChannelHandlerInitializer(_handler));
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Bootstrap(io.netty.bootstrap.Bootstrap)

Aggregations

Bootstrap (io.netty.bootstrap.Bootstrap)163 Channel (io.netty.channel.Channel)81 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)73 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)68 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)68 ChannelFuture (io.netty.channel.ChannelFuture)62 EventLoopGroup (io.netty.channel.EventLoopGroup)61 Test (org.junit.Test)61 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)49 InetSocketAddress (java.net.InetSocketAddress)49 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)37 SocketChannel (io.netty.channel.socket.SocketChannel)33 ChannelPipeline (io.netty.channel.ChannelPipeline)31 LocalAddress (io.netty.channel.local.LocalAddress)26 ClosedChannelException (java.nio.channels.ClosedChannelException)26 LocalChannel (io.netty.channel.local.LocalChannel)22 LocalServerChannel (io.netty.channel.local.LocalServerChannel)22 CountDownLatch (java.util.concurrent.CountDownLatch)22 ChannelFutureListener (io.netty.channel.ChannelFutureListener)20 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)18