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 f92ff595492a CAMEL-27567: camel-file - FileLockClusterView must not 
leave a timed-out open of the lock file to the garbage collector (#30863)
f92ff595492a is described below

commit f92ff595492aba4d8fb9edfb229e111c799dc4ca
Author: allthingssecurity <[email protected]>
AuthorDate: Thu Nov 26 21:04:08 2026 +0530

    CAMEL-27567: camel-file - FileLockClusterView must not leave a timed-out 
open of the lock file to the garbage collector (#30863)
    
    An open of the lock file that timed out keeps running, as cancelling the
    CompletableFuture of the cluster task executor does not interrupt it.
    The retry took the lock and the view became leader, then the late
    attempt returned a second RandomAccessFile on the lock file that nothing
    referenced. When the garbage collector closed it, the OS lock of the
    process was released while the view still reported LEADER, and a member
    in another JVM could become leader too.
    
    The view no longer leaves a file on the lock file to the garbage
    collector. Finished attempts are closed before the lock is tried. While
    a timed-out attempt still runs, the view does not try the lock and keeps
    the lock file registered in the JVM-wide registry of CAMEL-27322; the
    late attempt closes its file and the last one to end removes the entry.
    The wait is logged once at WARN (naming clusterDataTaskTimeout) and its
    end at INFO. If an open never returns, no view of that JVM tries that
    lock again until a restart; the 4.24 upgrade guide has an entry.
    
    Carries the CAMEL-27566 line byte for byte. New
    FileLockClusterViewLateLockFileOpenTest, with an openFile(Path) hook.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../file/cluster/FileLockClusterView.java          | 167 +++++++++++++++-
 .../FileLockClusterViewLateLockFileOpenTest.java   | 211 +++++++++++++++++++++
 .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc    |   9 +
 3 files changed, 384 insertions(+), 3 deletions(-)

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 d72527b7d699..b233aa8d8ab9 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
@@ -24,6 +24,7 @@ import java.nio.channels.OverlappingFileLockException;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.Paths;
+import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 import java.util.Map;
@@ -68,6 +69,16 @@ public class FileLockClusterView extends 
AbstractCamelClusterView {
     private volatile FileLock lock;
     // the key of the lock file in LOCK_PATHS while the view holds the lock 
(written with lock, under stateLock)
     private volatile Path lockPathKey;
+    // The opens of the lock file that acquireLock gave up on and that are 
still running (an attempt that timed out
+    // keeps running, as the cluster task executor cannot interrupt it), and 
the key of the lock file to remove from
+    // LOCK_PATHS when the last of them ended (both guarded by stateLock). 
Closing a channel of the lock file releases the
+    // lock of the process (see LOCK_PATHS), so the file of such an open must 
not be left to the garbage collector, which
+    // closes it at any time, also while this view or another view of the JVM 
holds the lock. It is closed as soon as it
+    // is opened, and until then the view keeps the key registered and does 
not try the lock. If such an open never
+    // returns (a hung mount), no view of this JVM tries the lock again until 
the JVM restarts: both survive a stop and
+    // start of the view, as the open is still running.
+    private int lateLockFileOpens;
+    private Path lateLockFileOpensKey;
     private int heartbeatTimeoutMultiplier;
     private long acquireLockIntervalMilliseconds;
     private FileLockClusterTaskExecutor clusterTaskExecutor;
@@ -293,7 +304,45 @@ public class FileLockClusterView extends 
AbstractCamelClusterView {
 
     private void unregisterLockPath(Path key) {
         if (key != null) {
-            LOCK_PATHS.remove(key, this);
+            stateLock.lock();
+            try {
+                if (lateLockFileOpens > 0) {
+                    // removed when the last late open of the lock file ended
+                    lateLockFileOpensKey = key;
+                } else {
+                    LOCK_PATHS.remove(key, this);
+                }
+            } finally {
+                stateLock.unlock();
+            }
+        }
+    }
+
+    private boolean hasLateLockFileOpens() {
+        stateLock.lock();
+        try {
+            return lateLockFileOpens > 0;
+        } finally {
+            stateLock.unlock();
+        }
+    }
+
+    private void lateLockFileOpenEnded() {
+        boolean last;
+        stateLock.lock();
+        try {
+            lateLockFileOpens--;
+            last = lateLockFileOpens == 0;
+            if (last && lateLockFileOpensKey != null) {
+                LOCK_PATHS.remove(lateLockFileOpensKey, this);
+                lateLockFileOpensKey = null;
+            }
+        } finally {
+            stateLock.unlock();
+        }
+        if (last) {
+            LOGGER.info("The open of lock file {} that timed out has ended 
(cluster-member-id={})",
+                    leaderLockPath, localMember.getUuid());
         }
     }
 
@@ -453,6 +502,11 @@ public class FileLockClusterView extends 
AbstractCamelClusterView {
             // stopped while the cluster data was read: do not take the lock, 
even briefly
             return false;
         }
+        if (hasLateLockFileOpens()) {
+            LOGGER.debug("An open of lock file {} that timed out is still 
running (cluster-member-id={}), not trying the lock",
+                    leaderLockPath, localMember.getUuid());
+            return false;
+        }
         // resolved before the key is registered, so a timeout leaves nothing 
in LOCK_PATHS
         Path key = lockPathKey();
         if (key == null) {
@@ -473,7 +527,11 @@ public class FileLockClusterView extends 
AbstractCamelClusterView {
         boolean published = false;
         try {
             newLockFile = createRandomAccessFile(leaderLockPath);
-            newDataFile = createRandomAccessFile(leaderDataPath);
+            if (newLockFile != null) {
+                // null if an open of the lock file is still running: the lock 
is not tried, so the data file is not
+                // needed
+                newDataFile = createRandomAccessFile(leaderDataPath);
+            }
             if (newLockFile != null && newDataFile != null) {
                 newLock = newLockFile.getChannel().tryLock(0, Math.max(1, 
newLockFile.getChannel().size()), false);
             }
@@ -576,14 +634,117 @@ public class FileLockClusterView extends 
AbstractCamelClusterView {
     }
 
     RandomAccessFile createRandomAccessFile(Path path) throws 
ExecutionException, TimeoutException {
+        if (path.equals(leaderLockPath)) {
+            LockFileOpen open = new LockFileOpen();
+            try {
+                return 
open.end(clusterTaskExecutor.run(ThrowingHelper.wrapAsSupplier(open)));
+            } finally {
+                // closes what the attempts opened if the executor gave up (no 
effect if the call already ended)
+                open.end(null);
+            }
+        }
         return clusterTaskExecutor.run(ThrowingHelper.wrapAsSupplier(new 
ThrowingSupplier<RandomAccessFile, Throwable>() {
             @Override
             public RandomAccessFile get() throws Throwable {
-                return new RandomAccessFile(path.toFile(), "rw");
+                return openFile(path);
             }
         }));
     }
 
+    RandomAccessFile openFile(Path path) throws IOException {
+        return new RandomAccessFile(path.toFile(), "rw");
+    }
+
+    /**
+     * One open of the lock file by acquireLock. The cluster task executor 
runs it once per attempt, and an attempt that
+     * timed out keeps running. Every file an attempt opens is returned by 
{@link #end} or closed: by end if the attempt
+     * finished before the call ended, otherwise as soon as it is opened (see 
lateLockFileOpens).
+     */
+    private final class LockFileOpen implements 
ThrowingSupplier<RandomAccessFile, Throwable> {
+        // guarded by stateLock
+        private final List<RandomAccessFile> opened = new ArrayList<>();
+        private int running;
+        private boolean ended;
+
+        @Override
+        public RandomAccessFile get() throws Throwable {
+            stateLock.lock();
+            try {
+                if (ended) {
+                    // an attempt that only starts after the call ended
+                    return null;
+                }
+                running++;
+            } finally {
+                stateLock.unlock();
+            }
+            RandomAccessFile file = null;
+            try {
+                file = openFile(leaderLockPath);
+                return file;
+            } finally {
+                attemptEnded(file);
+            }
+        }
+
+        private void attemptEnded(RandomAccessFile file) {
+            boolean late;
+            stateLock.lock();
+            try {
+                running--;
+                late = ended;
+                if (!late && file != null) {
+                    opened.add(file);
+                }
+            } finally {
+                stateLock.unlock();
+            }
+            if (late) {
+                // this view has not tried the lock since the call ended, and 
no other view of the JVM has, as the key
+                // is still registered: closing the file releases no lock
+                closeFile(file);
+                lateLockFileOpenEnded();
+            }
+        }
+
+        /**
+         * Ends the call with the file the executor returned. Returns that 
file, or null if an attempt is still running:
+         * the lock must not be tried then, as closing the file of that 
attempt later would release it. Closes the other
+         * files the attempts opened.
+         */
+        RandomAccessFile end(RandomAccessFile result) {
+            List<RandomAccessFile> files;
+            boolean stillRunning;
+            stateLock.lock();
+            try {
+                if (ended) {
+                    return null;
+                }
+                ended = true;
+                stillRunning = running > 0;
+                lateLockFileOpens += running;
+                files = new ArrayList<>(opened);
+                opened.clear();
+            } finally {
+                stateLock.unlock();
+            }
+            RandomAccessFile file = stillRunning ? null : result;
+            for (RandomAccessFile f : files) {
+                if (f != file) {
+                    closeFile(f);
+                }
+            }
+            if (stillRunning) {
+                // logged once per wait (acquireLock does not open the lock 
file again until the wait ended), at WARN
+                // as the wait lasts until the JVM restarts if the open never 
returns
+                LOGGER.warn(
+                        "An open of lock file {} timed out and is still 
running. This JVM does not try the lock until the open ends; on a hung mount 
that takes a JVM restart. If every open is this slow, raise 
clusterDataTaskTimeout (cluster-member-id={})",
+                        leaderLockPath, localMember.getUuid());
+            }
+            return file;
+        }
+    }
+
     FileLockClusterLeaderInfo readClusterLeaderInfo() throws Exception {
         return clusterTaskExecutor
                 .run(ThrowingHelper.wrapAsSupplier(new 
ThrowingSupplier<FileLockClusterLeaderInfo, Throwable>() {
diff --git 
a/core/camel-core/src/test/java/org/apache/camel/component/file/cluster/FileLockClusterViewLateLockFileOpenTest.java
 
b/core/camel-core/src/test/java/org/apache/camel/component/file/cluster/FileLockClusterViewLateLockFileOpenTest.java
new file mode 100644
index 000000000000..5782700cb12e
--- /dev/null
+++ 
b/core/camel-core/src/test/java/org/apache/camel/component/file/cluster/FileLockClusterViewLateLockFileOpenTest.java
@@ -0,0 +1,211 @@
+/*
+ * 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.io.RandomAccessFile;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.camel.CamelContext;
+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.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * An attempt to open the lock file that times out keeps running, as the 
cluster task executor cannot interrupt it, and
+ * the executor retries. The file locks are locks of the process, and closing 
any channel of the lock file releases them
+ * all at OS level (see {@link java.nio.channels.FileLock}). So the file of 
the late attempt must not be left open for
+ * the garbage collector to close it while the lock is held: a member in 
another JVM could then take the lock too, while
+ * this member still reports that it is the leader.
+ */
+class FileLockClusterViewLateLockFileOpenTest {
+
+    private static final String NAMESPACE = "ns";
+
+    @TempDir
+    Path root;
+
+    private final List<CamelContext> contexts = new ArrayList<>();
+    private final List<CountDownLatch> latches = new ArrayList<>();
+
+    @AfterEach
+    void stopContexts() {
+        latches.forEach(CountDownLatch::countDown);
+        contexts.forEach(CamelContext::stop);
+    }
+
+    @Test
+    void viewDoesNotTakeTheLockWhileATimedOutOpenOfTheLockFileIsRunning() 
throws Exception {
+        OpenTrackingFileLockClusterService service = newService(new 
OpenTrackingFileLockClusterService(true), "A");
+        startContext().addService(service);
+        CamelClusterView view = service.getView(NAMESPACE);
+
+        // the first attempt to open the lock file outlives the task timeout, 
the retry opens the file at once
+        assertTrue(service.slowOpenStarted.await(10, TimeUnit.SECONDS));
+        await().atMost(10, TimeUnit.SECONDS).until(() -> 
!service.lockFiles.isEmpty());
+        int checks = service.checks.get();
+        await().atMost(10, TimeUnit.SECONDS).until(() -> service.checks.get() 
>= checks + 3);
+
+        // the file of the slow attempt is opened later and closed then: 
holding the lock now would lose it at that time
+        assertFalse(view.getLocalMember().isLeader(),
+                "the view took the lock while an open of the lock file that 
timed out was still running");
+        assertEquals(0, service.openLockFiles(), "a lock file opened by the 
view is still open");
+
+        service.releaseSlowOpen.countDown();
+        await().atMost(10, TimeUnit.SECONDS).until(() -> 
view.getLocalMember().isLeader());
+        assertEquals(1, service.openLockFiles(), "only the lock file that 
holds the lock may be open");
+    }
+
+    @Test
+    void 
anotherViewOfTheJvmDoesNotOpenTheLockFileWhileATimedOutOpenIsRunning() throws 
Exception {
+        OpenTrackingFileLockClusterService serviceA = newService(new 
OpenTrackingFileLockClusterService(true), "A");
+        CamelContext contextA = startContext();
+        contextA.addService(serviceA);
+        CamelClusterView viewA = serviceA.getView(NAMESPACE);
+        assertTrue(serviceA.slowOpenStarted.await(10, TimeUnit.SECONDS));
+        await().atMost(10, TimeUnit.SECONDS).until(() -> 
!serviceA.lockFiles.isEmpty());
+
+        // A stops while its slow open is still running
+        contextA.stop();
+
+        OpenTrackingFileLockClusterService serviceB = newService(new 
OpenTrackingFileLockClusterService(false), "B");
+        startContext().addService(serviceB);
+        CamelClusterView viewB = serviceB.getView(NAMESPACE);
+        await().atMost(10, TimeUnit.SECONDS).until(() -> serviceB.checks.get() 
>= 3);
+
+        // closing the late file of A would release a lock that B took 
meanwhile
+        assertEquals(0, serviceB.lockFiles.size(),
+                "a view opened the lock file while an open of it by another 
view of the JVM was still running");
+        assertFalse(viewB.getLocalMember().isLeader());
+
+        serviceA.releaseSlowOpen.countDown();
+        await().atMost(10, TimeUnit.SECONDS).until(() -> 
viewB.getLocalMember().isLeader());
+        assertEquals(0, serviceA.openLockFiles(), "a lock file opened by the 
stopped view is still open");
+        assertFalse(viewA.getLocalMember().isLeader());
+    }
+
+    @Test
+    void 
onlyMemberLeadsAgainAfterATimedOutOpenOfTheLockFileWhileTakingTheLeadershipBack()
 throws Exception {
+        OpenTrackingFileLockClusterService service = newService(new 
OpenTrackingFileLockClusterService(false), "A");
+        startContext().addService(service);
+        CamelClusterView view = service.getView(NAMESPACE);
+        await().atMost(10, TimeUnit.SECONDS).until(() -> 
view.getLocalMember().isLeader());
+
+        // one failed read makes the leader step down; the cluster data still 
names it, so it takes the leadership back,
+        // and the first open of the lock file for that outlives the task 
timeout
+        service.slow.set(true);
+        service.readFailures.set(1);
+        await().atMost(10, TimeUnit.SECONDS).until(() -> 
!view.getLocalMember().isLeader());
+        assertTrue(service.slowOpenStarted.await(10, TimeUnit.SECONDS));
+        int checks = service.checks.get();
+        await().atMost(10, TimeUnit.SECONDS).until(() -> service.checks.get() 
>= checks + 3);
+        assertFalse(view.getLocalMember().isLeader(),
+                "the view took the lock while an open of the lock file that 
timed out was still running");
+
+        // the failed attempt must not keep the member in the backoff for 
good: it is the only member of the cluster
+        service.releaseSlowOpen.countDown();
+        await().atMost(10, TimeUnit.SECONDS).until(() -> 
view.getLocalMember().isLeader());
+        assertEquals(1, service.openLockFiles(), "only the lock file that 
holds the lock may be open");
+    }
+
+    private CamelContext startContext() {
+        CamelContext context = new DefaultCamelContext();
+        context.disableJMX();
+        contexts.add(context);
+        context.start();
+        return context;
+    }
+
+    private <T extends OpenTrackingFileLockClusterService> T newService(T 
service, String id) {
+        latches.add(service.releaseSlowOpen);
+        service.setId("node-" + id);
+        service.setRoot(root.toString());
+        service.setAcquireLockDelay(100, TimeUnit.MILLISECONDS);
+        service.setAcquireLockInterval(100, TimeUnit.MILLISECONDS);
+        service.setHeartbeatTimeoutMultiplier(2);
+        service.setClusterDataTaskTimeout(200, TimeUnit.MILLISECONDS);
+        return service;
+    }
+
+    /**
+     * Keeps the lock files its view opens and counts the leadership checks. 
If slow, the first open of the lock file
+     * waits until {@link #releaseSlowOpen} is counted down, as on a slow 
network mount. The next {@link #readFailures}
+     * reads of the cluster data fail.
+     */
+    private static final class OpenTrackingFileLockClusterService extends 
FileLockClusterService {
+        final List<RandomAccessFile> lockFiles = new CopyOnWriteArrayList<>();
+        final AtomicInteger checks = new AtomicInteger();
+        final CountDownLatch slowOpenStarted = new CountDownLatch(1);
+        final CountDownLatch releaseSlowOpen = new CountDownLatch(1);
+        final AtomicInteger readFailures = new AtomicInteger();
+        final AtomicBoolean slow;
+
+        OpenTrackingFileLockClusterService(boolean slow) {
+            this.slow = new AtomicBoolean(slow);
+        }
+
+        long openLockFiles() {
+            return lockFiles.stream().filter(file -> 
file.getChannel().isOpen()).count();
+        }
+
+        @Override
+        protected FileLockClusterView createView(String namespace) {
+            return new FileLockClusterView(this, namespace) {
+                @Override
+                FileLockClusterLeaderInfo readClusterLeaderInfo() throws 
Exception {
+                    checks.incrementAndGet();
+                    if (readFailures.getAndUpdate(n -> Math.max(0, n - 1)) > 
0) {
+                        throw new IOException("Simulated failure to read the 
cluster data");
+                    }
+                    return super.readClusterLeaderInfo();
+                }
+
+                @Override
+                RandomAccessFile openFile(Path path) throws IOException {
+                    if (!path.getFileName().toString().equals(NAMESPACE)) {
+                        return super.openFile(path);
+                    }
+                    if (slow.compareAndSet(true, false)) {
+                        slowOpenStarted.countDown();
+                        try {
+                            releaseSlowOpen.await(30, TimeUnit.SECONDS);
+                        } catch (InterruptedException e) {
+                            Thread.currentThread().interrupt();
+                        }
+                    }
+                    RandomAccessFile file = super.openFile(path);
+                    lockFiles.add(file);
+                    return file;
+                }
+            };
+        }
+    }
+}
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 078068558101..38b8b68c3feb 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
@@ -272,6 +272,15 @@ client library) is now a failed poll, as an exception, and 
the consumer polls ag
 scheduler, it also ended the scheduled task. See the section "camel-core - a 
VirtualMachineError fails the exchange,
 and Camel does not recover from it".
 
+=== camel-file - a file lock cluster member waits for an open of the lock file 
that timed out
+
+When an open of the lock file of the file lock cluster service 
(`FileLockClusterService`) takes longer than
+`clusterDataTaskTimeout`, the open keeps running, and the member no longer 
tries the lock with a retry meanwhile:
+the file of the late open, closed later by the garbage collector, released the 
lock of the leader. The member tries
+the lock again once the open has ended, and a WARN names the lock file when 
the wait starts. If the open never returns
+(for example on a hung network mount), no cluster view of that JVM tries the 
lock on that file until the JVM restarts,
+so a cluster with no member on another JVM stays without a leader. Previously 
the retry took the lock in that case.
+
 === camel-jms, camel-spring-rabbitmq - suspending or stopping a consumer waits 
at most shutdownAwaitTermination for its listener container
 
 Suspending or stopping a consumer of camel-jms (and of the components built on 
it, such as camel-activemq,

Reply via email to