Search in sources :

Example 16 with GenericFutureListener

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

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 : 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) Supplier(java.util.function.Supplier) Unpooled(io.netty.buffer.Unpooled) 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) 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 17 with GenericFutureListener

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

the class DefaultCloseSessionTest method testDefaultCloseSession.

@Test
public void testDefaultCloseSession() throws Exception {
    AutoCloseable res = mock(AutoCloseable.class);
    doNothing().when(res).close();
    DefaultCloseSession close = new DefaultCloseSession("", res);
    final Document doc = XmlUtil.newDocument();
    final XmlElement elem = XmlElement.fromDomElement(XmlUtil.readXmlToElement("<elem/>"));
    final Channel channel = mock(Channel.class);
    doReturn("channel").when(channel).toString();
    mockEventLoop(channel);
    final ChannelFuture channelFuture = mock(ChannelFuture.class);
    doReturn(channelFuture).when(channel).close();
    doReturn(channelFuture).when(channelFuture).addListener(any(GenericFutureListener.class));
    final ChannelPromise sendFuture = mock(ChannelPromise.class);
    doAnswer(invocation -> {
        invocation.<GenericFutureListener>getArgument(0).operationComplete(sendFuture);
        return null;
    }).when(sendFuture).addListener(any(GenericFutureListener.class));
    doReturn(sendFuture).when(channel).newPromise();
    doReturn(sendFuture).when(channel).writeAndFlush(any(), any());
    doReturn(true).when(sendFuture).isSuccess();
    final NetconfServerSessionListener listener = mock(NetconfServerSessionListener.class);
    doNothing().when(listener).onSessionTerminated(any(NetconfServerSession.class), any(NetconfTerminationReason.class));
    final NetconfServerSession session = new NetconfServerSession(listener, channel, 1L, NetconfHelloMessageAdditionalHeader.fromString("[netconf;10.12.0.102:48528;ssh;;;;;;]"));
    close.setNetconfSession(session);
    close.handleWithNoSubsequentOperations(doc, elem);
    // Fake close response to trigger delayed close
    session.sendMessage(new NetconfMessage(XmlUtil.readXmlToDocument("<rpc-reply message-id=\"101\"\n" + "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" + "<ok/>\n" + "</rpc-reply>")));
    verify(channel).close();
    verify(listener).onSessionTerminated(any(NetconfServerSession.class), any(NetconfTerminationReason.class));
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NetconfTerminationReason(org.opendaylight.netconf.api.NetconfTerminationReason) NetconfServerSessionListener(org.opendaylight.netconf.impl.NetconfServerSessionListener) NetconfMessage(org.opendaylight.netconf.api.NetconfMessage) Channel(io.netty.channel.Channel) NetconfServerSession(org.opendaylight.netconf.impl.NetconfServerSession) XmlElement(org.opendaylight.netconf.api.xml.XmlElement) ChannelPromise(io.netty.channel.ChannelPromise) Document(org.w3c.dom.Document) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) Test(org.junit.Test)

Example 18 with GenericFutureListener

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

the class NetconfDeviceCommunicatorTest method testSendRequest.

@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testSendRequest() throws Exception {
    setupSession();
    NetconfMessage message = new NetconfMessage(UntrustedXML.newDocumentBuilder().newDocument());
    QName rpc = QName.create("", "mockRpc");
    ArgumentCaptor<GenericFutureListener> futureListener = ArgumentCaptor.forClass(GenericFutureListener.class);
    ChannelFuture mockChannelFuture = mock(ChannelFuture.class);
    doReturn(mockChannelFuture).when(mockChannelFuture).addListener(futureListener.capture());
    doReturn(mockChannelFuture).when(mockSession).sendMessage(same(message));
    ListenableFuture<RpcResult<NetconfMessage>> resultFuture = communicator.sendRequest(message, rpc);
    verify(mockSession).sendMessage(same(message));
    assertNotNull("ListenableFuture is null", resultFuture);
    verify(mockChannelFuture).addListener(futureListener.capture());
    Future<Void> operationFuture = mock(Future.class);
    doReturn(true).when(operationFuture).isSuccess();
    futureListener.getValue().operationComplete(operationFuture);
    try {
        // verify it's not cancelled or has an error set
        resultFuture.get(1, TimeUnit.MILLISECONDS);
    } catch (TimeoutException e) {
        LOG.info("Operation failed due timeout.");
    }
// expected
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NetconfMessage(org.opendaylight.netconf.api.NetconfMessage) QName(org.opendaylight.yangtools.yang.common.QName) RpcResult(org.opendaylight.yangtools.yang.common.RpcResult) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.Test)

