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 42f2f59673d2 CAMEL-27587: camel-master - a late start of the delegated 
consumer no longer replaces the consumer of a restarted MasterConsumer (#30909)
42f2f59673d2 is described below

commit 42f2f59673d2a6767697c7fc653527dcf92337f5
Author: allthingssecurity <[email protected]>
AuthorDate: Fri Nov 27 20:25:49 2026 +0530

    CAMEL-27587: camel-master - a late start of the delegated consumer no 
longer replaces the consumer of a restarted MasterConsumer (#30909)
    
    A start of the delegated consumer that did not stop on the interrupt of 
doStop
    kept running after stop() returned. When the same MasterConsumer was started
    again, the new lifecycle started a second delegated consumer, and the late
    start then published its consumer over it: the second one kept running
    unreferenced, also after the leadership was lost and after the next stop.
    
    The start task now publishes its consumer only while it is still the current
    task and no delegated consumer is set; otherwise it only stops (does not 
shut
    down) its own consumer, and not the delegated endpoint, which a newer 
consumer
    may use. As stopping a consumer also stops the processor of the route, the
    processor is started again whenever this master consumer is running. A late
    start after the leadership was lost and taken again within the same 
lifecycle
    publishes its consumer, as before. doStop waits for a start that is
    still running (shutdownGraceful of the leadership pool, bounded by the
    shutdownAwaitTermination of the ExecutorServiceManager) before it stops the
    delegated consumer, so the delegate no longer finishes starting after the
    route stopped.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../camel/component/master/MasterConsumer.java     |  53 ++++--
 .../master/MasterConsumerLeadershipTest.java       | 209 ++++++++++++++++++++-
 .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc    |  10 +
 3 files changed, 259 insertions(+), 13 deletions(-)

diff --git 
a/components/camel-master/src/main/java/org/apache/camel/component/master/MasterConsumer.java
 
b/components/camel-master/src/main/java/org/apache/camel/component/master/MasterConsumer.java
index f6250afe46fd..11b3d1550a80 100644
--- 
a/components/camel-master/src/main/java/org/apache/camel/component/master/MasterConsumer.java
+++ 
b/components/camel-master/src/main/java/org/apache/camel/component/master/MasterConsumer.java
@@ -62,7 +62,8 @@ public class MasterConsumer extends DefaultConsumer 
implements ResumeAware<Resum
     private volatile Consumer delegatedConsumer;
     private volatile CamelClusterView view;
     private ResumeStrategy resumeStrategy;
-    private ScheduledExecutorService leaderPool;
+    // a new pool for each lifecycle (doInit); the start attempts compare it 
with the pool they run on
+    private volatile ScheduledExecutorService leaderPool;
     // leadership state and the pending start task are guarded by 
leadershipLock. This is deliberately not
     // the lock of BaseService: the cluster view dispatches events while 
holding its own read lock and then
     // needs this lock, while doStop holds the service lock and needs the 
write lock of the view to remove
@@ -125,6 +126,10 @@ public class MasterConsumer extends DefaultConsumer 
implements ResumeAware<Resum
         }
 
         try {
+            // the start task was cancelled above, but an attempt may still be 
running: the delegated consumer it
+            // starts may not stop on the interrupt. Wait for it (bounded by 
the shutdown await termination of the
+            // executor service manager) so it does not finish starting after 
this consumer has stopped
+            
getEndpoint().getCamelContext().getExecutorServiceManager().shutdownGraceful(leaderPool);
             // the delegated consumer is stopped while this node still holds 
the leadership, and before the processor
             // of the route, so no other node starts consuming while it stops, 
and the messages it still routes while
             // it stops (a consumer may wait in its stop for the messages it 
processes) reach a started route. A
@@ -132,8 +137,6 @@ public class MasterConsumer extends DefaultConsumer 
implements ResumeAware<Resum
             Consumer delegate = delegatedConsumer;
             delegatedConsumer = null;
             ServiceHelper.stopAndShutdownServices(delegate, delegatedEndpoint);
-            // the start task was cancelled above
-            
getEndpoint().getCamelContext().getExecutorServiceManager().shutdown(leaderPool);
         } finally {
             try {
                 super.doStop();
@@ -211,14 +214,17 @@ public class MasterConsumer extends DefaultConsumer 
implements ResumeAware<Resum
             final BackgroundTask task = createTask();
             // the consumer is created once and re-used by the start attempts 
of this task
             final AtomicReference<Consumer> attempt = new AtomicReference<>();
+            final ScheduledExecutorService pool = leaderPool;
             leaderTask = task;
-            leaderTaskFuture = task.schedule(getEndpoint().getCamelContext(), 
() -> startDelegatedConsumer(task, attempt));
+            leaderTaskFuture
+                    = task.schedule(getEndpoint().getCamelContext(), () -> 
startDelegatedConsumer(task, pool, attempt));
         } finally {
             leadershipLock.unlock();
         }
     }
 
