From e5cd3e459ab1b40ebed23cc3e6e8f86a86a43ddc Mon Sep 17 00:00:00 2001 From: Caideyipi <87789683+Caideyipi@users.noreply.github.com> Date: Tue, 1 Dec 2026 18:30:48 +0800 Subject: [PATCH 1/4] Start Pipe tasks in downstream-first order (#19455) * Fix Pipe startup sequencing * Fix Pipe subtask test imports (cherry picked from commit be57cd48a511413a55be9f6d5831e062090a4223) --- .../db/pipe/agent/task/PipeDataNodeTask.java | 41 ++- .../task/stage/PipeTaskProcessorStage.java | 27 +- .../agent/task/stage/PipeTaskSourceStage.java | 68 ++++- .../processor/PipeProcessorSubtask.java | 12 + .../sink/PipeSinkSubtaskLifeCycle.java | 12 + .../subtask/sink/PipeSinkSubtaskManager.java | 93 +++++-- .../pipe/agent/task/PipeDataNodeTaskTest.java | 182 ++++++++++++++ .../task/stage/PipeTaskSourceStageTest.java | 236 ++++++++++++++++++ .../iotdb/commons/i18n/UtilMessages.java | 10 + .../iotdb/commons/i18n/UtilMessages.java | 9 + .../pipe/agent/task/PipeTaskAgent.java | 63 ++++- .../pipe/agent/task/subtask/PipeSubtask.java | 45 ++++ .../pipe/agent/task/PipeTaskAgentTest.java | 67 +++++ .../agent/task/subtask/PipeSubtaskTest.java | 147 +++++++++++ 14 files changed, 977 insertions(+), 35 deletions(-) create mode 100644 iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTaskTest.java create mode 100644 iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSourceStageTest.java create mode 100644 iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtaskTest.java diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTask.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTask.java index 0d0b955c2109d..afd70c49ecbe0 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTask.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTask.java @@ -21,10 +21,15 @@ import org.apache.iotdb.commons.pipe.agent.task.PipeTask; import org.apache.iotdb.commons.pipe.agent.task.stage.PipeTaskStage; +import org.apache.iotdb.db.pipe.agent.task.stage.PipeTaskProcessorStage; +import org.apache.iotdb.db.pipe.agent.task.stage.PipeTaskSourceStage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.List; + public class PipeDataNodeTask implements PipeTask { private static final Logger LOGGER = LoggerFactory.getLogger(PipeDataNodeTask.class); @@ -50,10 +55,15 @@ public PipeDataNodeTask( this.sourceStage = sourceStage; this.processorStage = processorStage; this.sinkStage = sinkStage; + + if (sourceStage instanceof PipeTaskSourceStage pipeTaskSourceStage + && processorStage instanceof PipeTaskProcessorStage pipeTaskProcessorStage) { + pipeTaskSourceStage.setSourceStartedCallback(pipeTaskProcessorStage::wakeUpWorker); + } } @Override - public void create() { + public synchronized void create() { final long startTime = System.currentTimeMillis(); sourceStage.create(); processorStage.create(); @@ -65,7 +75,7 @@ public void create() { } @Override - public void drop() { + public synchronized void drop() { final long startTime = System.currentTimeMillis(); sourceStage.drop(); processorStage.drop(); @@ -77,11 +87,28 @@ public void drop() { } @Override - public void start() { + public synchronized void start() { final long startTime = System.currentTimeMillis(); - sourceStage.start(); - processorStage.start(); - sinkStage.start(); + final List startedStages = new ArrayList<>(3); + try { + sinkStage.start(); + startedStages.add(sinkStage); + processorStage.start(); + startedStages.add(processorStage); + sourceStage.start(); + startedStages.add(sourceStage); + } catch (final RuntimeException | Error e) { + for (int i = startedStages.size() - 1; i >= 0; --i) { + try { + startedStages.get(i).stop(); + } catch (final RuntimeException | Error stopException) { + if (stopException != e) { + e.addSuppressed(stopException); + } + } + } + throw e; + } LOGGER.info( "Start pipe DN task {} successfully within {} ms", this, @@ -89,7 +116,7 @@ public void start() { } @Override - public void stop() { + public synchronized void stop() { final long startTime = System.currentTimeMillis(); sourceStage.stop(); processorStage.stop(); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskProcessorStage.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskProcessorStage.java index e2607267fbdd9..15fdc19a1c3c9 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskProcessorStage.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskProcessorStage.java @@ -125,7 +125,32 @@ public void createSubtask() throws PipeException { @Override public void startSubtask() throws PipeException { - executor.start(pipeProcessorSubtask.getTaskID()); + pipeProcessorSubtask.prepareForStart(); + try { + executor.start(pipeProcessorSubtask.getTaskID()); + pipeProcessorSubtask.awaitFirstExecution(); + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + stopAfterFailedStart(e); + throw new PipeException(e.getMessage(), e); + } catch (final RuntimeException | Error e) { + stopAfterFailedStart(e); + throw e; + } + } + + private void stopAfterFailedStart(final Throwable failure) { + try { + executor.stop(pipeProcessorSubtask.getTaskID()); + } catch (final RuntimeException | Error stopException) { + if (stopException != failure) { + failure.addSuppressed(stopException); + } + } + } + + public void wakeUpWorker() { + pipeProcessorSubtask.wakeUpWorker(); } @Override diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSourceStage.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSourceStage.java index 240b5499e92b2..675fedc4260ca 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSourceStage.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSourceStage.java @@ -35,11 +35,21 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.concurrent.atomic.AtomicReference; + public class PipeTaskSourceStage extends PipeTaskStage { private static final Logger LOGGER = LoggerFactory.getLogger(PipeTaskSourceStage.class); private final PipeExtractor pipeExtractor; + private volatile boolean isStarted; + private boolean isClosed; + private final AtomicReference startFailure = new AtomicReference<>(); + private final AtomicReference sourceStartedCallback = new AtomicReference<>(); + + PipeTaskSourceStage(final PipeExtractor pipeExtractor) { + this.pipeExtractor = pipeExtractor; + } public PipeTaskSourceStage( String pipeName, @@ -63,14 +73,20 @@ public PipeTaskSourceStage( new PipeTaskRuntimeConfiguration( new PipeTaskSourceRuntimeEnvironment(pipeName, creationTime, regionId, pipeTaskMeta)); pipeExtractor.customize(sourceParameters, runtimeConfiguration); - } catch (Exception e) { + } catch (Exception | Error e) { try { pipeExtractor.close(); - } catch (Exception closeException) { + } catch (Exception | Error closeException) { + if (closeException != e) { + e.addSuppressed(closeException); + } LOGGER.warn( "Failed to close source after failed to initialize source. " + "Ignore this exception.", closeException); } + if (e instanceof Error) { + throw (Error) e; + } throw new PipeException(e.getMessage(), e); } } @@ -82,28 +98,66 @@ public void createSubtask() throws PipeException { @Override public void startSubtask() throws PipeException { + final Throwable previousStartFailure = startFailure.get(); + if (previousStartFailure != null) { + if (previousStartFailure instanceof Error error) { + throw error; + } + throw (PipeException) previousStartFailure; + } try { pipeExtractor.start(); - } catch (Exception e) { - throw new PipeException(e.getMessage(), e); + isStarted = true; + final Runnable callback = sourceStartedCallback.get(); + if (callback != null) { + callback.run(); + } + } catch (Exception | Error e) { + isStarted = false; + try { + closeExtractor(); + } catch (Exception | Error closeException) { + if (closeException != e) { + e.addSuppressed(closeException); + } + } + if (e instanceof Error error) { + startFailure.set(error); + throw error; + } + final PipeException pipeException = new PipeException(e.getMessage(), e); + startFailure.set(pipeException); + throw pipeException; } } @Override public void stopSubtask() throws PipeException { - // Extractor continuously extracts data, so do nothing in stop + isStarted = false; } @Override public void dropSubtask() throws PipeException { try { - pipeExtractor.close(); + closeExtractor(); } catch (Exception e) { throw new PipeException(e.getMessage(), e); } } + private synchronized void closeExtractor() throws Exception { + isStarted = false; + if (!isClosed) { + pipeExtractor.close(); + isClosed = true; + } + } + + public void setSourceStartedCallback(final Runnable sourceStartedCallback) { + this.sourceStartedCallback.set(sourceStartedCallback); + } + public EventSupplier getEventSupplier() { - return pipeExtractor::supply; + return () -> isStarted ? pipeExtractor.supply() : null; } } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/processor/PipeProcessorSubtask.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/processor/PipeProcessorSubtask.java index 814e2b9d61538..81253c4bf3509 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/processor/PipeProcessorSubtask.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/processor/PipeProcessorSubtask.java @@ -137,6 +137,11 @@ public Boolean call() throws Exception { } } + @Override + protected void onExecutionStart() { + executionGuard.check(); + } + @Override protected boolean executeOnce() throws Exception { if (isClosed.get()) { @@ -275,6 +280,13 @@ void setWorkerWakeUpCallback(final Runnable wakeUpCallback) { executionGuard.setWorkerWakeUpCallback(wakeUpCallback); } + public void wakeUpWorker() { + final Runnable wakeUpCallback = executionGuard.getWorkerWakeUpCallback(); + if (wakeUpCallback != null) { + wakeUpCallback.run(); + } + } + @Override protected void onAllowSubmittingSelf() { executionGuard.start(); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskLifeCycle.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskLifeCycle.java index 61a064e1637a4..f5c678037c814 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskLifeCycle.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskLifeCycle.java @@ -28,6 +28,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.concurrent.TimeUnit; + public class PipeSinkSubtaskLifeCycle implements AutoCloseable { private static final Logger LOGGER = LoggerFactory.getLogger(PipeSinkSubtaskLifeCycle.class); @@ -124,6 +126,7 @@ public synchronized void start() { if (runningTaskCount == 0) { try { + subtask.prepareForStart(); subtask.increaseHighPriorityTaskCount(); executor.start(subtask.getTaskID()); } finally { @@ -139,6 +142,15 @@ public synchronized void start() { registeredTaskCount); } + public void awaitFirstExecution() throws InterruptedException { + subtask.awaitFirstExecution(); + } + + public void awaitFirstExecution(final long timeout, final TimeUnit timeUnit) + throws InterruptedException { + subtask.awaitFirstExecution(timeout, timeUnit); + } + public synchronized void stop() { if (runningTaskCount <= 0) { throw new IllegalStateException("runningTaskCount <= 0"); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskManager.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskManager.java index c28089090c755..50bab06c277c0 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskManager.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskManager.java @@ -25,6 +25,7 @@ import org.apache.iotdb.commons.pipe.agent.task.meta.PipeRuntimeMeta; import org.apache.iotdb.commons.pipe.agent.task.progress.CommitterKey; import org.apache.iotdb.commons.pipe.agent.task.progress.PipeEventCommitManager; +import org.apache.iotdb.commons.pipe.agent.task.subtask.PipeSubtask; import org.apache.iotdb.commons.pipe.config.constant.PipeSinkConstant; import org.apache.iotdb.commons.pipe.config.constant.SystemConstant; import org.apache.iotdb.commons.pipe.config.plugin.configuraion.PipeTaskRuntimeConfiguration; @@ -50,6 +51,7 @@ import java.util.Map; import java.util.Objects; import java.util.TreeMap; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; @@ -211,17 +213,70 @@ public synchronized void deregister( PipeEventCommitManager.getInstance().deregister(pipeName, creationTime, regionId); } - public synchronized void start( + public void start( final String pipeName, final long creationTime, final String attributeSortedString) { final PipeSinkSubtaskKey pipeSinkSubtaskKey = new PipeSinkSubtaskKey(pipeName, creationTime, attributeSortedString); - if (!pipeSinkSubtaskKey2SubtaskLifeCycleMap.containsKey(pipeSinkSubtaskKey)) { - throwNoSuchSubtaskException(pipeSinkSubtaskKey); + final List lifeCycles; + synchronized (this) { + if (!pipeSinkSubtaskKey2SubtaskLifeCycleMap.containsKey(pipeSinkSubtaskKey)) { + throwNoSuchSubtaskException(pipeSinkSubtaskKey); + } + + lifeCycles = new ArrayList<>(pipeSinkSubtaskKey2SubtaskLifeCycleMap.get(pipeSinkSubtaskKey)); + startLifeCycles(lifeCycles); } - for (final PipeSinkSubtaskLifeCycle lifeCycle : - pipeSinkSubtaskKey2SubtaskLifeCycleMap.get(pipeSinkSubtaskKey)) { - lifeCycle.start(); + awaitFirstExecution(lifeCycles); + } + + private void startLifeCycles(final List lifeCycles) { + final List startedLifeCycles = new ArrayList<>(); + try { + for (final PipeSinkSubtaskLifeCycle lifeCycle : lifeCycles) { + lifeCycle.start(); + startedLifeCycles.add(lifeCycle); + } + } catch (final RuntimeException | Error e) { + stopLifeCycles(startedLifeCycles, e); + throw e; + } + } + + private void awaitFirstExecution(final List lifeCycles) { + try { + final long deadlineNanos = + System.nanoTime() + + TimeUnit.MILLISECONDS.toNanos(PipeSubtask.getFirstExecutionTimeoutInMs()); + for (final PipeSinkSubtaskLifeCycle lifeCycle : lifeCycles) { + lifeCycle.awaitFirstExecution( + Math.max(0L, deadlineNanos - System.nanoTime()), TimeUnit.NANOSECONDS); + } + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + final PipeException failure = new PipeException(e.getMessage(), e); + synchronized (this) { + stopLifeCycles(lifeCycles, failure); + } + throw failure; + } catch (final RuntimeException | Error e) { + synchronized (this) { + stopLifeCycles(lifeCycles, e); + } + throw e; + } + } + + private void stopLifeCycles( + final List lifeCycles, final Throwable failure) { + for (int i = lifeCycles.size() - 1; i >= 0; --i) { + try { + lifeCycles.get(i).stop(); + } catch (final RuntimeException | Error stopException) { + if (stopException != failure) { + failure.addSuppressed(stopException); + } + } } } @@ -229,18 +284,22 @@ public synchronized void start( * @deprecated Use {@link #start(String, long, String)} to identify the pipe explicitly. */ @Deprecated - public synchronized void start(final String attributeSortedString) { - final PipeSinkSubtaskKey pipeSinkSubtaskKey = - getUniquePipeSinkSubtaskKey(attributeSortedString); - if (pipeSinkSubtaskKey == null) { - throwNoSuchSubtaskException( - new PipeSinkSubtaskKey(null, Long.MIN_VALUE, attributeSortedString)); - } - - for (final PipeSinkSubtaskLifeCycle lifeCycle : - pipeSinkSubtaskKey2SubtaskLifeCycleMap.get(pipeSinkSubtaskKey)) { - lifeCycle.start(); + public void start(final String attributeSortedString) { + final PipeSinkSubtaskKey pipeSinkSubtaskKey; + final List lifeCycles; + synchronized (this) { + pipeSinkSubtaskKey = getUniquePipeSinkSubtaskKey(attributeSortedString); + if (pipeSinkSubtaskKey == null) { + throwNoSuchSubtaskException( + new PipeSinkSubtaskKey(null, Long.MIN_VALUE, attributeSortedString)); + } + if (!pipeSinkSubtaskKey2SubtaskLifeCycleMap.containsKey(pipeSinkSubtaskKey)) { + throwNoSuchSubtaskException(pipeSinkSubtaskKey); + } + lifeCycles = new ArrayList<>(pipeSinkSubtaskKey2SubtaskLifeCycleMap.get(pipeSinkSubtaskKey)); + startLifeCycles(lifeCycles); } + awaitFirstExecution(lifeCycles); } public synchronized void stop( diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTaskTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTaskTest.java new file mode 100644 index 0000000000000..393cc004d0730 --- /dev/null +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTaskTest.java @@ -0,0 +1,182 @@ +/* + * 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.iotdb.db.pipe.agent.task; + +import org.apache.iotdb.commons.pipe.agent.task.stage.PipeTaskStage; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +public class PipeDataNodeTaskTest { + + @Test + public void testStartStartsSinkAndProcessorBeforeSource() { + final List startedStages = new ArrayList<>(); + final PipeDataNodeTask task = + new PipeDataNodeTask( + "pipe", + 1, + new RecordingStage("source", startedStages), + new RecordingStage("processor", startedStages), + new RecordingStage("sink", startedStages)); + + task.create(); + task.start(); + + Assert.assertEquals(Arrays.asList("sink", "processor", "source"), startedStages); + } + + @Test + public void testStartFailureStopsPreviouslyStartedStagesInReverseOrder() { + final List stageEvents = new ArrayList<>(); + final PipeDataNodeTask task = + new PipeDataNodeTask( + "pipe", + 1, + new RecordingStage("source", stageEvents, new IllegalStateException("failed")), + new RecordingStage("processor", stageEvents), + new RecordingStage("sink", stageEvents)); + + task.create(); + + Assert.assertThrows(IllegalStateException.class, task::start); + Assert.assertEquals( + Arrays.asList("sink", "processor", "source", "stop-processor", "stop-sink"), stageEvents); + } + + @Test + public void testStopDoesNotInterleaveWithAnInProgressStart() throws Exception { + final List stageEvents = Collections.synchronizedList(new ArrayList<>()); + final CountDownLatch sinkStartEntered = new CountDownLatch(1); + final CountDownLatch allowSinkStartToComplete = new CountDownLatch(1); + final PipeDataNodeTask task = + new PipeDataNodeTask( + "pipe", + 1, + new RecordingStage("source", stageEvents), + new RecordingStage("processor", stageEvents), + new BlockingStage("sink", stageEvents, sinkStartEntered, allowSinkStartToComplete)); + task.create(); + + final ExecutorService executor = Executors.newFixedThreadPool(2); + try { + final Future start = executor.submit(task::start); + Assert.assertTrue(sinkStartEntered.await(1, TimeUnit.SECONDS)); + + final CountDownLatch stopAttempted = new CountDownLatch(1); + final Future stop = + executor.submit( + () -> { + stopAttempted.countDown(); + task.stop(); + }); + Assert.assertTrue(stopAttempted.await(1, TimeUnit.SECONDS)); + Assert.assertThrows(TimeoutException.class, () -> stop.get(100, TimeUnit.MILLISECONDS)); + + allowSinkStartToComplete.countDown(); + start.get(1, TimeUnit.SECONDS); + stop.get(1, TimeUnit.SECONDS); + } finally { + allowSinkStartToComplete.countDown(); + executor.shutdownNow(); + } + + Assert.assertEquals( + Arrays.asList("sink", "processor", "source", "stop-source", "stop-processor", "stop-sink"), + stageEvents); + } + + private static class RecordingStage extends PipeTaskStage { + + private final String stageName; + private final List startedStages; + private final RuntimeException startException; + + private RecordingStage(final String stageName, final List startedStages) { + this(stageName, startedStages, null); + } + + private RecordingStage( + final String stageName, + final List startedStages, + final RuntimeException startException) { + this.stageName = stageName; + this.startedStages = startedStages; + this.startException = startException; + } + + @Override + protected void createSubtask() {} + + @Override + protected void startSubtask() { + startedStages.add(stageName); + if (startException != null) { + throw startException; + } + } + + @Override + protected void stopSubtask() { + startedStages.add("stop-" + stageName); + } + + @Override + protected void dropSubtask() {} + } + + private static class BlockingStage extends RecordingStage { + + private final CountDownLatch startEntered; + private final CountDownLatch allowStartToComplete; + + private BlockingStage( + final String stageName, + final List startedStages, + final CountDownLatch startEntered, + final CountDownLatch allowStartToComplete) { + super(stageName, startedStages); + this.startEntered = startEntered; + this.allowStartToComplete = allowStartToComplete; + } + + @Override + protected void startSubtask() { + super.startSubtask(); + startEntered.countDown(); + try { + allowStartToComplete.await(); + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } + } + } +} diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSourceStageTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSourceStageTest.java new file mode 100644 index 0000000000000..f4e6805ca3724 --- /dev/null +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSourceStageTest.java @@ -0,0 +1,236 @@ +/* + * 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.iotdb.db.pipe.agent.task.stage; + +import org.apache.iotdb.commons.pipe.agent.task.connection.EventSupplier; +import org.apache.iotdb.pipe.api.PipeExtractor; +import org.apache.iotdb.pipe.api.customizer.configuration.PipeExtractorRuntimeConfiguration; +import org.apache.iotdb.pipe.api.customizer.parameter.PipeParameterValidator; +import org.apache.iotdb.pipe.api.customizer.parameter.PipeParameters; +import org.apache.iotdb.pipe.api.event.Event; +import org.apache.iotdb.pipe.api.exception.PipeException; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +public class PipeTaskSourceStageTest { + + @Test + public void testSupplierWaitsForSourceStartAndNotifiesProcessor() throws Exception { + final TestExtractor extractor = new TestExtractor(null); + final PipeTaskSourceStage stage = new PipeTaskSourceStage(extractor); + final AtomicInteger notifications = new AtomicInteger(); + stage.setSourceStartedCallback(notifications::incrementAndGet); + final EventSupplier supplier = stage.getEventSupplier(); + + Assert.assertNull(supplier.supply()); + Assert.assertEquals(0, extractor.supplyCount); + + stage.create(); + stage.start(); + + Assert.assertNull(supplier.supply()); + Assert.assertEquals(1, extractor.supplyCount); + Assert.assertEquals(1, notifications.get()); + } + + @Test + public void testFailedSourceStartClosesPartiallyStartedExtractorOnce() { + final TestExtractor extractor = new TestExtractor(new IllegalStateException("failed")); + final PipeTaskSourceStage stage = new PipeTaskSourceStage(extractor); + stage.create(); + + final PipeException startFailure = Assert.assertThrows(PipeException.class, stage::start); + Assert.assertEquals(1, extractor.closeCount); + Assert.assertSame(startFailure, Assert.assertThrows(PipeException.class, stage::start)); + + stage.drop(); + Assert.assertEquals(1, extractor.closeCount); + } + + @Test + public void testSupplierRemainsGatedUntilAsynchronousSourceStartCompletes() throws Exception { + final CountDownLatch startEntered = new CountDownLatch(1); + final CountDownLatch allowStartToComplete = new CountDownLatch(1); + final TestExtractor extractor = new TestExtractor(startEntered, allowStartToComplete); + final PipeTaskSourceStage stage = new PipeTaskSourceStage(extractor); + final EventSupplier supplier = stage.getEventSupplier(); + stage.create(); + + final ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + final Future startFuture = executor.submit(stage::start); + Assert.assertTrue(startEntered.await(1, TimeUnit.SECONDS)); + Assert.assertNull(supplier.supply()); + Assert.assertEquals(0, extractor.supplyCount); + + allowStartToComplete.countDown(); + startFuture.get(1, TimeUnit.SECONDS); + Assert.assertNull(supplier.supply()); + Assert.assertEquals(1, extractor.supplyCount); + } finally { + allowStartToComplete.countDown(); + executor.shutdownNow(); + } + } + + @Test + public void testSupplierGateIsResetAcrossStopAndRestart() throws Exception { + final TestExtractor extractor = new TestExtractor(null); + final PipeTaskSourceStage stage = new PipeTaskSourceStage(extractor); + final EventSupplier supplier = stage.getEventSupplier(); + final AtomicInteger notifications = new AtomicInteger(); + stage.setSourceStartedCallback(notifications::incrementAndGet); + stage.create(); + + stage.start(); + Assert.assertNull(supplier.supply()); + Assert.assertEquals(1, extractor.supplyCount); + + stage.stop(); + Assert.assertNull(supplier.supply()); + Assert.assertEquals(1, extractor.supplyCount); + + stage.start(); + Assert.assertEquals(2, notifications.get()); + Assert.assertNull(supplier.supply()); + Assert.assertEquals(2, extractor.supplyCount); + } + + @Test + public void testSourceStartErrorRemainsPrimaryAndDropRetriesFailedClose() throws Exception { + final AssertionError startError = new AssertionError("start failed"); + final AssertionError closeError = new AssertionError("close failed"); + final TestExtractor extractor = new TestExtractor(startError, closeError); + final PipeTaskSourceStage stage = new PipeTaskSourceStage(extractor); + stage.create(); + + final AssertionError thrown = Assert.assertThrows(AssertionError.class, stage::start); + Assert.assertSame(startError, thrown); + Assert.assertArrayEquals(new Throwable[] {closeError}, thrown.getSuppressed()); + Assert.assertNull(stage.getEventSupplier().supply()); + + stage.drop(); + Assert.assertEquals(2, extractor.closeCount); + } + + @Test + public void testSourceStartedCallbackFailureClosesExtractorAndKeepsSupplierGated() + throws Exception { + final TestExtractor extractor = new TestExtractor(null); + final PipeTaskSourceStage stage = new PipeTaskSourceStage(extractor); + final EventSupplier supplier = stage.getEventSupplier(); + final IllegalStateException callbackFailure = new IllegalStateException("callback failed"); + stage.setSourceStartedCallback( + () -> { + throw callbackFailure; + }); + stage.create(); + + final PipeException thrown = Assert.assertThrows(PipeException.class, stage::start); + Assert.assertSame(callbackFailure, thrown.getCause()); + Assert.assertNull(supplier.supply()); + Assert.assertEquals(0, extractor.supplyCount); + Assert.assertEquals(1, extractor.closeCount); + + stage.drop(); + Assert.assertEquals(1, extractor.closeCount); + } + + private static class TestExtractor implements PipeExtractor { + + private final RuntimeException startException; + private final Error startError; + private final Error closeError; + private final CountDownLatch startEntered; + private final CountDownLatch allowStartToComplete; + private boolean started; + private int supplyCount; + private int closeCount; + + private TestExtractor(final RuntimeException startException) { + this.startException = startException; + startError = null; + closeError = null; + startEntered = null; + allowStartToComplete = null; + } + + private TestExtractor( + final CountDownLatch startEntered, final CountDownLatch allowStartToComplete) { + startException = null; + startError = null; + closeError = null; + this.startEntered = startEntered; + this.allowStartToComplete = allowStartToComplete; + } + + private TestExtractor(final Error startError, final Error closeError) { + startException = null; + this.startError = startError; + this.closeError = closeError; + startEntered = null; + allowStartToComplete = null; + } + + @Override + public void validate(final PipeParameterValidator validator) {} + + @Override + public void customize( + final PipeParameters parameters, final PipeExtractorRuntimeConfiguration configuration) {} + + @Override + public void start() throws Exception { + if (startEntered != null) { + startEntered.countDown(); + allowStartToComplete.await(); + } + started = true; + if (startException != null) { + throw startException; + } + if (startError != null) { + throw startError; + } + } + + @Override + public Event supply() { + Assert.assertTrue(started); + supplyCount++; + return null; + } + + @Override + public void close() { + closeCount++; + if (closeError != null && closeCount == 1) { + throw closeError; + } + } + } +} diff --git a/iotdb-core/node-commons/src/main/i18n/en/org/apache/iotdb/commons/i18n/UtilMessages.java b/iotdb-core/node-commons/src/main/i18n/en/org/apache/iotdb/commons/i18n/UtilMessages.java index e4ea264564204..b6fb1e1b26e48 100644 --- a/iotdb-core/node-commons/src/main/i18n/en/org/apache/iotdb/commons/i18n/UtilMessages.java +++ b/iotdb-core/node-commons/src/main/i18n/en/org/apache/iotdb/commons/i18n/UtilMessages.java @@ -24,4 +24,14 @@ private UtilMessages() {} public static final String EXCEPTION_FILE_CHANNEL_WRITE_MADE_NO_PROGRESS_B0F24ACD = "File channel write made no progress"; + public static final String + EXCEPTION_TIMED_OUT_AFTER_ARG_MS_WAITING_FOR_THE_FIRST_EXECUTION_OF_SUBTASK_ARG_71E546A8 = + "Timed out after %d ms waiting for the first execution of subtask %s"; + public static final String + LOG_FAILED_TO_START_THE_TASK_OF_CONSENSUS_GROUP_ARG_FOR_PIPE_ARG_THE_TASK_IS_DROPPED_AND_WILL_BE_RECREATED_BY_THE_FOLLOWING_META_SYNC_7594577C = + "Failed to start the task of consensus group {} for pipe {}. The task is dropped and " + + "will be recreated by the following meta sync."; + public static final String + LOG_FAILED_TO_DROP_THE_TASK_OF_CONSENSUS_GROUP_ARG_FOR_PIPE_ARG_AFTER_IT_FAILED_TO_START_394297EC = + "Failed to drop the task of consensus group {} for pipe {} after it failed to start."; } diff --git a/iotdb-core/node-commons/src/main/i18n/zh/org/apache/iotdb/commons/i18n/UtilMessages.java b/iotdb-core/node-commons/src/main/i18n/zh/org/apache/iotdb/commons/i18n/UtilMessages.java index dd7fa81e2bd4c..8900910f26f0c 100644 --- a/iotdb-core/node-commons/src/main/i18n/zh/org/apache/iotdb/commons/i18n/UtilMessages.java +++ b/iotdb-core/node-commons/src/main/i18n/zh/org/apache/iotdb/commons/i18n/UtilMessages.java @@ -24,4 +24,13 @@ private UtilMessages() {} public static final String EXCEPTION_FILE_CHANNEL_WRITE_MADE_NO_PROGRESS_B0F24ACD = "文件通道写入未取得进展"; + public static final String + EXCEPTION_TIMED_OUT_AFTER_ARG_MS_WAITING_FOR_THE_FIRST_EXECUTION_OF_SUBTASK_ARG_71E546A8 = + "等待子任务 %2$s 首次执行超时,已等待 %1$d 毫秒"; + public static final String + LOG_FAILED_TO_START_THE_TASK_OF_CONSENSUS_GROUP_ARG_FOR_PIPE_ARG_THE_TASK_IS_DROPPED_AND_WILL_BE_RECREATED_BY_THE_FOLLOWING_META_SYNC_7594577C = + "启动共识组 {} 的 Pipe {} 任务失败。该任务已被丢弃,将由下一次元数据同步重新创建。"; + public static final String + LOG_FAILED_TO_DROP_THE_TASK_OF_CONSENSUS_GROUP_ARG_FOR_PIPE_ARG_AFTER_IT_FAILED_TO_START_394297EC = + "启动失败后,丢弃共识组 {} 的 Pipe {} 任务时出错。"; } diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/PipeTaskAgent.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/PipeTaskAgent.java index dcb6b899a47d8..2df4ea5f1d0db 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/PipeTaskAgent.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/PipeTaskAgent.java @@ -25,6 +25,7 @@ import org.apache.iotdb.commons.exception.pipe.PipeRuntimeCriticalException; import org.apache.iotdb.commons.exception.pipe.PipeRuntimeException; import org.apache.iotdb.commons.exception.pipe.PipeRuntimeSinkCriticalException; +import org.apache.iotdb.commons.i18n.UtilMessages; import org.apache.iotdb.commons.pipe.agent.task.meta.PipeMeta; import org.apache.iotdb.commons.pipe.agent.task.meta.PipeMetaKeeper; import org.apache.iotdb.commons.pipe.agent.task.meta.PipeRuntimeMeta; @@ -52,6 +53,7 @@ import java.util.Arrays; import java.util.Collection; import java.util.Collections; +import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; @@ -721,9 +723,29 @@ protected void startPipe(final String pipeName, final long creationTime) { return; } + final List tasksToStart = new ArrayList<>(pipeTasks.size()); + final Map taskToRegionId = new IdentityHashMap<>(); + pipeTasks.forEach( + (regionId, pipeTask) -> { + tasksToStart.add(pipeTask); + taskToRegionId.put(pipeTask, regionId); + }); + // Trigger start() method for each pipe task by parallel stream final long startTime = System.currentTimeMillis(); - runPipeTasks(pipeTasks.values(), PipeTask::start); + runPipeTasks( + tasksToStart, + pipeTask -> { + try { + pipeTask.start(); + } catch (final RuntimeException | Error e) { + final Integer regionId = taskToRegionId.get(pipeTask); + if (regionId != null) { + rollbackPipeTask(regionId, existedPipeMeta.getStaticMeta(), e); + } + throw e; + } + }); LOGGER.info( "Start all pipe tasks on Pipe {} successfully within {} ms", pipeName, @@ -1017,9 +1039,44 @@ private void dropPipeTask(final int consensusGroupId, final PipeStaticMeta pipeS private void startPipeTask(final int consensusGroupId, final PipeStaticMeta pipeStaticMeta) { final PipeTask pipeTask = pipeTaskManager.getPipeTask(pipeStaticMeta, consensusGroupId); - if (pipeTask != null) { + if (pipeTask == null) { + return; + } + + try { pipeTask.start(); - thawRate(pipeStaticMeta.getPipeName(), pipeStaticMeta.getCreationTime()); + } catch (final RuntimeException | Error e) { + LOGGER.error( + UtilMessages + .LOG_FAILED_TO_START_THE_TASK_OF_CONSENSUS_GROUP_ARG_FOR_PIPE_ARG_THE_TASK_IS_DROPPED_AND_WILL_BE_RECREATED_BY_THE_FOLLOWING_META_SYNC_7594577C, + consensusGroupId, + pipeStaticMeta.getPipeName(), + e); + + rollbackPipeTask(consensusGroupId, pipeStaticMeta, e); + if (e instanceof Error error) { + throw error; + } + return; + } + + thawRate(pipeStaticMeta.getPipeName(), pipeStaticMeta.getCreationTime()); + } + + private void rollbackPipeTask( + final int consensusGroupId, final PipeStaticMeta pipeStaticMeta, final Throwable failure) { + try { + dropPipeTask(consensusGroupId, pipeStaticMeta); + } catch (final RuntimeException | Error e) { + if (e != failure) { + failure.addSuppressed(e); + } + LOGGER.warn( + UtilMessages + .LOG_FAILED_TO_DROP_THE_TASK_OF_CONSENSUS_GROUP_ARG_FOR_PIPE_ARG_AFTER_IT_FAILED_TO_START_394297EC, + consensusGroupId, + pipeStaticMeta.getPipeName(), + e); } } diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtask.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtask.java index b583276fa90f5..5d3a9bae7393f 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtask.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtask.java @@ -19,9 +19,12 @@ package org.apache.iotdb.commons.pipe.agent.task.subtask; +import org.apache.iotdb.commons.conf.CommonDescriptor; +import org.apache.iotdb.commons.i18n.UtilMessages; import org.apache.iotdb.commons.pipe.agent.task.execution.PipeSubtaskScheduler; import org.apache.iotdb.commons.pipe.event.EnrichedEvent; import org.apache.iotdb.pipe.api.event.Event; +import org.apache.iotdb.pipe.api.exception.PipeException; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.ListeningExecutorService; @@ -30,15 +33,21 @@ import org.slf4j.LoggerFactory; import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; public abstract class PipeSubtask implements FutureCallback, Callable, AutoCloseable { private static final Logger LOGGER = LoggerFactory.getLogger(PipeSubtask.class); + private static final long MAX_FIRST_EXECUTION_TIMEOUT_IN_MS = TimeUnit.MINUTES.toMillis(1); + // Used for identifying the subtask protected final String taskID; @@ -52,6 +61,8 @@ public abstract class PipeSubtask protected final AtomicBoolean shouldStopSubmittingSelf = new AtomicBoolean(true); protected final AtomicBoolean isClosed = new AtomicBoolean(false); protected PipeSubtaskScheduler subtaskScheduler; + private final AtomicReference firstExecutionLatch = + new AtomicReference<>(new CountDownLatch(0)); // For fail-over public static final int MAX_RETRY_TIMES = 5; @@ -72,11 +83,16 @@ public abstract void bindExecutors( @Override public Boolean call() throws Exception { + final CountDownLatch currentFirstExecutionLatch = firstExecutionLatch.get(); boolean hasAtLeastOneEventProcessed = false; try { // If the scheduler allows to schedule, then try to consume an event while (subtaskScheduler.schedule()) { + onExecutionStart(); + if (isSubmittingSelf()) { + currentFirstExecutionLatch.countDown(); + } // If the event is consumed successfully, then continue to consume the next event // otherwise, stop consuming if (!executeOnce()) { @@ -92,6 +108,35 @@ public Boolean call() throws Exception { return hasAtLeastOneEventProcessed; } + protected void onExecutionStart() {} + + public final void prepareForStart() { + firstExecutionLatch.set(new CountDownLatch(1)); + } + + public final void awaitFirstExecution() throws InterruptedException { + awaitFirstExecution(getFirstExecutionTimeoutInMs(), TimeUnit.MILLISECONDS); + } + + public final void awaitFirstExecution(final long timeout, final TimeUnit timeUnit) + throws InterruptedException { + if (!firstExecutionLatch.get().await(timeout, timeUnit)) { + throw new PipeException( + String.format( + UtilMessages + .EXCEPTION_TIMED_OUT_AFTER_ARG_MS_WAITING_FOR_THE_FIRST_EXECUTION_OF_SUBTASK_ARG_71E546A8, + timeUnit.toMillis(timeout), + getDisplayTaskID()), + new TimeoutException()); + } + } + + public static long getFirstExecutionTimeoutInMs() { + return Math.min( + MAX_FIRST_EXECUTION_TIMEOUT_IN_MS, + Math.max(1L, CommonDescriptor.getInstance().getConfig().getDnConnectionTimeoutInMS() / 6L)); + } + /** Should be synchronized with {@link PipeSubtask#decreaseReferenceCountAndReleaseLastEvent} */ protected synchronized void setLastEvent(final Event event) { lastEvent = event; diff --git a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/agent/task/PipeTaskAgentTest.java b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/agent/task/PipeTaskAgentTest.java index b6766425f9904..64e5894422677 100644 --- a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/agent/task/PipeTaskAgentTest.java +++ b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/agent/task/PipeTaskAgentTest.java @@ -20,21 +20,27 @@ package org.apache.iotdb.commons.pipe.agent.task; import org.apache.iotdb.common.rpc.thrift.TPipeHeartbeatResp; +import org.apache.iotdb.commons.consensus.index.impl.MinimumProgressIndex; import org.apache.iotdb.commons.pipe.agent.task.meta.PipeMeta; import org.apache.iotdb.commons.pipe.agent.task.meta.PipeRuntimeMeta; import org.apache.iotdb.commons.pipe.agent.task.meta.PipeStaticMeta; +import org.apache.iotdb.commons.pipe.agent.task.meta.PipeStatus; +import org.apache.iotdb.commons.pipe.agent.task.meta.PipeTaskMeta; import org.apache.iotdb.commons.pipe.agent.task.progress.CommitterKey; import org.apache.iotdb.commons.pipe.agent.task.progress.PipeEventCommitManager; import org.apache.iotdb.commons.pipe.sink.limiter.PipeEndPointRateLimiter; import org.apache.iotdb.commons.pipe.sink.protocol.IoTDBSink; import org.apache.iotdb.mpp.rpc.thrift.TPipeHeartbeatReq; +import org.apache.iotdb.pipe.api.exception.PipeException; import org.apache.thrift.TException; import org.apache.tsfile.utils.Pair; import org.junit.Assert; import org.junit.Test; +import org.mockito.Mockito; import java.lang.reflect.Field; +import java.lang.reflect.Method; import java.util.Collection; import java.util.HashMap; import java.util.Map; @@ -50,6 +56,63 @@ public class PipeTaskAgentTest { + private static final int TEST_REGION_ID = 7; + + @Test + public void testFailedTaskStartIsRolledBackForRetry() throws Exception { + final DummyPipeTaskAgent agent = new DummyPipeTaskAgent(); + final PipeMeta pipeMeta = generatePipeMeta("failedStartPipe", 1L); + pipeMeta.getRuntimeMeta().getStatus().set(PipeStatus.RUNNING); + pipeMeta + .getRuntimeMeta() + .getConsensusGroupId2TaskMetaMap() + .put(TEST_REGION_ID, new PipeTaskMeta(MinimumProgressIndex.INSTANCE, 1)); + agent.createPipeForTest(pipeMeta); + + final PipeException startFailure = new PipeException("failed to start the task"); + final IllegalStateException dropFailure = new IllegalStateException("failed to drop"); + final PipeTask failedTask = Mockito.mock(PipeTask.class); + Mockito.doThrow(startFailure).when(failedTask).start(); + Mockito.doThrow(dropFailure).when(failedTask).drop(); + agent.pipeTaskManager.addPipeTask(pipeMeta.getStaticMeta(), TEST_REGION_ID, failedTask); + + final Method startPipeTask = + PipeTaskAgent.class.getDeclaredMethod("startPipeTask", int.class, PipeStaticMeta.class); + startPipeTask.setAccessible(true); + startPipeTask.invoke(agent, TEST_REGION_ID, pipeMeta.getStaticMeta()); + + Mockito.verify(failedTask).drop(); + Assert.assertNull(agent.pipeTaskManager.getPipeTask(pipeMeta.getStaticMeta(), TEST_REGION_ID)); + Assert.assertNull( + pipeMeta.getRuntimeMeta().getConsensusGroupId2TaskMetaMap().get(TEST_REGION_ID)); + Assert.assertEquals(PipeStatus.RUNNING, pipeMeta.getRuntimeMeta().getStatus().get()); + Assert.assertArrayEquals(new Throwable[] {dropFailure}, startFailure.getSuppressed()); + } + + @Test + public void testFailedTaskStartFromPipeStartIsRemovedForMetaSyncRetry() { + final DummyPipeTaskAgent agent = new DummyPipeTaskAgent(); + final PipeMeta pipeMeta = generatePipeMeta("failedStartPipe", 1L); + pipeMeta.getRuntimeMeta().getStatus().set(PipeStatus.STOPPED); + pipeMeta + .getRuntimeMeta() + .getConsensusGroupId2TaskMetaMap() + .put(TEST_REGION_ID, new PipeTaskMeta(MinimumProgressIndex.INSTANCE, 1)); + agent.createPipeForTest(pipeMeta); + + final PipeTask failedTask = Mockito.mock(PipeTask.class); + Mockito.doThrow(new PipeException("failed to start the task")).when(failedTask).start(); + agent.pipeTaskManager.addPipeTask(pipeMeta.getStaticMeta(), TEST_REGION_ID, failedTask); + + Assert.assertThrows(PipeException.class, () -> agent.startPipeForTest("failedStartPipe", 1L)); + + Mockito.verify(failedTask).drop(); + Assert.assertNull(agent.pipeTaskManager.getPipeTask(pipeMeta.getStaticMeta(), TEST_REGION_ID)); + Assert.assertNull( + pipeMeta.getRuntimeMeta().getConsensusGroupId2TaskMetaMap().get(TEST_REGION_ID)); + Assert.assertEquals(PipeStatus.STOPPED, pipeMeta.getRuntimeMeta().getStatus().get()); + } + @Test public void testFloatingMemoryUsageSurvivesDropUntilLateRelease() { final DummyPipeTaskAgent agent = new DummyPipeTaskAgent(); @@ -304,6 +367,10 @@ private static boolean waitForDrop( private static class DummyPipeTaskAgent extends PipeTaskAgent { + private void startPipeForTest(final String pipeName, final long creationTime) { + startPipe(pipeName, creationTime); + } + private void createPipeForTest(final PipeMeta pipeMeta) { pipeTaskManager.addPipeTasks(pipeMeta.getStaticMeta(), new HashMap<>()); pipeMetaKeeper.addPipeMeta(pipeMeta.getStaticMeta().getPipeName(), pipeMeta); diff --git a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtaskTest.java b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtaskTest.java new file mode 100644 index 0000000000000..ebbf1da1b0caf --- /dev/null +++ b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtaskTest.java @@ -0,0 +1,147 @@ +/* + * 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.iotdb.commons.pipe.agent.task.subtask; + +import org.apache.iotdb.commons.conf.CommonDescriptor; +import org.apache.iotdb.commons.pipe.agent.task.execution.PipeSubtaskScheduler; +import org.apache.iotdb.pipe.api.exception.PipeException; + +import com.google.common.util.concurrent.ListeningExecutorService; +import com.google.common.util.concurrent.ListeningScheduledExecutorService; +import org.junit.Assert; +import org.junit.Test; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class PipeSubtaskTest { + + @Test + public void testFirstExecutionTimeoutTracksDataNodeConnectionTimeout() { + final int previousTimeout = + CommonDescriptor.getInstance().getConfig().getDnConnectionTimeoutInMS(); + try { + CommonDescriptor.getInstance().getConfig().setDnConnectionTimeoutInMS(12_000); + Assert.assertEquals(2_000L, PipeSubtask.getFirstExecutionTimeoutInMs()); + } finally { + CommonDescriptor.getInstance().getConfig().setDnConnectionTimeoutInMS(previousTimeout); + } + } + + @Test + public void testFirstExecutionSignalIsResetForEachStart() throws Exception { + final TestSubtask subtask = new TestSubtask(); + final ExecutorService workerExecutor = Executors.newSingleThreadExecutor(); + try { + for (int startCount = 0; startCount < 2; startCount++) { + subtask.prepareForStart(); + subtask.allowSubmittingSelf(); + Assert.assertThrows( + PipeException.class, () -> subtask.awaitFirstExecution(1, TimeUnit.MILLISECONDS)); + subtask.scheduleOneExecution(); + + final Future execution = workerExecutor.submit(subtask); + subtask.awaitFirstExecution(1, TimeUnit.SECONDS); + Assert.assertFalse(execution.get(1, TimeUnit.SECONDS)); + subtask.disallowSubmittingSelf(); + } + } finally { + workerExecutor.shutdownNow(); + } + } + + @Test + public void testStoppedQueuedExecutionDoesNotSatisfyNextStart() throws Exception { + final TestSubtask subtask = new TestSubtask(); + final ExecutorService workerExecutor = Executors.newSingleThreadExecutor(); + final CountDownLatch queuedWorkerReady = new CountDownLatch(1); + final CountDownLatch allowQueuedWorkerToRun = new CountDownLatch(1); + try { + subtask.prepareForStart(); + subtask.allowSubmittingSelf(); + subtask.scheduleOneExecution(); + final Future queuedExecution = + workerExecutor.submit( + () -> { + queuedWorkerReady.countDown(); + allowQueuedWorkerToRun.await(); + return subtask.call(); + }); + Assert.assertTrue(queuedWorkerReady.await(1, TimeUnit.SECONDS)); + + subtask.disallowSubmittingSelf(); + subtask.prepareForStart(); + allowQueuedWorkerToRun.countDown(); + + Assert.assertFalse(queuedExecution.get(1, TimeUnit.SECONDS)); + Assert.assertThrows( + PipeException.class, () -> subtask.awaitFirstExecution(1, TimeUnit.MILLISECONDS)); + + subtask.allowSubmittingSelf(); + subtask.scheduleOneExecution(); + final Future currentExecution = workerExecutor.submit(subtask); + subtask.awaitFirstExecution(1, TimeUnit.SECONDS); + Assert.assertFalse(currentExecution.get(1, TimeUnit.SECONDS)); + } finally { + allowQueuedWorkerToRun.countDown(); + workerExecutor.shutdownNow(); + } + } + + private static class TestSubtask extends PipeSubtask { + + private final PipeSubtaskScheduler scheduler; + + private TestSubtask() { + super("test", 0); + scheduler = mock(PipeSubtaskScheduler.class); + subtaskScheduler = scheduler; + } + + private void scheduleOneExecution() { + when(scheduler.schedule()).thenReturn(true, false); + } + + @Override + public void bindExecutors( + final ListeningExecutorService workerExecutor, + final ListeningScheduledExecutorService scheduledExecutor, + final ExecutorService callbackExecutor, + final PipeSubtaskScheduler scheduler) { + subtaskScheduler = scheduler; + } + + @Override + protected boolean executeOnce() { + return false; + } + + @Override + public void submitSelf() {} + + @Override + public void onFailure(final Throwable throwable) {} + } +} From 1302c946501b3a85f033f4a68f52f6df985c3426 Mon Sep 17 00:00:00 2001 From: Caideyipi <87789683+Caideyipi@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:45:59 +0800 Subject: [PATCH 2/4] Fix PipeSubtask compile error in 1.3 backport --- .../iotdb/commons/pipe/agent/task/subtask/PipeSubtask.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtask.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtask.java index 5d3a9bae7393f..441d581f9ac5d 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtask.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtask.java @@ -126,7 +126,7 @@ public final void awaitFirstExecution(final long timeout, final TimeUnit timeUni UtilMessages .EXCEPTION_TIMED_OUT_AFTER_ARG_MS_WAITING_FOR_THE_FIRST_EXECUTION_OF_SUBTASK_ARG_71E546A8, timeUnit.toMillis(timeout), - getDisplayTaskID()), + getTaskID()), new TimeoutException()); } } From 847e0598dcbcc607933b262b7a8f7d41e07509cb Mon Sep 17 00:00:00 2001 From: Caideyipi <87789683+Caideyipi@users.noreply.github.com> Date: Wed, 2 Dec 2026 17:01:36 +0800 Subject: [PATCH 3/4] Fix Pipe task startup when subtasks are starved --- .../sink/PipeSinkSubtaskLifeCycle.java | 8 +++--- .../subtask/sink/PipeSinkSubtaskManager.java | 6 +++-- .../iotdb/commons/i18n/UtilMessages.java | 4 +-- .../iotdb/commons/i18n/UtilMessages.java | 4 +-- .../pipe/agent/task/subtask/PipeSubtask.java | 25 +++++++++---------- .../agent/task/subtask/PipeSubtaskTest.java | 11 +++----- 6 files changed, 28 insertions(+), 30 deletions(-) diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskLifeCycle.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskLifeCycle.java index f5c678037c814..8054af30c26bc 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskLifeCycle.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskLifeCycle.java @@ -142,13 +142,13 @@ public synchronized void start() { registeredTaskCount); } - public void awaitFirstExecution() throws InterruptedException { - subtask.awaitFirstExecution(); + public boolean awaitFirstExecution() throws InterruptedException { + return subtask.awaitFirstExecution(); } - public void awaitFirstExecution(final long timeout, final TimeUnit timeUnit) + public boolean awaitFirstExecution(final long timeout, final TimeUnit timeUnit) throws InterruptedException { - subtask.awaitFirstExecution(timeout, timeUnit); + return subtask.awaitFirstExecution(timeout, timeUnit); } public synchronized void stop() { diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskManager.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskManager.java index 50bab06c277c0..fc1d6c6b36dec 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskManager.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskManager.java @@ -249,8 +249,10 @@ private void awaitFirstExecution(final List lifeCycles System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(PipeSubtask.getFirstExecutionTimeoutInMs()); for (final PipeSinkSubtaskLifeCycle lifeCycle : lifeCycles) { - lifeCycle.awaitFirstExecution( - Math.max(0L, deadlineNanos - System.nanoTime()), TimeUnit.NANOSECONDS); + if (!lifeCycle.awaitFirstExecution( + Math.max(0L, deadlineNanos - System.nanoTime()), TimeUnit.NANOSECONDS)) { + return; + } } } catch (final InterruptedException e) { Thread.currentThread().interrupt(); diff --git a/iotdb-core/node-commons/src/main/i18n/en/org/apache/iotdb/commons/i18n/UtilMessages.java b/iotdb-core/node-commons/src/main/i18n/en/org/apache/iotdb/commons/i18n/UtilMessages.java index b6fb1e1b26e48..7f7ea9487a453 100644 --- a/iotdb-core/node-commons/src/main/i18n/en/org/apache/iotdb/commons/i18n/UtilMessages.java +++ b/iotdb-core/node-commons/src/main/i18n/en/org/apache/iotdb/commons/i18n/UtilMessages.java @@ -25,8 +25,8 @@ private UtilMessages() {} public static final String EXCEPTION_FILE_CHANNEL_WRITE_MADE_NO_PROGRESS_B0F24ACD = "File channel write made no progress"; public static final String - EXCEPTION_TIMED_OUT_AFTER_ARG_MS_WAITING_FOR_THE_FIRST_EXECUTION_OF_SUBTASK_ARG_71E546A8 = - "Timed out after %d ms waiting for the first execution of subtask %s"; + LOG_TIMED_OUT_AFTER_ARG_MS_WAITING_FOR_THE_FIRST_EXECUTION_OF_SUBTASK_ARG_CONTINUING_TASK_STARTUP_48AA75E6 = + "Timed out after %d ms waiting for the first execution of subtask %s; continuing task startup"; public static final String LOG_FAILED_TO_START_THE_TASK_OF_CONSENSUS_GROUP_ARG_FOR_PIPE_ARG_THE_TASK_IS_DROPPED_AND_WILL_BE_RECREATED_BY_THE_FOLLOWING_META_SYNC_7594577C = "Failed to start the task of consensus group {} for pipe {}. The task is dropped and " diff --git a/iotdb-core/node-commons/src/main/i18n/zh/org/apache/iotdb/commons/i18n/UtilMessages.java b/iotdb-core/node-commons/src/main/i18n/zh/org/apache/iotdb/commons/i18n/UtilMessages.java index 8900910f26f0c..70852511f3601 100644 --- a/iotdb-core/node-commons/src/main/i18n/zh/org/apache/iotdb/commons/i18n/UtilMessages.java +++ b/iotdb-core/node-commons/src/main/i18n/zh/org/apache/iotdb/commons/i18n/UtilMessages.java @@ -25,8 +25,8 @@ private UtilMessages() {} public static final String EXCEPTION_FILE_CHANNEL_WRITE_MADE_NO_PROGRESS_B0F24ACD = "文件通道写入未取得进展"; public static final String - EXCEPTION_TIMED_OUT_AFTER_ARG_MS_WAITING_FOR_THE_FIRST_EXECUTION_OF_SUBTASK_ARG_71E546A8 = - "等待子任务 %2$s 首次执行超时,已等待 %1$d 毫秒"; + LOG_TIMED_OUT_AFTER_ARG_MS_WAITING_FOR_THE_FIRST_EXECUTION_OF_SUBTASK_ARG_CONTINUING_TASK_STARTUP_48AA75E6 = + "等待子任务 %2$s 首次执行超时,已等待 %1$d 毫秒;继续启动任务"; public static final String LOG_FAILED_TO_START_THE_TASK_OF_CONSENSUS_GROUP_ARG_FOR_PIPE_ARG_THE_TASK_IS_DROPPED_AND_WILL_BE_RECREATED_BY_THE_FOLLOWING_META_SYNC_7594577C = "启动共识组 {} 的 Pipe {} 任务失败。该任务已被丢弃,将由下一次元数据同步重新创建。"; diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtask.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtask.java index 441d581f9ac5d..6deb492dbaaf4 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtask.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtask.java @@ -24,7 +24,6 @@ import org.apache.iotdb.commons.pipe.agent.task.execution.PipeSubtaskScheduler; import org.apache.iotdb.commons.pipe.event.EnrichedEvent; import org.apache.iotdb.pipe.api.event.Event; -import org.apache.iotdb.pipe.api.exception.PipeException; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.ListeningExecutorService; @@ -36,7 +35,6 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; @@ -114,21 +112,22 @@ public final void prepareForStart() { firstExecutionLatch.set(new CountDownLatch(1)); } - public final void awaitFirstExecution() throws InterruptedException { - awaitFirstExecution(getFirstExecutionTimeoutInMs(), TimeUnit.MILLISECONDS); + public final boolean awaitFirstExecution() throws InterruptedException { + return awaitFirstExecution(getFirstExecutionTimeoutInMs(), TimeUnit.MILLISECONDS); } - public final void awaitFirstExecution(final long timeout, final TimeUnit timeUnit) + public final boolean awaitFirstExecution(final long timeout, final TimeUnit timeUnit) throws InterruptedException { - if (!firstExecutionLatch.get().await(timeout, timeUnit)) { - throw new PipeException( - String.format( - UtilMessages - .EXCEPTION_TIMED_OUT_AFTER_ARG_MS_WAITING_FOR_THE_FIRST_EXECUTION_OF_SUBTASK_ARG_71E546A8, - timeUnit.toMillis(timeout), - getTaskID()), - new TimeoutException()); + if (firstExecutionLatch.get().await(timeout, timeUnit)) { + return true; } + LOGGER.warn( + String.format( + UtilMessages + .LOG_TIMED_OUT_AFTER_ARG_MS_WAITING_FOR_THE_FIRST_EXECUTION_OF_SUBTASK_ARG_CONTINUING_TASK_STARTUP_48AA75E6, + timeUnit.toMillis(timeout), + getTaskID())); + return false; } public static long getFirstExecutionTimeoutInMs() { diff --git a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtaskTest.java b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtaskTest.java index ebbf1da1b0caf..b8879520f0ff2 100644 --- a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtaskTest.java +++ b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtaskTest.java @@ -20,7 +20,6 @@ import org.apache.iotdb.commons.conf.CommonDescriptor; import org.apache.iotdb.commons.pipe.agent.task.execution.PipeSubtaskScheduler; -import org.apache.iotdb.pipe.api.exception.PipeException; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.ListeningScheduledExecutorService; @@ -58,12 +57,11 @@ public void testFirstExecutionSignalIsResetForEachStart() throws Exception { for (int startCount = 0; startCount < 2; startCount++) { subtask.prepareForStart(); subtask.allowSubmittingSelf(); - Assert.assertThrows( - PipeException.class, () -> subtask.awaitFirstExecution(1, TimeUnit.MILLISECONDS)); + Assert.assertFalse(subtask.awaitFirstExecution(1, TimeUnit.MILLISECONDS)); subtask.scheduleOneExecution(); final Future execution = workerExecutor.submit(subtask); - subtask.awaitFirstExecution(1, TimeUnit.SECONDS); + Assert.assertTrue(subtask.awaitFirstExecution(1, TimeUnit.SECONDS)); Assert.assertFalse(execution.get(1, TimeUnit.SECONDS)); subtask.disallowSubmittingSelf(); } @@ -96,13 +94,12 @@ public void testStoppedQueuedExecutionDoesNotSatisfyNextStart() throws Exception allowQueuedWorkerToRun.countDown(); Assert.assertFalse(queuedExecution.get(1, TimeUnit.SECONDS)); - Assert.assertThrows( - PipeException.class, () -> subtask.awaitFirstExecution(1, TimeUnit.MILLISECONDS)); + Assert.assertFalse(subtask.awaitFirstExecution(1, TimeUnit.MILLISECONDS)); subtask.allowSubmittingSelf(); subtask.scheduleOneExecution(); final Future currentExecution = workerExecutor.submit(subtask); - subtask.awaitFirstExecution(1, TimeUnit.SECONDS); + Assert.assertTrue(subtask.awaitFirstExecution(1, TimeUnit.SECONDS)); Assert.assertFalse(currentExecution.get(1, TimeUnit.SECONDS)); } finally { allowQueuedWorkerToRun.countDown(); From 0aeecc1b65fedd93c40fa63ab855de5a317c6d51 Mon Sep 17 00:00:00 2001 From: Caideyipi <87789683+Caideyipi@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:51:28 +0800 Subject: [PATCH 4/4] Fix pipe task startup review findings --- .../db/pipe/agent/task/PipeDataNodeTask.java | 19 +++ .../task/stage/PipeTaskProcessorStage.java | 13 +- .../agent/task/stage/PipeTaskSinkStage.java | 5 + .../subtask/sink/PipeSinkSubtaskManager.java | 27 +++- .../pipe/agent/task/PipeDataNodeTaskTest.java | 57 +++++++++ .../commons/pipe/agent/task/PipeTask.java | 2 + .../pipe/agent/task/PipeTaskAgent.java | 109 +++++++++++++++- .../pipe/agent/task/stage/PipeTaskStage.java | 2 + .../pipe/agent/task/PipeTaskAgentTest.java | 118 +++++++++++++++++- 9 files changed, 335 insertions(+), 17 deletions(-) diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTask.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTask.java index bccf939fd281c..2e80848b8064c 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTask.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTask.java @@ -116,6 +116,25 @@ public synchronized void start() { System.currentTimeMillis() - startTime); } + @Override + public void awaitFirstExecution() { + try { + sinkStage.awaitFirstExecution(); + processorStage.awaitFirstExecution(); + } catch (final RuntimeException | Error e) { + for (final PipeTaskStage startedStage : List.of(sourceStage, processorStage, sinkStage)) { + try { + startedStage.stop(); + } catch (final RuntimeException | Error stopException) { + if (stopException != e) { + e.addSuppressed(stopException); + } + } + } + throw e; + } + } + @Override public synchronized void stop() { final long startTime = System.currentTimeMillis(); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskProcessorStage.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskProcessorStage.java index 5f50a35eac372..09204e243e3b6 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskProcessorStage.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskProcessorStage.java @@ -134,14 +134,19 @@ public void startSubtask() throws PipeException { pipeProcessorSubtask.prepareForStart(); try { executor.start(pipeProcessorSubtask.getTaskID()); + } catch (final RuntimeException | Error e) { + stopAfterFailedStart(e); + throw e; + } + } + + @Override + public void awaitFirstExecution() { + try { pipeProcessorSubtask.awaitFirstExecution(); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); - stopAfterFailedStart(e); throw new PipeException(e.getMessage(), e); - } catch (final RuntimeException | Error e) { - stopAfterFailedStart(e); - throw e; } } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSinkStage.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSinkStage.java index 2bbcc1248d8d1..f8673f482cda2 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSinkStage.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSinkStage.java @@ -74,6 +74,11 @@ public void startSubtask() throws PipeException { PipeSinkSubtaskManager.instance().start(pipeName, creationTime, sinkSubtaskId); } + @Override + public void awaitFirstExecution() { + PipeSinkSubtaskManager.instance().awaitFirstExecution(pipeName, creationTime, sinkSubtaskId); + } + @Override public void stopSubtask() throws PipeException { PipeSinkSubtaskManager.instance().stop(pipeName, creationTime, sinkSubtaskId); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskManager.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskManager.java index fc1d6c6b36dec..28d7b49c5f5f7 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskManager.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskManager.java @@ -226,7 +226,20 @@ public void start( lifeCycles = new ArrayList<>(pipeSinkSubtaskKey2SubtaskLifeCycleMap.get(pipeSinkSubtaskKey)); startLifeCycles(lifeCycles); } + } + + public void awaitFirstExecution( + final String pipeName, final long creationTime, final String attributeSortedString) { + final PipeSinkSubtaskKey pipeSinkSubtaskKey = + new PipeSinkSubtaskKey(pipeName, creationTime, attributeSortedString); + final List lifeCycles; + synchronized (this) { + if (!pipeSinkSubtaskKey2SubtaskLifeCycleMap.containsKey(pipeSinkSubtaskKey)) { + throwNoSuchSubtaskException(pipeSinkSubtaskKey); + } + lifeCycles = new ArrayList<>(pipeSinkSubtaskKey2SubtaskLifeCycleMap.get(pipeSinkSubtaskKey)); + } awaitFirstExecution(lifeCycles); } @@ -256,11 +269,13 @@ private void awaitFirstExecution(final List lifeCycles } } catch (final InterruptedException e) { Thread.currentThread().interrupt(); - final PipeException failure = new PipeException(e.getMessage(), e); - synchronized (this) { - stopLifeCycles(lifeCycles, failure); - } - throw failure; + throw new PipeException(e.getMessage(), e); + } + } + + private void awaitFirstExecutionWithRollback(final List lifeCycles) { + try { + awaitFirstExecution(lifeCycles); } catch (final RuntimeException | Error e) { synchronized (this) { stopLifeCycles(lifeCycles, e); @@ -301,7 +316,7 @@ public void start(final String attributeSortedString) { lifeCycles = new ArrayList<>(pipeSinkSubtaskKey2SubtaskLifeCycleMap.get(pipeSinkSubtaskKey)); startLifeCycles(lifeCycles); } - awaitFirstExecution(lifeCycles); + awaitFirstExecutionWithRollback(lifeCycles); } public synchronized void stop( diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTaskTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTaskTest.java index 393cc004d0730..65b8614f77c7d 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTaskTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTaskTest.java @@ -51,6 +51,39 @@ public void testStartStartsSinkAndProcessorBeforeSource() { task.start(); Assert.assertEquals(Arrays.asList("sink", "processor", "source"), startedStages); + task.awaitFirstExecution(); + Assert.assertEquals( + Arrays.asList("sink", "processor", "source", "await-sink", "await-processor"), + startedStages); + } + + @Test + public void testFirstExecutionFailureStopsStartedStagesInReverseOrder() { + final List stageEvents = new ArrayList<>(); + final PipeDataNodeTask task = + new PipeDataNodeTask( + "pipe", + 1, + new RecordingStage("source", stageEvents), + new FailingAwaitStage( + "processor", stageEvents, new IllegalStateException("failed to await")), + new RecordingStage("sink", stageEvents)); + + task.create(); + task.start(); + + Assert.assertThrows(IllegalStateException.class, task::awaitFirstExecution); + Assert.assertEquals( + Arrays.asList( + "sink", + "processor", + "source", + "await-sink", + "await-processor", + "stop-source", + "stop-processor", + "stop-sink"), + stageEvents); } @Test @@ -135,6 +168,11 @@ private RecordingStage( @Override protected void createSubtask() {} + @Override + public void awaitFirstExecution() { + startedStages.add("await-" + stageName); + } + @Override protected void startSubtask() { startedStages.add(stageName); @@ -152,6 +190,25 @@ protected void stopSubtask() { protected void dropSubtask() {} } + private static class FailingAwaitStage extends RecordingStage { + + private final RuntimeException awaitException; + + private FailingAwaitStage( + final String stageName, + final List stageEvents, + final RuntimeException awaitException) { + super(stageName, stageEvents); + this.awaitException = awaitException; + } + + @Override + public void awaitFirstExecution() { + super.awaitFirstExecution(); + throw awaitException; + } + } + private static class BlockingStage extends RecordingStage { private final CountDownLatch startEntered; diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/PipeTask.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/PipeTask.java index f5717d780a2a7..40afb6c7e12e6 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/PipeTask.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/PipeTask.java @@ -27,5 +27,7 @@ public interface PipeTask { void start(); + default void awaitFirstExecution() {} + void stop(); } diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/PipeTaskAgent.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/PipeTaskAgent.java index 168f1b7f13c6c..d980b161ea74b 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/PipeTaskAgent.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/PipeTaskAgent.java @@ -62,6 +62,7 @@ import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; @@ -103,6 +104,7 @@ public abstract class PipeTaskAgent { protected final PipeMetaKeeper pipeMetaKeeper; protected final PipeTaskManager pipeTaskManager; + private volatile ConcurrentLinkedQueue pipeTasksToAwaitFirstExecution; private final Map pipeNameWithCreationTime2FloatingMemoryUsageInByteMap; private final Map> pipeName2CreationTimeSetMap; @@ -181,11 +183,20 @@ public TPushPipeMetaRespExceptionMessage handleSinglePipeMetaChanges( pipeName), System.currentTimeMillis()); } + final ConcurrentLinkedQueue startedPipeTasks = new ConcurrentLinkedQueue<>(); + pipeTasksToAwaitFirstExecution = startedPipeTasks; + final TPushPipeMetaRespExceptionMessage exceptionMessage; try { - return handleSinglePipeMetaChangesInternal(pipeMetaFromCoordinator); + exceptionMessage = handleSinglePipeMetaChangesInternal(pipeMetaFromCoordinator); } finally { + pipeTasksToAwaitFirstExecution = null; releaseWriteLock(); } + final List waitExceptionMessages = + awaitFirstExecutionAfterMetaChanges(startedPipeTasks, new ArrayList<>()); + return exceptionMessage != null + ? exceptionMessage + : waitExceptionMessages.isEmpty() ? null : waitExceptionMessages.get(0); } protected TPushPipeMetaRespExceptionMessage handleSinglePipeMetaChangesInternal( @@ -430,11 +441,63 @@ public List handlePipeMetaChanges( CommonDescriptor.getInstance().getConfig().getDnConnectionTimeoutInMS() * 2L / 3)) { return null; } + final ConcurrentLinkedQueue startedPipeTasks = new ConcurrentLinkedQueue<>(); + pipeTasksToAwaitFirstExecution = startedPipeTasks; + final List exceptionMessages; try { - return handlePipeMetaChangesInternal(pipeMetaListFromCoordinator); + exceptionMessages = handlePipeMetaChangesInternal(pipeMetaListFromCoordinator); } finally { + pipeTasksToAwaitFirstExecution = null; releaseWriteLock(); } + return awaitFirstExecutionAfterMetaChanges(startedPipeTasks, exceptionMessages); + } + + private List awaitFirstExecutionAfterMetaChanges( + final ConcurrentLinkedQueue startedPipeTasks, + final List exceptionMessages) { + if (startedPipeTasks.isEmpty()) { + return exceptionMessages; + } + + final List pipeTasks = new ArrayList<>(startedPipeTasks.size()); + final Map> pipeTask2StartedTasksMap = + new IdentityHashMap<>(); + for (final StartedPipeTask startedPipeTask : startedPipeTasks) { + pipeTasks.add(startedPipeTask.pipeTask()); + pipeTask2StartedTasksMap + .computeIfAbsent(startedPipeTask.pipeTask(), ignored -> new ConcurrentLinkedQueue<>()) + .add(startedPipeTask); + } + + final ConcurrentLinkedQueue waitExceptionMessages = + new ConcurrentLinkedQueue<>(); + runPipeTasks( + pipeTasks, + pipeTask -> { + final StartedPipeTask startedPipeTask = pipeTask2StartedTasksMap.get(pipeTask).poll(); + if (pipeTaskManager.getPipeTask( + startedPipeTask.pipeStaticMeta(), startedPipeTask.consensusGroupId()) + != pipeTask) { + return; + } + try { + pipeTask.awaitFirstExecution(); + } catch (final RuntimeException | Error e) { + if (rollbackPipeTaskAfterMetaChange(startedPipeTask, e)) { + waitExceptionMessages.add( + new TPushPipeMetaRespExceptionMessage( + startedPipeTask.pipeStaticMeta().getPipeName(), + Objects.toString(e.getMessage(), e.toString()), + System.currentTimeMillis())); + } + } + }); + + final List result = + exceptionMessages == null ? new ArrayList<>() : exceptionMessages; + result.addAll(waitExceptionMessages); + return result; } protected List handlePipeMetaChangesInternal( @@ -748,6 +811,10 @@ protected void startPipe(final String pipeName, final long creationTime) { pipeTask -> { try { pipeTask.start(); + final Integer regionId = taskToRegionId.get(pipeTask); + if (regionId != null) { + awaitFirstExecutionOrDefer(regionId, existedPipeMeta.getStaticMeta(), pipeTask); + } } catch (final RuntimeException | Error e) { final Integer regionId = taskToRegionId.get(pipeTask); if (regionId != null) { @@ -1055,6 +1122,7 @@ private void startPipeTask(final int consensusGroupId, final PipeStaticMeta pipe try { pipeTask.start(); + awaitFirstExecutionOrDefer(consensusGroupId, pipeStaticMeta, pipeTask); } catch (final RuntimeException | Error e) { LOGGER.error( UtilMessages @@ -1064,15 +1132,44 @@ private void startPipeTask(final int consensusGroupId, final PipeStaticMeta pipe e); rollbackPipeTask(consensusGroupId, pipeStaticMeta, e); - if (e instanceof Error error) { - throw error; - } - return; + throw e; } thawRate(pipeStaticMeta.getPipeName(), pipeStaticMeta.getCreationTime()); } + private void awaitFirstExecutionOrDefer( + final int consensusGroupId, final PipeStaticMeta pipeStaticMeta, final PipeTask pipeTask) { + final StartedPipeTask startedPipeTask = + new StartedPipeTask(consensusGroupId, pipeStaticMeta, pipeTask); + final ConcurrentLinkedQueue pendingTasks = pipeTasksToAwaitFirstExecution; + if (pendingTasks == null) { + pipeTask.awaitFirstExecution(); + } else { + pendingTasks.add(startedPipeTask); + } + } + + private boolean rollbackPipeTaskAfterMetaChange( + final StartedPipeTask startedPipeTask, final Throwable failure) { + acquireWriteLock(); + try { + if (pipeTaskManager.getPipeTask( + startedPipeTask.pipeStaticMeta(), startedPipeTask.consensusGroupId()) + != startedPipeTask.pipeTask()) { + return false; + } + rollbackPipeTask( + startedPipeTask.consensusGroupId(), startedPipeTask.pipeStaticMeta(), failure); + return true; + } finally { + releaseWriteLock(); + } + } + + private record StartedPipeTask( + int consensusGroupId, PipeStaticMeta pipeStaticMeta, PipeTask pipeTask) {} + private void rollbackPipeTask( final int consensusGroupId, final PipeStaticMeta pipeStaticMeta, final Throwable failure) { try { diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/stage/PipeTaskStage.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/stage/PipeTaskStage.java index d315787611273..6bd89580cda67 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/stage/PipeTaskStage.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/stage/PipeTaskStage.java @@ -88,6 +88,8 @@ public synchronized void start() { status = PipeStatus.RUNNING; } + public void awaitFirstExecution() {} + protected abstract void startSubtask() throws PipeException; /** diff --git a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/agent/task/PipeTaskAgentTest.java b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/agent/task/PipeTaskAgentTest.java index 96d0ad4ea905c..392ec4b3e34e7 100644 --- a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/agent/task/PipeTaskAgentTest.java +++ b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/agent/task/PipeTaskAgentTest.java @@ -31,6 +31,7 @@ import org.apache.iotdb.commons.pipe.sink.limiter.PipeEndPointRateLimiter; import org.apache.iotdb.commons.pipe.sink.protocol.IoTDBSink; import org.apache.iotdb.mpp.rpc.thrift.TPipeHeartbeatReq; +import org.apache.iotdb.mpp.rpc.thrift.TPushPipeMetaRespExceptionMessage; import org.apache.iotdb.pipe.api.exception.PipeException; import org.apache.thrift.TException; @@ -40,12 +41,17 @@ import org.mockito.Mockito; import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collection; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; @@ -79,8 +85,12 @@ public void testFailedTaskStartIsRolledBackForRetry() throws Exception { final Method startPipeTask = PipeTaskAgent.class.getDeclaredMethod("startPipeTask", int.class, PipeStaticMeta.class); startPipeTask.setAccessible(true); - startPipeTask.invoke(agent, TEST_REGION_ID, pipeMeta.getStaticMeta()); + final InvocationTargetException exception = + Assert.assertThrows( + InvocationTargetException.class, + () -> startPipeTask.invoke(agent, TEST_REGION_ID, pipeMeta.getStaticMeta())); + Assert.assertSame(startFailure, exception.getCause()); Mockito.verify(failedTask).drop(); Assert.assertNull(agent.pipeTaskManager.getPipeTask(pipeMeta.getStaticMeta(), TEST_REGION_ID)); Assert.assertNull( @@ -113,6 +123,85 @@ public void testFailedTaskStartFromPipeStartIsRemovedForMetaSyncRetry() { Assert.assertEquals(PipeStatus.STOPPED, pipeMeta.getRuntimeMeta().getStatus().get()); } + @Test + public void testFailedTaskStartIsReportedByMetaSync() { + final PipeTask failedTask = Mockito.mock(PipeTask.class); + Mockito.doThrow(new PipeException("failed to start the task")).when(failedTask).start(); + + final WaitingPipeTaskAgent agent = new WaitingPipeTaskAgent(failedTask); + final PipeMeta pipeMeta = generatePipeMeta("failedStartPipe", 1L); + pipeMeta.getRuntimeMeta().getStatus().set(PipeStatus.RUNNING); + pipeMeta + .getRuntimeMeta() + .getConsensusGroupId2TaskMetaMap() + .put(TEST_REGION_ID, new PipeTaskMeta(MinimumProgressIndex.INSTANCE, 1)); + + final List exceptionMessages = + agent.handlePipeMetaChanges(List.of(pipeMeta)); + + Assert.assertEquals(1, exceptionMessages.size()); + Assert.assertTrue(exceptionMessages.get(0).getMessage().contains("failed to start")); + Mockito.verify(failedTask).drop(); + Assert.assertNull(agent.pipeTaskManager.getPipeTask(pipeMeta.getStaticMeta(), TEST_REGION_ID)); + } + + @Test + public void testBatchFirstExecutionWaitDoesNotHoldWriteLockAndReportsFailure() throws Exception { + assertFirstExecutionWaitDoesNotHoldWriteLockAndReportsFailure(false); + } + + @Test + public void testSingleFirstExecutionWaitDoesNotHoldWriteLockAndReportsFailure() throws Exception { + assertFirstExecutionWaitDoesNotHoldWriteLockAndReportsFailure(true); + } + + private void assertFirstExecutionWaitDoesNotHoldWriteLockAndReportsFailure( + final boolean singlePipeMetaChange) throws Exception { + final CountDownLatch firstExecutionWaitEntered = new CountDownLatch(1); + final CountDownLatch allowFirstExecutionWaitToFinish = new CountDownLatch(1); + final PipeException waitFailure = new PipeException("failed to await first execution"); + final PipeTask waitingTask = Mockito.mock(PipeTask.class); + Mockito.doAnswer( + invocation -> { + firstExecutionWaitEntered.countDown(); + Assert.assertTrue(allowFirstExecutionWaitToFinish.await(10, TimeUnit.SECONDS)); + throw waitFailure; + }) + .when(waitingTask) + .awaitFirstExecution(); + + final WaitingPipeTaskAgent agent = new WaitingPipeTaskAgent(waitingTask); + final PipeMeta pipeMeta = generatePipeMeta("waitOutsideLock", 1L); + pipeMeta.getRuntimeMeta().getStatus().set(PipeStatus.RUNNING); + pipeMeta + .getRuntimeMeta() + .getConsensusGroupId2TaskMetaMap() + .put(TEST_REGION_ID, new PipeTaskMeta(MinimumProgressIndex.INSTANCE, 1)); + + final ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + final Future> metaChange = + executor.submit( + () -> { + if (!singlePipeMetaChange) { + return agent.handlePipeMetaChanges(List.of(pipeMeta)); + } + final TPushPipeMetaRespExceptionMessage exceptionMessage = + agent.handleSinglePipeMetaChangesForTest(pipeMeta); + return exceptionMessage == null ? List.of() : List.of(exceptionMessage); + }); + Assert.assertTrue(firstExecutionWaitEntered.await(10, TimeUnit.SECONDS)); + Assert.assertTrue(agent.canAcquireReadLockForTest()); + + allowFirstExecutionWaitToFinish.countDown(); + Assert.assertEquals(1, metaChange.get(10, TimeUnit.SECONDS).size()); + Mockito.verify(waitingTask).start(); + } finally { + allowFirstExecutionWaitToFinish.countDown(); + executor.shutdownNow(); + } + } + @Test public void testFloatingMemoryUsageSurvivesDropUntilLateRelease() { final DummyPipeTaskAgent agent = new DummyPipeTaskAgent(); @@ -427,6 +516,11 @@ private void createPipeForTest(final PipeMeta pipeMeta) { pipeMetaKeeper.addPipeMeta(pipeMeta.getStaticMeta().getPipeName(), pipeMeta); } + protected TPushPipeMetaRespExceptionMessage handleSinglePipeMetaChangesForTest( + final PipeMeta pipeMeta) { + return handleSinglePipeMetaChanges(pipeMeta); + } + private boolean dropPipeForTest(final String pipeName, final long creationTime) { return dropPipe(pipeName, creationTime); } @@ -442,6 +536,14 @@ private PipeMeta getPipeMetaForTest(final String pipeName, final long creationTi : null; } + boolean canAcquireReadLockForTest() { + if (!tryReadLockWithTimeOutInMs(100)) { + return false; + } + releaseReadLock(); + return true; + } + @Override protected boolean isShutdown() { return false; @@ -483,6 +585,20 @@ public void runPipeTasks( } } + private static class WaitingPipeTaskAgent extends DummyPipeTaskAgent { + + private final PipeTask pipeTask; + + private WaitingPipeTaskAgent(final PipeTask pipeTask) { + this.pipeTask = pipeTask; + } + + @Override + protected Map buildPipeTasks(final PipeMeta pipeMetaFromCoordinator) { + return Map.of(TEST_REGION_ID, pipeTask); + } + } + private static class FailingDropPipeTaskAgent extends DummyPipeTaskAgent { @Override