Search in sources :

Example 46 with GenericFutureListener

use of io.netty.util.concurrent.GenericFutureListener in project vert.x by eclipse.

the class HttpServerWorker method handle.

@Override
public void handle(Channel ch) {
    if (HAProxyMessageCompletionHandler.canUseProxyProtocol(options.isUseProxyProtocol())) {
        IdleStateHandler idle;
        io.netty.util.concurrent.Promise<Channel> p = ch.eventLoop().newPromise();
        ch.pipeline().addLast(new HAProxyMessageDecoder());
        if (options.getProxyProtocolTimeout() > 0) {
            ch.pipeline().addLast("idle", idle = new IdleStateHandler(0, 0, options.getProxyProtocolTimeout(), options.getProxyProtocolTimeoutUnit()));
        } else {
            idle = null;
        }
        ch.pipeline().addLast(new HAProxyMessageCompletionHandler(p));
        p.addListener((GenericFutureListener<Future<Channel>>) future -> {
            if (future.isSuccess()) {
                if (idle != null) {
                    ch.pipeline().remove(idle);
                }
                configurePipeline(future.getNow());
            } else {
                handleException(future.cause());
            }
        });
    } else {
        configurePipeline(ch);
    }
}
Also used : HttpContentCompressor(io.netty.handler.codec.http.HttpContentCompressor) HAProxyMessageCompletionHandler(io.vertx.core.net.impl.HAProxyMessageCompletionHandler) SniHandler(io.netty.handler.ssl.SniHandler) LoggingHandler(io.netty.handler.logging.LoggingHandler) FlashPolicyHandler(io.vertx.core.http.impl.cgbystrom.FlashPolicyHandler) ContextInternal(io.vertx.core.impl.ContextInternal) SslHandshakeCompletionHandler(io.vertx.core.net.impl.SslHandshakeCompletionHandler) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Unpooled(io.netty.buffer.Unpooled) ArrayList(java.util.ArrayList) StandardCompressionOptions(io.netty.handler.codec.compression.StandardCompressionOptions) CompressionOptions(io.netty.handler.codec.compression.CompressionOptions) HttpServerMetrics(io.vertx.core.spi.metrics.HttpServerMetrics) IdleState(io.netty.handler.timeout.IdleState) io.netty.channel(io.netty.channel) VertxHandler(io.vertx.core.net.impl.VertxHandler) IdleStateEvent(io.netty.handler.timeout.IdleStateEvent) VertxInternal(io.vertx.core.impl.VertxInternal) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) SSLHelper(io.vertx.core.net.impl.SSLHelper) StandardCharsets(java.nio.charset.StandardCharsets) HAProxyMessageDecoder(io.netty.handler.codec.haproxy.HAProxyMessageDecoder) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) EventLoopContext(io.vertx.core.impl.EventLoopContext) List(java.util.List) SslHandler(io.netty.handler.ssl.SslHandler) HttpServerOptions(io.vertx.core.http.HttpServerOptions) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) Future(io.netty.util.concurrent.Future) Handler(io.vertx.core.Handler) HAProxyMessageCompletionHandler(io.vertx.core.net.impl.HAProxyMessageCompletionHandler) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) HAProxyMessageDecoder(io.netty.handler.codec.haproxy.HAProxyMessageDecoder) Future(io.netty.util.concurrent.Future)

Example 47 with GenericFutureListener

use of io.netty.util.concurrent.GenericFutureListener in project vert.x by eclipse.

the class NetClientImpl method connectInternal.

