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 6fa023f7e5e4 CAMEL-27566: camel-file - FileLockClusterView must take 
the leadership back after a failed attempt (#30862)
6fa023f7e5e4 is described below

commit 6fa023f7e5e4f0c3a874834de86c44d878efea6c
Author: allthingssecurity <[email protected]>
AuthorDate: Thu Nov 26 21:03:30 2026 +0530

    CAMEL-27566: camel-file - FileLockClusterView must take the leadership back 
after a failed attempt (#30862)
    
    A member that lost the leadership reads its own id in the data file and
    tries to take the leadership back. If that one attempt failed (a timeout
    or an I/O error), it kept its own id as the previous observation, and
    every later check took the "Backoff so the current cluster leader can
    notice" return. Only a leader writes the data file, so the backoff never
    ended and a single-member cluster had no leader until a restart.
    
    The backoff now lasts one check: the member forgets the observation of
    its own id (compareAndSet of the reference it just stored to null), so
    the next check tries the lock again. The OS lock still decides.
    
    New FileLockClusterViewReclaimLeadershipTest, which records the
    leadership changes with a Leadership listener.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../file/cluster/FileLockClusterView.java          |   7 +-
 .../FileLockClusterViewReclaimLeadershipTest.java  | 137 +++++++++++++++++++++
 2 files changed, 143 insertions(+), 1 deletion(-)

diff --git 
a/components/camel-file/src/main/java/org/apache/camel/component/file/cluster/FileLockClusterView.java
 
b/components/camel-file/src/main/java/org/apache/camel/component/file/cluster/FileLockClusterView.java
index b12af1dede9e..d72527b7d699 100644
--- 
a/components/camel-file/src/main/java/org/apache/camel/component/file/cluster/FileLockClusterView.java
+++ 
b/components/camel-file/src/main/java/org/apache/camel/component/file/cluster/FileLockClusterView.java
@@ -401,7 +401,12 @@ public class FileLockClusterView extends 
AbstractCamelClusterView {
                 if (isLeaderStale(latestClusterLeaderInfo, 
previousClusterLeaderInfo)
                         || canReclaimLeadership(latestClusterLeaderInfo)) {
                     if (previousClusterLeaderInfo != null && 
canReclaimLeadership(previousClusterLeaderInfo)) {
-                        // Backoff so the current cluster leader can notice 
leadership is relinquished
+                        // Backoff so the current cluster leader can notice 
leadership is relinquished. Only for this
+                        // check: the cluster data still names this member 
because no leader has written it since the
+                        // last attempt to take the lock failed, so the next 
check tries again. Otherwise a member
+                        // whose attempt failed (for example on a transient 
I/O error) would back off for good, and a
+                        // cluster with no other member would stay without a 
leader.
+                        
clusterLeaderInfoRef.compareAndSet(latestClusterLeaderInfo, null);
                         return;
                     }
 
diff --git 
a/core/camel-core/src/test/java/org/apache/camel/component/file/cluster/FileLockClusterViewReclaimLeadershipTest.java
 
b/core/camel-core/src/test/java/org/apache/camel/component/file/cluster/FileLockClusterViewReclaimLeadershipTest.java
new file mode 100644
index 000000000000..c951d10ddf62
--- /dev/null
+++ 
b/core/camel-core/src/test/java/org/apache/camel/component/file/cluster/FileLockClusterViewReclaimLeadershipTest.java
@@ -0,0 +1,137 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.file.cluster;
+
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.cluster.CamelClusterEventListener;
+import org.apache.camel.cluster.CamelClusterView;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The only member of a cluster loses the leadership after a failed read of 
the cluster data. The data file still holds
+ * its id, so the member tries to take the leadership back at once, and once 
the file system is healthy again it must
+ * get it, even if that first attempt fails too.
+ */
+class FileLockClusterViewReclaimLeadershipTest {
+
+    private static final String NAMESPACE = "ns";
+
+    @TempDir
+    Path root;
+
+    private CamelContext context;
+
+    @AfterEach
+    void stopContext() {
+        if (context != null) {
+            context.stop();
+        }
+    }
+
+    @Test
+    void memberTakesTheLeadershipBackAfterAFailedAttempt() throws Exception {
+        loseAndTakeBackLeadership(true);
+    }
+
+    @Test
+    void memberTakesTheLeadershipBackAtOnce() throws Exception {
+        loseAndTakeBackLeadership(false);
+    }
+
+    private void loseAndTakeBackLeadership(boolean failFirstAttempt) throws 
Exception {
+        AtomicInteger readFailures = new AtomicInteger();
+        AtomicInteger keyFailures = new AtomicInteger();
+        FileLockClusterService service = new FileLockClusterService() {
+            @Override
+            protected FileLockClusterView createView(String namespace) {
+                return new FileLockClusterView(this, namespace) {
+                    @Override
+                    FileLockClusterLeaderInfo readClusterLeaderInfo() throws 
Exception {
+                        if (readFailures.getAndUpdate(n -> Math.max(0, n - 1)) 
> 0) {
+                            throw new IOException("Simulated failure reading 
the cluster data");
+                        }
+                        return super.readClusterLeaderInfo();
+                    }
+
+                    @Override
+                    Path resolveLockPathKey() throws IOException {
+                        if (keyFailures.getAndUpdate(n -> Math.max(0, n - 1)) 
> 0) {
+                            throw new IOException("Simulated failure resolving 
the lock file directory");
+                        }
+                        return super.resolveLockPathKey();
+                    }
+                };
+            }
+        };
+        service.setId("node-A");
+        service.setRoot(root.toString());
+        service.setAcquireLockDelay(100, TimeUnit.MILLISECONDS);
+        service.setAcquireLockInterval(100, TimeUnit.MILLISECONDS);
+        service.setHeartbeatTimeoutMultiplier(2);
+        service.setClusterDataTaskMaxAttempts(2);
+
+        context = new DefaultCamelContext();
+        context.disableJMX();
+        context.start();
+        context.addService(service);
+        CamelClusterView view = service.getView(NAMESPACE);
+        Path dataFile = root.resolve(NAMESPACE + ".dat");
+        await().atMost(10, TimeUnit.SECONDS).until(() -> 
view.getLocalMember().isLeader()
+                && FileLockClusterUtils.readClusterLeaderInfo(dataFile) != 
null);
+        String id = 
FileLockClusterUtils.readClusterLeaderInfo(dataFile).getId();
+
+        // record the leadership changes (true: this member is leader) instead 
of polling for the loss: a member that
+        // takes the leadership back at once is follower for only one check, 
which polling can miss. The listener is
+        // told the current leader when it is added, so the first entry is true
+        List<Boolean> leadership = new CopyOnWriteArrayList<>();
+        view.addEventListener((CamelClusterEventListener.Leadership) (v, 
leader) -> leadership
+                .add(leader != null && leader.isLocal()));
+        assertEquals(List.of(true), leadership);
+
+        // the next read of the leader fails, so it gives up the leadership. 
If failFirstAttempt, every attempt of the
+        // task that resolves the lock file key fails in its first try to take 
the leadership back. The file system is
+        // healthy after that, so the member must take the leadership back
+        if (failFirstAttempt) {
+            keyFailures.set(service.getClusterDataTaskMaxAttempts());
+        }
+        readFailures.set(1);
+        await().atMost(10, TimeUnit.SECONDS).until(() -> leadership.size() >= 
3);
+        assertEquals(List.of(true, false, true), leadership);
+        assertEquals(0, readFailures.get());
+        assertEquals(0, keyFailures.get());
+        assertTrue(view.getLocalMember().isLeader());
+        // the member is told it is leader before it writes the cluster data, 
which it truncates first
+        await().atMost(10, TimeUnit.SECONDS).until(() -> {
+            FileLockClusterLeaderInfo info = 
FileLockClusterUtils.readClusterLeaderInfo(dataFile);
+            return info != null && id.equals(info.getId());
+        });
+    }
+}

Reply via email to