@Override public void operationComplete(Future<InetAddress> future) throws Exception { if (future.isSuccess()) { promise.setSuccess(new InetSocketAddress(future.getNow(), unresolvedAddress.getPort())); } else { promise.setFailure(future.cause()); } } });
public void resolveHostname(String hostname, Handler<AsyncResult<InetAddress>> resultHandler) { ContextInternal callback = (ContextInternal) vertx.getOrCreateContext(); io.netty.resolver.AddressResolver<InetSocketAddress> resolver = resolverGroup.getResolver(callback.nettyEventLoop()); io.netty.util.concurrent.Future<InetSocketAddress> fut = resolver.resolve(InetSocketAddress.createUnresolved(hostname, 0)); fut.addListener(a -> { callback.runOnContext(v -> { if (a.isSuccess()) { InetSocketAddress address = fut.getNow(); resultHandler.handle(Future.succeededFuture(address.getAddress())); } else { resultHandler.handle(Future.failedFuture(a.cause())); } }); }); }
public void stop() throws IOException, InterruptedException { LOG.info("Stopping LlapOutputFormatService"); if (listeningChannelFuture != null) { listeningChannelFuture.channel().close().sync(); listeningChannelFuture = null; } else { LOG.warn("LlapOutputFormatService does not appear to have a listening port to close."); } eventLoopGroup.shutdownGracefully(1, WAIT_TIME, TimeUnit.SECONDS).sync(); }
@Override public void operationComplete(Future<T> future) throws Exception { if (future.isSuccess()) { promise.setSuccess(future.getNow()); } else { doResolveRec(inetHost, promise, resolverIndex + 1, future.cause()); } } });
public void start() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .remoteAddress(new InetSocketAddress(host, port)) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( new EchoClientHandler()); } }); ChannelFuture f = b.connect().sync(); f.channel().closeFuture().sync(); } finally { group.shutdownGracefully().sync(); } }
InetSocketAddress remoteDestination = new InetSocketAddress(IPV6Util.stripBracketsAndZoneID(host), port); future = bootstrap.connect(remoteDestination, localDestination); } else { future = bootstrap.connect(remoteDestination); future.awaitUninterruptibly(); if (future.isSuccess()) { final Channel ch = future.channel(); SslHandler sslHandler = ch.pipeline().get(SslHandler.class); if (sslHandler != null) { Future<Channel> handshakeFuture = sslHandler.handshakeFuture(); if (handshakeFuture.awaitUninterruptibly(30000)) { if (handshakeFuture.isSuccess()) { ChannelPipeline channelPipeline = ch.pipeline(); ActiveMQChannelHandler channelHandler = channelPipeline.get(ActiveMQChannelHandler.class); channelHandler.active = true; } else { ch.close().awaitUninterruptibly(); ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(handshakeFuture.cause()); return null; HttpUpgradeHandler httpUpgradeHandler = (HttpUpgradeHandler) ch.pipeline().get("http-upgrade"); String scheme = "http"; if (sslEnabled) {
public void start() throws Exception { final EchoServerHandler serverHandler = new EchoServerHandler(); EventLoopGroup group = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(group) .channel(NioServerSocketChannel.class) .localAddress(new InetSocketAddress(port)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(serverHandler); } }); ChannelFuture f = b.bind().sync(); System.out.println(EchoServer.class.getName() + " started and listening for connections on " + f.channel().localAddress()); f.channel().closeFuture().sync(); } finally { group.shutdownGracefully().sync(); } } }
public ChannelFuture connect(String host, int port, Listener listener) { return bootstrap.connect(new InetSocketAddress(host, port)).addListener(f -> { if (f.isSuccess()) { if (listener != null) listener.onSuccess(port); LOGGER.info("start netty client success, host={}, port={}", host, port); } else { if (listener != null) listener.onFailure(f.cause()); LOGGER.error("start netty client failure, host={}, port={}", host, port, f.cause()); } }); }
@Test public void shouldLogOnlyTheFirstCaughtException() throws Exception { AssertableLogProvider logProvider = new AssertableLogProvider(); BoltConnection connection = mock( BoltConnection.class ); HouseKeeper houseKeeper = new HouseKeeper( connection, logProvider.getLog( HouseKeeper.class ) ); Bootstrap bootstrap = newBootstrap( houseKeeper ); RuntimeException error1 = new RuntimeException( "error #1" ); RuntimeException error2 = new RuntimeException( "error #2" ); RuntimeException error3 = new RuntimeException( "error #3" ); try ( ServerSocket serverSocket = new ServerSocket( 0 ) ) { ChannelFuture future = bootstrap.connect( "localhost", serverSocket.getLocalPort() ).sync(); Channel channel = future.channel(); // fire multiple errors channel.pipeline().fireExceptionCaught( error1 ); channel.pipeline().fireExceptionCaught( error2 ); channel.pipeline().fireExceptionCaught( error3 ); // await for the channel to be closed by the HouseKeeper channel.closeFuture().sync(); } finally { // make sure event loop group is always terminated bootstrap.config().group().shutdownGracefully().sync(); } logProvider.assertExactly( inLog( HouseKeeper.class ).error( startsWith( "Fatal error occurred when handling a client connection" ), equalTo( error1 ) ) ); }
@Test public void shouldNotLogExceptionsWhenEvenLoopIsShuttingDown() throws Exception { AssertableLogProvider logProvider = new AssertableLogProvider(); BoltConnection connection = mock( BoltConnection.class ); HouseKeeper houseKeeper = new HouseKeeper( connection, logProvider.getLog( HouseKeeper.class ) ); Bootstrap bootstrap = newBootstrap( houseKeeper ); try ( ServerSocket serverSocket = new ServerSocket( 0 ) ) { ChannelFuture future = bootstrap.connect( "localhost", serverSocket.getLocalPort() ).sync(); Channel channel = future.channel(); // write some messages without flushing for ( int i = 0; i < 100; i++ ) { // use void promise which should redirect all write errors back to the pipeline and the HouseKeeper channel.write( writeUtf8( channel.alloc(), "Hello" ), channel.voidPromise() ); } // stop the even loop to make all pending writes fail bootstrap.config().group().shutdownGracefully(); // await for the channel to be closed by the HouseKeeper channel.closeFuture().sync(); } finally { // make sure event loop group is always terminated bootstrap.config().group().shutdownGracefully().sync(); } logProvider.assertNoLoggingOccurred(); }
private void handleConnect(SocketAddress remoteAddress, SocketAddress peerAddress, String serverName, Handler<AsyncResult<Channel>> channelHandler) { VertxInternal vertx = context.owner(); bootstrap.resolver(vertx.nettyAddressResolverGroup()); bootstrap.handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) { initSSL(peerAddress, serverName, ch, channelHandler); } }); ChannelFuture fut = bootstrap.connect(vertx.transport().convert(remoteAddress, false)); fut.addListener(res -> { if (res.isSuccess()) { connected(fut.channel(), channelHandler); } else { channelHandler.handle(io.vertx.core.Future.failedFuture(res.cause())); } }); }
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { if (LOG.isTraceEnabled()) { LOG.trace("Channel active {}", ctx.channel()); } final Channel channel = ctx.channel(); InetAddress addr = ((InetSocketAddress) channel.remoteAddress()) .getAddress(); if (maxClientCnxns > 0 && getClientCnxnCount(addr) >= maxClientCnxns) { ServerMetrics.CONNECTION_REJECTED.add(1); LOG.warn("Too many connections from {} - max is {}", addr, maxClientCnxns); channel.close(); return; } NettyServerCnxn cnxn = new NettyServerCnxn(channel, zkServer, NettyServerCnxnFactory.this); ctx.channel().attr(CONNECTION_ATTRIBUTE).set(cnxn); if (secure) { SslHandler sslHandler = ctx.pipeline().get(SslHandler.class); Future<Channel> handshakeFuture = sslHandler.handshakeFuture(); handshakeFuture.addListener(new CertificateVerifier(sslHandler, cnxn)); } else { allChannels.add(ctx.channel()); addCnxn(cnxn); } }
AtomicReference<Thread> channelThread = new AtomicReference<>(); CountDownLatch connectLatch = new CountDownLatch(1); Bootstrap bootstrap = new Bootstrap(); bootstrap.channelFactory(((VertxInternal)vertx).transport().channelFactory(false)); bootstrap.group(vertx.nettyEventLoopGroup()); bootstrap.resolver(((VertxInternal) vertx).nettyAddressResolverGroup()); bootstrap.handler(new ChannelInitializer<Channel>() { ChannelFuture channelFut = bootstrap.connect("localhost", 1234); awaitLatch(connectLatch); channelFut.addListener(v -> { assertTrue(v.isSuccess()); assertEquals(channelThread.get(), Thread.currentThread()); testComplete();
public ChannelFuture connect(InetSocketAddress remote, InetSocketAddress local, ClientConfig clientConfig) { ChannelFuture future = local != null ? bootstrap.connect(remote, local) : bootstrap.connect(remote); if (future.channel() != null) future.channel().attr(CONFIG_KEY).set(clientConfig); future.addListener(f -> { if (f.isSuccess()) { future.channel().attr(CONFIG_KEY).set(clientConfig); LOGGER.info("start netty client success, remote={}, local={}", remote, local); } else { LOGGER.error("start netty client failure, remote={}, local={}", remote, local, f.cause()); } }); return future; }
@Override public CompletableFuture<Void> sendAsync(ProtocolRequest message) { CompletableFuture<Void> future = new CompletableFuture<>(); channel.writeAndFlush(message).addListener(channelFuture -> { if (!channelFuture.isSuccess()) { future.completeExceptionally(channelFuture.cause()); } else { future.complete(null); } }); return future; }
private void doCloseSync() { final CountDownLatch outerLatch = eventLoop.submit(() -> { if (allChannels.isEmpty()) { return null; final ChannelFuture f = ch.closeFuture(); closeFutures.add(f); f.addListener((ChannelFutureListener) future -> latch.countDown()); closeFutures.forEach(f -> f.channel().close()); return latch; }).syncUninterruptibly().getNow();
@Override public void channelRead(final ChannelHandlerContext ctx, final Object mesg) throws Exception { if (mesg instanceof FullHttpRequest) { final FullHttpRequest req = (FullHttpRequest) mesg; if ((req.method() == HttpMethod.GET) && (PushProtocol.SSE.getPath().equals(req.uri()))) { ctx.pipeline().fireUserEventTriggered(PushProtocol.SSE.getHandshakeCompleteEvent()); final DefaultHttpResponse resp = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK); final HttpHeaders headers = resp.headers(); headers.add("Connection", "keep-alive"); headers.add("Content-Type", "text/event-stream"); headers.add("Transfer-Encoding", "chunked"); final ChannelFuture cf = ctx.channel().writeAndFlush(resp); cf.addListener(future -> { if (future.isSuccess()) { ChannelPipeline pipeline = ctx.pipeline(); if (pipeline.get(HttpObjectAggregator.class) != null) { pipeline.remove(HttpObjectAggregator.class); } if (pipeline.get(HttpContentCompressor.class) != null) { pipeline.remove(HttpContentCompressor.class); } final String reconnetInterval = "retry: " + SSE_RETRY_BASE_INTERVAL.get() + "\r\n\r\n"; ctx.writeAndFlush(reconnetInterval); } }); } } }
private void addConnection(String host, int port, boolean sync) { ChannelFuture future = gatewayClient.connect(host, port); future.channel().attr(attrKey).set(getHostAndPort(host, port)); future.addListener(f -> { if (!f.isSuccess()) { logger.error("create gateway connection failure, host={}, port={}", host, port, f.cause()); } }); if (sync) future.awaitUninterruptibly(); }
private void doStop() { if (future != null) { future.channel().close().syncUninterruptibly(); future = null; } if (group != null) { Future<?> groupFuture = group.shutdownGracefully(0, 0, TimeUnit.SECONDS); try { groupFuture.get(); } catch (Exception e) { throw new IllegalStateException(e); } group = null; } } }