public void connectInternal(ProxyOptions proxyOptions, SocketAddress remoteAddress, SocketAddress peerAddress, String serverName, boolean ssl, boolean useAlpn, boolean registerWriteHandlers, Promise<NetSocket> connectHandler, ContextInternal context, int remainingAttempts) {
    checkClosed();
    EventLoop eventLoop = context.nettyEventLoop();
    if (eventLoop.inEventLoop()) {
        Objects.requireNonNull(connectHandler, "No null connectHandler accepted");
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventLoop);
        bootstrap.option(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
        vertx.transport().configure(options, remoteAddress.isDomainSocket(), bootstrap);
        ChannelProvider channelProvider = new ChannelProvider(bootstrap, sslHelper, context).proxyOptions(proxyOptions);
        channelProvider.handler(ch -> connected(context, ch, connectHandler, remoteAddress, channelProvider.applicationProtocol(), registerWriteHandlers));
        io.netty.util.concurrent.Future<Channel> fut = channelProvider.connect(remoteAddress, peerAddress, serverName, ssl, useAlpn);
        fut.addListener((GenericFutureListener<io.netty.util.concurrent.Future<Channel>>) future -> {
            if (!future.isSuccess()) {
                Throwable cause = future.cause();
                boolean connectError = cause instanceof ConnectException || cause instanceof FileNotFoundException;
                if (connectError && (remainingAttempts > 0 || remainingAttempts == -1)) {
                    context.emit(v -> {
                        log.debug("Failed to create connection. Will retry in " + options.getReconnectInterval() + " milliseconds");
                        vertx.setTimer(options.getReconnectInterval(), tid -> connectInternal(proxyOptions, remoteAddress, peerAddress, serverName, ssl, useAlpn, registerWriteHandlers, connectHandler, context, remainingAttempts == -1 ? remainingAttempts : remainingAttempts - 1));
                    });
                } else {
                    failed(context, null, cause, connectHandler);
                }
            }
        });
    } else {
        eventLoop.execute(() -> connectInternal(proxyOptions, remoteAddress, peerAddress, serverName, ssl, useAlpn, registerWriteHandlers, connectHandler, context, remainingAttempts));
    }
}
Also used : ChannelOption(io.netty.channel.ChannelOption) LoggingHandler(io.netty.handler.logging.LoggingHandler) LoggerFactory(io.vertx.core.impl.logging.LoggerFactory) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) ContextInternal(io.vertx.core.impl.ContextInternal) TCPMetrics(io.vertx.core.spi.metrics.TCPMetrics) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) ConnectException(java.net.ConnectException) AsyncResult(io.vertx.core.AsyncResult) NetClient(io.vertx.core.net.NetClient) Metrics(io.vertx.core.spi.metrics.Metrics) SocketAddress(io.vertx.core.net.SocketAddress) Logger(io.vertx.core.impl.logging.Logger) Closeable(io.vertx.core.Closeable) ProxyOptions(io.vertx.core.net.ProxyOptions) ChannelGroup(io.netty.channel.group.ChannelGroup) PromiseInternal(io.vertx.core.impl.future.PromiseInternal) VertxInternal(io.vertx.core.impl.VertxInternal) Predicate(java.util.function.Predicate) Promise(io.vertx.core.Promise) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) MetricsProvider(io.vertx.core.spi.metrics.MetricsProvider) ChannelPipeline(io.netty.channel.ChannelPipeline) EventLoop(io.netty.channel.EventLoop) PartialPooledByteBufAllocator(io.vertx.core.buffer.impl.PartialPooledByteBufAllocator) Future(io.vertx.core.Future) FileNotFoundException(java.io.FileNotFoundException) NetClientOptions(io.vertx.core.net.NetClientOptions) Channel(io.netty.channel.Channel) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) Bootstrap(io.netty.bootstrap.Bootstrap) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) CloseFuture(io.vertx.core.impl.CloseFuture) ChannelGroupFuture(io.netty.channel.group.ChannelGroupFuture) Handler(io.vertx.core.Handler) NetSocket(io.vertx.core.net.NetSocket) Channel(io.netty.channel.Channel) FileNotFoundException(java.io.FileNotFoundException) EventLoop(io.netty.channel.EventLoop) Bootstrap(io.netty.bootstrap.Bootstrap) Future(io.vertx.core.Future) CloseFuture(io.vertx.core.impl.CloseFuture) ChannelGroupFuture(io.netty.channel.group.ChannelGroupFuture) ConnectException(java.net.ConnectException)

Example 48 with GenericFutureListener

use of io.netty.util.concurrent.GenericFutureListener in project vert.x by eclipse.

the class DatagramSocketImpl method send.

