Search in sources :

Example 76 with Future

use of org.apache.flink.shaded.netty4.io.netty.util.concurrent.Future in project californium by eclipse.

the class TcpClientConnector method send.

@Override
public void send(final RawData msg) {
    if (msg == null) {
        throw new NullPointerException("Message must not be null");
    }
    if (msg.isMulticast()) {
        LOGGER.warn("TcpConnector drops {} bytes to multicast {}", msg.getSize(), StringUtil.toLog(msg.getInetSocketAddress()));
        msg.onError(new MulticastNotSupportedException("TCP doesn't support multicast!"));
        return;
    }
    if (workerGroup == null) {
        msg.onError(new IllegalStateException("TCP client connector not running!"));
        return;
    }
    InetSocketAddress addressKey = msg.getInetSocketAddress();
    final boolean connected = poolMap.contains(addressKey);
    final EndpointContextMatcher endpointMatcher = getEndpointContextMatcher();
    /* check, if a new connection should be established */
    if (endpointMatcher != null && !connected && !endpointMatcher.isToBeSent(msg.getEndpointContext(), null)) {
        LOGGER.warn("TcpConnector drops {} bytes to new {}", msg.getSize(), StringUtil.toLog(msg.getInetSocketAddress()));
        msg.onError(new EndpointMismatchException("no connection"));
        return;
    }
    if (!connected) {
        msg.onConnecting();
    }
    final ChannelPool channelPool = poolMap.get(addressKey);
    Future<Channel> acquire = channelPool.acquire();
    acquire.addListener(new GenericFutureListener<Future<Channel>>() {

        @Override
        public void operationComplete(Future<Channel> future) throws Exception {
            Throwable cause = null;
            if (future.isSuccess()) {
                Channel channel = future.getNow();
                try {
                    send(channel, endpointMatcher, msg);
                } catch (Throwable t) {
                    cause = t;
                } finally {
                    try {
                        channelPool.release(channel);
                    } catch (RejectedExecutionException e) {
                        LOGGER.debug("{}", e.getMessage());
                    }
                }
            } else if (future.isCancelled()) {
                cause = new CancellationException();
            } else {
                cause = future.cause();
            }
            if (cause != null) {
                if (cause instanceof ConnectTimeoutException) {
                    LOGGER.debug("{}", cause.getMessage());
                } else if (cause instanceof CancellationException) {
                    if (isRunning()) {
                        LOGGER.debug("{}", cause.getMessage());
                    } else {
                        LOGGER.trace("{}", cause.getMessage());
                    }
                } else if (cause instanceof IllegalStateException) {
                    if (isRunning()) {
                        LOGGER.debug("{}", cause.getMessage());
                    } else {
                        LOGGER.trace("{}", cause.getMessage());
                    }
                } else {
                    LOGGER.warn("Unable to open connection to {}", StringUtil.toLog(msg.getInetSocketAddress()), future.cause());
                }
                msg.onError(future.cause());
            }
        }
    });
}
Also used : FixedChannelPool(io.netty.channel.pool.FixedChannelPool) ChannelPool(io.netty.channel.pool.ChannelPool) EndpointMismatchException(org.eclipse.californium.elements.exception.EndpointMismatchException) InetSocketAddress(java.net.InetSocketAddress) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) RawDataChannel(org.eclipse.californium.elements.RawDataChannel) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) CancellationException(java.util.concurrent.CancellationException) EndpointMismatchException(org.eclipse.californium.elements.exception.EndpointMismatchException) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException) MulticastNotSupportedException(org.eclipse.californium.elements.exception.MulticastNotSupportedException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) MulticastNotSupportedException(org.eclipse.californium.elements.exception.MulticastNotSupportedException) EndpointContextMatcher(org.eclipse.californium.elements.EndpointContextMatcher) CancellationException(java.util.concurrent.CancellationException) Future(io.netty.util.concurrent.Future)

Example 77 with Future

use of org.apache.flink.shaded.netty4.io.netty.util.concurrent.Future in project flink-kubernetes-operator by apache.

the class AdmissionHandler method sendResponse.

public static void sendResponse(@Nonnull ChannelHandlerContext channelHandlerContext, @Nonnull String json) {
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK);
    response.headers().set(CONTENT_TYPE, APPLICATION_JSON);
    byte[] buf = json.getBytes(Charset.defaultCharset());
    ByteBuf b = Unpooled.copiedBuffer(buf);
    HttpUtil.setContentLength(response, buf.length);
    // write the initial line and the header.
    channelHandlerContext.write(response);
    channelHandlerContext.write(b);
    ChannelFuture channelFuture = channelHandlerContext.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    final CompletableFuture<Void> completableFuture = new CompletableFuture<>();
    channelFuture.addListener(future -> {
        if (future.isSuccess()) {
            completableFuture.complete(null);
        } else {
            completableFuture.completeExceptionally(future.cause());
        }
    });
}
Also used : ChannelFuture(org.apache.flink.shaded.netty4.io.netty.channel.ChannelFuture) CompletableFuture(java.util.concurrent.CompletableFuture) DefaultHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse) DefaultHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponse) DefaultFullHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultFullHttpResponse) ByteBuf(org.apache.flink.shaded.netty4.io.netty.buffer.ByteBuf)