-    private boolean startDelegatedConsumer(BackgroundTask task, 
AtomicReference<Consumer> attempt) {
+    private boolean startDelegatedConsumer(
+            BackgroundTask task, ScheduledExecutorService pool, 
AtomicReference<Consumer> attempt) {
         leadershipLock.lock();
         try {
             if (!isRunAllowed()) {
@@ -290,11 +296,35 @@ public class MasterConsumer extends DefaultConsumer 
implements ResumeAware<Resum
                 throw new TaskRunFailureException(message, cause);
             }
 
-            if (!leadershipTaken || !isRunAllowed()) {
-                // the leadership went away while the consumer was starting, 
so stop what was just started
-                // instead of publishing it. No leadership event is going to 
do it, delegatedConsumer is unset
-                LOG.info("Leadership lost while the consumer was starting. 
Stopping consumer: {}", delegatedEndpoint);
-                ServiceHelper.stopAndShutdownServices(consumer, 
delegatedEndpoint);
+            // an attempt of an earlier lifecycle of this consumer (a stop and 
start of the same instance) runs on the
+            // pool of that lifecycle. Within one lifecycle, a task newer than 
this one only exists when the leadership
+            // was lost and taken again while this attempt was starting, and 
as the pool has a single thread, that task
+            // has not run yet: this attempt publishes its consumer below and 
cancels it
+            boolean earlierLifecycle = pool != leaderPool;
+            if (earlierLifecycle || delegatedConsumer != null || 
!leadershipTaken || !isRunAllowed()) {
+                // the leadership went away, or this consumer was stopped (and 
maybe started again), while the
+                // consumer was starting. This attempt is no longer the 
current one, so stop what it started instead
+                // of publishing it over the consumer of a newer attempt. Only 
the consumer: the endpoint is shared
+                // with that newer consumer, and onLeadershipLost and doStop 
stop it. And only stop it
+                // (stopService, not stopAndShutdownServices): a shutdown 
calls DefaultConsumer.doShutdown, which
+                // shuts down the processor of the route, and that cannot be 
undone, so a newer consumer that uses
+                // the same processor would be broken
+                LOG.info("Leadership lost or consumer stopped while the 
delegated consumer was starting. Stopping it: {}",
+                        delegatedEndpoint);
+                ServiceHelper.stopService(consumer);
+                if (isRunAllowed()) {
+                    // stopping a consumer also stops the processor of the 
route, which a delegated consumer of this
+                    // lifecycle may use (running, or still starting), so 
start it again while this master consumer
+                    // runs. It is not enough to check for a published 
consumer: the attempt of the restarted
+                    // consumer may still be inside its start, after its 
doStart has started the processor. Until
+                    // then, a message of a running delegated consumer that 
reaches the stopped processor fails (a
+                    // SendProcessor that is not started fails the exchange). 
This window only opens when an attempt
+                    // of an earlier lifecycle outlived the wait of doStop 
(shutdownGraceful, bounded by the shutdown
+                    // await termination of the executor service manager). 
When the leadership was lost within this
+                    // lifecycle the route is started, so the processor runs 
as it does on a node that is not the
+                    // leader. When this master consumer is stopping, its own 
stop stops the processor
+                    ServiceHelper.startService(processor);
+                }
                 attempt.set(null);
                 return true; // no more attempts
             }
@@ -302,7 +332,8 @@ public class MasterConsumer extends DefaultConsumer 
implements ResumeAware<Resum
             delegatedConsumer = consumer;
             LOG.info("Leadership taken. Attempt #{} success. Consumer started: 
{}", task.iteration(),
                     delegatedEndpoint);
-            // release the task, a later leadership term schedules a new one
+            // release the task, a later leadership term schedules a new one. 
When the leadership was lost and taken
+            // again while this attempt was starting, this cancels the newer 
task before it starts a second consumer
             cancelLeaderTask(false);
             return true; // no more attempts
         } finally {
diff --git 
a/components/camel-master/src/test/java/org/apache/camel/component/master/MasterConsumerLeadershipTest.java
 
b/components/camel-master/src/test/java/org/apache/camel/component/master/MasterConsumerLeadershipTest.java
index a42388473ed5..c98a3c934858 100644
--- 
a/components/camel-master/src/test/java/org/apache/camel/component/master/MasterConsumerLeadershipTest.java
+++ 
b/components/camel-master/src/test/java/org/apache/camel/component/master/MasterConsumerLeadershipTest.java
@@ -20,6 +20,8 @@ import java.util.List;
 import java.util.Map;
 import java.util.Optional;
 import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CopyOnWriteArrayList;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
@@ -342,6 +344,187 @@ public class MasterConsumerLeadershipTest {
         assertFalse(view.isRunAllowed(), "The view is not released");
     }
 
+    @Test
+    @Timeout(60)
+    void testStartAttemptFromBeforeARestartDoesNotReplaceTheNewConsumer() 
throws Exception {
+        // the route has threads(), whose thread pool cannot be started again 
after a shutdown
+        useRouteWithThreads();
+        // the stop below waits this long for the start attempt that is still 
running, which outlasts it
+        context.getExecutorServiceManager().setShutdownAwaitTermination(100);
+        TestClusterView view = clusterService.getTestView();
+        CountDownLatch startGate = new CountDownLatch(1);
+        probe.ignoreInterrupt.set(true);
+        probe.startGate.set(startGate);
+        try {
+            view.setLeader(true);
+            await().atMost(10, TimeUnit.SECONDS).until(() -> 
probe.startAttempts.get() == 1);
+
+            // the same consumer is stopped and started again (as its JMX 
operations do) while the first attempt
+            // still starts the first delegated consumer, and the new 
lifecycle starts a second one
+            MasterConsumer consumer = (MasterConsumer) 
context.getRoute("master-route").getConsumer();
+            consumer.stop();
+            probe.startGate.set(null);
+            consumer.start();
+            await().atMost(10, TimeUnit.SECONDS).until(() -> 
probe.started.get() == 1);
+        } finally {
+            startGate.countDown();
+        }
+
+        // the attempt from before the restart stops its own consumer instead 
of publishing it over the second one
+        await().atMost(10, TimeUnit.SECONDS).untilAsserted(() -> {
+            assertEquals(2, probe.started.get());
+            assertEquals(1, probe.stopped.get(), "The consumer of the attempt 
from before the restart is still running");
+        });
+        // it is only stopped: a shutdown would also shut down the processor 
of the route, which the second one uses
+        ProbeConsumer first = probe.consumers.get(0);
+        assertFalse(first.isShutdown(), "The consumer of the attempt from 
before the restart was shut down");
+        ProbeConsumer second = probe.consumers.get(1);
+        assertTrue(second.isStarted());
+        assertTrue(((ProbeEndpoint) second.getEndpoint()).isStarted(), "The 
endpoint of the running consumer was stopped");
+
+        // the route behind the running consumer still routes its messages
+        assertRoutes(second, "after restart");
+
+        // losing the leadership stops the running consumer, so none is left 
behind
+        view.setLeader(false);
+        await().atMost(10, TimeUnit.SECONDS).untilAsserted(() -> 
assertEquals(2, probe.stopped.get()));
+        assertFalse(second.isStarted());
+    }
+
+    @Test
+    @Timeout(60)
+    void 
testStartAttemptFromBeforeARestartFinishingWhileTheNewConsumerStartsKeepsTheRouteWorking()
 throws Exception {
+        useRouteWithThreads();
+        // the stop below waits this long for the start attempt that is still 
running, which outlasts it
+        context.getExecutorServiceManager().setShutdownAwaitTermination(100);
+        TestClusterView view = clusterService.getTestView();
+        CountDownLatch firstGate = new CountDownLatch(1);
+        CountDownLatch secondGate = new CountDownLatch(1);
+        probe.ignoreInterrupt.set(true);
+        probe.startGate.set(firstGate);
+        try {
+            view.setLeader(true);
+            await().atMost(10, TimeUnit.SECONDS).until(() -> 
probe.startAttempts.get() == 1);
+
+            // the same consumer is stopped and started again while the first 
attempt still starts the first
+            // delegated consumer, and the attempt of the new lifecycle is 
held inside the start of the second one,
+            // after its doStart has started the processor of the route
+            MasterConsumer consumer = (MasterConsumer) 
context.getRoute("master-route").getConsumer();
+            consumer.stop();
+            probe.startGate.set(secondGate);
+            consumer.start();
+            await().atMost(10, TimeUnit.SECONDS).until(() -> 
probe.startAttempts.get() == 2);
+
+            // the attempt from before the restart finishes first and stops 
its own consumer, which also stops the
+            // processor of the route, while no delegated consumer is 
published yet
+            firstGate.countDown();
+            await().atMost(10, TimeUnit.SECONDS).untilAsserted(() -> {
+                assertEquals(1, probe.started.get());
+                assertEquals(1, probe.stopped.get(), "The consumer of the 
attempt from before the restart is still running");
+            });
+        } finally {
+            firstGate.countDown();
+            secondGate.countDown();
+        }
+
+        await().atMost(10, TimeUnit.SECONDS).until(() -> probe.started.get() 
== 2);
+        ProbeConsumer second = probe.consumers.get(1);
+        assertTrue(second.isStarted());
+
+        // the route behind the consumer that started last still routes its 
messages
+        assertRoutes(second, "after restart");
+
+        view.setLeader(false);
+        await().atMost(10, TimeUnit.SECONDS).untilAsserted(() -> 
assertEquals(2, probe.stopped.get()));
+        assertFalse(second.isStarted());
+    }
+
+    @Test
+    @Timeout(60)
+    void 
testLeadershipLostAndTakenAgainWhileStartIsInProgressKeepsTheRouteWorking() 
throws Exception {
+        useRouteWithThreads();
+        TestClusterView view = clusterService.getTestView();
+        CountDownLatch startGate = new CountDownLatch(1);
+        probe.startGate.set(startGate);
+        try {
+            view.setLeader(true);
+            await().atMost(10, TimeUnit.SECONDS).until(() -> 
probe.startAttempts.get() == 1);
+
+            // the leadership is lost and taken again while the first 
delegated consumer is still starting
+            view.setLeader(false);
+            view.setLeader(true);
+        } finally {
+            startGate.countDown();
+        }
+
+        // outlast the initial delay of a second start task, then exactly one 
delegated consumer must run
+        await().atMost(10, TimeUnit.SECONDS).until(() -> probe.started.get() 
>= 1);
+        await().during(2, TimeUnit.SECONDS).atMost(10, TimeUnit.SECONDS)
+                .until(() -> 
probe.consumers.stream().filter(ProbeConsumer::isStarted).count() == 1);
+        ProbeConsumer running = 
probe.consumers.stream().filter(ProbeConsumer::isStarted).findFirst().orElseThrow();
+
+        // and the route behind it, with threads(), still routes its messages
+        assertRoutes(running, "after leadership flap");
+        // the attempt that was starting is published, so no second consumer 
is started
+        assertEquals(1, probe.created.get(), "A second delegated consumer was 
started");
+        assertEquals(0, probe.stopped.get());
+
+        view.setLeader(false);
+        await().atMost(10, TimeUnit.SECONDS).untilAsserted(() -> 
assertEquals(1, probe.stopped.get()));
+    }
+
+    @Test
+    @Timeout(60)
+    void testStopWaitsForAStartAttemptInFlight() throws Exception {
+        TestClusterView view = clusterService.getTestView();
+        CountDownLatch startGate = new CountDownLatch(1);
+        probe.ignoreInterrupt.set(true);
+        probe.startGate.set(startGate);
+        AtomicInteger stoppedWhenStopReturned = new AtomicInteger(-1);
+        CompletableFuture<Void> stop;
+        try {
+            view.setLeader(true);
+            await().atMost(10, TimeUnit.SECONDS).until(() -> 
probe.startAttempts.get() == 1);
+
+            MasterConsumer consumer = (MasterConsumer) 
context.getRoute("master-route").getConsumer();
+            stop = CompletableFuture.runAsync(() -> {
+                consumer.stop();
+                stoppedWhenStopReturned.set(probe.stopped.get());
+            });
+            // the stop waits for the attempt instead of returning while the 
delegated consumer is still starting
+            await().during(500, TimeUnit.MILLISECONDS).atMost(5, 
TimeUnit.SECONDS).until(() -> !stop.isDone());
+        } finally {
+            startGate.countDown();
+        }
+
+        stop.get(10, TimeUnit.SECONDS);
+        assertEquals(1, probe.started.get());
+        assertEquals(1, stoppedWhenStopReturned.get(), "The delegated consumer 
was still running when the stop returned");
+    }
+
+    private void useRouteWithThreads() throws Exception {
+        context.getRouteController().stopRoute("master-route");
+        context.removeRoute("master-route");
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                
from("master:ns:probe:test").routeId("master-route").threads().to("mock:result");
+            }
+        });
+    }
+
+    private void assertRoutes(ProbeConsumer consumer, String body) throws 
Exception {
+        MockEndpoint mock = context.getEndpoint("mock:result", 
MockEndpoint.class);
+        mock.expectedBodiesReceived(body);
+        Exchange exchange = consumer.createExchange(false);
+        exchange.getMessage().setBody(body);
+        CountDownLatch done = new CountDownLatch(1);
+        consumer.getAsyncProcessor().process(exchange, doneSync -> 
done.countDown());
+        assertTrue(done.await(10, TimeUnit.SECONDS), "The route did not 
complete the message");
+        assertNull(exchange.getException());
+        mock.assertIsSatisfied();
+    }
+
     // ************************************
     // Delegated endpoint under observation
     // ************************************
@@ -352,6 +535,9 @@ public class MasterConsumerLeadershipTest {
         private final AtomicInteger started = new AtomicInteger();
         private final AtomicInteger stopped = new AtomicInteger();
         private final AtomicBoolean failStart = new AtomicBoolean();
+        // the start gate is awaited like a connect that does not stop on an 
interrupt
+        private final AtomicBoolean ignoreInterrupt = new AtomicBoolean();
+        private final List<ProbeConsumer> consumers = new 
CopyOnWriteArrayList<>();
         private final AtomicReference<CountDownLatch> startGate = new 
AtomicReference<>();
         private final AtomicReference<CountDownLatch> suspendEntered = new 
AtomicReference<>();
         private final AtomicReference<CountDownLatch> suspendGate = new 
AtomicReference<>();
@@ -394,7 +580,9 @@ public class MasterConsumerLeadershipTest {
         @Override
         public Consumer createConsumer(Processor processor) {
             component.created.incrementAndGet();
-            return new ProbeConsumer(this, processor, component);
+            ProbeConsumer consumer = new ProbeConsumer(this, processor, 
component);
+            component.consumers.add(consumer);
+            return consumer;
         }
 
         @Override
@@ -417,7 +605,9 @@ public class MasterConsumerLeadershipTest {
             // counted before the failure flag is read, so a test can await an 
attempt that has made its decision
             component.startAttempts.incrementAndGet();
             CountDownLatch gate = component.startGate.get();
-            if (gate != null) {
+            if (gate != null && component.ignoreInterrupt.get()) {
+                awaitIgnoringInterrupts(gate);
+            } else if (gate != null) {
                 gate.await();
             }
             if (component.failStart.get()) {
@@ -426,6 +616,21 @@ public class MasterConsumerLeadershipTest {
             component.started.incrementAndGet();
         }
 
+        private static void awaitIgnoringInterrupts(CountDownLatch gate) {
+            boolean interrupted = false;
+            while (true) {
+                try {
+                    gate.await();
+                    break;
+                } catch (InterruptedException e) {
+                    interrupted = true;
+                }
+            }
+            if (interrupted) {
+                Thread.currentThread().interrupt();
+            }
+        }
+
         @Override
         protected void doStop() throws Exception {
             StopHook hook = component.stopHook.get();
diff --git 
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc 
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
index 23e47aa196bc..1b6a4d066081 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
@@ -320,6 +320,16 @@ camel-jms, and `SpringRabbitMQStopListenerContainer` for 
camel-spring-rabbitmq.
 `camelContext.getExecutorServiceManager().setShutdownAwaitTermination(...)`; 
it is also the time that Camel waits for
 each thread pool to terminate when the CamelContext stops.
 
+=== camel-master - stopping a master consumer waits for the start of its 
delegated consumer
+
+Stopping a `master` consumer while the start of its delegated consumer is 
still running (for example a client connect
+that does not stop on an interrupt) now waits for that start, at most the 
`shutdownAwaitTermination` of the
+`ExecutorServiceManager` (10 seconds by default), and as long again after 
interrupting it. Previously the stop returned
+at once, and the delegated consumer could finish starting after the route had 
stopped. A delegated consumer that
+finishes starting after the master consumer was stopped, or lost the 
leadership, is now stopped, also when the master
+consumer was started again meanwhile; previously it replaced the delegated 
consumer of the new start, which kept
+running without being stopped again.
+
 === camel-core - a to with an expression in its endpoint uri logs a WARN
 
 A `to` resolves its endpoint once, when the route starts, so 
`to("jms:queue:${header.queue}")` sends every message to

Reply via email to