kfaraz commented on code in PR #16481: URL: https://github.com/apache/druid/pull/16481#discussion_r1626257336
########## extensions-core/s3-extensions/src/main/java/org/apache/druid/storage/s3/output/S3UploadManager.java: ########## @@ -0,0 +1,154 @@ +/* + * 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.druid.storage.s3.output; + +import com.amazonaws.services.s3.model.UploadPartRequest; +import com.amazonaws.services.s3.model.UploadPartResult; +import com.google.common.annotations.VisibleForTesting; +import com.google.inject.Inject; +import org.apache.druid.guice.ManageLifecycle; +import org.apache.druid.java.util.common.RetryUtils; +import org.apache.druid.java.util.common.concurrent.Execs; +import org.apache.druid.java.util.common.lifecycle.LifecycleStart; +import org.apache.druid.java.util.common.lifecycle.LifecycleStop; +import org.apache.druid.java.util.common.logger.Logger; +import org.apache.druid.storage.s3.S3Utils; +import org.apache.druid.storage.s3.ServerSideEncryptingAmazonS3; +import org.apache.druid.utils.RuntimeInfo; + +import java.io.File; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; + +/** + * This class manages uploading files to S3 in chunks, while ensuring that the + * number of chunks currently present on local disk does not exceed a specific limit. + */ +@ManageLifecycle +public class S3UploadManager +{ + private final ExecutorService uploadExecutor; + + private static final Logger log = new Logger(S3UploadManager.class); + + @Inject + public S3UploadManager(S3OutputConfig s3OutputConfig, S3ExportConfig s3ExportConfig, RuntimeInfo runtimeInfo) + { + int poolSize = Math.max(4, runtimeInfo.getAvailableProcessors()); + int maxNumConcurrentChunks = computeMaxNumConcurrentChunks(s3OutputConfig, s3ExportConfig); + this.uploadExecutor = createExecutorService(poolSize, maxNumConcurrentChunks); + log.info("Initialized executor service for S3 multipart upload with pool size [%d] and work queue capacity [%d]", + poolSize, maxNumConcurrentChunks); + } + + /** + * Computes the maximum number of concurrent chunks for an S3 multipart upload. + * We want to determine the maximum number of concurrent chunks on disk based on the maximum value of chunkSize + * between the 2 configs: S3OutputConfig and S3ExportConfig. + * + * @param s3OutputConfig The S3 output configuration, which may specify a custom chunk size. + * @param s3ExportConfig The S3 export configuration, which may also specify a custom chunk size. + * @return The maximum number of concurrent chunks. + */ + @VisibleForTesting + int computeMaxNumConcurrentChunks(S3OutputConfig s3OutputConfig, S3ExportConfig s3ExportConfig) + { + long chunkSize = S3OutputConfig.S3_MULTIPART_UPLOAD_MIN_PART_SIZE_BYTES; + if (s3OutputConfig != null && s3OutputConfig.getChunkSize() != null) { + chunkSize = Math.max(chunkSize, s3OutputConfig.getChunkSize()); + } + if (s3ExportConfig != null && s3ExportConfig.getChunkSize() != null) { + chunkSize = Math.max(chunkSize, s3ExportConfig.getChunkSize().getBytes()); + } + + return (int) (S3OutputConfig.S3_MULTIPART_UPLOAD_MAX_PART_SIZE_BYTES / chunkSize); Review Comment: Shouldn't the numerator be the overall disk size available for keeping chunks? The value used here `S3OutputConfig.S3_MULTIPART_UPLOAD_MAX_PART_SIZE_BYTES` is 5gb which just seems to be the maximum object size limit imposed by S3. ########## extensions-core/s3-extensions/src/main/java/org/apache/druid/storage/s3/output/S3UploadManager.java: ########## @@ -0,0 +1,154 @@ +/* + * 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.druid.storage.s3.output; + +import com.amazonaws.services.s3.model.UploadPartRequest; +import com.amazonaws.services.s3.model.UploadPartResult; +import com.google.common.annotations.VisibleForTesting; +import com.google.inject.Inject; +import org.apache.druid.guice.ManageLifecycle; +import org.apache.druid.java.util.common.RetryUtils; +import org.apache.druid.java.util.common.concurrent.Execs; +import org.apache.druid.java.util.common.lifecycle.LifecycleStart; +import org.apache.druid.java.util.common.lifecycle.LifecycleStop; +import org.apache.druid.java.util.common.logger.Logger; +import org.apache.druid.storage.s3.S3Utils; +import org.apache.druid.storage.s3.ServerSideEncryptingAmazonS3; +import org.apache.druid.utils.RuntimeInfo; + +import java.io.File; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; + +/** + * This class manages uploading files to S3 in chunks, while ensuring that the + * number of chunks currently present on local disk does not exceed a specific limit. + */ +@ManageLifecycle +public class S3UploadManager +{ + private final ExecutorService uploadExecutor; + + private static final Logger log = new Logger(S3UploadManager.class); + + @Inject + public S3UploadManager(S3OutputConfig s3OutputConfig, S3ExportConfig s3ExportConfig, RuntimeInfo runtimeInfo) + { + int poolSize = Math.max(4, runtimeInfo.getAvailableProcessors()); + int maxNumConcurrentChunks = computeMaxNumConcurrentChunks(s3OutputConfig, s3ExportConfig); + this.uploadExecutor = createExecutorService(poolSize, maxNumConcurrentChunks); + log.info("Initialized executor service for S3 multipart upload with pool size [%d] and work queue capacity [%d]", + poolSize, maxNumConcurrentChunks); + } + + /** + * Computes the maximum number of concurrent chunks for an S3 multipart upload. + * We want to determine the maximum number of concurrent chunks on disk based on the maximum value of chunkSize + * between the 2 configs: S3OutputConfig and S3ExportConfig. + * + * @param s3OutputConfig The S3 output configuration, which may specify a custom chunk size. + * @param s3ExportConfig The S3 export configuration, which may also specify a custom chunk size. + * @return The maximum number of concurrent chunks. + */ + @VisibleForTesting + int computeMaxNumConcurrentChunks(S3OutputConfig s3OutputConfig, S3ExportConfig s3ExportConfig) + { + long chunkSize = S3OutputConfig.S3_MULTIPART_UPLOAD_MIN_PART_SIZE_BYTES; Review Comment: ```suggestion long maxChunkSize = S3OutputConfig.S3_MULTIPART_UPLOAD_MIN_PART_SIZE_BYTES; ``` ########## extensions-core/s3-extensions/src/main/java/org/apache/druid/storage/s3/output/RetryableS3OutputStream.java: ########## @@ -269,52 +213,74 @@ public void close() throws IOException // Closeables are closed in LIFO order closer.register(() -> { // This should be emitted as a metric + long totalChunkSize = (currentChunk.id - 1) * chunkSize + currentChunk.length(); LOG.info( "Pushed total [%d] parts containing [%d] bytes in [%d]ms.", - numChunksPushed, - resultsSize, + futures.size(), + totalChunkSize, pushStopwatch.elapsed(TimeUnit.MILLISECONDS) ); }); - closer.register(() -> org.apache.commons.io.FileUtils.forceDelete(chunkStorePath)); + try (Closer ignored = closer) { + if (!error) { + pushCurrentChunk(); + completeMultipartUpload(); + } + } + } - closer.register(() -> { + private void completeMultipartUpload() + { + for (Future<UploadPartResult> future : futures) { try { - if (resultsSize > 0 && isAllPushSucceeded()) { - RetryUtils.retry( - () -> s3.completeMultipartUpload( - new CompleteMultipartUploadRequest(config.getBucket(), s3Key, uploadId, pushResults) - ), - S3Utils.S3RETRY, - config.getMaxRetry() - ); - } else { - RetryUtils.retry( - () -> { - s3.cancelMultiPartUpload(new AbortMultipartUploadRequest(config.getBucket(), s3Key, uploadId)); - return null; - }, - S3Utils.S3RETRY, - config.getMaxRetry() - ); - } + UploadPartResult result = future.get(); + pushResults.add(result.getPartETag()); } catch (Exception e) { - throw new IOException(e); + error = true; + LOG.error(e, "Error in uploading part for upload ID [%s]", uploadId); + break; } - }); + } - try (Closer ignored = closer) { - if (!error) { - pushCurrentChunk(); + try { + if (isAllPushSucceeded()) { Review Comment: I don't think `isAllPushSucceeded()` needs to be a separate method anymore as all the relevant fields i.e `error` and `pushResults` are being updated in this method itself. On that note, AFAICT, `pushResults` need not be a member field anymore and can just be a local variable in this method. So, this if-else will simply reduce to: ``` if (error) cancel multipart upload else finish multipart upload ``` ########## extensions-core/s3-extensions/src/main/java/org/apache/druid/storage/s3/output/RetryableS3OutputStream.java: ########## @@ -103,27 +94,28 @@ public class RetryableS3OutputStream extends OutputStream private boolean error; private boolean closed; - public RetryableS3OutputStream( - S3OutputConfig config, - ServerSideEncryptingAmazonS3 s3, - String s3Key - ) throws IOException - { + /** + * Helper class for calculating maximum number of simultaneous chunks allowed on local disk. + */ + private final S3UploadManager uploadManager; - this(config, s3, s3Key, true); - } + /** + * A list of futures to allow us to wait for completion of all uploadPart() calls + * before hitting {@link ServerSideEncryptingAmazonS3#completeMultipartUpload(CompleteMultipartUploadRequest)}. + */ + private final List<Future<UploadPartResult>> futures = new ArrayList<>(); Review Comment: This could even be a map from `Chunk` to `Future` ########## extensions-core/s3-extensions/src/main/java/org/apache/druid/storage/s3/output/RetryableS3OutputStream.java: ########## @@ -269,52 +213,74 @@ public void close() throws IOException // Closeables are closed in LIFO order closer.register(() -> { // This should be emitted as a metric + long totalChunkSize = (currentChunk.id - 1) * chunkSize + currentChunk.length(); LOG.info( "Pushed total [%d] parts containing [%d] bytes in [%d]ms.", - numChunksPushed, - resultsSize, + futures.size(), + totalChunkSize, pushStopwatch.elapsed(TimeUnit.MILLISECONDS) ); }); - closer.register(() -> org.apache.commons.io.FileUtils.forceDelete(chunkStorePath)); + try (Closer ignored = closer) { + if (!error) { + pushCurrentChunk(); + completeMultipartUpload(); + } + } + } - closer.register(() -> { + private void completeMultipartUpload() + { + for (Future<UploadPartResult> future : futures) { try { - if (resultsSize > 0 && isAllPushSucceeded()) { - RetryUtils.retry( - () -> s3.completeMultipartUpload( - new CompleteMultipartUploadRequest(config.getBucket(), s3Key, uploadId, pushResults) - ), - S3Utils.S3RETRY, - config.getMaxRetry() - ); - } else { - RetryUtils.retry( - () -> { - s3.cancelMultiPartUpload(new AbortMultipartUploadRequest(config.getBucket(), s3Key, uploadId)); - return null; - }, - S3Utils.S3RETRY, - config.getMaxRetry() - ); - } + UploadPartResult result = future.get(); + pushResults.add(result.getPartETag()); } catch (Exception e) { - throw new IOException(e); + error = true; + LOG.error(e, "Error in uploading part for upload ID [%s]", uploadId); + break; } - }); + } - try (Closer ignored = closer) { - if (!error) { - pushCurrentChunk(); + try { + if (isAllPushSucceeded()) { + RetryUtils.retry( + () -> s3.completeMultipartUpload( + new CompleteMultipartUploadRequest(config.getBucket(), s3Key, uploadId, pushResults) + ), + S3Utils.S3RETRY, + config.getMaxRetry() + ); + } else { + RetryUtils.retry( + () -> { + s3.cancelMultiPartUpload(new AbortMultipartUploadRequest(config.getBucket(), s3Key, uploadId)); + return null; + }, + S3Utils.S3RETRY, + config.getMaxRetry() + ); + } + } + catch (Exception e) { + throw new RuntimeException(e); + } + finally { + try { + org.apache.commons.io.FileUtils.forceDelete(chunkStorePath); + pushStopwatch.stop(); Review Comment: It would be better to do this in `close()`. No particular reason, just for symmetry. The stopwatch is started in the constructor so it should be stopped in the last action performed on the object i.e. `close()`. In fact, the stopwatch doesn't even need to be stopped as there are no more time consuming operations after this anyway. ########## extensions-core/s3-extensions/src/main/java/org/apache/druid/storage/s3/output/S3UploadManager.java: ########## @@ -0,0 +1,154 @@ +/* + * 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.druid.storage.s3.output; + +import com.amazonaws.services.s3.model.UploadPartRequest; +import com.amazonaws.services.s3.model.UploadPartResult; +import com.google.common.annotations.VisibleForTesting; +import com.google.inject.Inject; +import org.apache.druid.guice.ManageLifecycle; +import org.apache.druid.java.util.common.RetryUtils; +import org.apache.druid.java.util.common.concurrent.Execs; +import org.apache.druid.java.util.common.lifecycle.LifecycleStart; +import org.apache.druid.java.util.common.lifecycle.LifecycleStop; +import org.apache.druid.java.util.common.logger.Logger; +import org.apache.druid.storage.s3.S3Utils; +import org.apache.druid.storage.s3.ServerSideEncryptingAmazonS3; +import org.apache.druid.utils.RuntimeInfo; + +import java.io.File; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; + +/** + * This class manages uploading files to S3 in chunks, while ensuring that the + * number of chunks currently present on local disk does not exceed a specific limit. + */ +@ManageLifecycle +public class S3UploadManager +{ + private final ExecutorService uploadExecutor; + + private static final Logger log = new Logger(S3UploadManager.class); + + @Inject + public S3UploadManager(S3OutputConfig s3OutputConfig, S3ExportConfig s3ExportConfig, RuntimeInfo runtimeInfo) + { + int poolSize = Math.max(4, runtimeInfo.getAvailableProcessors()); + int maxNumConcurrentChunks = computeMaxNumConcurrentChunks(s3OutputConfig, s3ExportConfig); + this.uploadExecutor = createExecutorService(poolSize, maxNumConcurrentChunks); + log.info("Initialized executor service for S3 multipart upload with pool size [%d] and work queue capacity [%d]", + poolSize, maxNumConcurrentChunks); + } + + /** + * Computes the maximum number of concurrent chunks for an S3 multipart upload. + * We want to determine the maximum number of concurrent chunks on disk based on the maximum value of chunkSize + * between the 2 configs: S3OutputConfig and S3ExportConfig. + * + * @param s3OutputConfig The S3 output configuration, which may specify a custom chunk size. + * @param s3ExportConfig The S3 export configuration, which may also specify a custom chunk size. + * @return The maximum number of concurrent chunks. + */ + @VisibleForTesting + int computeMaxNumConcurrentChunks(S3OutputConfig s3OutputConfig, S3ExportConfig s3ExportConfig) + { + long chunkSize = S3OutputConfig.S3_MULTIPART_UPLOAD_MIN_PART_SIZE_BYTES; + if (s3OutputConfig != null && s3OutputConfig.getChunkSize() != null) { + chunkSize = Math.max(chunkSize, s3OutputConfig.getChunkSize()); + } + if (s3ExportConfig != null && s3ExportConfig.getChunkSize() != null) { + chunkSize = Math.max(chunkSize, s3ExportConfig.getChunkSize().getBytes()); + } + + return (int) (S3OutputConfig.S3_MULTIPART_UPLOAD_MAX_PART_SIZE_BYTES / chunkSize); + } + + /** + * Queues a chunk of a file for upload to S3 as part of a multipart upload. + */ + public Future<UploadPartResult> queueChunkForUpload(ServerSideEncryptingAmazonS3 s3Client, String key, int chunkNumber, File chunkFile, String uploadId, S3OutputConfig config) Review Comment: Please put the method args in separate lines. ########## extensions-core/s3-extensions/src/main/java/org/apache/druid/storage/s3/output/S3UploadManager.java: ########## @@ -0,0 +1,154 @@ +/* + * 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.druid.storage.s3.output; + +import com.amazonaws.services.s3.model.UploadPartRequest; +import com.amazonaws.services.s3.model.UploadPartResult; +import com.google.common.annotations.VisibleForTesting; +import com.google.inject.Inject; +import org.apache.druid.guice.ManageLifecycle; +import org.apache.druid.java.util.common.RetryUtils; +import org.apache.druid.java.util.common.concurrent.Execs; +import org.apache.druid.java.util.common.lifecycle.LifecycleStart; +import org.apache.druid.java.util.common.lifecycle.LifecycleStop; +import org.apache.druid.java.util.common.logger.Logger; +import org.apache.druid.storage.s3.S3Utils; +import org.apache.druid.storage.s3.ServerSideEncryptingAmazonS3; +import org.apache.druid.utils.RuntimeInfo; + +import java.io.File; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; + +/** + * This class manages uploading files to S3 in chunks, while ensuring that the + * number of chunks currently present on local disk does not exceed a specific limit. + */ +@ManageLifecycle +public class S3UploadManager +{ + private final ExecutorService uploadExecutor; + + private static final Logger log = new Logger(S3UploadManager.class); + + @Inject + public S3UploadManager(S3OutputConfig s3OutputConfig, S3ExportConfig s3ExportConfig, RuntimeInfo runtimeInfo) + { + int poolSize = Math.max(4, runtimeInfo.getAvailableProcessors()); + int maxNumConcurrentChunks = computeMaxNumConcurrentChunks(s3OutputConfig, s3ExportConfig); Review Comment: ```suggestion int maxNumChunksOnDisk = computeMaxNumChunksOnDisk(s3OutputConfig, s3ExportConfig); ``` ########## extensions-core/s3-extensions/src/main/java/org/apache/druid/storage/s3/output/RetryableS3OutputStream.java: ########## @@ -269,52 +213,74 @@ public void close() throws IOException // Closeables are closed in LIFO order closer.register(() -> { // This should be emitted as a metric + long totalChunkSize = (currentChunk.id - 1) * chunkSize + currentChunk.length(); LOG.info( "Pushed total [%d] parts containing [%d] bytes in [%d]ms.", - numChunksPushed, - resultsSize, + futures.size(), + totalChunkSize, pushStopwatch.elapsed(TimeUnit.MILLISECONDS) ); }); - closer.register(() -> org.apache.commons.io.FileUtils.forceDelete(chunkStorePath)); + try (Closer ignored = closer) { + if (!error) { + pushCurrentChunk(); + completeMultipartUpload(); + } + } + } - closer.register(() -> { + private void completeMultipartUpload() + { + for (Future<UploadPartResult> future : futures) { try { - if (resultsSize > 0 && isAllPushSucceeded()) { - RetryUtils.retry( - () -> s3.completeMultipartUpload( - new CompleteMultipartUploadRequest(config.getBucket(), s3Key, uploadId, pushResults) - ), - S3Utils.S3RETRY, - config.getMaxRetry() - ); - } else { - RetryUtils.retry( - () -> { - s3.cancelMultiPartUpload(new AbortMultipartUploadRequest(config.getBucket(), s3Key, uploadId)); - return null; - }, - S3Utils.S3RETRY, - config.getMaxRetry() - ); - } + UploadPartResult result = future.get(); Review Comment: Better to use `future.get()` with some timeout i.e `future.get(timeout, unit)` rather than blocking indefinitely in case the executor is misbehaving. To start with, the timeout maybe a large enough value, say 1 hour. ########## extensions-core/s3-extensions/src/main/java/org/apache/druid/storage/s3/output/RetryableS3OutputStream.java: ########## @@ -199,64 +188,19 @@ private void pushCurrentChunk() throws IOException { currentChunk.close(); final Chunk chunk = currentChunk; - try { - if (chunk.length() > 0) { - resultsSize += chunk.length(); - - pushStopwatch.start(); - pushResults.add(push(chunk)); - pushStopwatch.stop(); - numChunksPushed++; - } - } - finally { - if (!chunk.delete()) { - LOG.warn("Failed to delete chunk [%s]", chunk.getAbsolutePath()); - } - } - } - - private PartETag push(Chunk chunk) throws IOException - { - try { - return RetryUtils.retry( - () -> uploadPartIfPossible(uploadId, config.getBucket(), s3Key, chunk), - S3Utils.S3RETRY, - config.getMaxRetry() + if (chunk.length() > 0) { + Future<UploadPartResult> uploadPartResultFuture = uploadManager.queueChunkForUpload( + s3, + s3Key, + chunk.id, + chunk.file, + uploadId, + config ); - } - catch (AmazonServiceException e) { - throw new IOException(e); - } - catch (Exception e) { - throw new RuntimeException(e); + futures.add(uploadPartResultFuture); Review Comment: Nit: Probably more readable as ```java futures.add( uploadManager.queueChunkForUpload(s3, s3Key, chunk.id, chunk.file, uploadId, config) ); ``` ########## extensions-core/s3-extensions/src/main/java/org/apache/druid/storage/s3/output/S3UploadManager.java: ########## @@ -0,0 +1,154 @@ +/* + * 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.druid.storage.s3.output; + +import com.amazonaws.services.s3.model.UploadPartRequest; +import com.amazonaws.services.s3.model.UploadPartResult; +import com.google.common.annotations.VisibleForTesting; +import com.google.inject.Inject; +import org.apache.druid.guice.ManageLifecycle; +import org.apache.druid.java.util.common.RetryUtils; +import org.apache.druid.java.util.common.concurrent.Execs; +import org.apache.druid.java.util.common.lifecycle.LifecycleStart; +import org.apache.druid.java.util.common.lifecycle.LifecycleStop; +import org.apache.druid.java.util.common.logger.Logger; +import org.apache.druid.storage.s3.S3Utils; +import org.apache.druid.storage.s3.ServerSideEncryptingAmazonS3; +import org.apache.druid.utils.RuntimeInfo; + +import java.io.File; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; + +/** + * This class manages uploading files to S3 in chunks, while ensuring that the + * number of chunks currently present on local disk does not exceed a specific limit. + */ +@ManageLifecycle +public class S3UploadManager +{ + private final ExecutorService uploadExecutor; + + private static final Logger log = new Logger(S3UploadManager.class); + + @Inject + public S3UploadManager(S3OutputConfig s3OutputConfig, S3ExportConfig s3ExportConfig, RuntimeInfo runtimeInfo) + { + int poolSize = Math.max(4, runtimeInfo.getAvailableProcessors()); + int maxNumConcurrentChunks = computeMaxNumConcurrentChunks(s3OutputConfig, s3ExportConfig); + this.uploadExecutor = createExecutorService(poolSize, maxNumConcurrentChunks); + log.info("Initialized executor service for S3 multipart upload with pool size [%d] and work queue capacity [%d]", + poolSize, maxNumConcurrentChunks); + } + + /** + * Computes the maximum number of concurrent chunks for an S3 multipart upload. + * We want to determine the maximum number of concurrent chunks on disk based on the maximum value of chunkSize + * between the 2 configs: S3OutputConfig and S3ExportConfig. + * + * @param s3OutputConfig The S3 output configuration, which may specify a custom chunk size. + * @param s3ExportConfig The S3 export configuration, which may also specify a custom chunk size. + * @return The maximum number of concurrent chunks. Review Comment: Not really needed. ########## extensions-core/s3-extensions/src/test/java/org/apache/druid/storage/s3/output/RetryableS3OutputStreamTest.java: ########## @@ -198,17 +205,15 @@ public void testFailToUploadAfterRetries() throws IOException config, s3, path, - false + s3UploadManager )) { for (int i = 0; i < 2; i++) { bb.clear(); bb.putInt(i); out.write(bb.array()); } - expectedException.expect(RuntimeException.class); - expectedException.expectCause(CoreMatchers.instanceOf(AmazonClientException.class)); - expectedException.expectMessage("Upload failure test. Remaining failures [1]"); + // No exception is thrown in the main thread, since the upload now happens in a separate threadpool. Review Comment: not needed. ########## extensions-core/s3-extensions/src/main/java/org/apache/druid/storage/s3/output/RetryableS3OutputStream.java: ########## @@ -269,52 +213,74 @@ public void close() throws IOException // Closeables are closed in LIFO order closer.register(() -> { // This should be emitted as a metric + long totalChunkSize = (currentChunk.id - 1) * chunkSize + currentChunk.length(); Review Comment: Hmm, while this is correct, it seems better to simply add up the size of every chunk and not rely on the chunkSize here. If you use a map to maintain the futures, you could the total size of the successfully uploaded chunks. ########## extensions-core/s3-extensions/src/main/java/org/apache/druid/storage/s3/output/S3UploadManager.java: ########## @@ -0,0 +1,154 @@ +/* + * 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.druid.storage.s3.output; + +import com.amazonaws.services.s3.model.UploadPartRequest; +import com.amazonaws.services.s3.model.UploadPartResult; +import com.google.common.annotations.VisibleForTesting; +import com.google.inject.Inject; +import org.apache.druid.guice.ManageLifecycle; +import org.apache.druid.java.util.common.RetryUtils; +import org.apache.druid.java.util.common.concurrent.Execs; +import org.apache.druid.java.util.common.lifecycle.LifecycleStart; +import org.apache.druid.java.util.common.lifecycle.LifecycleStop; +import org.apache.druid.java.util.common.logger.Logger; +import org.apache.druid.storage.s3.S3Utils; +import org.apache.druid.storage.s3.ServerSideEncryptingAmazonS3; +import org.apache.druid.utils.RuntimeInfo; + +import java.io.File; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; + +/** + * This class manages uploading files to S3 in chunks, while ensuring that the + * number of chunks currently present on local disk does not exceed a specific limit. + */ +@ManageLifecycle +public class S3UploadManager +{ + private final ExecutorService uploadExecutor; + + private static final Logger log = new Logger(S3UploadManager.class); + + @Inject + public S3UploadManager(S3OutputConfig s3OutputConfig, S3ExportConfig s3ExportConfig, RuntimeInfo runtimeInfo) + { + int poolSize = Math.max(4, runtimeInfo.getAvailableProcessors()); + int maxNumConcurrentChunks = computeMaxNumConcurrentChunks(s3OutputConfig, s3ExportConfig); + this.uploadExecutor = createExecutorService(poolSize, maxNumConcurrentChunks); + log.info("Initialized executor service for S3 multipart upload with pool size [%d] and work queue capacity [%d]", + poolSize, maxNumConcurrentChunks); + } + + /** + * Computes the maximum number of concurrent chunks for an S3 multipart upload. + * We want to determine the maximum number of concurrent chunks on disk based on the maximum value of chunkSize + * between the 2 configs: S3OutputConfig and S3ExportConfig. + * + * @param s3OutputConfig The S3 output configuration, which may specify a custom chunk size. + * @param s3ExportConfig The S3 export configuration, which may also specify a custom chunk size. + * @return The maximum number of concurrent chunks. + */ + @VisibleForTesting + int computeMaxNumConcurrentChunks(S3OutputConfig s3OutputConfig, S3ExportConfig s3ExportConfig) + { + long chunkSize = S3OutputConfig.S3_MULTIPART_UPLOAD_MIN_PART_SIZE_BYTES; + if (s3OutputConfig != null && s3OutputConfig.getChunkSize() != null) { + chunkSize = Math.max(chunkSize, s3OutputConfig.getChunkSize()); + } + if (s3ExportConfig != null && s3ExportConfig.getChunkSize() != null) { + chunkSize = Math.max(chunkSize, s3ExportConfig.getChunkSize().getBytes()); + } + + return (int) (S3OutputConfig.S3_MULTIPART_UPLOAD_MAX_PART_SIZE_BYTES / chunkSize); + } + + /** + * Queues a chunk of a file for upload to S3 as part of a multipart upload. + */ + public Future<UploadPartResult> queueChunkForUpload(ServerSideEncryptingAmazonS3 s3Client, String key, int chunkNumber, File chunkFile, String uploadId, S3OutputConfig config) + { + return uploadExecutor.submit(() -> RetryUtils.retry( + () -> { + log.info("Uploading chunk [%d] for uploadId [%s].", chunkNumber, uploadId); + UploadPartResult uploadPartResult = uploadPartIfPossible( + s3Client, + uploadId, + config.getBucket(), + key, + chunkNumber, + chunkFile + ); + if (!chunkFile.delete()) { + log.warn("Failed to delete chunk [%s]", chunkFile.getAbsolutePath()); + } + return uploadPartResult; + }, + S3Utils.S3RETRY, + config.getMaxRetry() + )); + } + + @VisibleForTesting + UploadPartResult uploadPartIfPossible( + ServerSideEncryptingAmazonS3 s3Client, + String uploadId, + String bucket, + String key, + int chunkNumber, + File chunkFile + ) + { + final UploadPartRequest uploadPartRequest = new UploadPartRequest() + .withUploadId(uploadId) + .withBucketName(bucket) + .withKey(key) + .withFile(chunkFile) + .withPartNumber(chunkNumber) + .withPartSize(chunkFile.length()); + + if (log.isDebugEnabled()) { + log.debug("Pushing chunk [%s] to bucket[%s] and key[%s].", chunkNumber, bucket, key); + } + return s3Client.uploadPart(uploadPartRequest); + } + + @VisibleForTesting + ExecutorService createExecutorService(int poolSize, int maxNumConcurrentChunks) + { + return Execs.newBlockingThreaded("S3UploadThreadPool-%d", poolSize, maxNumConcurrentChunks); + } + + @LifecycleStart + public void start() + { + // No state startup required + } + + @LifecycleStop + public void stop() + { + log.info("Stopping S3UploadManager"); + uploadExecutor.shutdown(); + log.info("Stopped S3UploadManager"); Review Comment: The logs are not needed as we are simply shutting down an executor. ########## extensions-core/s3-extensions/src/main/java/org/apache/druid/storage/s3/output/RetryableS3OutputStream.java: ########## @@ -269,52 +213,74 @@ public void close() throws IOException // Closeables are closed in LIFO order closer.register(() -> { // This should be emitted as a metric + long totalChunkSize = (currentChunk.id - 1) * chunkSize + currentChunk.length(); LOG.info( "Pushed total [%d] parts containing [%d] bytes in [%d]ms.", - numChunksPushed, - resultsSize, + futures.size(), + totalChunkSize, pushStopwatch.elapsed(TimeUnit.MILLISECONDS) ); }); - closer.register(() -> org.apache.commons.io.FileUtils.forceDelete(chunkStorePath)); + try (Closer ignored = closer) { + if (!error) { + pushCurrentChunk(); + completeMultipartUpload(); + } + } + } - closer.register(() -> { + private void completeMultipartUpload() + { + for (Future<UploadPartResult> future : futures) { try { - if (resultsSize > 0 && isAllPushSucceeded()) { - RetryUtils.retry( - () -> s3.completeMultipartUpload( - new CompleteMultipartUploadRequest(config.getBucket(), s3Key, uploadId, pushResults) - ), - S3Utils.S3RETRY, - config.getMaxRetry() - ); - } else { - RetryUtils.retry( - () -> { - s3.cancelMultiPartUpload(new AbortMultipartUploadRequest(config.getBucket(), s3Key, uploadId)); - return null; - }, - S3Utils.S3RETRY, - config.getMaxRetry() - ); - } + UploadPartResult result = future.get(); + pushResults.add(result.getPartETag()); } catch (Exception e) { - throw new IOException(e); + error = true; + LOG.error(e, "Error in uploading part for upload ID [%s]", uploadId); + break; } - }); + } - try (Closer ignored = closer) { - if (!error) { - pushCurrentChunk(); + try { + if (isAllPushSucceeded()) { + RetryUtils.retry( + () -> s3.completeMultipartUpload( + new CompleteMultipartUploadRequest(config.getBucket(), s3Key, uploadId, pushResults) + ), + S3Utils.S3RETRY, + config.getMaxRetry() + ); + } else { + RetryUtils.retry( + () -> { + s3.cancelMultiPartUpload(new AbortMultipartUploadRequest(config.getBucket(), s3Key, uploadId)); + return null; + }, + S3Utils.S3RETRY, + config.getMaxRetry() + ); + } + } + catch (Exception e) { + throw new RuntimeException(e); + } + finally { + try { + org.apache.commons.io.FileUtils.forceDelete(chunkStorePath); Review Comment: this should also happen in `close()`. The `completeMultipartUpload()` method should be concerned only with finishing up (or canceling) the upload work. ########## extensions-core/s3-extensions/src/main/java/org/apache/druid/storage/s3/output/S3UploadManager.java: ########## @@ -0,0 +1,154 @@ +/* + * 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.druid.storage.s3.output; + +import com.amazonaws.services.s3.model.UploadPartRequest; +import com.amazonaws.services.s3.model.UploadPartResult; +import com.google.common.annotations.VisibleForTesting; +import com.google.inject.Inject; +import org.apache.druid.guice.ManageLifecycle; +import org.apache.druid.java.util.common.RetryUtils; +import org.apache.druid.java.util.common.concurrent.Execs; +import org.apache.druid.java.util.common.lifecycle.LifecycleStart; +import org.apache.druid.java.util.common.lifecycle.LifecycleStop; +import org.apache.druid.java.util.common.logger.Logger; +import org.apache.druid.storage.s3.S3Utils; +import org.apache.druid.storage.s3.ServerSideEncryptingAmazonS3; +import org.apache.druid.utils.RuntimeInfo; + +import java.io.File; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; + +/** + * This class manages uploading files to S3 in chunks, while ensuring that the + * number of chunks currently present on local disk does not exceed a specific limit. + */ +@ManageLifecycle +public class S3UploadManager +{ + private final ExecutorService uploadExecutor; + + private static final Logger log = new Logger(S3UploadManager.class); + + @Inject + public S3UploadManager(S3OutputConfig s3OutputConfig, S3ExportConfig s3ExportConfig, RuntimeInfo runtimeInfo) + { + int poolSize = Math.max(4, runtimeInfo.getAvailableProcessors()); + int maxNumConcurrentChunks = computeMaxNumConcurrentChunks(s3OutputConfig, s3ExportConfig); + this.uploadExecutor = createExecutorService(poolSize, maxNumConcurrentChunks); + log.info("Initialized executor service for S3 multipart upload with pool size [%d] and work queue capacity [%d]", + poolSize, maxNumConcurrentChunks); + } + + /** + * Computes the maximum number of concurrent chunks for an S3 multipart upload. + * We want to determine the maximum number of concurrent chunks on disk based on the maximum value of chunkSize + * between the 2 configs: S3OutputConfig and S3ExportConfig. + * + * @param s3OutputConfig The S3 output configuration, which may specify a custom chunk size. + * @param s3ExportConfig The S3 export configuration, which may also specify a custom chunk size. + * @return The maximum number of concurrent chunks. + */ + @VisibleForTesting Review Comment: Let's not do this, it really defeats the purpose of keeping this as an internal implementation detail. You might as well make this method `public static`. ########## extensions-core/s3-extensions/src/main/java/org/apache/druid/storage/s3/output/S3UploadManager.java: ########## @@ -0,0 +1,154 @@ +/* + * 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.druid.storage.s3.output; + +import com.amazonaws.services.s3.model.UploadPartRequest; +import com.amazonaws.services.s3.model.UploadPartResult; +import com.google.common.annotations.VisibleForTesting; +import com.google.inject.Inject; +import org.apache.druid.guice.ManageLifecycle; +import org.apache.druid.java.util.common.RetryUtils; +import org.apache.druid.java.util.common.concurrent.Execs; +import org.apache.druid.java.util.common.lifecycle.LifecycleStart; +import org.apache.druid.java.util.common.lifecycle.LifecycleStop; +import org.apache.druid.java.util.common.logger.Logger; +import org.apache.druid.storage.s3.S3Utils; +import org.apache.druid.storage.s3.ServerSideEncryptingAmazonS3; +import org.apache.druid.utils.RuntimeInfo; + +import java.io.File; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; + +/** + * This class manages uploading files to S3 in chunks, while ensuring that the + * number of chunks currently present on local disk does not exceed a specific limit. + */ +@ManageLifecycle +public class S3UploadManager +{ + private final ExecutorService uploadExecutor; + + private static final Logger log = new Logger(S3UploadManager.class); + + @Inject + public S3UploadManager(S3OutputConfig s3OutputConfig, S3ExportConfig s3ExportConfig, RuntimeInfo runtimeInfo) + { + int poolSize = Math.max(4, runtimeInfo.getAvailableProcessors()); + int maxNumConcurrentChunks = computeMaxNumConcurrentChunks(s3OutputConfig, s3ExportConfig); + this.uploadExecutor = createExecutorService(poolSize, maxNumConcurrentChunks); + log.info("Initialized executor service for S3 multipart upload with pool size [%d] and work queue capacity [%d]", + poolSize, maxNumConcurrentChunks); + } + + /** + * Computes the maximum number of concurrent chunks for an S3 multipart upload. + * We want to determine the maximum number of concurrent chunks on disk based on the maximum value of chunkSize + * between the 2 configs: S3OutputConfig and S3ExportConfig. + * + * @param s3OutputConfig The S3 output configuration, which may specify a custom chunk size. + * @param s3ExportConfig The S3 export configuration, which may also specify a custom chunk size. + * @return The maximum number of concurrent chunks. + */ + @VisibleForTesting + int computeMaxNumConcurrentChunks(S3OutputConfig s3OutputConfig, S3ExportConfig s3ExportConfig) Review Comment: Seems like this method should also take an argument for maximum disk space allocated for storing chunks. ########## extensions-core/s3-extensions/src/main/java/org/apache/druid/storage/s3/output/S3UploadManager.java: ########## @@ -0,0 +1,154 @@ +/* + * 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.druid.storage.s3.output; + +import com.amazonaws.services.s3.model.UploadPartRequest; +import com.amazonaws.services.s3.model.UploadPartResult; +import com.google.common.annotations.VisibleForTesting; +import com.google.inject.Inject; +import org.apache.druid.guice.ManageLifecycle; +import org.apache.druid.java.util.common.RetryUtils; +import org.apache.druid.java.util.common.concurrent.Execs; +import org.apache.druid.java.util.common.lifecycle.LifecycleStart; +import org.apache.druid.java.util.common.lifecycle.LifecycleStop; +import org.apache.druid.java.util.common.logger.Logger; +import org.apache.druid.storage.s3.S3Utils; +import org.apache.druid.storage.s3.ServerSideEncryptingAmazonS3; +import org.apache.druid.utils.RuntimeInfo; + +import java.io.File; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; + +/** + * This class manages uploading files to S3 in chunks, while ensuring that the + * number of chunks currently present on local disk does not exceed a specific limit. + */ +@ManageLifecycle +public class S3UploadManager +{ + private final ExecutorService uploadExecutor; + + private static final Logger log = new Logger(S3UploadManager.class); + + @Inject + public S3UploadManager(S3OutputConfig s3OutputConfig, S3ExportConfig s3ExportConfig, RuntimeInfo runtimeInfo) + { + int poolSize = Math.max(4, runtimeInfo.getAvailableProcessors()); + int maxNumConcurrentChunks = computeMaxNumConcurrentChunks(s3OutputConfig, s3ExportConfig); + this.uploadExecutor = createExecutorService(poolSize, maxNumConcurrentChunks); + log.info("Initialized executor service for S3 multipart upload with pool size [%d] and work queue capacity [%d]", + poolSize, maxNumConcurrentChunks); + } + + /** + * Computes the maximum number of concurrent chunks for an S3 multipart upload. + * We want to determine the maximum number of concurrent chunks on disk based on the maximum value of chunkSize + * between the 2 configs: S3OutputConfig and S3ExportConfig. Review Comment: ```suggestion * Computes the maximum number of S3 upload chunks that can be kept on disk using the * maximum chunk size specified in {@link S3OutputConfig} and {@link S3ExportConfig}. ``` ########## extensions-core/s3-extensions/src/main/java/org/apache/druid/storage/s3/output/S3UploadManager.java: ########## @@ -0,0 +1,154 @@ +/* + * 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.druid.storage.s3.output; + +import com.amazonaws.services.s3.model.UploadPartRequest; +import com.amazonaws.services.s3.model.UploadPartResult; +import com.google.common.annotations.VisibleForTesting; +import com.google.inject.Inject; +import org.apache.druid.guice.ManageLifecycle; +import org.apache.druid.java.util.common.RetryUtils; +import org.apache.druid.java.util.common.concurrent.Execs; +import org.apache.druid.java.util.common.lifecycle.LifecycleStart; +import org.apache.druid.java.util.common.lifecycle.LifecycleStop; +import org.apache.druid.java.util.common.logger.Logger; +import org.apache.druid.storage.s3.S3Utils; +import org.apache.druid.storage.s3.ServerSideEncryptingAmazonS3; +import org.apache.druid.utils.RuntimeInfo; + +import java.io.File; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; + +/** + * This class manages uploading files to S3 in chunks, while ensuring that the + * number of chunks currently present on local disk does not exceed a specific limit. + */ +@ManageLifecycle +public class S3UploadManager +{ + private final ExecutorService uploadExecutor; + + private static final Logger log = new Logger(S3UploadManager.class); + + @Inject + public S3UploadManager(S3OutputConfig s3OutputConfig, S3ExportConfig s3ExportConfig, RuntimeInfo runtimeInfo) + { + int poolSize = Math.max(4, runtimeInfo.getAvailableProcessors()); + int maxNumConcurrentChunks = computeMaxNumConcurrentChunks(s3OutputConfig, s3ExportConfig); + this.uploadExecutor = createExecutorService(poolSize, maxNumConcurrentChunks); + log.info("Initialized executor service for S3 multipart upload with pool size [%d] and work queue capacity [%d]", + poolSize, maxNumConcurrentChunks); + } + + /** + * Computes the maximum number of concurrent chunks for an S3 multipart upload. + * We want to determine the maximum number of concurrent chunks on disk based on the maximum value of chunkSize + * between the 2 configs: S3OutputConfig and S3ExportConfig. + * + * @param s3OutputConfig The S3 output configuration, which may specify a custom chunk size. + * @param s3ExportConfig The S3 export configuration, which may also specify a custom chunk size. + * @return The maximum number of concurrent chunks. + */ + @VisibleForTesting + int computeMaxNumConcurrentChunks(S3OutputConfig s3OutputConfig, S3ExportConfig s3ExportConfig) + { + long chunkSize = S3OutputConfig.S3_MULTIPART_UPLOAD_MIN_PART_SIZE_BYTES; + if (s3OutputConfig != null && s3OutputConfig.getChunkSize() != null) { + chunkSize = Math.max(chunkSize, s3OutputConfig.getChunkSize()); + } + if (s3ExportConfig != null && s3ExportConfig.getChunkSize() != null) { + chunkSize = Math.max(chunkSize, s3ExportConfig.getChunkSize().getBytes()); + } + + return (int) (S3OutputConfig.S3_MULTIPART_UPLOAD_MAX_PART_SIZE_BYTES / chunkSize); + } + + /** + * Queues a chunk of a file for upload to S3 as part of a multipart upload. + */ + public Future<UploadPartResult> queueChunkForUpload(ServerSideEncryptingAmazonS3 s3Client, String key, int chunkNumber, File chunkFile, String uploadId, S3OutputConfig config) + { + return uploadExecutor.submit(() -> RetryUtils.retry( + () -> { + log.info("Uploading chunk [%d] for uploadId [%s].", chunkNumber, uploadId); + UploadPartResult uploadPartResult = uploadPartIfPossible( + s3Client, + uploadId, + config.getBucket(), + key, + chunkNumber, + chunkFile + ); + if (!chunkFile.delete()) { + log.warn("Failed to delete chunk [%s]", chunkFile.getAbsolutePath()); + } + return uploadPartResult; + }, + S3Utils.S3RETRY, + config.getMaxRetry() + )); + } + + @VisibleForTesting + UploadPartResult uploadPartIfPossible( + ServerSideEncryptingAmazonS3 s3Client, + String uploadId, + String bucket, + String key, + int chunkNumber, + File chunkFile + ) + { + final UploadPartRequest uploadPartRequest = new UploadPartRequest() + .withUploadId(uploadId) + .withBucketName(bucket) + .withKey(key) + .withFile(chunkFile) + .withPartNumber(chunkNumber) + .withPartSize(chunkFile.length()); + + if (log.isDebugEnabled()) { + log.debug("Pushing chunk [%s] to bucket[%s] and key[%s].", chunkNumber, bucket, key); Review Comment: ```suggestion log.debug("Pushing chunk[%s] to bucket[%s] and key[%s].", chunkNumber, bucket, key); ``` ########## extensions-core/s3-extensions/src/main/java/org/apache/druid/storage/s3/output/RetryableS3OutputStream.java: ########## @@ -269,52 +213,74 @@ public void close() throws IOException // Closeables are closed in LIFO order closer.register(() -> { // This should be emitted as a metric + long totalChunkSize = (currentChunk.id - 1) * chunkSize + currentChunk.length(); LOG.info( "Pushed total [%d] parts containing [%d] bytes in [%d]ms.", - numChunksPushed, - resultsSize, + futures.size(), + totalChunkSize, pushStopwatch.elapsed(TimeUnit.MILLISECONDS) ); }); - closer.register(() -> org.apache.commons.io.FileUtils.forceDelete(chunkStorePath)); + try (Closer ignored = closer) { + if (!error) { + pushCurrentChunk(); + completeMultipartUpload(); + } + } + } - closer.register(() -> { + private void completeMultipartUpload() + { + for (Future<UploadPartResult> future : futures) { try { - if (resultsSize > 0 && isAllPushSucceeded()) { - RetryUtils.retry( - () -> s3.completeMultipartUpload( - new CompleteMultipartUploadRequest(config.getBucket(), s3Key, uploadId, pushResults) - ), - S3Utils.S3RETRY, - config.getMaxRetry() - ); - } else { - RetryUtils.retry( - () -> { - s3.cancelMultiPartUpload(new AbortMultipartUploadRequest(config.getBucket(), s3Key, uploadId)); - return null; - }, - S3Utils.S3RETRY, - config.getMaxRetry() - ); - } + UploadPartResult result = future.get(); + pushResults.add(result.getPartETag()); } catch (Exception e) { - throw new IOException(e); + error = true; + LOG.error(e, "Error in uploading part for upload ID [%s]", uploadId); + break; } - }); + } - try (Closer ignored = closer) { - if (!error) { - pushCurrentChunk(); + try { + if (isAllPushSucceeded()) { Review Comment: In case of error, we must make sure to cancel any pending futures. -- 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] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
