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 dedca5ba0e3b CAMEL-27509: camel-infinispan - a stopping cluster view
gives up the leadership first, and does not wait twice for its leadership
thread (#30818)
dedca5ba0e3b is described below
commit dedca5ba0e3befaea1f8c5f13b75bbd728716013
Author: allthingssecurity <[email protected]>
AuthorDate: Thu Nov 26 16:08:11 2026 +0530
CAMEL-27509: camel-infinispan - a stopping cluster view gives up the
leadership first, and does not wait twice for its leadership thread (#30818)
The leadership run of the remote and embedded cluster views took the lock
of the LeadershipService, which BaseService.stop() holds for the whole
doStop(). A run that started during the stop blocked on that lock, so
shutdownGraceful waited the shutdown await termination twice, and a run
waiting for the server held up stop() itself. All that time the stopping
node kept leader=true without refreshing the leader key, so another node
could take the key and both were leader.
- doStop sets running to false and gives up the leadership (fires the
lost event) before it removes the listener and waits for the executor;
the leader key is still removed afterwards as before.
- run() no longer takes the service lock and returns at once when
stopped; it skips the acquire and the membership refresh once stopped.
- a run takes the leadership only while running (under a small lock
shared with doStop), and still records the version so the stop
releases a key it acquired meanwhile.
- an error of a run while stopping is logged at DEBUG; version is
volatile (remote).
The review nits are addressed as well: a comment says why the version is
read also while stopping, and the stop test leaves more room for a slow
machine (shutdown await termination 2 s).
_Claude Code on behalf of allthingssecurity_
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../cluster/InfinispanEmbeddedClusterView.java | 76 ++--
.../InfinispanEmbeddedClusterViewStopTest.java | 258 ++++++++++++++
.../cluster/InfinispanRemoteClusterView.java | 85 +++--
.../InfinispanRemoteClusterViewStopTest.java | 386 +++++++++++++++++++++
4 files changed, 758 insertions(+), 47 deletions(-)
diff --git
a/components/camel-infinispan/camel-infinispan-embedded/src/main/java/org/apache/camel/component/infinispan/embedded/cluster/InfinispanEmbeddedClusterView.java
b/components/camel-infinispan/camel-infinispan-embedded/src/main/java/org/apache/camel/component/infinispan/embedded/cluster/InfinispanEmbeddedClusterView.java
index a0db91d60c35..ff0b5405dbde 100644
---
a/components/camel-infinispan/camel-infinispan-embedded/src/main/java/org/apache/camel/component/infinispan/embedded/cluster/InfinispanEmbeddedClusterView.java
+++
b/components/camel-infinispan/camel-infinispan-embedded/src/main/java/org/apache/camel/component/infinispan/embedded/cluster/InfinispanEmbeddedClusterView.java
@@ -22,6 +22,8 @@ import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import org.apache.camel.cluster.CamelClusterMember;
@@ -139,6 +141,9 @@ public class InfinispanEmbeddedClusterView extends
InfinispanClusterView {
@Listener(clustered = true, sync = false)
private final class LeadershipService extends ServiceSupport {
private final AtomicBoolean running;
+ // held while running is set to false on stop and while a run takes
the leadership, so that a run still in
+ // progress when the service is stopped cannot make the local member
the leader again
+ private final Lock leadershipLock = new ReentrantLock();
private ScheduledExecutorService executorService;
LeadershipService() {
@@ -175,19 +180,27 @@ public class InfinispanEmbeddedClusterView extends
InfinispanClusterView {
protected void doStop() throws Exception {
super.doStop();
- this.running.set(false);
-
- if (cache != null) {
- cache.removeListener(this);
+ leadershipLock.lock();
+ try {
+ this.running.set(false);
+ } finally {
+ leadershipLock.unlock();
}
-
getCamelContext().getExecutorServiceManager().shutdownGraceful(executorService);
-
try {
- // tell the listeners (such as clustered routes) that the
local member is no longer the leader, before
- // the leader key is removed and another member can take over
the leadership
+ // tell the listeners (such as clustered routes) that the
local member is no longer the leader right
+ // away, as it no longer refreshes the leader key, and before
the leader key is removed and another
+ // member can take over the leadership
setLeader(false);
} finally {
+ if (cache != null) {
+ cache.removeListener(this);
+ }
+
+ // a run in progress does not wait for the lock of this
service (held while stopping), so this waits
+ // until that run ends (and interrupts it after the shutdown
await termination)
+
getCamelContext().getExecutorServiceManager().shutdownGraceful(executorService);
+
if (cache != null) {
cache.remove(InfinispanClusterService.LEADER_KEY,
getClusterService().getId());
@@ -201,21 +214,34 @@ public class InfinispanEmbeddedClusterView extends
InfinispanClusterView {
return getLocalMember().isLeader();
}
+ /**
+ * Makes the local member the leader, unless this service has been
stopped meanwhile (stopping gives up the
+ * leadership and then releases the leader key).
+ */
+ private void takeLeadership() {
+ leadershipLock.lock();
+ try {
+ if (running.get()) {
+ setLeader(true);
+ }
+ } finally {
+ leadershipLock.unlock();
+ }
+ }
+
private void setLeader(boolean leader) {
((LocalMember) getLocalMember()).setLeader(leader);
}
private void run() {
- lock.lock();
- try {
- if (!running.get()) {
- return;
- }
+ // without the lock of this service: stopping holds it while it
waits for the run in progress to end
+ if (!running.get()) {
+ return;
+ }
- refreshLeadership();
+ refreshLeadership();
+ if (running.get()) {
refreshMembership();
- } finally {
- lock.unlock();
}
}
@@ -237,7 +263,7 @@ public class InfinispanEmbeddedClusterView extends
InfinispanClusterView {
setLeader(false);
}
}
- if (!isLeader()) {
+ if (!isLeader() && running.get()) {
LOGGER.debug("Try to acquire lock key={}, id={}",
leaderKey, localId);
Object result =
cache.putIfAbsent(InfinispanClusterService.LEADER_KEY,
getClusterService().getId(),
@@ -245,12 +271,12 @@ public class InfinispanEmbeddedClusterView extends
InfinispanClusterView {
if (result == null) {
LOGGER.debug("Lock acquired key={}, id={}", leaderKey,
localId);
// Acquired the key so I'm the leader.
- setLeader(true);
+ takeLeadership();
} else if (Objects.equals(getClusterService().getId(),
result) && !isLeader()) {
LOGGER.debug("Lock resumed key={}, id={}", leaderKey,
localId);
// Hey, I may have recovered from failure (or reboot
was really
// fast) and my key was still there so yeah, I'm the
leader again!
- setLeader(true);
+ takeLeadership();
} else {
LOGGER.debug("Failed to acquire the lock key={},
id={}", leaderKey, localId);
setLeader(false);
@@ -259,9 +285,15 @@ public class InfinispanEmbeddedClusterView extends
InfinispanClusterView {
} catch (Exception e) {
// an exception must not end the periodic refresh of the
leadership (as it would with an exception
// thrown out of this task), and as the leadership could not
be refreshed, give it up until the next run
- LOGGER.warn("Error while refreshing the leadership of id={}
(will try again): {}",
- getLocalMember().getId(), e.getMessage());
- LOGGER.debug("Error while refreshing the leadership", e);
+ if (running.get()) {
+ LOGGER.warn("Error while refreshing the leadership of
id={} (will try again): {}",
+ getLocalMember().getId(), e.getMessage());
+ LOGGER.debug("Error while refreshing the leadership", e);
+ } else {
+ // such as a call interrupted by stopping
+ LOGGER.debug("Error while refreshing the leadership of
id={} while stopping",
+ getLocalMember().getId(), e);
+ }
try {
setLeader(false);
} catch (Exception ex) {
diff --git
a/components/camel-infinispan/camel-infinispan-embedded/src/test/java/org/apache/camel/component/infinispan/embedded/cluster/InfinispanEmbeddedClusterViewStopTest.java
b/components/camel-infinispan/camel-infinispan-embedded/src/test/java/org/apache/camel/component/infinispan/embedded/cluster/InfinispanEmbeddedClusterViewStopTest.java
new file mode 100644
index 000000000000..b305b2080fcf
--- /dev/null
+++
b/components/camel-infinispan/camel-infinispan-embedded/src/test/java/org/apache/camel/component/infinispan/embedded/cluster/InfinispanEmbeddedClusterViewStopTest.java
@@ -0,0 +1,258 @@
+/*
+ * 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.infinispan.embedded.cluster;
+
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.cluster.CamelClusterEventListener;
+import org.apache.camel.cluster.CamelClusterView;
+import org.apache.camel.component.infinispan.cluster.InfinispanClusterService;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.spi.ThreadPoolProfile;
+import org.apache.camel.support.DefaultThreadPoolFactory;
+import org.infinispan.Cache;
+import org.infinispan.cache.impl.AbstractDelegatingCache;
+import org.infinispan.manager.DefaultCacheManager;
+import org.infinispan.manager.EmbeddedCacheManager;
+import org.infinispan.manager.impl.AbstractDelegatingEmbeddedCacheManager;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+import static
org.apache.camel.component.infinispan.embedded.cluster.InfinispanEmbeddedClusteredTestSupport.createCache;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
+
+/**
+ * Stopping the view while the leadership thread is busy: the local member
gives up the leadership at once, and the stop
+ * does not wait on the lock of the leadership service.
+ */
+class InfinispanEmbeddedClusterViewStopTest {
+ private static final String VIEW_NAME = "myView";
+ private static final String NODE_ID = "node";
+ private static final long SHUTDOWN_AWAIT_TERMINATION = 1000;
+
+ private final DefaultCacheManager cacheContainer = new
DefaultCacheManager();
+ private final BlockingCacheManager cacheManager = new
BlockingCacheManager(cacheContainer);
+ private final LeadershipThreadPoolFactory pools = new
LeadershipThreadPoolFactory();
+ private final ExecutorService stopper =
Executors.newSingleThreadExecutor();
+ private final List<Boolean> events = new CopyOnWriteArrayList<>();
+ private DefaultCamelContext context;
+ private CamelClusterView view;
+
+ @AfterEach
+ void tearDown() throws Exception {
+ cacheManager.releaseAll();
+ stopper.shutdownNow();
+ stopper.awaitTermination(10, TimeUnit.SECONDS);
+ if (context != null) {
+ context.close();
+ }
+ cacheContainer.close();
+ }
+
+ @Test
+ void runStartedWhileStoppingDoesNotDelayTheStop() throws Exception {
+ startView();
+ await().atMost(10, TimeUnit.SECONDS).until(() ->
view.getLocalMember().isLeader());
+ int received = events.size();
+
+ // the stop is held in the removal of the cache listener, while a
leadership run starts (as the periodic run or
+ // a run queued by an event would)
+ cacheManager.blockRemoveListener = true;
+ CompletableFuture<Long> stop = stopAsync();
+ assertThat(cacheManager.removeListenerCalled.await(10,
TimeUnit.SECONDS)).isTrue();
+ CountDownLatch runStarted = new CountDownLatch(1);
+ pools.runAgain(runStarted::countDown);
+ assertThat(runStarted.await(10, TimeUnit.SECONDS)).isTrue();
+ cacheManager.removeListenerRelease.countDown();
+
+ // the stop does not wait for that run until the shutdown await
termination runs out twice, as the run does not
+ // wait for the lock of the leadership service held by the stop
+ assertThat(stop.get(10,
TimeUnit.SECONDS)).isLessThan(SHUTDOWN_AWAIT_TERMINATION);
+
+ // and the leadership was given up before the stop waited for anything
else
+ assertThat(cacheManager.leaderWhenRemovingListener).isFalse();
+ assertThat(cacheManager.eventsWhenRemovingListener).isEqualTo(events);
+ assertThat(events.subList(received,
events.size())).containsExactly(false);
+
assertThat(cacheContainer.getCache(VIEW_NAME).get(InfinispanClusterService.LEADER_KEY)).isNull();
+ }
+
+ @Test
+ void runThatAcquiresTheLeaderKeyWhileStoppingDoesNotTakeTheLeadership()
throws Exception {
+ // the first leadership run is held while it acquires the leader key
+ cacheManager.blockPutIfAbsent = true;
+ startView();
+ assertThat(cacheManager.putIfAbsentCalled.await(10,
TimeUnit.SECONDS)).isTrue();
+ // (a new leadership listener is told the current leader when it is
added)
+ int received = events.size();
+
+ CompletableFuture<Long> stop = stopAsync();
+ assertThat(cacheManager.removeListenerCalled.await(10,
TimeUnit.SECONDS)).isTrue();
+
+ // the key is then acquired
+ cacheManager.putIfAbsentRelease.countDown();
+ stop.get(10, TimeUnit.SECONDS);
+
+ // the stopped member did not become the leader, and the key it
acquired is released
+ assertThat(view.getLocalMember().isLeader()).isFalse();
+ assertThat(events.subList(received, events.size())).isEmpty();
+ assertThat(events).doesNotContain(true);
+
assertThat(cacheContainer.getCache(VIEW_NAME).get(InfinispanClusterService.LEADER_KEY)).isNull();
+ }
+
+ private void startView() throws Exception {
+ createCache(cacheContainer, VIEW_NAME);
+
+ context = new DefaultCamelContext();
+ context.disableJMX();
+ context.getExecutorServiceManager().setThreadPoolFactory(pools);
+
context.getExecutorServiceManager().setShutdownAwaitTermination(SHUTDOWN_AWAIT_TERMINATION);
+
+ InfinispanEmbeddedClusterService clusterService = new
InfinispanEmbeddedClusterService();
+ clusterService.setCacheContainer(cacheManager);
+ clusterService.setId(NODE_ID);
+ // a long lifespan, so that the periodic run does not run during the
test (the test runs it instead)
+ clusterService.setLifespan(60);
+ clusterService.setLifespanTimeUnit(TimeUnit.SECONDS);
+ context.addService(clusterService);
+ context.start();
+
+ view = clusterService.getView(VIEW_NAME);
+ cacheManager.view = view;
+ cacheManager.events = events;
+ view.addEventListener((CamelClusterEventListener.Leadership) (v,
leader) -> events
+ .add(v.getLocalMember().isLeader()));
+ }
+
+ /**
+ * Stops the view on another thread, and returns how long the stop took in
millis.
+ */
+ private CompletableFuture<Long> stopAsync() {
+ return CompletableFuture.supplyAsync(() -> {
+ long start = System.nanoTime();
+ view.stop();
+ return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
+ }, stopper);
+ }
+
+ /**
+ * A thread pool factory that keeps the executor and the periodic task of
the leadership service, so that the test
+ * can run the task again on the leadership thread when it needs to.
+ */
+ private static final class LeadershipThreadPoolFactory extends
DefaultThreadPoolFactory {
+ private volatile ScheduledExecutorService leadershipExecutor;
+ private volatile Runnable leadershipRun;
+
+ @Override
+ public ScheduledExecutorService
newScheduledThreadPool(ThreadPoolProfile profile, ThreadFactory threadFactory) {
+ if (!profile.getId().startsWith("LeadershipService")) {
+ return super.newScheduledThreadPool(profile, threadFactory);
+ }
+ ScheduledExecutorService executor = new
ScheduledThreadPoolExecutor(1, threadFactory) {
+ @Override
+ public ScheduledFuture<?> scheduleAtFixedRate(
+ Runnable command, long initialDelay, long period,
TimeUnit unit) {
+ leadershipRun = command;
+ return super.scheduleAtFixedRate(command, initialDelay,
period, unit);
+ }
+ };
+ leadershipExecutor = executor;
+ return executor;
+ }
+
+ void runAgain(Runnable before) {
+ Runnable run = leadershipRun;
+ leadershipExecutor.execute(() -> {
+ before.run();
+ run.run();
+ });
+ }
+ }
+
+ /**
+ * A cache manager whose caches hold the removal of the listener or the
acquisition of the leader key until the test
+ * releases them.
+ */
+ private static final class BlockingCacheManager extends
AbstractDelegatingEmbeddedCacheManager {
+ private final CountDownLatch removeListenerCalled = new
CountDownLatch(1);
+ private final CountDownLatch removeListenerRelease = new
CountDownLatch(1);
+ private final CountDownLatch putIfAbsentCalled = new CountDownLatch(1);
+ private final CountDownLatch putIfAbsentRelease = new
CountDownLatch(1);
+
+ private volatile CamelClusterView view;
+ private volatile List<Boolean> events;
+ private volatile boolean blockRemoveListener;
+ private volatile boolean blockPutIfAbsent;
+ private volatile Boolean leaderWhenRemovingListener;
+ private volatile List<Boolean> eventsWhenRemovingListener;
+
+ private BlockingCacheManager(EmbeddedCacheManager cm) {
+ super(cm);
+ }
+
+ void releaseAll() {
+ removeListenerRelease.countDown();
+ putIfAbsentRelease.countDown();
+ }
+
+ @Override
+ public <K, V> Cache<K, V> getCache(String cacheName) {
+ Cache<K, V> cache = super.getCache(cacheName);
+ return new AbstractDelegatingCache<>(cache) {
+ @Override
+ public void removeListener(Object listener) {
+ leaderWhenRemovingListener =
view.getLocalMember().isLeader();
+ eventsWhenRemovingListener = List.copyOf(events);
+ removeListenerCalled.countDown();
+ if (blockRemoveListener) {
+ waitFor(removeListenerRelease);
+ }
+ super.removeListener(listener);
+ }
+
+ @Override
+ public V putIfAbsent(K key, V value, long lifespan, TimeUnit
unit) {
+ if (InfinispanClusterService.LEADER_KEY.equals(key)) {
+ putIfAbsentCalled.countDown();
+ if (blockPutIfAbsent) {
+ waitFor(putIfAbsentRelease);
+ }
+ }
+ return super.putIfAbsent(key, value, lifespan, unit);
+ }
+ };
+ }
+
+ private static void waitFor(CountDownLatch latch) {
+ try {
+ latch.await(1, TimeUnit.MINUTES);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ }
+}
diff --git
a/components/camel-infinispan/camel-infinispan/src/main/java/org/apache/camel/component/infinispan/remote/cluster/InfinispanRemoteClusterView.java
b/components/camel-infinispan/camel-infinispan/src/main/java/org/apache/camel/component/infinispan/remote/cluster/InfinispanRemoteClusterView.java
index 46417b936a5b..6c3b638a4949 100644
---
a/components/camel-infinispan/camel-infinispan/src/main/java/org/apache/camel/component/infinispan/remote/cluster/InfinispanRemoteClusterView.java
+++
b/components/camel-infinispan/camel-infinispan/src/main/java/org/apache/camel/component/infinispan/remote/cluster/InfinispanRemoteClusterView.java
@@ -22,6 +22,8 @@ import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import org.apache.camel.cluster.CamelClusterMember;
@@ -143,9 +145,12 @@ public class InfinispanRemoteClusterView extends
InfinispanClusterView {
private final class LeadershipService extends ServiceSupport {
private final int lifespan;
private final AtomicBoolean running;
+ // held while running is set to false on stop and while a run takes
the leadership, so that a run still in
+ // progress when the service is stopped cannot make the local member
the leader again
+ private final Lock leadershipLock = new ReentrantLock();
private ScheduledExecutorService executorService;
- private Long version;
+ private volatile Long version;
LeadershipService() {
this.lifespan = (int)
configuration.getLifespanTimeUnit().toSeconds(configuration.getLifespan());
@@ -182,19 +187,28 @@ public class InfinispanRemoteClusterView extends
InfinispanClusterView {
protected void doStop() throws Exception {
super.doStop();
- this.running.set(false);
-
- if (cache != null) {
- cache.removeClientListener(this);
+ leadershipLock.lock();
+ try {
+ this.running.set(false);
+ } finally {
+ leadershipLock.unlock();
}
-
getCamelContext().getExecutorServiceManager().shutdownGraceful(executorService);
-
try {
- // tell the listeners (such as clustered routes) that the
local member is no longer the leader, before
- // the leader key is removed and another member can take over
the leadership
+ // tell the listeners (such as clustered routes) that the
local member is no longer the leader right
+ // away, as it no longer refreshes the leader key, and before
the leader key is removed and another
+ // member can take over the leadership
setLeader(false);
} finally {
+ if (cache != null) {
+ cache.removeClientListener(this);
+ }
+
+ // a run in progress does not wait for the lock of this
service (held while stopping), so this waits
+ // until that run ends, or interrupts it after the shutdown
await termination if it is still waiting
+ // for the server
+
getCamelContext().getExecutorServiceManager().shutdownGraceful(executorService);
+
try {
if (cache != null) {
if (this.version != null) {
@@ -210,6 +224,21 @@ public class InfinispanRemoteClusterView extends
InfinispanClusterView {
}
}
+ /**
+ * Makes the local member the leader, unless this service has been
stopped meanwhile (stopping gives up the
+ * leadership, and releases the leader key with the version this run
reads afterwards).
+ */
+ private void takeLeadership() {
+ leadershipLock.lock();
+ try {
+ if (running.get()) {
+ setLeader(true);
+ }
+ } finally {
+ leadershipLock.unlock();
+ }
+ }
+
private boolean isLeader() {
return getLocalMember().isLeader();
}
@@ -219,16 +248,14 @@ public class InfinispanRemoteClusterView extends
InfinispanClusterView {
}
private void run() {
- lock.lock();
- try {
- if (!running.get()) {
- return;
- }
+ // without the lock of this service: stopping holds it while it
waits for the run in progress to end
+ if (!running.get()) {
+ return;
+ }
- refreshLeadership();
+ refreshLeadership();
+ if (running.get()) {
refreshMembership();
- } finally {
- lock.unlock();
}
}
@@ -253,7 +280,7 @@ public class InfinispanRemoteClusterView extends
InfinispanClusterView {
}
}
- if (!isLeader()) {
+ if (!isLeader() && running.get()) {
LOGGER.debug("Try to acquire lock key={}, id={}",
leaderKey, localId);
Object result = cache.withFlags(Flag.FORCE_RETURN_VALUE)
@@ -261,18 +288,20 @@ public class InfinispanRemoteClusterView extends
InfinispanClusterView {
if (result == null) {
// Acquired the key so I'm the leader.
- setLeader(true);
+ takeLeadership();
- // Get the version
+ // Get the version, also when stopping (then
takeLeadership did not take the leadership),
+ // so that doStop releases the leader key this run
acquired meanwhile
version =
cache.getWithMetadata(leaderKey).getVersion();
LOGGER.debug("Lock acquired key={}, id={}, with
version={}", leaderKey, localId, version);
} else if (Objects.equals(getClusterService().getId(),
result) && !isLeader()) {
// Hey, I may have recovered from failure (or reboot
was really
// fast) and my key was still there so yeah, I'm the
leader again!
- setLeader(true);
+ takeLeadership();
- // Get the version
+ // Get the version, also when stopping (then
takeLeadership did not take the leadership),
+ // so that doStop releases the leader key this run
acquired meanwhile
version =
cache.getWithMetadata(leaderKey).getVersion();
LOGGER.debug("Lock resumed key={}, id={} with
version={}", leaderKey, localId, version);
@@ -285,9 +314,15 @@ public class InfinispanRemoteClusterView extends
InfinispanClusterView {
} catch (Exception e) {
// an exception must not end the periodic refresh of the
leadership (as it would with an exception
// thrown out of this task), and as the leadership could not
be refreshed, give it up until the next run
- LOGGER.warn("Error while refreshing the leadership of id={}
(will try again): {}",
- getLocalMember().getId(), e.getMessage());
- LOGGER.debug("Error while refreshing the leadership", e);
+ if (running.get()) {
+ LOGGER.warn("Error while refreshing the leadership of
id={} (will try again): {}",
+ getLocalMember().getId(), e.getMessage());
+ LOGGER.debug("Error while refreshing the leadership", e);
+ } else {
+ // such as a call interrupted by stopping
+ LOGGER.debug("Error while refreshing the leadership of
id={} while stopping",
+ getLocalMember().getId(), e);
+ }
try {
setLeader(false);
} catch (Exception ex) {
diff --git
a/components/camel-infinispan/camel-infinispan/src/test/java/org/apache/camel/component/infinispan/remote/cluster/InfinispanRemoteClusterViewStopTest.java
b/components/camel-infinispan/camel-infinispan/src/test/java/org/apache/camel/component/infinispan/remote/cluster/InfinispanRemoteClusterViewStopTest.java
new file mode 100644
index 000000000000..79ac39af53b7
--- /dev/null
+++
b/components/camel-infinispan/camel-infinispan/src/test/java/org/apache/camel/component/infinispan/remote/cluster/InfinispanRemoteClusterViewStopTest.java
@@ -0,0 +1,386 @@
+/*
+ * 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.infinispan.remote.cluster;
+
+import java.lang.reflect.Proxy;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.apache.camel.cluster.CamelClusterEventListener;
+import org.apache.camel.cluster.CamelClusterView;
+import org.apache.camel.component.infinispan.cluster.InfinispanClusterService;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.spi.ThreadPoolProfile;
+import org.apache.camel.support.DefaultThreadPoolFactory;
+import org.infinispan.client.hotrod.MetadataValue;
+import org.infinispan.client.hotrod.RemoteCache;
+import org.infinispan.client.hotrod.RemoteCacheManager;
+import org.infinispan.client.hotrod.exceptions.HotRodClientException;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
+
+/**
+ * Stopping the view while the leadership thread is busy: the local member
gives up the leadership at once, and the stop
+ * does not wait on the lock of the leadership service.
+ */
+class InfinispanRemoteClusterViewStopTest {
+ private static final String VIEW_NAME = "myView";
+ private static final String NODE_ID = "node";
+ private static final String LEADER_KEY =
InfinispanClusterService.LEADER_KEY;
+ // the stop time is compared with this, so it leaves room for a slow
(loaded) machine: a stop that waits for the
+ // leadership thread once takes a bit more than this, a stop that waits
twice takes more than twice this
+ private static final long SHUTDOWN_AWAIT_TERMINATION = 2000;
+
+ private final FakeRemoteCache server = new FakeRemoteCache();
+ private final LeadershipThreadPoolFactory pools = new
LeadershipThreadPoolFactory();
+ private final ExecutorService stopper =
Executors.newSingleThreadExecutor();
+ private final List<Boolean> events = new CopyOnWriteArrayList<>();
+ private DefaultCamelContext context;
+ private CamelClusterView view;
+
+ @AfterEach
+ void tearDown() throws Exception {
+ server.releaseAll();
+ stopper.shutdownNow();
+ stopper.awaitTermination(10, TimeUnit.SECONDS);
+ if (context != null) {
+ context.close();
+ }
+ }
+
+ @Test
+ void runStartedWhileStoppingDoesNotDelayTheStop() throws Exception {
+ startView();
+ await().atMost(10, TimeUnit.SECONDS).until(() ->
view.getLocalMember().isLeader());
+ int received = events.size();
+
+ // the stop is held in the removal of the client listener, while a
leadership run starts (as the periodic run
+ // or a run queued by an event would)
+ server.blockRemoveClientListener = true;
+ CompletableFuture<Long> stop = stopAsync();
+ assertThat(server.removeClientListenerCalled.await(10,
TimeUnit.SECONDS)).isTrue();
+ CountDownLatch runStarted = new CountDownLatch(1);
+ pools.runAgain(runStarted::countDown);
+ assertThat(runStarted.await(10, TimeUnit.SECONDS)).isTrue();
+ server.removeClientListenerRelease.countDown();
+
+ // the stop does not wait for that run until the shutdown await
termination runs out twice, as the run does not
+ // wait for the lock of the leadership service held by the stop
+ assertThat(stop.get(10,
TimeUnit.SECONDS)).isLessThan(SHUTDOWN_AWAIT_TERMINATION);
+
+ // and the leadership was given up before the stop waited for anything
else
+ assertThat(server.leaderWhenRemovingClientListener).isFalse();
+ assertThat(server.eventsWhenRemovingClientListener).isEqualTo(events);
+ assertThat(events.subList(received,
events.size())).containsExactly(false);
+ assertThat(server.value(LEADER_KEY)).isNull();
+ }
+
+ @Test
+ void stopGivesUpTheLeadershipWhileARunWaitsForTheServer() throws Exception
{
+ startView();
+ await().atMost(10, TimeUnit.SECONDS).until(() ->
view.getLocalMember().isLeader());
+ int received = events.size();
+
+ // the refresh of the leader key waits for the server
+ server.blockReplaceWithVersion = true;
+ pools.runAgain(() -> {
+ });
+ assertThat(server.replaceWithVersionCalled.await(10,
TimeUnit.SECONDS)).isTrue();
+
+ CompletableFuture<Long> stop = stopAsync();
+
+ // the listeners are told that the local member is no longer the
leader while that refresh still waits
+ await().atMost(10, TimeUnit.SECONDS).until(() ->
!view.getLocalMember().isLeader());
+ assertThat(server.replaceWithVersionReturned).isFalse();
+ assertThat(events.subList(received,
events.size())).containsExactly(false);
+
+ // the stop waits for the run once, then interrupts the call that
still waits for the server, which ends the run
+ assertThat(stop.get(10,
TimeUnit.SECONDS)).isBetween(SHUTDOWN_AWAIT_TERMINATION, 2 *
SHUTDOWN_AWAIT_TERMINATION);
+ assertThat(server.replaceWithVersionReturned).isTrue();
+
+ // the leader key is still released with the version that the local
member holds
+ assertThat(server.value(LEADER_KEY)).isNull();
+ assertThat(events.subList(received,
events.size())).containsExactly(false);
+ }
+
+ @Test
+ void runThatAcquiresTheLeaderKeyWhileStoppingDoesNotTakeTheLeadership()
throws Exception {
+ // the first leadership run waits for the server while it acquires the
leader key
+ server.blockPutIfAbsent = true;
+ startView();
+ assertThat(server.putIfAbsentCalled.await(10,
TimeUnit.SECONDS)).isTrue();
+ // (a new leadership listener is told the current leader when it is
added)
+ int received = events.size();
+
+ CompletableFuture<Long> stop = stopAsync();
+ assertThat(server.removeClientListenerCalled.await(10,
TimeUnit.SECONDS)).isTrue();
+
+ // the server then answers that the key was acquired
+ server.putIfAbsentRelease.countDown();
+ stop.get(10, TimeUnit.SECONDS);
+
+ // the stopped member did not become the leader, and the key it
acquired is released
+ assertThat(view.getLocalMember().isLeader()).isFalse();
+ assertThat(events.subList(received, events.size())).isEmpty();
+ assertThat(events).doesNotContain(true);
+ assertThat(server.value(LEADER_KEY)).isNull();
+ }
+
+ private void startView() throws Exception {
+ context = new DefaultCamelContext();
+ context.disableJMX();
+ context.getExecutorServiceManager().setThreadPoolFactory(pools);
+
context.getExecutorServiceManager().setShutdownAwaitTermination(SHUTDOWN_AWAIT_TERMINATION);
+
+ InfinispanRemoteClusterService clusterService = new
InfinispanRemoteClusterService();
+ clusterService.setId(NODE_ID);
+ clusterService.setCacheContainer(server.cacheManager());
+ // a long lifespan, so that the periodic run does not run during the
test (the test runs it instead)
+ clusterService.setLifespan(60);
+ clusterService.setLifespanTimeUnit(TimeUnit.SECONDS);
+ context.addService(clusterService);
+ context.start();
+
+ view = clusterService.getView(VIEW_NAME);
+ server.view = view;
+ server.events = events;
+ view.addEventListener((CamelClusterEventListener.Leadership) (v,
leader) -> events
+ .add(v.getLocalMember().isLeader()));
+ }
+
+ /**
+ * Stops the view on another thread, and returns how long the stop took in
millis.
+ */
+ private CompletableFuture<Long> stopAsync() {
+ return CompletableFuture.supplyAsync(() -> {
+ long start = System.nanoTime();
+ view.stop();
+ return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
+ }, stopper);
+ }
+
+ /**
+ * A thread pool factory that keeps the executor and the periodic task of
the leadership service, so that the test
+ * can run the task again on the leadership thread when it needs to.
+ */
+ private static final class LeadershipThreadPoolFactory extends
DefaultThreadPoolFactory {
+ private volatile ScheduledExecutorService leadershipExecutor;
+ private volatile Runnable leadershipRun;
+
+ @Override
+ public ScheduledExecutorService
newScheduledThreadPool(ThreadPoolProfile profile, ThreadFactory threadFactory) {
+ if (!profile.getId().startsWith("LeadershipService")) {
+ return super.newScheduledThreadPool(profile, threadFactory);
+ }
+ ScheduledExecutorService executor = new
ScheduledThreadPoolExecutor(1, threadFactory) {
+ @Override
+ public ScheduledFuture<?> scheduleAtFixedRate(
+ Runnable command, long initialDelay, long period,
TimeUnit unit) {
+ leadershipRun = command;
+ return super.scheduleAtFixedRate(command, initialDelay,
period, unit);
+ }
+ };
+ leadershipExecutor = executor;
+ return executor;
+ }
+
+ void runAgain(Runnable before) {
+ Runnable run = leadershipRun;
+ leadershipExecutor.execute(() -> {
+ before.run();
+ run.run();
+ });
+ }
+ }
+
+ /**
+ * A remote cache of a single client, with the versioned entries the
leadership relies on. Selected calls can wait
+ * for the test. As the Hot Rod client, a call that is interrupted (or
made by an interrupted thread) throws a
+ * {@link HotRodClientException} and keeps the interrupt status of the
thread (see
+ * {@code org.infinispan.client.hotrod.impl.Util#await}).
+ */
+ private static final class FakeRemoteCache {
+ private final Map<String, String> values = new HashMap<>();
+ private final Map<String, Long> versions = new HashMap<>();
+ private final AtomicLong lastVersion = new AtomicLong();
+
+ private final CountDownLatch removeClientListenerCalled = new
CountDownLatch(1);
+ private final CountDownLatch removeClientListenerRelease = new
CountDownLatch(1);
+ private final CountDownLatch replaceWithVersionCalled = new
CountDownLatch(1);
+ private final CountDownLatch replaceWithVersionRelease = new
CountDownLatch(1);
+ private final CountDownLatch putIfAbsentCalled = new CountDownLatch(1);
+ private final CountDownLatch putIfAbsentRelease = new
CountDownLatch(1);
+
+ private volatile CamelClusterView view;
+ private volatile List<Boolean> events;
+ private volatile boolean blockRemoveClientListener;
+ private volatile boolean blockReplaceWithVersion;
+ private volatile boolean blockPutIfAbsent;
+ private volatile boolean replaceWithVersionReturned;
+ private volatile Boolean leaderWhenRemovingClientListener;
+ private volatile List<Boolean> eventsWhenRemovingClientListener;
+
+ RemoteCacheManager cacheManager() {
+ RemoteCache<String, String> cache = cache();
+ return new RemoteCacheManager(false) {
+ @Override
+ @SuppressWarnings("unchecked")
+ public <K, V> RemoteCache<K, V> getCache(String cacheName) {
+ return (RemoteCache<K, V>) cache;
+ }
+ };
+ }
+
+ synchronized String value(String key) {
+ return values.get(key);
+ }
+
+ void releaseAll() {
+ removeClientListenerRelease.countDown();
+ replaceWithVersionRelease.countDown();
+ putIfAbsentRelease.countDown();
+ }
+
+ @SuppressWarnings("unchecked")
+ private RemoteCache<String, String> cache() {
+ Object[] self = new Object[1];
+ self[0] = Proxy.newProxyInstance(getClass().getClassLoader(), new
Class<?>[] { RemoteCache.class },
+ (proxy, method, args) -> switch (method.getName()) {
+ case "toString" -> "FakeRemoteCache";
+ case "hashCode" -> System.identityHashCode(proxy);
+ case "equals" -> proxy == args[0];
+ case "withFlags" -> self[0];
+ case "addClientListener" -> null;
+ default -> call(method.getName(), args);
+ });
+ return (RemoteCache<String, String>) self[0];
+ }
+
+ private Object call(String name, Object[] args) {
+ if (Thread.currentThread().isInterrupted()) {
+ throw new HotRodClientException(new InterruptedException());
+ }
+ switch (name) {
+ case "removeClientListener":
+ leaderWhenRemovingClientListener =
view.getLocalMember().isLeader();
+ eventsWhenRemovingClientListener = List.copyOf(events);
+ removeClientListenerCalled.countDown();
+ if (blockRemoveClientListener) {
+ waitFor(removeClientListenerRelease);
+ }
+ return null;
+ case "putIfAbsent":
+ putIfAbsentCalled.countDown();
+ if (blockPutIfAbsent) {
+ waitFor(putIfAbsentRelease);
+ }
+ return putIfAbsent((String) args[0], (String) args[1]);
+ case "replaceWithVersion":
+ replaceWithVersionCalled.countDown();
+ try {
+ if (blockReplaceWithVersion) {
+ waitFor(replaceWithVersionRelease);
+ }
+ return replaceWithVersion((String) args[0], (String)
args[1], (Long) args[2]);
+ } finally {
+ replaceWithVersionReturned = true;
+ }
+ case "put":
+ return put((String) args[0], (String) args[1]);
+ case "get":
+ return value((String) args[0]);
+ case "getWithMetadata":
+ return metadata((String) args[0]);
+ case "removeWithVersion":
+ return removeWithVersion((String) args[0], (Long) args[1]);
+ case "remove":
+ return remove((String) args[0]);
+ default:
+ throw new UnsupportedOperationException(name);
+ }
+ }
+
+ private static void waitFor(CountDownLatch latch) {
+ try {
+ latch.await(1, TimeUnit.MINUTES);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new HotRodClientException(e);
+ }
+ }
+
+ private synchronized String put(String key, String value) {
+ versions.put(key, lastVersion.incrementAndGet());
+ return values.put(key, value);
+ }
+
+ private synchronized String putIfAbsent(String key, String value) {
+ String old = values.get(key);
+ if (old == null) {
+ put(key, value);
+ }
+ return old;
+ }
+
+ private synchronized boolean replaceWithVersion(String key, String
value, long version) {
+ if (!values.containsKey(key) || versions.get(key) != version) {
+ return false;
+ }
+ put(key, value);
+ return true;
+ }
+
+ private synchronized boolean removeWithVersion(String key, long
version) {
+ if (!values.containsKey(key) || versions.get(key) != version) {
+ return false;
+ }
+ remove(key);
+ return true;
+ }
+
+ private synchronized String remove(String key) {
+ versions.remove(key);
+ return values.remove(key);
+ }
+
+ @SuppressWarnings("unchecked")
+ private synchronized MetadataValue<String> metadata(String key) {
+ if (!values.containsKey(key)) {
+ return null;
+ }
+ long version = versions.get(key);
+ return (MetadataValue<String>)
Proxy.newProxyInstance(getClass().getClassLoader(),
+ new Class<?>[] { MetadataValue.class },
+ (proxy, method, args) ->
"getVersion".equals(method.getName()) ? version : null);
+ }
+ }
+}