Search in sources :

Example 11 with GenericFutureListener

use of org.apache.flink.shaded.netty4.io.netty.util.concurrent.GenericFutureListener in project ambry by linkedin.

the class Http2NetworkClient method warmUpConnections.

@Override
public int warmUpConnections(List<DataNodeId> dataNodeIds, int connectionWarmUpPercentagePerDataNode, long timeForWarmUp, List<ResponseInfo> responseInfoList) {
    long startTime = System.currentTimeMillis();
    AtomicInteger successCount = new AtomicInteger();
    AtomicInteger failCount = new AtomicInteger();
    int warmUpConnectionPerPort = http2ClientConfig.http2MinConnectionPerPort * connectionWarmUpPercentagePerDataNode / 100;
    int expectedConnections = dataNodeIds.size() * warmUpConnectionPerPort;
    for (DataNodeId dataNodeId : dataNodeIds) {
        for (int i = 0; i < warmUpConnectionPerPort; i++) {
            this.pools.get(InetSocketAddress.createUnresolved(dataNodeId.getHostname(), dataNodeId.getHttp2Port())).acquire().addListener((GenericFutureListener<Future<Channel>>) future -> {
                if (future.isSuccess()) {
                    Channel streamChannel = future.getNow();
                    releaseAndCloseStreamChannel(streamChannel);
                    successCount.incrementAndGet();
                } else {
                    failCount.incrementAndGet();
                    responseInfoList.add(new ResponseInfo(null, NetworkClientErrorCode.NetworkError, null, dataNodeId));
                    logger.error("Couldn't acquire stream channel to {}:{} . Cause: {}.", dataNodeId.getHostname(), dataNodeId.getHttp2Port(), future.cause());
                }
            });
        }
    }
    while (System.currentTimeMillis() - startTime < timeForWarmUp) {
        if (successCount.get() + failCount.get() == expectedConnections) {
            break;
        } else {
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                break;
            }
        }
    }
    logger.info("HTTP2 connection warm up done. Tried: {}, Succeeded: {}, Failed: {}, Time elapsed: {} ms", expectedConnections, successCount, failCount, System.currentTimeMillis() - startTime);
    return successCount.get();
}
Also used : ResponseInfo(com.github.ambry.network.ResponseInfo) AttributeKey(io.netty.util.AttributeKey) Http2ClientConfig(com.github.ambry.config.Http2ClientConfig) DataNodeId(com.github.ambry.clustermap.DataNodeId) LoggerFactory(org.slf4j.LoggerFactory) ArrayList(java.util.ArrayList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) NetworkClientErrorCode(com.github.ambry.network.NetworkClientErrorCode) Http2StreamFrameToHttpObjectCodec(io.netty.handler.codec.http2.Http2StreamFrameToHttpObjectCodec) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Map(java.util.Map) Http2Utils(com.github.ambry.network.http2.Http2Utils) EventLoopGroup(io.netty.channel.EventLoopGroup) Logger(org.slf4j.Logger) SSLFactory(com.github.ambry.commons.SSLFactory) ChannelInitializer(io.netty.channel.ChannelInitializer) NetworkClient(com.github.ambry.network.NetworkClient) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) Set(java.util.Set) InetSocketAddress(java.net.InetSocketAddress) RequestInfo(com.github.ambry.network.RequestInfo) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) List(java.util.List) ChannelPool(io.netty.channel.pool.ChannelPool) ChannelPoolMap(io.netty.channel.pool.ChannelPoolMap) Future(io.netty.util.concurrent.Future) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) ResponseInfo(com.github.ambry.network.ResponseInfo) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Channel(io.netty.channel.Channel) ChannelFuture(io.netty.channel.ChannelFuture) Future(io.netty.util.concurrent.Future) DataNodeId(com.github.ambry.clustermap.DataNodeId)

Example 12 with GenericFutureListener

use of org.apache.flink.shaded.netty4.io.netty.util.concurrent.GenericFutureListener in project flink by apache.

the class TaskManagerLogHandler method respondAsLeader.

/**
	 * Response when running with leading JobManager.
	 */
