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 58ac144912a0 CAMEL-27583: camel-support - 
RebalancingCamelClusterService keeps rebalancing after a failed pass and runs 
one loop after a restart (#30912)
58ac144912a0 is described below

commit 58ac144912a0ab022944395199d4925a8bb2101e
Author: allthingssecurity <[email protected]>
AuthorDate: Fri Nov 27 15:12:53 2026 +0530

    CAMEL-27583: camel-support - RebalancingCamelClusterService keeps 
rebalancing after a failed pass and runs one loop after a restart (#30912)
    
    Each rebalancing pass scheduled the next one at its end, with no catch
    around the pass. An exception or error in a pass (for example from
    getNamespaces() of the delegate) ended the rebalancing for good while the
    service stayed started. A pass now runs inside a catch of Throwable (WARN
    on the first failure, DEBUG on repeats) and the next pass is scheduled in
    a finally.
    
    doStop shut the executor down with shutdown(), after which a scheduled
    executor still runs its delayed pass, and that pass then scheduled itself
    on the executor of the next start, so each stop and start added a chain
    of passes. doStop now uses shutdownNow(), and a pass only schedules the
    next one on the executor it ran on, while that is still the executor of
    the service.
    
    Review:
    - log a VirtualMachineError of a pass at ERROR, and wait for a running pass 
in doStop
    - keep the failure state of the passes per start, and explain the test 
ceiling
    - log a failure right after a VirtualMachineError at WARN
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../cluster/RebalancingClusterServiceLoopTest.java | 338 +++++++++++++++++++++
 .../cluster/RebalancingCamelClusterService.java    |  86 +++++-
 2 files changed, 409 insertions(+), 15 deletions(-)

diff --git 
a/core/camel-core/src/test/java/org/apache/camel/cluster/RebalancingClusterServiceLoopTest.java
 
b/core/camel-core/src/test/java/org/apache/camel/cluster/RebalancingClusterServiceLoopTest.java
new file mode 100644
index 000000000000..86c078d08d08
--- /dev/null
+++ 
b/core/camel-core/src/test/java/org/apache/camel/cluster/RebalancingClusterServiceLoopTest.java
@@ -0,0 +1,338 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.cluster;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Optional;
+import java.util.Queue;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.support.cluster.AbstractCamelClusterService;
+import org.apache.camel.support.cluster.AbstractCamelClusterView;
+import org.apache.camel.support.cluster.RebalancingCamelClusterService;
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.core.LogEvent;
+import org.apache.logging.log4j.core.LoggerContext;
+import org.apache.logging.log4j.core.appender.AbstractAppender;
+import org.apache.logging.log4j.core.config.Property;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The passes of the rebalancing cluster service form one chain: a failing 
pass does not end it, and a stop and start of
+ * the service does not leave the chain of the previous start running next to 
the new one.
+ */
+class RebalancingClusterServiceLoopTest {
+
+    private static final long PERIOD_MILLIS = 200;
+
+    private CamelContext context;
+    private TestClusterService delegate;
+    private CountingRebalancingClusterService service;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        context = new DefaultCamelContext();
+        delegate = new TestClusterService("node-1");
+        service = new CountingRebalancingClusterService(delegate);
+        context.addService(service);
+    }
+
+    @AfterEach
+    void tearDown() {
+        context.stop();
+    }
+
+    @Test
+    void failingPassDoesNotEndRebalancing() throws Exception {
+        context.start();
+        delegate.getView("my-ns");
+        await().atMost(10, TimeUnit.SECONDS).until(() -> service.passes.get() 
>= 2);
+
+        delegate.failures.set(1);
+        await().atMost(10, TimeUnit.SECONDS).until(() -> 
delegate.failures.get() == 0);
+        int passes = service.passes.get();
+
+        // the next passes run, and they still rebalance: a disabled partition 
of the only member is opened
+        TestClusterView view = delegate.view("my-ns");
+        view.setDisabled(true);
+        await().atMost(10, TimeUnit.SECONDS).until(() -> service.passes.get() 
>= passes + 3 && !view.isDisabled());
+    }
+
+    @Test
+    void restartDoesNotAddChainOfPasses() throws Exception {
+        context.start();
+        delegate.getView("my-ns");
+        await().atMost(10, TimeUnit.SECONDS).until(() -> service.passes.get() 
>= 2);
+
+        for (int i = 0; i < 3; i++) {
+            service.stop();
+            Thread stopped = service.lastThread;
+            service.threads.clear();
+            service.start();
+            await().atMost(10, TimeUnit.SECONDS).until(() -> 
service.threads.size() >= 3);
+            // no pass starts on the executor of the previous start once the 
service is stopped
+            assertTrue(service.threads.stream().noneMatch(t -> t == stopped),
+                    "A pass ran on the executor of the previous start after 
the stop");
+        }
+
+        // one chain: the next pass is scheduled a period after the previous 
one ends, so at most elapsed / period + 1
+        // passes start in the window (fewer on a busy machine). The 3 also 
allows for the pass counter and the clock
+        // not being read at the same instant, at the start and at each check. 
A second chain would add one pass per
+        // period, about 10 in the 2 seconds, which is well above it
+        int before = service.passes.get();
+        long start = System.nanoTime();
+        await().during(2, TimeUnit.SECONDS).atMost(10, 
TimeUnit.SECONDS).until(() -> service.passes.get() - before
+                                                                               
      <= TimeUnit.NANOSECONDS.toMillis(
+                                                                               
              System.nanoTime() - start)
+                                                                               
         / PERIOD_MILLIS + 3);
+        assertEquals(1, service.maxConcurrent.get(), "Passes ran at the same 
time");
+    }
+
+    @Test
+    void stopWaitsForTheRunningPass() throws Exception {
+        context.start();
+        delegate.getView("my-ns");
+        await().atMost(10, TimeUnit.SECONDS).until(() -> service.passes.get() 
>= 1);
+
+        // the next pass takes a quarter of the period, and does not stop on 
the interrupt of the stop
+        CountDownLatch entered = new CountDownLatch(1);
+        service.blockNextPass.set(entered);
+        assertTrue(entered.await(10, TimeUnit.SECONDS), "The slow pass did not 
start");
+        service.stop();
+        service.start();
+
+        // the first pass after the start runs once the slow pass is over, not 
next to it
+        int passes = service.passes.get();
+        await().atMost(10, TimeUnit.SECONDS).until(() -> service.passes.get() 
>= passes + 2);
+        assertEquals(1, service.maxConcurrent.get(), "The first pass after the 
start ran next to the pass of the stop");
+    }
+
+    @Test
+    void failuresAreLoggedWithTheStackTrace() throws Exception {
+        List<LogEvent> events = new CopyOnWriteArrayList<>();
+        AbstractAppender appender = new AbstractAppender(
+                "rebalancing-errors-" + UUID.randomUUID(), null, null, true, 
Property.EMPTY_ARRAY) {
+            @Override
+            public void append(LogEvent event) {
+                if 
(RebalancingCamelClusterService.class.getName().equals(event.getLoggerName())) {
+                    events.add(event.toImmutable());
+                }
+            }
+        };
+        appender.start();
+        LoggerContext logging = (LoggerContext) LogManager.getContext(false);
+        logging.getConfiguration().getRootLogger().addAppender(appender, 
Level.WARN, null);
+        logging.updateLoggers();
+        try {
+            context.start();
+            delegate.getView("my-ns");
+            await().atMost(10, TimeUnit.SECONDS).until(() -> 
service.passes.get() >= 1);
+
+            // a VirtualMachineError is logged at ERROR, with the stack trace, 
and another failure in the pass right
+            // after it is still logged at WARN, with the stack trace
+            delegate.nextFailures.add(new OutOfMemoryError("Simulated out of 
memory while listing the namespaces"));
+            delegate.nextFailures.add(new IllegalStateException("Simulated 
failure right after the out of memory"));
+            await().atMost(10, TimeUnit.SECONDS).until(() -> events.size() >= 
2);
+            assertEquals(Level.ERROR, events.get(0).getLevel());
+            assertTrue(events.get(0).getThrown() instanceof OutOfMemoryError, 
"The stack trace was not logged");
+            assertEquals(Level.WARN, events.get(1).getLevel());
+            assertTrue(events.get(1).getThrown() instanceof 
IllegalStateException, "The stack trace was not logged");
+
+            // after a pass that works (the passes run one at a time, so the 
one after it has started), another
+            // failure is logged at WARN, with the stack trace
+            int passes = service.passes.get();
+            await().atMost(10, TimeUnit.SECONDS).until(() -> 
service.passes.get() >= passes + 2);
+            delegate.nextFailures.add(new IllegalStateException("Simulated 
failure while listing the namespaces"));
+            await().atMost(10, TimeUnit.SECONDS).until(() -> events.size() >= 
3);
+            assertEquals(Level.WARN, events.get(2).getLevel());
+            assertTrue(events.get(2).getThrown() instanceof 
IllegalStateException, "The stack trace was not logged");
+        } finally {
+            
logging.getConfiguration().getRootLogger().removeAppender(appender.getName());
+            logging.updateLoggers();
+            appender.stop();
+        }
+    }
+
+    // *********************************
+    // Helpers
+    // *********************************
+
+    private static final class CountingRebalancingClusterService extends 
RebalancingCamelClusterService {
+        private final AtomicInteger passes = new AtomicInteger();
+        private final AtomicInteger running = new AtomicInteger();
+        private final AtomicInteger maxConcurrent = new AtomicInteger();
+        private final Queue<Thread> threads = new ConcurrentLinkedQueue<>();
+        // the next pass counts this down and then takes a quarter of the 
period
+        private final AtomicReference<CountDownLatch> blockNextPass = new 
AtomicReference<>();
+        private volatile Thread lastThread;
+
+        CountingRebalancingClusterService(CamelPreemptiveClusterService 
delegate) {
+            super(delegate, PERIOD_MILLIS);
+        }
+
+        @Override
+        protected void reconcile() {
+            passes.incrementAndGet();
+            lastThread = Thread.currentThread();
+            threads.add(Thread.currentThread());
+            maxConcurrent.accumulateAndGet(running.incrementAndGet(), 
Math::max);
+            try {
+                CountDownLatch block = blockNextPass.getAndSet(null);
+                if (block != null) {
+                    block.countDown();
+                    workIgnoringInterrupts(PERIOD_MILLIS / 4);
+                }
+                super.reconcile();
+            } finally {
+                running.decrementAndGet();
+            }
+        }
+
+        // a pass that does not stop on an interrupt (as one that waits for 
I/O)
+        private static void workIgnoringInterrupts(long millis) {
+            CountDownLatch never = new CountDownLatch(1);
+            long deadline = System.nanoTime() + 
TimeUnit.MILLISECONDS.toNanos(millis);
+            boolean interrupted = false;
+            long left;
+            while ((left = deadline - System.nanoTime()) > 0) {
+                try {
+                    never.await(left, TimeUnit.NANOSECONDS);
+                } catch (InterruptedException e) {
+                    interrupted = true;
+                }
+            }
+            if (interrupted) {
+                Thread.currentThread().interrupt();
+            }
+        }
+    }
+
+    private static final class TestClusterView extends 
AbstractCamelClusterView implements CamelPreemptiveClusterView {
+        private final CamelClusterMember local;
+        private volatile boolean disabled;
+
+        TestClusterView(CamelClusterService cluster, String namespace) {
+            super(cluster, namespace);
+            this.local = new CamelClusterMember() {
+                @Override
+                public boolean isLeader() {
+                    return false;
+                }
+
+                @Override
+                public boolean isLocal() {
+                    return true;
+                }
+
+                @Override
+                public String getId() {
+                    return getClusterService().getId();
+                }
+            };
+        }
+
+        @Override
+        public Optional<CamelClusterMember> getLeader() {
+            return Optional.empty();
+        }
+
+        @Override
+        public CamelClusterMember getLocalMember() {
+            return local;
+        }
+
+        @Override
+        public List<CamelClusterMember> getMembers() {
+            return List.of(local);
+        }
+
+        @Override
+        public void setDisabled(boolean disabled) {
+            this.disabled = disabled;
+        }
+
+        @Override
+        public boolean isDisabled() {
+            return disabled;
+        }
+
+        @Override
+        protected void doStart() {
+        }
+
+        @Override
+        protected void doStop() {
+        }
+    }
+
+    private static final class TestClusterService extends 
AbstractCamelClusterService<TestClusterView>
+            implements CamelPreemptiveClusterService {
+        private final AtomicInteger failures = new AtomicInteger();
+        // each is thrown once, in order, by the next listings of the 
namespaces
+        private final Queue<Throwable> nextFailures = new 
ConcurrentLinkedQueue<>();
+        private volatile TestClusterView view;
+
+        TestClusterService(String id) {
+            super(id);
+        }
+
+        @Override
+        protected TestClusterView createView(String namespace) {
+            view = new TestClusterView(this, namespace);
+            return view;
+        }
+
+        @Override
+        public CamelPreemptiveClusterView getView(String namespace) throws 
Exception {
+            return (CamelPreemptiveClusterView) super.getView(namespace);
+        }
+
+        @Override
+        public Collection<String> getNamespaces() {
+            Throwable failure = nextFailures.poll();
+            if (failure instanceof Error error) {
+                throw error;
+            } else if (failure instanceof RuntimeException e) {
+                throw e;
+            }
+            if (failures.getAndUpdate(f -> Math.max(0, f - 1)) > 0) {
+                throw new IllegalStateException("Simulated failure while 
listing the namespaces");
+            }
+            return super.getNamespaces();
+        }
+
+        TestClusterView view(String namespace) {
+            return view;
+        }
+    }
+}
diff --git 
a/core/camel-support/src/main/java/org/apache/camel/support/cluster/RebalancingCamelClusterService.java
 
b/core/camel-support/src/main/java/org/apache/camel/support/cluster/RebalancingCamelClusterService.java
index 71a9f62bc47e..669b32c4686f 100644
--- 
a/core/camel-support/src/main/java/org/apache/camel/support/cluster/RebalancingCamelClusterService.java
+++ 
b/core/camel-support/src/main/java/org/apache/camel/support/cluster/RebalancingCamelClusterService.java
@@ -22,6 +22,7 @@ import java.util.Collections;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
+import java.util.concurrent.RejectedExecutionException;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
 import java.util.stream.Collectors;
@@ -47,7 +48,8 @@ public class RebalancingCamelClusterService extends 
ServiceSupport implements Ca
 
     private static final Logger LOG = 
LoggerFactory.getLogger(RebalancingCamelClusterService.class);
 
-    protected ScheduledExecutorService serializedExecutor;
+    // set to null by doStop: a pass that runs on an executor that is no 
longer this one does not schedule the next pass
+    protected volatile ScheduledExecutorService serializedExecutor;
     protected CamelPreemptiveClusterService delegate;
     protected CamelContext camelContext;
     protected final long periodMillis;
@@ -76,19 +78,34 @@ public class RebalancingCamelClusterService extends 
ServiceSupport implements Ca
         super.doStart();
         ServiceHelper.startService(delegate);
         if (serializedExecutor == null) {
-            serializedExecutor = 
getCamelContext().getExecutorServiceManager().newSingleThreadScheduledExecutor(this,
-                    "RebalancingClusterService");
-            serializedExecutor.execute(this::reconcile);
+            ScheduledExecutorService executor = 
getCamelContext().getExecutorServiceManager()
+                    .newSingleThreadScheduledExecutor(this, 
"RebalancingClusterService");
+            serializedExecutor = executor;
+            // each start has its own chain of passes, with its own failure 
state
+            PassState state = new PassState();
+            executor.execute(() -> reconcileAndReschedule(executor, state));
         }
     }
 
     @Override
     protected void doStop() throws Exception {
         super.doStop();
-        if (serializedExecutor != null) {
-            
getCamelContext().getExecutorServiceManager().shutdown(serializedExecutor);
-        }
+        ScheduledExecutorService executor = serializedExecutor;
         serializedExecutor = null;
+        if (executor != null) {
+            // the pending pass is dropped (a scheduled executor runs its 
delayed tasks after a plain shutdown), so a
+            // start does not add a second chain of passes
+            
getCamelContext().getExecutorServiceManager().shutdownNow(executor);
+            // and a pass that is still running is given up to one period to 
finish (shutdownNow does not wait for it),
+            // so it does not run at the same time as the first pass after a 
quick start
+            try {
+                if 
(!getCamelContext().getExecutorServiceManager().awaitTermination(executor, 
periodMillis)) {
+                    LOG.debug("The running rebalancing pass did not finish 
within {} ms of the stop", periodMillis);
+                }
+            } catch (InterruptedException e) {
+                Thread.currentThread().interrupt();
+            }
+        }
         ServiceHelper.stopService(delegate);
     }
 
@@ -104,13 +121,48 @@ public class RebalancingCamelClusterService extends 
ServiceSupport implements Ca
         this.delegate = delegate;
     }
 
+    /**
+     * Runs a rebalancing pass, and schedules the next one on the same 
executor while it is the executor of this
+     * service, also when the pass fails.
+     */
+    private void reconcileAndReschedule(ScheduledExecutorService executor, 
PassState state) {
+        try {
+            reconcile();
+            state.previousPassFailed = false;
+            state.previousPassFatal = false;
+        } catch (Throwable e) {
+            // a VirtualMachineError (such as an OutOfMemoryError) is logged 
at ERROR, another failure at WARN, each with
+            // the stack trace and only the first time in a row of its kind: a 
failure that repeats every period is
+            // logged at DEBUG, while a failure of the other kind than the one 
before it (such as an
+            // IllegalStateException right after an OutOfMemoryError) is 
logged at its own level again
+            boolean fatal = ObjectHelper.getVirtualMachineError(e) != null;
+            if (fatal && !state.previousPassFatal) {
+                LOG.error("Error while rebalancing the partitions (will try 
again in {} ms)", periodMillis, e);
+            } else if (!fatal && (!state.previousPassFailed || 
state.previousPassFatal)) {
+                LOG.warn("Error while rebalancing the partitions (will try 
again in {} ms)", periodMillis, e);
+            } else {
+                LOG.debug("Error while rebalancing the partitions (will try 
again in {} ms)", periodMillis, e);
+            }
+            state.previousPassFailed = true;
+            state.previousPassFatal = fatal;
+        } finally {
+            if (executor == serializedExecutor) {
+                try {
+                    executor.schedule(() -> reconcileAndReschedule(executor, 
state), periodMillis,
+                            TimeUnit.MILLISECONDS);
+                } catch (RejectedExecutionException e) {
+                    LOG.debug("Cannot schedule the next rebalancing pass as 
the service is stopping");
+                }
+            }
+        }
+    }
+
     protected void reconcile() {
         Integer n = members();
         List<String> partitions = partitionList();
         int k = partitions.size();
 
         if (n == null || n == 0 || k == 0) {
-            rescheduleAfterDelay();
             return;
         }
 
@@ -133,7 +185,6 @@ public class RebalancingCamelClusterService extends 
ServiceSupport implements Ca
 
         rebalanceGroup(main, quota);
         rebalanceGroup(remaining, 1);
-        rescheduleAfterDelay();
     }
 
     protected void rebalanceGroup(List<String> partitions, int quota) {
@@ -278,12 +329,6 @@ public class RebalancingCamelClusterService extends 
ServiceSupport implements Ca
         }
     }
 
-    private void rescheduleAfterDelay() {
-        this.serializedExecutor.schedule(this::reconcile,
-                this.periodMillis,
-                TimeUnit.MILLISECONDS);
-    }
-
     @Override
     public CamelPreemptiveClusterView getView(String namespace) throws 
Exception {
         return delegate.getView(namespace);
@@ -334,4 +379,15 @@ public class RebalancingCamelClusterService extends 
ServiceSupport implements Ca
     public String getId() {
         return delegate.getId();
     }
+
+    /**
+     * Whether the previous pass of a chain failed, and with a 
VirtualMachineError. A chain is the passes of one start:
+     * they run one at a time on its executor, which orders them, so the 
fields need no synchronization. A pass of the
+     * previous start that is still running after the stop has its own state, 
and does not change the state of the new
+     * chain.
+     */
+    private static final class PassState {
+        private boolean previousPassFailed;
+        private boolean previousPassFatal;
+    }
 }

Reply via email to