nfsantos commented on code in PR #728: URL: https://github.com/apache/jackrabbit-oak/pull/728#discussion_r990976753
########## oak-run/src/main/java/org/apache/jackrabbit/oak/run/Downloader.java: ########## @@ -0,0 +1,263 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.jackrabbit.oak.run; + +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import org.apache.jackrabbit.oak.commons.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.Closeable; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.URL; +import java.net.URLConnection; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +/** + * Generic concurrent file downloader which uses Java NIO channels to potentially leverage OS internal optimizations. + */ +public class Downloader implements Closeable { + + private static final Logger LOG = LoggerFactory.getLogger(Downloader.class); + + private final ExecutorService executorService; + private final int connectTimeoutMs; + private final int readTimeoutMs; + private final int slowLogThreshold; + private final int maxRetries; + private final boolean failOnError; + private final List<Future<ItemResponse>> responses; + + public Downloader(int concurrency, int connectTimeoutMs, int readTimeoutMs) { + this(concurrency, connectTimeoutMs, readTimeoutMs, 3, false, 10_000); + } + + public Downloader(int concurrency, int connectTimeoutMs, int readTimeoutMs, int maxRetries, boolean failOnError, int slowLogThreshold) { + if (concurrency <= 0 || concurrency > 1000) { + throw new IllegalArgumentException("concurrency range must be between 1 and 1000"); + } + if (connectTimeoutMs < 0 || readTimeoutMs < 0) { + throw new IllegalArgumentException("connect and/or read timeouts can not be negative"); + } + if (maxRetries <= 0 || maxRetries > 100) { + throw new IllegalArgumentException("maxRetries range must be between 1 and 100"); + } + LOG.info("Initializing Downloader with max number of concurrent requests={}", concurrency); + this.connectTimeoutMs = connectTimeoutMs; + this.readTimeoutMs = readTimeoutMs; + this.slowLogThreshold = slowLogThreshold; + this.maxRetries = maxRetries; + this.failOnError = failOnError; + this.executorService = new ThreadPoolExecutor( + (int) Math.ceil(concurrency * .1), concurrency, 60L, TimeUnit.SECONDS, + new LinkedBlockingQueue<>(), + new ThreadFactoryBuilder() + .setNameFormat("downloader-%d") + .setDaemon(true) + .build() + ); + this.responses = new ArrayList<>(); + } + + public void offer(Item item) { + responses.add( + this.executorService.submit(new RetryingCallable<>(maxRetries, new DownloaderWorker(item))) + ); + } + + public DownloadReport waitUntilComplete() { + List<ItemResponse> itemResponses = responses.stream() + .map(itemResponseFuture -> { + try { + return itemResponseFuture.get(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("thread waiting for the response was interrupted", e); + } catch (ExecutionException e) { + if (failOnError) { + throw new RuntimeException("execution failed, e"); + } else { + return ItemResponse.FAILURE; + } + } + }).collect(Collectors.toList()); + + return new DownloadReport( + itemResponses.stream().filter(r -> !r.failed).count(), + itemResponses.stream().filter(r -> r.failed).count(), + itemResponses.stream().filter(r -> !r.failed).mapToLong(r -> r.size).sum() + ); + } + + @Override + public void close() throws IOException { + executorService.shutdown(); + } + + private class DownloaderWorker implements Callable<ItemResponse> { + + private final Item item; + + public DownloaderWorker(Item item) { + this.item = item; + } + + @Override + public ItemResponse call() throws Exception { + long t0 = System.nanoTime(); + + URLConnection sourceUrl = new URL(item.source).openConnection(); + sourceUrl.setConnectTimeout(Downloader.this.connectTimeoutMs); + sourceUrl.setReadTimeout(Downloader.this.readTimeoutMs); + + Path destinationPath = Paths.get(item.destination); + Files.createDirectories(destinationPath.getParent()); + long size; + try (ReadableByteChannel byteChannel = Channels.newChannel(sourceUrl.getInputStream()); + FileOutputStream outputStream = new FileOutputStream(destinationPath.toFile())) { + size = outputStream.getChannel() + .transferFrom(byteChannel, 0, Long.MAX_VALUE); + } + long elapsed = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - t0); + if (slowLogThreshold > 0 && elapsed >= slowLogThreshold) { + LOG.warn("{} [{}] downloaded in {} ms", item.source, IOUtils.humanReadableByteCount(size), elapsed); + } else { + LOG.debug("{} [{}] downloaded in {} ms", item.source, IOUtils.humanReadableByteCount(size), elapsed); + } + return ItemResponse.success(size); + } + + @Override + public String toString() { + return "DownloaderWorker{" + + "item=" + item + + '}'; + } + } + + private static class RetryingCallable<V> implements Callable<V> { + private final Callable<V> callable; + private final int retries; + + public RetryingCallable(int retries, Callable<V> callable) { + this.retries = retries; + this.callable = callable; + } + + public V call() { + int retried = 0; + // Save exceptions that are thrown after each failure, so they can be printed if all retries fail + List<Throwable> exceptions = new ArrayList<>(); + + // Loop until it doesn't throw an exception or max number of tries is reached + while (true) { + try { + return callable.call(); + } catch (Exception e) { Review Comment: We should have a backoff mechanism. Otherwise we risk doing an excessive number of requests. For instance, if the failure happens immediately after a request is sent (so it is not a timeout, and instead is something like a blob not found, service is down, or throttling limits reached), we will be retrying as fast as the network speed allows it. If all requests are failing and we have a high concurrency level, we can easily end up doing hundreds or even thousands of requests per second, which will likely trigger some throttling mechanism on the side of Azure. I've seen this library being used to implement retries and other fault tolerance mechanisms, maybe it's worth to have a look: https://resilience4j.readme.io/docs Another similar library is Failsafe. There's a nice comparison here: https://blog.frankel.ch/comparison-fault-tolerance-libraries/ -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
