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