@Override
protected void respondAsLeader(final ChannelHandlerContext ctx, final Routed routed, final ActorGateway jobManager) {
    if (cache == null) {
        scala.concurrent.Future<Object> portFuture = jobManager.ask(JobManagerMessages.getRequestBlobManagerPort(), timeout);
        scala.concurrent.Future<BlobCache> cacheFuture = portFuture.map(new Mapper<Object, BlobCache>() {

            @Override
            public BlobCache checkedApply(Object result) throws IOException {
                Option<String> hostOption = jobManager.actor().path().address().host();
                String host = hostOption.isDefined() ? hostOption.get() : "localhost";
                int port = (int) result;
                return new BlobCache(new InetSocketAddress(host, port), config);
            }
        }, executor);
        cache = new FlinkFuture<>(cacheFuture);
    }
    final String taskManagerID = routed.pathParams().get(TaskManagersHandler.TASK_MANAGER_ID_KEY);
    final HttpRequest request = routed.request();
    //fetch TaskManager logs if no other process is currently doing it
    if (lastRequestPending.putIfAbsent(taskManagerID, true) == null) {
        try {
            InstanceID instanceID = new InstanceID(StringUtils.hexStringToByte(taskManagerID));
            scala.concurrent.Future<JobManagerMessages.TaskManagerInstance> scalaTaskManagerFuture = jobManager.ask(new JobManagerMessages.RequestTaskManagerInstance(instanceID), timeout).mapTo(ClassTag$.MODULE$.<JobManagerMessages.TaskManagerInstance>apply(JobManagerMessages.TaskManagerInstance.class));
            Future<JobManagerMessages.TaskManagerInstance> taskManagerFuture = new FlinkFuture<>(scalaTaskManagerFuture);
            Future<BlobKey> blobKeyFuture = taskManagerFuture.thenCompose(new ApplyFunction<JobManagerMessages.TaskManagerInstance, Future<BlobKey>>() {

                @Override
                public Future<BlobKey> apply(JobManagerMessages.TaskManagerInstance value) {
                    Instance taskManager = value.instance().get();
                    if (serveLogFile) {
                        return taskManager.getTaskManagerGateway().requestTaskManagerLog(timeTimeout);
                    } else {
                        return taskManager.getTaskManagerGateway().requestTaskManagerStdout(timeTimeout);
                    }
                }
            });
            Future<String> logPathFuture = blobKeyFuture.thenCombine(cache, new BiFunction<BlobKey, BlobCache, Tuple2<BlobKey, BlobCache>>() {

                @Override
                public Tuple2<BlobKey, BlobCache> apply(BlobKey blobKey, BlobCache blobCache) {
                    return Tuple2.of(blobKey, blobCache);
                }
            }).thenComposeAsync(new ApplyFunction<Tuple2<BlobKey, BlobCache>, Future<String>>() {

                @Override
                public Future<String> apply(Tuple2<BlobKey, BlobCache> value) {
                    final BlobKey blobKey = value.f0;
                    final BlobCache blobCache = value.f1;
                    //delete previous log file, if it is different than the current one
                    HashMap<String, BlobKey> lastSubmittedFile = serveLogFile ? lastSubmittedLog : lastSubmittedStdout;
                    if (lastSubmittedFile.containsKey(taskManagerID)) {
                        if (!blobKey.equals(lastSubmittedFile.get(taskManagerID))) {
                            try {
                                blobCache.deleteGlobal(lastSubmittedFile.get(taskManagerID));
                            } catch (IOException e) {
                                return FlinkCompletableFuture.completedExceptionally(new Exception("Could not delete file for " + taskManagerID + '.', e));
                            }
                            lastSubmittedFile.put(taskManagerID, blobKey);
                        }
                    } else {
                        lastSubmittedFile.put(taskManagerID, blobKey);
                    }
                    try {
                        return FlinkCompletableFuture.completed(blobCache.getURL(blobKey).getFile());
                    } catch (IOException e) {
                        return FlinkCompletableFuture.completedExceptionally(new Exception("Could not retrieve blob for " + blobKey + '.', e));
                    }
                }
            }, executor);
            logPathFuture.exceptionally(new ApplyFunction<Throwable, Void>() {

                @Override
                public Void apply(Throwable failure) {
                    display(ctx, request, "Fetching TaskManager log failed.");
                    LOG.error("Fetching TaskManager log failed.", failure);
                    lastRequestPending.remove(taskManagerID);
                    return null;
                }
            });
            logPathFuture.thenAccept(new AcceptFunction<String>() {

                @Override
                public void accept(String filePath) {
                    File file = new File(filePath);
                    final RandomAccessFile raf;
                    try {
                        raf = new RandomAccessFile(file, "r");
                    } catch (FileNotFoundException e) {
                        display(ctx, request, "Displaying TaskManager log failed.");
                        LOG.error("Displaying TaskManager log failed.", e);
                        return;
                    }
                    long fileLength;
                    try {
                        fileLength = raf.length();
                    } catch (IOException ioe) {
                        display(ctx, request, "Displaying TaskManager log failed.");
                        LOG.error("Displaying TaskManager log failed.", ioe);
                        try {
                            raf.close();
                        } catch (IOException e) {
                            LOG.error("Could not close random access file.", e);
                        }
                        return;
                    }
                    final FileChannel fc = raf.getChannel();
                    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
                    response.headers().set(CONTENT_TYPE, "text/plain");
                    if (HttpHeaders.isKeepAlive(request)) {
                        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
                    }
                    HttpHeaders.setContentLength(response, fileLength);
                    // write the initial line and the header.
                    ctx.write(response);
                    // write the content.
                    ChannelFuture lastContentFuture;
                    final GenericFutureListener<io.netty.util.concurrent.Future<? super Void>> completionListener = new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {

                        @Override
                        public void operationComplete(io.netty.util.concurrent.Future<? super Void> future) throws Exception {
                            lastRequestPending.remove(taskManagerID);
                            fc.close();
                            raf.close();
                        }
                    };
                    if (ctx.pipeline().get(SslHandler.class) == null) {
                        ctx.write(new DefaultFileRegion(fc, 0, fileLength), ctx.newProgressivePromise()).addListener(completionListener);
                        lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
                    } else {
                        try {
                            lastContentFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise()).addListener(completionListener);
                        } catch (IOException e) {
                            display(ctx, request, "Displaying TaskManager log failed.");
                            LOG.warn("Could not write http data.", e);
                            return;
                        }
                    // HttpChunkedInput will write the end marker (LastHttpContent) for us.
                    }
                    // close the connection, if no keep-alive is needed
                    if (!HttpHeaders.isKeepAlive(request)) {
                        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
                    }
                }
            });
        } catch (Exception e) {
            display(ctx, request, "Error: " + e.getMessage());
            LOG.error("Fetching TaskManager log failed.", e);
            lastRequestPending.remove(taskManagerID);
        }
    } else {
        display(ctx, request, "loading...");
    }
}
Also used : InstanceID(org.apache.flink.runtime.instance.InstanceID) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) InetSocketAddress(java.net.InetSocketAddress) FileNotFoundException(java.io.FileNotFoundException) FlinkFuture(org.apache.flink.runtime.concurrent.impl.FlinkFuture) BlobKey(org.apache.flink.runtime.blob.BlobKey) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) ChannelFuture(io.netty.channel.ChannelFuture) ChunkedFile(io.netty.handler.stream.ChunkedFile) JobManagerMessages(org.apache.flink.runtime.messages.JobManagerMessages) DefaultFileRegion(io.netty.channel.DefaultFileRegion) RandomAccessFile(java.io.RandomAccessFile) Option(scala.Option) RandomAccessFile(java.io.RandomAccessFile) ChunkedFile(io.netty.handler.stream.ChunkedFile) File(java.io.File) Instance(org.apache.flink.runtime.instance.Instance) BlobCache(org.apache.flink.runtime.blob.BlobCache) HttpChunkedInput(io.netty.handler.codec.http.HttpChunkedInput) HttpRequest(io.netty.handler.codec.http.HttpRequest) FileChannel(java.nio.channels.FileChannel) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) BiFunction(org.apache.flink.runtime.concurrent.BiFunction) Tuple2(org.apache.flink.api.java.tuple.Tuple2) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) FlinkFuture(org.apache.flink.runtime.concurrent.impl.FlinkFuture) Future(org.apache.flink.runtime.concurrent.Future) FlinkCompletableFuture(org.apache.flink.runtime.concurrent.impl.FlinkCompletableFuture) ChannelFuture(io.netty.channel.ChannelFuture)