@Override
public Future<Void> send(Buffer packet, int port, String host) {
    Objects.requireNonNull(packet, "no null packet accepted");
    Objects.requireNonNull(host, "no null host accepted");
    if (port < 0 || port > 65535) {
        throw new IllegalArgumentException("port out of range:" + port);
    }
    AddressResolver resolver = context.owner().addressResolver();
    PromiseInternal<Void> promise = context.promise();
    io.netty.util.concurrent.Future<InetSocketAddress> f1 = resolver.resolveHostname(context.nettyEventLoop(), host);
    f1.addListener((GenericFutureListener<io.netty.util.concurrent.Future<InetSocketAddress>>) res1 -> {
        if (res1.isSuccess()) {
            ChannelFuture f2 = channel.writeAndFlush(new DatagramPacket(packet.getByteBuf(), new InetSocketAddress(f1.getNow().getAddress(), port)));
            if (metrics != null) {
                f2.addListener(fut -> {
                    if (fut.isSuccess()) {
                        metrics.bytesWritten(null, SocketAddress.inetSocketAddress(port, host), packet.length());
                    }
                });
            }
            f2.addListener(promise);
        } else {
            promise.fail(res1.cause());
        }
    });
    return promise.future();
}
Also used : ChannelOption(io.netty.channel.ChannelOption) LoggingHandler(io.netty.handler.logging.LoggingHandler) DatagramSocket(io.vertx.core.datagram.DatagramSocket) Arguments(io.vertx.core.impl.Arguments) ContextInternal(io.vertx.core.impl.ContextInternal) ConnectionBase(io.vertx.core.net.impl.ConnectionBase) InetAddress(java.net.InetAddress) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) DatagramChannel(io.netty.channel.socket.DatagramChannel) ByteBuf(io.netty.buffer.ByteBuf) WriteStream(io.vertx.core.streams.WriteStream) DatagramPacket(io.netty.channel.socket.DatagramPacket) InternetProtocolFamily(io.netty.channel.socket.InternetProtocolFamily) AsyncResult(io.vertx.core.AsyncResult) DatagramSocketOptions(io.vertx.core.datagram.DatagramSocketOptions) MaxMessagesRecvByteBufAllocator(io.netty.channel.MaxMessagesRecvByteBufAllocator) SocketAddress(io.vertx.core.net.SocketAddress) VertxHandler(io.vertx.core.net.impl.VertxHandler) Closeable(io.vertx.core.Closeable) PromiseInternal(io.vertx.core.impl.future.PromiseInternal) VertxInternal(io.vertx.core.impl.VertxInternal) Transport(io.vertx.core.net.impl.transport.Transport) Promise(io.vertx.core.Promise) AddressResolver(io.vertx.core.impl.AddressResolver) NetworkInterface(java.net.NetworkInterface) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) Future(io.vertx.core.Future) InetSocketAddress(java.net.InetSocketAddress) UnknownHostException(java.net.UnknownHostException) ChannelFuture(io.netty.channel.ChannelFuture) Nullable(io.vertx.codegen.annotations.Nullable) Objects(java.util.Objects) Buffer(io.vertx.core.buffer.Buffer) CloseFuture(io.vertx.core.impl.CloseFuture) io.vertx.core.spi.metrics(io.vertx.core.spi.metrics) Handler(io.vertx.core.Handler) ChannelFuture(io.netty.channel.ChannelFuture) AddressResolver(io.vertx.core.impl.AddressResolver) InetSocketAddress(java.net.InetSocketAddress) DatagramPacket(io.netty.channel.socket.DatagramPacket) Future(io.vertx.core.Future) ChannelFuture(io.netty.channel.ChannelFuture) CloseFuture(io.vertx.core.impl.CloseFuture)

Example 49 with GenericFutureListener

use of io.netty.util.concurrent.GenericFutureListener in project vert.x by eclipse.

the class VertxImpl method deleteCacheDirAndShutdown.