Example 19 with GenericFutureListener

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

the class AbstractSocksServerConnectHandler method handleConnectRequest.

/**
 * Handles the CONNECT socks request.
 *
 * @param ctx the context object for the channel
 * @param destAddress the destination address
 * @param destPort the destination port that the remote {@code localhost} is listening to
 * @param responseFunc a {@link Function} for creating a {@link SocksMessage} to send back to client
 *                     once the relay channel has been established
 */
private void handleConnectRequest(ChannelHandlerContext ctx, String destAddress, int destPort, Function<InetSocketAddress, SocksMessage> responseFunc, Supplier<SocksMessage> failureResponseSupplier) {
    // Create a forwarding channel handler, which returns a Future.
    // When that handler future completed successfully, responds with a Socks success response.
    // After the success response completed successfully, add the relay handler to the pipeline.
    Channel inboundChannel = ctx.channel();
    createForwardingChannelHandler(inboundChannel, destAddress, destPort).addListener((GenericFutureListener<Future<RelayChannelHandler>>) handlerFuture -> {
        if (handlerFuture.isSuccess()) {
            RelayChannelHandler handler = handlerFuture.get();
            SocketAddress relayAddress = handler.getRelayAddress();
            if (!(relayAddress instanceof InetSocketAddress)) {
                LOG.warn("Relay address is not InetSocketAddress: {} {}", relayAddress.getClass(), relayAddress);
                inboundChannel.writeAndFlush(failureResponseSupplier.get()).addListener(channelFuture -> Channels.closeOnFlush(inboundChannel));
            } else {
                inboundChannel.writeAndFlush(responseFunc.apply((InetSocketAddress) relayAddress)).addListener(channelFuture -> {
                    if (channelFuture.isSuccess()) {
                        ctx.pipeline().remove(AbstractSocksServerConnectHandler.this);
                        ctx.pipeline().addLast(handler);
                    } else {
                        Channels.closeOnFlush(inboundChannel);
                    }
                });
            }
        } else {
            Channels.closeOnFlush(inboundChannel);
        }
    });
}
Also used : SocketAddress(java.net.SocketAddress) Socks4CommandType(io.netty.handler.codec.socksx.v4.Socks4CommandType) LoggerFactory(org.slf4j.LoggerFactory) Loggers(io.cdap.cdap.common.logging.Loggers) Channels(io.cdap.cdap.common.http.Channels) Socks5CommandType(io.netty.handler.codec.socksx.v5.Socks5CommandType) DefaultSocks5CommandResponse(io.netty.handler.codec.socksx.v5.DefaultSocks5CommandResponse) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Socks5CommandRequest(io.netty.handler.codec.socksx.v5.Socks5CommandRequest) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Socks5CommandStatus(io.netty.handler.codec.socksx.v5.Socks5CommandStatus) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Socks4CommandRequest(io.netty.handler.codec.socksx.v4.Socks4CommandRequest) Logger(org.slf4j.Logger) Socks5AddressType(io.netty.handler.codec.socksx.v5.Socks5AddressType) Socks4CommandStatus(io.netty.handler.codec.socksx.v4.Socks4CommandStatus) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) ChannelPipeline(io.netty.channel.ChannelPipeline) Inet4Address(java.net.Inet4Address) InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) TimeUnit(java.util.concurrent.TimeUnit) DefaultSocks4CommandResponse(io.netty.handler.codec.socksx.v4.DefaultSocks4CommandResponse) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) LogSamplers(io.cdap.cdap.common.logging.LogSamplers) ChannelHandler(io.netty.channel.ChannelHandler) SocksMessage(io.netty.handler.codec.socksx.SocksMessage) Future(io.netty.util.concurrent.Future) InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) Future(io.netty.util.concurrent.Future) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress)

Example 20 with GenericFutureListener

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

the class ServiceSocksServerConnectHandler method createForwardingChannelHandler.