Example 13 with GenericFutureListener

use of org.apache.flink.shaded.netty4.io.netty.util.concurrent.GenericFutureListener in project MinecraftForge by MinecraftForge.

the class NetworkDispatcher method kickWithMessage.

private void kickWithMessage(String message) {
    FMLLog.log(Level.ERROR, "Network Disconnect: %s", message);
    final TextComponentString TextComponentString = new TextComponentString(message);
    if (side == Side.CLIENT) {
        manager.closeChannel(TextComponentString);
    } else {
        manager.sendPacket(new SPacketDisconnect(TextComponentString), new GenericFutureListener<Future<? super Void>>() {

            @Override
            public void operationComplete(Future<? super Void> result) {
                manager.closeChannel(TextComponentString);
            }
        }, (GenericFutureListener<? extends Future<? super Void>>[]) null);
    }
    manager.channel().config().setAutoRead(false);
}
Also used : Future(io.netty.util.concurrent.Future) SPacketDisconnect(net.minecraft.network.play.server.SPacketDisconnect) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) TextComponentString(net.minecraft.util.text.TextComponentString)

Example 14 with GenericFutureListener

use of org.apache.flink.shaded.netty4.io.netty.util.concurrent.GenericFutureListener in project intellij-community by JetBrains.

the class ChannelRegistrar method close.