Example 78 with Future

use of org.apache.flink.shaded.netty4.io.netty.util.concurrent.Future in project netconf by opendaylight.

the class NetconfDeviceCommunicatorTest method testNetconfDeviceReconnectInCommunicator.

/**
 * Test whether reconnect is scheduled properly.
 */
@Test
public void testNetconfDeviceReconnectInCommunicator() {
    final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> device = mock(RemoteDevice.class);
    final TimedReconnectStrategy timedReconnectStrategy = new TimedReconnectStrategy(GlobalEventExecutor.INSTANCE, 10000, 0, 1.0, null, 100L, null);
    final ReconnectStrategy reconnectStrategy = spy(new ReconnectStrategy() {

        @Override
        @Deprecated
        public int getConnectTimeout() throws Exception {
            return timedReconnectStrategy.getConnectTimeout();
        }

        @Override
        @Deprecated
        public Future<Void> scheduleReconnect(final Throwable cause) {
            return timedReconnectStrategy.scheduleReconnect(cause);
        }

        @Override
        @Deprecated
        public void reconnectSuccessful() {
            timedReconnectStrategy.reconnectSuccessful();
        }
    });
    final EventLoopGroup group = new NioEventLoopGroup();
    final Timer time = new HashedWheelTimer();
    try {
        final NetconfDeviceCommunicator listener = new NetconfDeviceCommunicator(new RemoteDeviceId("test", InetSocketAddress.createUnresolved("localhost", 22)), device, 10);
        final NetconfReconnectingClientConfiguration cfg = NetconfReconnectingClientConfigurationBuilder.create().withAddress(new InetSocketAddress("localhost", 65000)).withReconnectStrategy(reconnectStrategy).withConnectStrategyFactory(() -> reconnectStrategy).withAuthHandler(new LoginPasswordHandler("admin", "admin")).withConnectionTimeoutMillis(10000).withProtocol(NetconfClientConfiguration.NetconfClientProtocol.SSH).withSessionListener(listener).build();
        listener.initializeRemoteConnection(new NetconfClientDispatcherImpl(group, group, time), cfg);
        verify(reconnectStrategy, timeout(TimeUnit.MINUTES.toMillis(4)).times(101)).scheduleReconnect(any(Throwable.class));
    } finally {
        time.stop();
        group.shutdownGracefully();
    }
}
Also used : TimedReconnectStrategy(org.opendaylight.netconf.nettyutil.TimedReconnectStrategy) ReconnectStrategy(org.opendaylight.netconf.nettyutil.ReconnectStrategy) InetSocketAddress(java.net.InetSocketAddress) HashedWheelTimer(io.netty.util.HashedWheelTimer) NetconfClientDispatcherImpl(org.opendaylight.netconf.client.NetconfClientDispatcherImpl) TimeoutException(java.util.concurrent.TimeoutException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) RemoteDeviceId(org.opendaylight.netconf.sal.connect.util.RemoteDeviceId) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) LoginPasswordHandler(org.opendaylight.netconf.nettyutil.handler.ssh.authentication.LoginPasswordHandler) HashedWheelTimer(io.netty.util.HashedWheelTimer) Timer(io.netty.util.Timer) NetconfMessage(org.opendaylight.netconf.api.NetconfMessage) TimedReconnectStrategy(org.opendaylight.netconf.nettyutil.TimedReconnectStrategy) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) ChannelFuture(io.netty.channel.ChannelFuture) Future(io.netty.util.concurrent.Future) NetconfReconnectingClientConfiguration(org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfiguration) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Test(org.junit.Test)

Example 79 with Future

use of org.apache.flink.shaded.netty4.io.netty.util.concurrent.Future 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 80 with Future

use of org.apache.flink.shaded.netty4.io.netty.util.concurrent.Future 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

Future (io.netty.util.concurrent.Future)177 Channel (io.netty.channel.Channel)61 ChannelFuture (io.netty.channel.ChannelFuture)58 InetSocketAddress (java.net.InetSocketAddress)45 ArrayList (java.util.ArrayList)45 IOException (java.io.IOException)44 GenericFutureListener (io.netty.util.concurrent.GenericFutureListener)42 CompletableFuture (java.util.concurrent.CompletableFuture)40 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)35 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)34 List (java.util.List)34 ChannelFutureListener (io.netty.channel.ChannelFutureListener)31 EventLoopGroup (io.netty.channel.EventLoopGroup)30 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)30 FutureListener (io.netty.util.concurrent.FutureListener)28 Logger (org.slf4j.Logger)28 LoggerFactory (org.slf4j.LoggerFactory)28 TimeUnit (java.util.concurrent.TimeUnit)27 Bootstrap (io.netty.bootstrap.Bootstrap)25 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)25