This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/main by this push:
new 0b67ca93733e CAMEL-27457: camel-aws2-s3 - streaming upload: a stop
resets the open upload and always stops the timeout task (#30813)
0b67ca93733e is described below
commit 0b67ca93733ed258b714136f56b2d1ac89e23393
Author: allthingssecurity <[email protected]>
AuthorDate: Thu Nov 26 14:40:37 2026 +0530
CAMEL-27457: camel-aws2-s3 - streaming upload: a stop resets the open
upload and always stops the timeout task (#30813)
doStop completed the open upload of uploadAggregate but kept the field.
When the same producer instance was started
again (a producer driven directly, or through JMX), the next small exchange
was added to the completed upload and
returned success; its bytes were never stored, and the next flush failed
with NoSuchUpload. doStop now sets
uploadAggregate to null, and clears the timestamp windows, in a finally:
after a completed upload, and also after a
failed one, whose failure the stop reports.
An S3 failure in doStop also skipped the shutdown of the
streamingUploadTimeout executor: the task of the stopped
producer kept running and calling S3, and a start created a second one.
doStop now shuts the executor down first and
waits for a run of the task that has started, so that it finishes before
the stop uploads what is left and no run of
the task happens after the stop (before, a run waiting for the lock during
the stop ran after it). The wait is bounded
by the shutdownAwaitTermination of the ExecutorServiceManager (10 seconds
by default); after it, the stop logs a WARN
and goes on.
* CAMEL-27457: camel-aws2-s3 - review follow-up: no WARN at every stop when
shutdownAwaitTermination is 0
- shutdownTimeoutChecker(): with a shutdownAwaitTermination of 0 the stop
does not wait for the timeout task (as
before, awaitTermination(0) did not wait either), and no longer logs that
the task is still running, which it did at
every clean stop as the pool thread had not ended yet.
- timeoutCheckerExecutorService stays a plain field: it is only read and
written in doStart() and doStop(), which
ServiceSupport runs one at a time under its lock.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../aws2/s3/stream/AWS2S3StreamUploadProducer.java | 30 ++-
.../s3/stream/AWS2S3StreamUploadStopStartTest.java | 222 +++++++++++++++++++++
2 files changed, 247 insertions(+), 5 deletions(-)
diff --git
a/components/camel-aws/camel-aws2-s3/src/main/java/org/apache/camel/component/aws2/s3/stream/AWS2S3StreamUploadProducer.java
b/components/camel-aws/camel-aws2-s3/src/main/java/org/apache/camel/component/aws2/s3/stream/AWS2S3StreamUploadProducer.java
index a3a632bc9fbd..a6db7845aacc 100644
---
a/components/camel-aws/camel-aws2-s3/src/main/java/org/apache/camel/component/aws2/s3/stream/AWS2S3StreamUploadProducer.java
+++
b/components/camel-aws/camel-aws2-s3/src/main/java/org/apache/camel/component/aws2/s3/stream/AWS2S3StreamUploadProducer.java
@@ -122,6 +122,8 @@ public class AWS2S3StreamUploadProducer extends
DefaultProducer {
@Override
protected void doStop() throws Exception {
+ // stop the timeout task first, so that it does not run after the stop
whether or not the uploads below fail
+ shutdownTimeoutChecker();
lock.lock();
try {
if (ObjectHelper.isNotEmpty(uploadAggregate)) {
@@ -138,18 +140,36 @@ public class AWS2S3StreamUploadProducer extends
DefaultProducer {
completedUploadsByWindow.merge(entry.getKey(), 1,
Integer::sum);
}
}
- timestampBasedUploads.clear();
} finally {
+ // the uploads are completed, or failed and reported by the stop:
when started again, the producer
+ // starts new uploads and does not add to these
+ uploadAggregate = null;
+ timestampBasedUploads.clear();
lock.unlock();
}
- if (timeoutCheckerExecutorService != null) {
-
getEndpoint().getCamelContext().getExecutorServiceManager().shutdown(timeoutCheckerExecutorService);
- timeoutCheckerExecutorService = null;
- }
super.doStop();
}
+ private void shutdownTimeoutChecker() {
+ ScheduledExecutorService executor = timeoutCheckerExecutorService;
+ if (executor != null) {
+ timeoutCheckerExecutorService = null;
+
getEndpoint().getCamelContext().getExecutorServiceManager().shutdown(executor);
+ // wait for a flush the task is running, so that it ends before
the stop uploads what is left. A
+ // shutdownAwaitTermination of 0 means no wait: there is then
nothing to warn about
+ long timeout =
getEndpoint().getCamelContext().getExecutorServiceManager().getShutdownAwaitTermination();
+ try {
+ if (timeout > 0 && !executor.awaitTermination(timeout,
TimeUnit.MILLISECONDS)) {
+ LOG.warn("The streamingUploadTimeout task of {} is still
running after {} ms, the stop goes on",
+ getConfiguration().getKeyName(), timeout);
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ }
+
/**
* Background task that triggers completion based on interval.
*/
diff --git
a/components/camel-aws/camel-aws2-s3/src/test/java/org/apache/camel/component/aws2/s3/stream/AWS2S3StreamUploadStopStartTest.java
b/components/camel-aws/camel-aws2-s3/src/test/java/org/apache/camel/component/aws2/s3/stream/AWS2S3StreamUploadStopStartTest.java
new file mode 100644
index 000000000000..e74199d97829
--- /dev/null
+++
b/components/camel-aws/camel-aws2-s3/src/test/java/org/apache/camel/component/aws2/s3/stream/AWS2S3StreamUploadStopStartTest.java
@@ -0,0 +1,222 @@
+/*
+ * 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.camel.component.aws2.s3.stream;
+
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.component.aws2.s3.AWS2S3Configuration;
+import org.apache.camel.component.aws2.s3.AWS2S3Endpoint;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.support.DefaultExchange;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import software.amazon.awssdk.core.sync.RequestBody;
+import software.amazon.awssdk.http.SdkHttpResponse;
+import software.amazon.awssdk.services.s3.S3Client;
+import software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest;
+import software.amazon.awssdk.services.s3.model.AbortMultipartUploadResponse;
+import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest;
+import
software.amazon.awssdk.services.s3.model.CompleteMultipartUploadResponse;
+import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest;
+import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse;
+import software.amazon.awssdk.services.s3.model.S3Exception;
+import software.amazon.awssdk.services.s3.model.UploadPartRequest;
+import software.amazon.awssdk.services.s3.model.UploadPartResponse;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.when;
+
+/**
+ * A streaming upload producer that is stopped and started again: the stop
completes the open upload and the producer
+ * starts a new one afterwards, and a stop that fails on S3 still stops the
timeout task. The mocked S3Client keeps the
+ * completed objects by key and, like S3, refuses parts for an upload that is
completed or aborted.
+ */
+class AWS2S3StreamUploadStopStartTest {
+
+ private static final String TIMEOUT_CHECKER =
"S3_Streaming_Upload_Timeout_Checker";
+
+ @Mock
+ private AWS2S3Endpoint endpoint;
+
+ @Mock
+ private AWS2S3Configuration configuration;
+
+ @Mock
+ private S3Client s3Client;
+
+ // the bucket: completed objects by key
+ private final Map<String, String> bucket = new ConcurrentHashMap<>();
+ private final Map<String, String> keysByUploadId = new
ConcurrentHashMap<>();
+ private final Map<String, ByteArrayOutputStream> partsByUploadId = new
ConcurrentHashMap<>();
+ // the uploads neither completed nor aborted
+ private final Set<String> openUploads = ConcurrentHashMap.newKeySet();
+ private final AtomicInteger uploadIds = new AtomicInteger();
+ // the next uploadPart calls that fail
+ private final AtomicInteger failingUploadParts = new AtomicInteger();
+
+ private DefaultCamelContext camelContext;
+ private AWS2S3StreamUploadProducer producer;
+
+ @BeforeEach
+ void setUp() {
+ MockitoAnnotations.openMocks(this);
+ camelContext = new DefaultCamelContext();
+ camelContext.start();
+
+ when(endpoint.getConfiguration()).thenReturn(configuration);
+ when(endpoint.getCamelContext()).thenReturn(camelContext);
+ when(endpoint.getS3Client()).thenReturn(s3Client);
+
+ when(configuration.getBucketName()).thenReturn("test-bucket");
+ when(configuration.getKeyName()).thenReturn("camel.txt");
+ when(configuration.isMultiPartUpload()).thenReturn(false);
+ when(configuration.getPartSize()).thenReturn(25L * 1024 * 1024);
+
when(configuration.getNamingStrategy()).thenReturn(AWSS3NamingStrategyEnum.progressive);
+
when(configuration.getRestartingPolicy()).thenReturn(AWSS3RestartingPolicyEnum.override);
+ // the defaults of the endpoint: a small exchange is kept for the next
ones
+ when(configuration.getBatchMessageNumber()).thenReturn(10);
+ when(configuration.getBatchSize()).thenReturn(1000000);
+ when(configuration.getBufferSize()).thenReturn(1000000);
+
+ SdkHttpResponse httpResponse =
SdkHttpResponse.builder().statusCode(200).build();
+
+
when(s3Client.createMultipartUpload(any(CreateMultipartUploadRequest.class))).thenAnswer(invocation
-> {
+ CreateMultipartUploadRequest request = invocation.getArgument(0);
+ String uploadId = "upload-" + uploadIds.incrementAndGet();
+ keysByUploadId.put(uploadId, request.key());
+ partsByUploadId.put(uploadId, new ByteArrayOutputStream());
+ openUploads.add(uploadId);
+ return
CreateMultipartUploadResponse.builder().uploadId(uploadId).sdkHttpResponse(httpResponse).build();
+ });
+
+ when(s3Client.uploadPart(any(UploadPartRequest.class),
any(RequestBody.class))).thenAnswer(invocation -> {
+ UploadPartRequest request = invocation.getArgument(0);
+ RequestBody body = invocation.getArgument(1);
+ if (!openUploads.contains(request.uploadId())) {
+ throw noSuchUpload(request.uploadId());
+ }
+ if (failingUploadParts.getAndUpdate(n -> Math.max(0, n - 1)) > 0) {
+ throw (S3Exception)
S3Exception.builder().statusCode(503).message("Slow Down").build();
+ }
+ ByteArrayOutputStream parts =
partsByUploadId.get(request.uploadId());
+ synchronized (parts) {
+
parts.write(body.contentStreamProvider().newStream().readAllBytes());
+ }
+ return
UploadPartResponse.builder().eTag("etag").sdkHttpResponse(httpResponse).build();
+ });
+
+
when(s3Client.completeMultipartUpload(any(CompleteMultipartUploadRequest.class))).thenAnswer(invocation
-> {
+ CompleteMultipartUploadRequest request = invocation.getArgument(0);
+ if (!openUploads.remove(request.uploadId())) {
+ throw noSuchUpload(request.uploadId());
+ }
+ bucket.put(keysByUploadId.get(request.uploadId()),
+
partsByUploadId.get(request.uploadId()).toString(StandardCharsets.UTF_8));
+ return
CompleteMultipartUploadResponse.builder().eTag("final-etag").sdkHttpResponse(httpResponse).build();
+ });
+
+
when(s3Client.abortMultipartUpload(any(AbortMultipartUploadRequest.class))).thenAnswer(invocation
-> {
+ AbortMultipartUploadRequest request = invocation.getArgument(0);
+ if (!openUploads.remove(request.uploadId())) {
+ throw noSuchUpload(request.uploadId());
+ }
+ return AbortMultipartUploadResponse.builder().build();
+ });
+
+ producer = new AWS2S3StreamUploadProducer(endpoint);
+ }
+
+ @AfterEach
+ void tearDown() {
+ producer.stop();
+ camelContext.stop();
+ }
+
+ @Test
+ void anExchangeAfterAStopAndStartIsUploadedToANewObject() throws Exception
{
+ producer.start();
+ send("message-0\n");
+ producer.stop();
+ assertEquals(Map.of("camel.txt", "message-0\n"), bucket, "the stop
completes the upload");
+
+ producer.start();
+ send("message-1\n");
+ producer.stop();
+
+ assertEquals(Map.of("camel.txt", "message-0\n", "camel-1.txt",
"message-1\n"), bucket,
+ "the exchange sent after the start is stored in an object of
its own");
+ assertEquals(Set.of(), openUploads, "every upload is completed");
+ }
+
+ @Test
+ void aStopThatFailsOnS3StopsTheTimeoutTask() throws Exception {
+ // the timeout task does not run during the test: the test checks that
it is stopped
+ when(configuration.getStreamingUploadTimeout()).thenReturn(60000L);
+ Set<Thread> others = timeoutCheckers();
+ producer.start();
+ assertEquals(1, timeoutCheckersOfTheProducer(others).size(), "the
start runs the timeout task");
+ send("message-0\n");
+
+ failingUploadParts.set(1);
+ assertThrows(S3Exception.class, producer::stop, "the upload of the
stop fails");
+ await().atMost(5, TimeUnit.SECONDS).until(() ->
timeoutCheckersOfTheProducer(others).isEmpty());
+
+ producer.start();
+ assertEquals(1, timeoutCheckersOfTheProducer(others).size(), "the
start after the failed stop runs one task");
+ send("message-1\n");
+ producer.stop();
+ assertEquals("message-1\n", bucket.get("camel.txt"),
+ "the exchange sent after the start is uploaded, not added to
the failed upload");
+ assertEquals(Set.of(), timeoutCheckersOfTheProducer(others), "the stop
ends the timeout task");
+ }
+
+ private void send(String body) throws Exception {
+ Exchange exchange = new DefaultExchange(camelContext);
+ exchange.getIn().setBody(body);
+ producer.process(exchange);
+ }
+
+ private static Set<Thread> timeoutCheckers() {
+ return Thread.getAllStackTraces().keySet().stream()
+ .filter(t -> t.isAlive() &&
t.getName().contains(TIMEOUT_CHECKER))
+ .collect(Collectors.toSet());
+ }
+
+ private static Set<Thread> timeoutCheckersOfTheProducer(Set<Thread>
others) {
+ Set<Thread> checkers = timeoutCheckers();
+ checkers.removeAll(others);
+ return checkers;
+ }
+
+ private static S3Exception noSuchUpload(String uploadId) {
+ return (S3Exception)
S3Exception.builder().statusCode(404).message("NoSuchUpload " +
uploadId).build();
+ }
+}