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 059d5eacba33 CAMEL-27337: camel-jgroups-raft - The cluster views of
all namespaces share the RaftHandle of the node (#30624)
059d5eacba33 is described below
commit 059d5eacba3396479025ebc4fcded589d1e136cb
Author: allthingssecurity <[email protected]>
AuthorDate: Mon Nov 23 15:10:38 2026 +0530
CAMEL-27337: camel-jgroups-raft - The cluster views of all namespaces share
the RaftHandle of the node (#30624)
A node is one Raft member, so the views of its namespaces share one
RaftHandle, but each view managed it as its own: a view that started
after the election never read the current role and never became leader,
stopping one view disconnected the handle (and closed its log) that the
other views still used, and without a configured raftHandle each view
created its own channel with the same raft id, so a second namespace
could not join (NO_DUPES).
JGroupsRaftClusterService now owns the handle (the configured one, or one
it creates), connects it for the first view and disconnects it after the
last one. One role listener on the handle forwards the role changes to
the views. A view reads the current role once it is connected, and
ignores the role changes still notified to it after it stopped.
The role change of the node is now notified to each cluster view in its own
try/catch with a WARN log, as RAFT did when each view was its own role
listener, so a cluster event listener that fails in one namespace does not
stop the other namespaces from getting the change.
The service records whether it created the connected handle, so a configured
raftHandle that is replaced while views use it is disconnected, not closed,
when the last view stops.
Docs: all namespaces of a node share one Raft member, so the Raft leader
leads every namespace (catalog copy updated). Javadoc on the constructor
parameters of JGroupsRaftClusterView that are ignored.
Tests for both changes, and for the check that ignores role changes once a
view is stopped.
When a cluster view starts, it reads whether the node is already the
leader. It compared RAFT.role(), which is the simple class name of the
internal state of jgroups-raft, with the name of Role.Leader. It now calls
RaftHandle.isLeader(), as JGroupsRaftEndpoint already does.
In jgroups-raft 1.1.4, isLeader() is true when the leader address is the
local address. RAFT sets that address first and then changes its role to
Leader and notifies the role listeners, so both checks agree once the role
change is done, and the listener of the view gets the change in either
case.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../camel/catalog/docs/jgroups-raft-component.adoc | 4 +
.../src/main/docs/jgroups-raft-component.adoc | 4 +
.../raft/cluster/ClusterRoleChangeListener.java | 17 +-
.../raft/cluster/JGroupsRaftClusterService.java | 148 +++++++++++++++
.../raft/cluster/JGroupsRaftClusterView.java | 141 +++++++-------
.../cluster/ClusterRoleChangeListenerTest.java | 18 ++
.../JGroupsRaftClusterServiceNamespacesTest.java | 203 +++++++++++++++++++++
7 files changed, 455 insertions(+), 80 deletions(-)
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/jgroups-raft-component.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/jgroups-raft-component.adoc
index 7039ae12a0aa..3c0536c7f167 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/jgroups-raft-component.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/jgroups-raft-component.adoc
@@ -191,3 +191,7 @@ context.addService(service);
from("master:mycluster:jetty:http://localhost:8080/orders").to("jms:orders");
----
+
+NOTE: All the namespaces of a node share one Raft member: the
`JGroupsRaftClusterService` connects one `RaftHandle`
+(with the raft id of the service) for the cluster views of all namespaces. So
the Raft leader is the leader of every
+namespace, and the master routes of all namespaces run on that node. Raft does
not elect a leader per namespace.
diff --git
a/components/camel-jgroups-raft/src/main/docs/jgroups-raft-component.adoc
b/components/camel-jgroups-raft/src/main/docs/jgroups-raft-component.adoc
index 7039ae12a0aa..3c0536c7f167 100644
--- a/components/camel-jgroups-raft/src/main/docs/jgroups-raft-component.adoc
+++ b/components/camel-jgroups-raft/src/main/docs/jgroups-raft-component.adoc
@@ -191,3 +191,7 @@ context.addService(service);
from("master:mycluster:jetty:http://localhost:8080/orders").to("jms:orders");
----
+
+NOTE: All the namespaces of a node share one Raft member: the
`JGroupsRaftClusterService` connects one `RaftHandle`
+(with the raft id of the service) for the cluster views of all namespaces. So
the Raft leader is the leader of every
+namespace, and the master routes of all namespaces run on that node. Raft does
not elect a leader per namespace.
diff --git
a/components/camel-jgroups-raft/src/main/java/org/apache/camel/component/jgroups/raft/cluster/ClusterRoleChangeListener.java
b/components/camel-jgroups-raft/src/main/java/org/apache/camel/component/jgroups/raft/cluster/ClusterRoleChangeListener.java
index da4eacd5f149..7f6293329fd8 100644
---
a/components/camel-jgroups-raft/src/main/java/org/apache/camel/component/jgroups/raft/cluster/ClusterRoleChangeListener.java
+++
b/components/camel-jgroups-raft/src/main/java/org/apache/camel/component/jgroups/raft/cluster/ClusterRoleChangeListener.java
@@ -16,7 +16,6 @@
*/
package org.apache.camel.component.jgroups.raft.cluster;
-import org.apache.camel.cluster.CamelClusterMember;
import org.apache.camel.util.ObjectHelper;
import org.jgroups.protocols.raft.RAFT;
import org.jgroups.protocols.raft.Role;
@@ -39,18 +38,11 @@ public class ClusterRoleChangeListener implements
RAFT.RoleChange {
LOG.debug("Role received {}.", role);
switch (role) {
case Leader:
- if (!jgroupsRaftClusterView.isMaster()) {
- jgroupsRaftClusterView.setMaster(true);
- jgroupsRaftClusterView
-
.fireLeadershipChangedEvent(jgroupsRaftClusterView.getLocalMember());
- }
+ jgroupsRaftClusterView.leadershipChanged(true);
break;
case Follower:
case Learner:
- if (jgroupsRaftClusterView.isMaster()) {
- jgroupsRaftClusterView.setMaster(false);
-
jgroupsRaftClusterView.fireLeadershipChangedEvent((CamelClusterMember) null);
- }
+ jgroupsRaftClusterView.leadershipChanged(false);
break;
default:
// Role enum is exhaustively handled above. This branch guards
against
@@ -59,4 +51,9 @@ public class ClusterRoleChangeListener implements
RAFT.RoleChange {
break;
}
}
+
+ @Override
+ public String toString() {
+ return "ClusterRoleChangeListener[namespace=" +
jgroupsRaftClusterView.getNamespace() + "]";
+ }
}
diff --git
a/components/camel-jgroups-raft/src/main/java/org/apache/camel/component/jgroups/raft/cluster/JGroupsRaftClusterService.java
b/components/camel-jgroups-raft/src/main/java/org/apache/camel/component/jgroups/raft/cluster/JGroupsRaftClusterService.java
index 8c481dabe678..5edfd51dac25 100644
---
a/components/camel-jgroups-raft/src/main/java/org/apache/camel/component/jgroups/raft/cluster/JGroupsRaftClusterService.java
+++
b/components/camel-jgroups-raft/src/main/java/org/apache/camel/component/jgroups/raft/cluster/JGroupsRaftClusterService.java
@@ -16,11 +16,22 @@
*/
package org.apache.camel.component.jgroups.raft.cluster;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+import org.apache.camel.component.jgroups.raft.utils.NopStateMachine;
import org.apache.camel.spi.Configurer;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.annotations.JdkService;
import org.apache.camel.support.cluster.AbstractCamelClusterService;
+import org.jgroups.JChannel;
+import org.jgroups.protocols.raft.RAFT;
+import org.jgroups.protocols.raft.Role;
import org.jgroups.raft.RaftHandle;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
@JdkService("cluster-service-jgroups-raft")
@Metadata(label = "bean",
@@ -29,6 +40,7 @@ import org.jgroups.raft.RaftHandle;
@Configurer(metadataOnly = true)
public class JGroupsRaftClusterService extends
AbstractCamelClusterService<JGroupsRaftClusterView> {
+ private static final Logger LOG =
LoggerFactory.getLogger(JGroupsRaftClusterService.class);
private static final String DEFAULT_JGROUPS_CONFIG = "raft.xml";
private static final String DEFAULT_JGROUPS_CLUSTERNAME =
"jgroupsraft-master";
@@ -41,6 +53,17 @@ public class JGroupsRaftClusterService extends
AbstractCamelClusterService<JGrou
@Metadata(label = "advanced", description = "To use a custom RaftHandler")
private RaftHandle raftHandle;
+ // the views of all namespaces share one RaftHandle, as the node is one
Raft member (one raft id): the configured
+ // raftHandle, or one this service creates. It is connected while views
use it, guarded by handleLock
+ private final Lock handleLock = new ReentrantLock();
+ private RaftHandle connectedHandle;
+ // the connected handle was created by this service (not the configured
raftHandle), so it is closed after use
+ private boolean createdHandle;
+ private int connectedViews;
+ // the role listeners of the connected views, notified by the one role
listener of the handle
+ private final List<RAFT.RoleChange> viewRoleListeners = new
CopyOnWriteArrayList<>();
+ private final RAFT.RoleChange handleRoleListener = this::notifyViews;
+
public JGroupsRaftClusterService() {
this.jgroupsConfig = DEFAULT_JGROUPS_CONFIG;
this.jgroupsClusterName = DEFAULT_JGROUPS_CLUSTERNAME;
@@ -58,6 +81,131 @@ public class JGroupsRaftClusterService extends
AbstractCamelClusterService<JGrou
return new JGroupsRaftClusterView(this, namespace, jgroupsConfig,
jgroupsClusterName, raftHandle, getId());
}
+ /**
+ * Connects the RaftHandle of this node for a view, which then gets the
role changes of the node.
+ *
+ * @return the connected handle
+ */
+ RaftHandle connectView(RAFT.RoleChange roleListener) throws Exception {
+ handleLock.lock();
+ try {
+ if (connectedViews == 0) {
+ boolean created = raftHandle == null;
+ RaftHandle handle = created ? createRaftHandle() : raftHandle;
+ // listen before connecting, so the role changes of the
election are not missed
+ handle.addRoleListener(handleRoleListener);
+ try {
+ connect(handle);
+ } catch (Exception e) {
+ handle.removeRoleListener(handleRoleListener);
+ if (created) {
+ close(handle);
+ }
+ throw e;
+ }
+ connectedHandle = handle;
+ createdHandle = created;
+ }
+ viewRoleListeners.add(roleListener);
+ connectedViews++;
+ return connectedHandle;
+ } finally {
+ handleLock.unlock();
+ }
+ }
+
+ /**
+ * Disconnects a view from the RaftHandle of this node, which is
disconnected when no view uses it anymore.
+ */
+ void disconnectView(RAFT.RoleChange roleListener) {
+ handleLock.lock();
+ try {
+ if (!viewRoleListeners.remove(roleListener) || --connectedViews >
0) {
+ return;
+ }
+ RaftHandle handle = connectedHandle;
+ connectedHandle = null;
+ handle.removeRoleListener(handleRoleListener);
+ if (!createdHandle) {
+ // the configured handle is connected again when a view starts
again
+ LOG.info("Disconnecting JGroupsraft Channel of
JGroupsRaftClusterService with Id {}", getId());
+ try {
+ handle.channel().disconnect();
+ } catch (Exception e) {
+ LOG.warn("Error disconnecting the JGroupsraft Channel with
Id {}: {}", getId(), e.getMessage(), e);
+ }
+ closeLog(handle);
+ } else {
+ close(handle);
+ }
+ } finally {
+ handleLock.unlock();
+ }
+ }
+
+ /**
+ * Notifies a role change of the node to the views. Each view is notified
on its own, as before each view was its
+ * own role listener of the handle, which RAFT notifies one by one: a
listener of one namespace that fails does not
+ * stop the other namespaces from getting the change.
+ */
+ void notifyViews(Role role) {
+ for (RAFT.RoleChange listener : viewRoleListeners) {
+ try {
+ listener.roleChanged(role);
+ } catch (VirtualMachineError e) {
+ throw e;
+ } catch (Throwable e) {
+ LOG.warn("Error notifying {} of the role change of the node
with Id {} to {}: {}."
+ + " The other cluster views are still notified.",
+ listener, getId(), role, e.getMessage(), e);
+ }
+ }
+ }
+
+ private RaftHandle createRaftHandle() throws Exception {
+ String config = jgroupsConfig != null && !jgroupsConfig.isEmpty() ?
jgroupsConfig : DEFAULT_JGROUPS_CONFIG;
+ return new RaftHandle(new JChannel(config), new
NopStateMachine()).raftId(getId());
+ }
+
+ private void connect(RaftHandle handle) throws Exception {
+ // it may take a while for event to trigger and allow us to join so
retry a while
+ Exception cause = null;
+ for (int i = 1; i < 11; i++) {
+ LOG.debug("Attempt #{} for raft {} to join {}", i, getId(),
jgroupsClusterName);
+ try {
+ handle.channel().connect(jgroupsClusterName);
+ LOG.debug("Joined and connected to {} with raft id: {}",
jgroupsClusterName, getId());
+ return;
+ } catch (Exception e) {
+ cause = e;
+ }
+ // wait for next attempt
+ Thread.sleep(5000);
+ }
+ throw cause;
+ }
+
+ private void close(RaftHandle handle) {
+ LOG.info("Closing JGroupsraft Channel of JGroupsRaftClusterService
with Id {}", getId());
+ try {
+ handle.channel().close();
+ } catch (Exception e) {
+ LOG.warn("Error closing the JGroupsraft Channel with Id {}: {}",
getId(), e.getMessage(), e);
+ }
+ closeLog(handle);
+ }
+
+ private void closeLog(RaftHandle handle) {
+ try {
+ if (handle.log() != null) {
+ handle.log().close();
+ LOG.info("Closed Log of JGroupsRaftClusterService with Id {}",
getId());
+ }
+ } catch (Exception e) {
+ LOG.warn("Error closing the Log with Id {}: {}", getId(),
e.getMessage(), e);
+ }
+ }
+
@Override
public void setId(String id) {
super.setId(id);
diff --git
a/components/camel-jgroups-raft/src/main/java/org/apache/camel/component/jgroups/raft/cluster/JGroupsRaftClusterView.java
b/components/camel-jgroups-raft/src/main/java/org/apache/camel/component/jgroups/raft/cluster/JGroupsRaftClusterView.java
index 9abca349bf48..15f6c2c6db64 100644
---
a/components/camel-jgroups-raft/src/main/java/org/apache/camel/component/jgroups/raft/cluster/JGroupsRaftClusterView.java
+++
b/components/camel-jgroups-raft/src/main/java/org/apache/camel/component/jgroups/raft/cluster/JGroupsRaftClusterView.java
@@ -19,13 +19,12 @@ package org.apache.camel.component.jgroups.raft.cluster;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
import org.apache.camel.cluster.CamelClusterMember;
import org.apache.camel.cluster.CamelClusterService;
-import org.apache.camel.component.jgroups.raft.JGroupsRaftConstants;
-import org.apache.camel.component.jgroups.raft.utils.NopStateMachine;
import org.apache.camel.support.cluster.AbstractCamelClusterView;
-import org.jgroups.JChannel;
import org.jgroups.raft.RaftHandle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -34,20 +33,31 @@ public class JGroupsRaftClusterView extends
AbstractCamelClusterView {
private static final transient Logger LOG =
LoggerFactory.getLogger(JGroupsRaftClusterView.class);
private final CamelClusterMember localMember = new
JGropusraftLocalMember();
- private String jgroupsConfig;
- private String jgroupsClusterName;
- private RaftHandle raftHandle;
private String raftId;
private volatile boolean isMaster;
- private ClusterRoleChangeListener roleListener;
-
+ // serializes the leadership changes (role changes of the node, start and
stop of this view)
+ private final Lock roleLock = new ReentrantLock();
+ // the view was stopped: a role change still being notified to it is
ignored, guarded by roleLock
+ private boolean disconnected;
+ private volatile ClusterRoleChangeListener roleListener;
+
+ /**
+ * Creates the view of a namespace. The view works only with a {@link
JGroupsRaftClusterService}: the views of all
+ * namespaces of a node share the RaftHandle of the node (one Raft
member), which the cluster service configures,
+ * connects and disconnects. So the Raft leader is the leader of every
namespace.
+ *
+ * @param cluster the {@link JGroupsRaftClusterService} of the
node
+ * @param namespace the namespace
+ * @param jgroupsConfig ignored: the cluster service uses its own
JGroups configuration
+ * @param jgroupsClusterName ignored: the cluster service uses its own
cluster name
+ * @param raftHandle ignored: the cluster service uses its
configured RaftHandle, or creates one
+ * @param raftId the raft id of the node, used in log messages
+ */
protected JGroupsRaftClusterView(CamelClusterService cluster, String
namespace, String jgroupsConfig,
String jgroupsClusterName, RaftHandle
raftHandle, String raftId) {
super(cluster, namespace);
- this.jgroupsConfig = jgroupsConfig;
- this.jgroupsClusterName = jgroupsClusterName;
- this.raftHandle = raftHandle;
+ // the views of all namespaces share the RaftHandle of the node, which
the cluster service configures and connects
this.raftId = raftId;
}
@@ -76,81 +86,72 @@ public class JGroupsRaftClusterView extends
AbstractCamelClusterView {
@Override
protected void doStart() throws Exception {
- if (raftHandle == null && jgroupsConfig != null &&
!jgroupsConfig.isEmpty()) {
- raftHandle = new RaftHandle(new JChannel(jgroupsConfig), new
NopStateMachine()).raftId(raftId);
- } else if (raftHandle == null) {
- raftHandle = new RaftHandle(new
JChannel(JGroupsRaftConstants.DEFAULT_JGROUPSRAFT_CONFIG), new
NopStateMachine())
- .raftId(raftId);
- }
fireLeadershipChangedEvent((CamelClusterMember) null);
-
- // Register the listener once before attempting to connect;
registering inside
- // the retry loop would accumulate duplicate listeners across retries.
- roleListener = new ClusterRoleChangeListener(this);
- raftHandle.addRoleListener(roleListener);
-
- // it may take a while for event to trigger and allow us to join so
retry a while
- Exception cause = null;
- for (int i = 1; i < 11; i++) {
- LOG.debug("Attempt #{} for raft {} to join {}", i, raftId,
jgroupsClusterName);
- try {
- raftHandle.channel().connect(jgroupsClusterName);
- LOG.debug("Joined and connected to {} with raft id: {}",
jgroupsClusterName, raftId);
- cause = null;
- break;
- } catch (Exception e) {
- cause = e;
- }
- // wait for next attempt
- Thread.sleep(5000);
+ roleLock.lock();
+ try {
+ disconnected = false;
+ } finally {
+ roleLock.unlock();
}
- if (cause != null) {
- throw cause;
+
+ ClusterRoleChangeListener listener = new
ClusterRoleChangeListener(this);
+ RaftHandle handle = getRaftClusterService().connectView(listener);
+ roleListener = listener;
+
+ // the node may already be the leader (elected before this view
started), and then no role change is notified
+ roleLock.lock();
+ try {
+ leadershipChanged(handle.isLeader());
+ } finally {
+ roleLock.unlock();
}
}
@Override
protected void doStop() throws Exception {
- isMaster = false;
- fireLeadershipChangedEvent((CamelClusterMember) null);
- if (raftHandle != null && raftHandle.channel() != null) {
- LOG.info("Disconnecting JGroupsraft Channel for
JGroupsRaftClusterView with Id {}", raftId);
- raftHandle.channel().disconnect();
- }
- if (roleListener != null) {
- raftHandle.removeRoleListener(roleListener);
- roleListener = null;
- }
- if (raftHandle != null && raftHandle.log() != null) {
- raftHandle.log().close();
- LOG.info("Closed Log for JGroupsRaftClusterView with Id {}",
raftId);
+ leadershipLost();
+ ClusterRoleChangeListener listener = roleListener;
+ roleListener = null;
+ if (listener != null) {
+ // the handle is disconnected when the views of the other
namespaces no longer use it either
+ LOG.debug("Disconnecting JGroupsRaftClusterView {} with Id {}",
getNamespace(), raftId);
+ getRaftClusterService().disconnectView(listener);
}
}
@Override
protected void doShutdown() throws Exception {
- isMaster = false;
- fireLeadershipChangedEvent((CamelClusterMember) null);
- if (raftHandle != null) {
-
- if (raftHandle.channel() != null) {
- LOG.info("Closing JGroupsraft Channel for
JGroupsRaftClusterView with Id {}", raftId);
- raftHandle.channel().close();
- LOG.info("Closed JGroupsraft Channel Channel for
JGroupsRaftClusterView with Id {}", raftId);
- }
+ doStop();
+ }
- if (roleListener != null) {
- raftHandle.removeRoleListener(roleListener);
- roleListener = null;
- }
+ private JGroupsRaftClusterService getRaftClusterService() {
+ return (JGroupsRaftClusterService) getClusterService();
+ }
- if (raftHandle.log() != null) {
- LOG.info("Closing Log for JGroupsRaftClusterView with Id {}",
raftId);
- raftHandle.log().close();
- LOG.info("Closed Log for JGroupsRaftClusterView with Id {}",
raftId);
+ /**
+ * Updates the leadership of this view, and notifies the listeners when it
changes.
+ */
+ void leadershipChanged(boolean leader) {
+ roleLock.lock();
+ try {
+ if (!disconnected && leader != isMaster) {
+ isMaster = leader;
+ fireLeadershipChangedEvent(leader ? localMember : null);
}
+ } finally {
+ roleLock.unlock();
+ }
+ }
- raftHandle = null;
+ private void leadershipLost() {
+ roleLock.lock();
+ try {
+ // the role changes that the handle notifies until this view's
listener is removed are ignored
+ disconnected = true;
+ isMaster = false;
+ fireLeadershipChangedEvent((CamelClusterMember) null);
+ } finally {
+ roleLock.unlock();
}
}
diff --git
a/components/camel-jgroups-raft/src/test/java/org/apache/camel/component/jgroups/raft/cluster/ClusterRoleChangeListenerTest.java
b/components/camel-jgroups-raft/src/test/java/org/apache/camel/component/jgroups/raft/cluster/ClusterRoleChangeListenerTest.java
index f8bc3ea44d78..998006472ae0 100644
---
a/components/camel-jgroups-raft/src/test/java/org/apache/camel/component/jgroups/raft/cluster/ClusterRoleChangeListenerTest.java
+++
b/components/camel-jgroups-raft/src/test/java/org/apache/camel/component/jgroups/raft/cluster/ClusterRoleChangeListenerTest.java
@@ -16,11 +16,15 @@
*/
package org.apache.camel.component.jgroups.raft.cluster;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.camel.cluster.CamelClusterEventListener;
import org.jgroups.protocols.raft.Role;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -64,6 +68,20 @@ public class ClusterRoleChangeListenerTest {
assertFalse(view.isMaster());
}
+ @Test
+ void roleChangeAfterTheViewStoppedIsIgnored() throws Exception {
+ AtomicInteger events = new AtomicInteger();
+ view.addEventListener((CamelClusterEventListener.Leadership) (v,
leader) -> events.incrementAndGet());
+ // the view stops, while the handle of the node may still notify a
role change to the view's listener
+ view.doStop();
+ int afterStop = events.get();
+
+ listener.roleChanged(Role.Leader);
+ assertFalse(view.isMaster());
+ assertFalse(view.getLeader().isPresent());
+ assertEquals(afterStop, events.get(), "A stopped view must not fire a
leadership event");
+ }
+
@Test
void learnerRoleWhenNotMasterIsNoOp() {
assertFalse(view.isMaster());
diff --git
a/components/camel-jgroups-raft/src/test/java/org/apache/camel/component/jgroups/raft/cluster/JGroupsRaftClusterServiceNamespacesTest.java
b/components/camel-jgroups-raft/src/test/java/org/apache/camel/component/jgroups/raft/cluster/JGroupsRaftClusterServiceNamespacesTest.java
new file mode 100644
index 000000000000..4c4026bd21ae
--- /dev/null
+++
b/components/camel-jgroups-raft/src/test/java/org/apache/camel/component/jgroups/raft/cluster/JGroupsRaftClusterServiceNamespacesTest.java
@@ -0,0 +1,203 @@
+/*
+ * 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.jgroups.raft.cluster;
+
+import java.lang.reflect.Method;
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.jgroups.raft.utils.NopStateMachine;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.jgroups.JChannel;
+import org.jgroups.protocols.raft.RAFT;
+import org.jgroups.protocols.raft.Role;
+import org.jgroups.raft.RaftHandle;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The views of all namespaces of a node use the same Raft member (one raft
id), so they share one RaftHandle. Each
+ * namespace must get the leadership of the node, whenever its view starts,
and must keep it when the view of another
+ * namespace stops.
+ */
+class JGroupsRaftClusterServiceNamespacesTest {
+
+ private DefaultCamelContext context;
+ private RaftHandle handle;
+ private RaftHandle otherHandle;
+
+ @AfterEach
+ void cleanup() {
+ if (context != null) {
+ context.stop();
+ }
+ if (handle != null) {
+ handle.channel().close();
+ }
+ if (otherHandle != null) {
+ otherHandle.channel().close();
+ }
+ }
+
+ @Test
+ void testNamespaceStartedAfterElectionGetsLeadership() throws Exception {
+ handle = newHandle();
+ JGroupsRaftClusterService service = newService();
+ service.setRaftHandle(handle);
+ AtomicInteger ns1 = new AtomicInteger();
+ AtomicInteger ns2 = new AtomicInteger();
+
+ startContext(service, ns1);
+ await().atMost(30, TimeUnit.SECONDS).until(() -> ns1.get() > 0 &&
handle.isLeader());
+
+ // a master route of another namespace starts after the node was
elected leader
+ context.addRoutes(masterRoute("ns2", ns2));
+ await().atMost(20, TimeUnit.SECONDS).until(() -> ns2.get() > 0);
+ assertTrue(service.isLeader("ns2"));
+ assertTrue(service.isLeader("ns1"));
+ }
+
+ @Test
+ void testStoppingOneNamespaceKeepsTheOthers() throws Exception {
+ handle = newHandle();
+ JGroupsRaftClusterService service = newService();
+ service.setRaftHandle(handle);
+ AtomicInteger ns1 = new AtomicInteger();
+ AtomicInteger ns2 = new AtomicInteger();
+
+ startContext(service, ns1, ns2);
+ await().atMost(30, TimeUnit.SECONDS).until(() -> ns1.get() > 0 &&
ns2.get() > 0);
+
+ context.getRouteController().stopRoute("route-ns1");
+ assertTrue(handle.channel().isConnected(), "The handle should stay
connected while namespace ns2 uses it");
+ int before = ns2.get();
+ await().atMost(20, TimeUnit.SECONDS).until(() -> ns2.get() > before +
5);
+ assertTrue(service.isLeader("ns2"));
+
+ // the handle is disconnected when the last namespace stops, and
connected again when one starts again
+ context.getRouteController().stopRoute("route-ns2");
+ assertFalse(handle.channel().isConnected(), "The handle should be
disconnected when no namespace uses it");
+ int restarted = ns1.get();
+ context.getRouteController().startRoute("route-ns1");
+ await().atMost(30, TimeUnit.SECONDS).until(() -> ns1.get() >
restarted);
+ assertTrue(service.isLeader("ns1"));
+ }
+
+ @Test
+ void testTwoNamespacesWithoutRaftHandle() throws Exception {
+ // no RaftHandle configured: the service creates the handle of the node
+ JGroupsRaftClusterService service = newService();
+ service.setJgroupsConfig("raft.xml");
+ AtomicInteger ns1 = new AtomicInteger();
+ AtomicInteger ns2 = new AtomicInteger();
+
+ startContext(service, ns1, ns2);
+ await().atMost(30, TimeUnit.SECONDS).until(() -> ns1.get() > 0 &&
ns2.get() > 0);
+ assertTrue(service.isLeader("ns1"));
+ assertTrue(service.isLeader("ns2"));
+ }
+
+ @Test
+ void testFailingViewDoesNotStopTheRoleChangeOfTheOtherViews() throws
Exception {
+ handle = newHandle();
+ JGroupsRaftClusterService service = newService();
+ service.setRaftHandle(handle);
+ // the role listener of a view whose cluster event listener throws,
and the one of another namespace
+ RAFT.RoleChange failing = role -> {
+ throw new IllegalStateException("Simulated failure of a cluster
event listener");
+ };
+ List<Role> roles = new CopyOnWriteArrayList<>();
+ RAFT.RoleChange other = roles::add;
+ service.connectView(failing);
+ service.connectView(other);
+ try {
+ await().atMost(30, TimeUnit.SECONDS).until(handle::isLeader);
+
+ // a role change of the node, as RAFT notifies it to the role
listeners of the handle (Learner, as this
+ // single node never becomes one by itself)
+ Method notify =
RAFT.class.getDeclaredMethod("notifyRoleChangeListeners", Role.class);
+ notify.setAccessible(true);
+ notify.invoke(handle.raft(), Role.Learner);
+
+ assertTrue(roles.contains(Role.Learner), "The other view should
get the role change, got " + roles);
+ } finally {
+ service.disconnectView(other);
+ service.disconnectView(failing);
+ }
+ }
+
+ @Test
+ void testConfiguredHandleReplacedWhileInUseIsNotClosed() throws Exception {
+ handle = newHandle();
+ JGroupsRaftClusterService service = newService();
+ service.setRaftHandle(handle);
+ AtomicInteger ns1 = new AtomicInteger();
+
+ startContext(service, ns1);
+ await().atMost(30, TimeUnit.SECONDS).until(() -> ns1.get() > 0);
+
+ // the configured handle is replaced while the view uses it: the view
keeps the handle it connected, and when it
+ // stops, the handle of the user is disconnected, not closed
+ otherHandle = newHandle();
+ service.setRaftHandle(otherHandle);
+ context.getRouteController().stopRoute("route-ns1");
+ assertFalse(handle.channel().isConnected(), "The handle should be
disconnected when no namespace uses it");
+ assertFalse(handle.channel().isClosed(), "The configured handle should
not be closed by the service");
+ assertFalse(otherHandle.channel().isConnected(), "The new handle
should not be connected yet");
+ }
+
+ private void startContext(JGroupsRaftClusterService service,
AtomicInteger... counters) throws Exception {
+ context = new DefaultCamelContext();
+ context.disableJMX();
+ context.addService(service);
+ for (int i = 0; i < counters.length; i++) {
+ context.addRoutes(masterRoute("ns" + (i + 1), counters[i]));
+ }
+ context.start();
+ }
+
+ private static RaftHandle newHandle() throws Exception {
+ RaftHandle raftHandle = new RaftHandle(new
JChannel("raft.xml").name("A"), new NopStateMachine()).raftId("A");
+ raftHandle.raft().logPrefix("namespaces-" + UUID.randomUUID() + "-A");
+ return raftHandle;
+ }
+
+ private static JGroupsRaftClusterService newService() {
+ JGroupsRaftClusterService service = new JGroupsRaftClusterService();
+ service.setId("A");
+ service.setJgroupsClusterName("namespaces-" + UUID.randomUUID());
+ return service;
+ }
+
+ private static RouteBuilder masterRoute(String namespace, AtomicInteger
counter) {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+ from("master:" + namespace + ":timer:" + namespace +
"?period=100").routeId("route-" + namespace)
+ .process(e -> counter.incrementAndGet());
+ }
+ };
+ }
+}