private void close(boolean shutdownEventLoopGroup) {
    ServerChannel serverChannel = this.serverChannel.get();
    if (serverChannel == null) {
        LOG.assertTrue(clientChannels.isEmpty());
        return;
    } else if (!this.serverChannel.compareAndSet(serverChannel, null)) {
        return;
    }
    EventLoopGroup eventLoopGroup = shutdownEventLoopGroup ? serverChannel.eventLoop().parent() : null;
    try {
        long start = System.currentTimeMillis();
        Channel[] clientChannels = this.clientChannels.toArray(new Channel[] {});
        this.clientChannels.clear();
        final CountDownLatch countDown = new CountDownLatch(clientChannels.length + 1);
        GenericFutureListener<ChannelFuture> listener = new GenericFutureListener<ChannelFuture>() {

            @Override
            public void operationComplete(@NotNull ChannelFuture future) throws Exception {
                try {
                    Throwable cause = future.cause();
                    if (cause != null) {
                        LOG.warn(cause);
                    }
                } finally {
                    countDown.countDown();
                }
            }
        };
        serverChannel.close().addListener(listener);
        for (Channel channel : clientChannels) {
            channel.close().addListener(listener);
        }
        try {
            countDown.await(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            LOG.warn("Cannot close all channels for 10 seconds, channels: " + Arrays.toString(clientChannels));
        }
        long duration = System.currentTimeMillis() - start;
        if (duration > 1000) {
            LOG.info("Close all channels took " + duration + " ms: " + (duration / 60000) + " min " + ((duration % 60000) / 1000) + "sec");
        }
    } finally {
        if (eventLoopGroup != null) {
            eventLoopGroup.shutdownGracefully(1, 2, TimeUnit.NANOSECONDS);
        }
    }
}
Also used : CountDownLatch(java.util.concurrent.CountDownLatch) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) NotNull(org.jetbrains.annotations.NotNull)

Example 15 with GenericFutureListener

use of org.apache.flink.shaded.netty4.io.netty.util.concurrent.GenericFutureListener in project tesla by linking12.

the class ConnectionFlow method fail.

@SuppressWarnings({ "unchecked", "rawtypes" })
public void fail(final Throwable cause) {
    final ConnectionState lastStateBeforeFailure = serverConnection.getCurrentState();
    serverConnection.disconnect().addListener(new GenericFutureListener() {

        @Override
        public void operationComplete(Future future) throws Exception {
            synchronized (connectLock) {
                if (!clientConnection.serverConnectionFailed(serverConnection, lastStateBeforeFailure, cause)) {
                    serverConnection.become(ConnectionState.DISCONNECTED);
                    notifyThreadsWaitingForConnection();
                }
            }
        }
    });
}
Also used : Future(io.netty.util.concurrent.Future) ConnectionState(io.github.tesla.gateway.netty.transmit.ConnectionState) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener)

Aggregations

GenericFutureListener (io.netty.util.concurrent.GenericFutureListener)26 ChannelFuture (io.netty.channel.ChannelFuture)11 Future (io.netty.util.concurrent.Future)11 Channel (io.netty.channel.Channel)7 InetSocketAddress (java.net.InetSocketAddress)7 Map (java.util.Map)7 Future (io.vertx.core.Future)5 Handler (io.vertx.core.Handler)5 ContextInternal (io.vertx.core.impl.ContextInternal)5 VertxInternal (io.vertx.core.impl.VertxInternal)5 IOException (java.io.IOException)5 Bootstrap (io.netty.bootstrap.Bootstrap)4 ChannelFutureListener (io.netty.channel.ChannelFutureListener)4 ChannelOption (io.netty.channel.ChannelOption)4 AsyncResult (io.vertx.core.AsyncResult)4 PromiseInternal (io.vertx.core.impl.future.PromiseInternal)4 SocketAddress (io.vertx.core.net.SocketAddress)4 List (java.util.List)4 Test (org.junit.Test)4 Logger (org.slf4j.Logger)4