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;
}
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;
}
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();
}
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);
}
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));
}
Aggregations