@Override
protected Future<RelayChannelHandler> createForwardingChannelHandler(Channel inboundChannel, String destAddress, int destPort) {
    Promise<RelayChannelHandler> promise = new DefaultPromise<>(inboundChannel.eventLoop());
    // Creates a bootstrap for connecting to the target service
    ChannelGroup channels = new DefaultChannelGroup(inboundChannel.eventLoop());
    Bootstrap bootstrap = new Bootstrap().group(inboundChannel.eventLoop()).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true).handler(new ChannelInboundHandlerAdapter() {

        @Override
        public void channelActive(ChannelHandlerContext ctx) {
            channels.add(ctx.channel());
            // When the outbound connection is active, adds the relay channel handler for the current pipeline,
            // which is for relaying traffic coming back from outbound connection.
            // Also complete the relay channel handler future, which is for relaying traffic from inbound to outbound.
            ctx.pipeline().addLast(new SimpleRelayChannelHandler(inboundChannel));
            promise.setSuccess(new SimpleRelayChannelHandler(ctx.channel()));
        }
    });
    // Discover the target address
    Promise<Discoverable> discoverablePromise = new DefaultPromise<>(inboundChannel.eventLoop());
    Cancellable cancellable = discoveryServiceClient.discover(destAddress).watchChanges(serviceDiscovered -> {
        // If it is discovered, make a connection and complete the channel handler future
        Discoverable discoverable = new RandomEndpointStrategy(() -> serviceDiscovered).pick();
        if (discoverable != null) {
            discoverablePromise.setSuccess(discoverable);
        }
    }, inboundChannel.eventLoop());
    // When discovery completed successfully, connect to the destination
    discoverablePromise.addListener((GenericFutureListener<Future<Discoverable>>) discoverableFuture -> {
        cancellable.cancel();
        if (discoverableFuture.isSuccess()) {
            Discoverable discoverable = discoverableFuture.get();
            bootstrap.connect(discoverable.getSocketAddress()).addListener((ChannelFutureListener) channelFuture -> {
                if (!channelFuture.isSuccess()) {
                    promise.setFailure(channelFuture.cause());
                }
            });
        } else {
            promise.setFailure(discoverableFuture.cause());
        }
    });
    // On inbound channel close, close all outbound channels.
    // Also cancel the watch since it is no longer needed.
    // This is to handle case where discovery never return an endpoint before client connection timeout
    inboundChannel.closeFuture().addListener((ChannelFutureListener) future -> {
        cancellable.cancel();
        channels.close();
    });
    return promise;
}
Also used : DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ChannelGroup(io.netty.channel.group.ChannelGroup) RandomEndpointStrategy(io.cdap.cdap.common.discovery.RandomEndpointStrategy) ChannelOption(io.netty.channel.ChannelOption) Promise(io.netty.util.concurrent.Promise) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) Channel(io.netty.channel.Channel) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) DefaultPromise(io.netty.util.concurrent.DefaultPromise) Discoverable(org.apache.twill.discovery.Discoverable) DiscoveryServiceClient(org.apache.twill.discovery.DiscoveryServiceClient) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Cancellable(org.apache.twill.common.Cancellable) Future(io.netty.util.concurrent.Future) Discoverable(org.apache.twill.discovery.Discoverable) Cancellable(org.apache.twill.common.Cancellable) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelFutureListener(io.netty.channel.ChannelFutureListener) DefaultPromise(io.netty.util.concurrent.DefaultPromise) Bootstrap(io.netty.bootstrap.Bootstrap) Future(io.netty.util.concurrent.Future) ChannelGroup(io.netty.channel.group.ChannelGroup) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) RandomEndpointStrategy(io.cdap.cdap.common.discovery.RandomEndpointStrategy)

Aggregations

GenericFutureListener (io.netty.util.concurrent.GenericFutureListener)73 ChannelFuture (io.netty.channel.ChannelFuture)40 Future (io.netty.util.concurrent.Future)39 Channel (io.netty.channel.Channel)27 InetSocketAddress (java.net.InetSocketAddress)22 Logger (org.slf4j.Logger)19 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)18 Bootstrap (io.netty.bootstrap.Bootstrap)17 IOException (java.io.IOException)17 ChannelPipeline (io.netty.channel.ChannelPipeline)15 List (java.util.List)14 ArrayList (java.util.ArrayList)13 SocketAddress (java.net.SocketAddress)12 URI (java.net.URI)12 Map (java.util.Map)12 ChannelHandler (io.netty.channel.ChannelHandler)11 EventLoopGroup (io.netty.channel.EventLoopGroup)11 ChannelOption (io.netty.channel.ChannelOption)10 SocketChannel (io.netty.channel.socket.SocketChannel)10 Future (io.vertx.core.Future)10