@SuppressWarnings("unchecked")
private void deleteCacheDirAndShutdown(Handler<AsyncResult<Void>> completionHandler) {
    executeBlockingInternal(fut -> {
        try {
            fileResolver.close();
            fut.complete();
        } catch (IOException e) {
            fut.tryFail(e);
        }
    }, ar -> {
        workerPool.close();
        internalWorkerPool.close();
        new ArrayList<>(namedWorkerPools.values()).forEach(WorkerPool::close);
        acceptorEventLoopGroup.shutdownGracefully(0, 10, TimeUnit.SECONDS).addListener(new GenericFutureListener() {

            @Override
            public void operationComplete(io.netty.util.concurrent.Future future) throws Exception {
                if (!future.isSuccess()) {
                    log.warn("Failure in shutting down acceptor event loop group", future.cause());
                }
                eventLoopGroup.shutdownGracefully(0, 10, TimeUnit.SECONDS).addListener(new GenericFutureListener() {

                    @Override
                    public void operationComplete(io.netty.util.concurrent.Future future) throws Exception {
                        if (!future.isSuccess()) {
                            log.warn("Failure in shutting down event loop group", future.cause());
                        }
                        if (metrics != null) {
                            metrics.close();
                        }
                        if (tracer != null) {
                            tracer.close();
                        }
                        checker.close();
                        if (completionHandler != null) {
                            eventLoopThreadFactory.newThread(() -> {
                                completionHandler.handle(Future.succeededFuture());
                            }).start();
                        }
                    }
                });
            }
        });
    });
}
Also used : java.util.concurrent(java.util.concurrent) Future(io.vertx.core.Future) IOException(java.io.IOException) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) IOException(java.io.IOException)

Example 50 with GenericFutureListener

use of io.netty.util.concurrent.GenericFutureListener in project netty by netty.

the class FixedChannelPoolTest method testCloseAsync.

@Test
public void testCloseAsync() throws ExecutionException, InterruptedException {
    LocalAddress addr = new LocalAddress(getLocalAddrId());
    Bootstrap cb = new Bootstrap();
    cb.remoteAddress(addr);
    cb.group(group).channel(LocalChannel.class);
    ServerBootstrap sb = new ServerBootstrap();
    sb.group(group).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<LocalChannel>() {

        @Override
        public void initChannel(LocalChannel ch) throws Exception {
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter());
        }
    });
    // Start server
    final Channel sc = sb.bind(addr).syncUninterruptibly().channel();
    final FixedChannelPool pool = new FixedChannelPool(cb, new TestChannelPoolHandler(), 2);
    pool.acquire().get();
    pool.acquire().get();
    final ChannelPromise closePromise = sc.newPromise();
    pool.closeAsync().addListener(new GenericFutureListener<Future<? super Void>>() {

        @Override
        public void operationComplete(Future<? super Void> future) throws Exception {
            assertEquals(0, pool.acquiredChannelCount());
            sc.close(closePromise).syncUninterruptibly();
        }
    }).awaitUninterruptibly();
    closePromise.awaitUninterruptibly();
}
Also used : LocalAddress(io.netty.channel.local.LocalAddress) LocalChannel(io.netty.channel.local.LocalChannel) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) Channel(io.netty.channel.Channel) ChannelPromise(io.netty.channel.ChannelPromise) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) TimeoutException(java.util.concurrent.TimeoutException) ExecutionException(java.util.concurrent.ExecutionException) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Future(io.netty.util.concurrent.Future) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

Aggregations

GenericFutureListener (io.netty.util.concurrent.GenericFutureListener)70 Future (io.netty.util.concurrent.Future)44 ChannelFuture (io.netty.channel.ChannelFuture)32 Channel (io.netty.channel.Channel)19 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)18 IOException (java.io.IOException)18 List (java.util.List)15 InetSocketAddress (java.net.InetSocketAddress)13 ArrayList (java.util.ArrayList)13 Map (java.util.Map)12 ChannelOption (io.netty.channel.ChannelOption)10 Future (io.vertx.core.Future)10 Handler (io.vertx.core.Handler)10 ContextInternal (io.vertx.core.impl.ContextInternal)10 VertxInternal (io.vertx.core.impl.VertxInternal)10 Logger (org.slf4j.Logger)10 LoggerFactory (org.slf4j.LoggerFactory)9 Bootstrap (io.netty.bootstrap.Bootstrap)8 LoggingHandler (io.netty.handler.logging.LoggingHandler)8 AsyncResult (io.vertx.core.AsyncResult)8