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 f73b3271ae2a CAMEL-27592: camel-cluster - ClusteredRoutePolicy stops a
route added while the leadership is lost, and works again after a CamelContext
restart (#30919)
f73b3271ae2a is described below
commit f73b3271ae2af21c9e20bf15f8c04476df4329ad
Author: allthingssecurity <[email protected]>
AuthorDate: Fri Nov 27 13:31:31 2026 +0530
CAMEL-27592: camel-cluster - ClusteredRoutePolicy stops a route added while
the leadership is lost, and works again after a CamelContext restart (#30919)
A route added to a running CamelContext while this node is the leader is
started by the route controller. If the leadership was lost before the
route had started, the policy thread skipped it (the policy was not started
yet, or the route was not stoppable yet), and nothing stopped it later: it
kept running on a node that is not the leader. Now, when such a route starts
on a node that is no longer the leader (onStart), the policy thread applies
the leadership again, and a stop pass that finds a route still starting
tries again after the retry delay, so such a route runs for about one retry
delay (5 seconds by default) before it is stopped. The route controller
still
starts a route added on the leader when addRoutes runs.
After CamelContext.stop() and start(), the routes created again with the
same policy were never started: the stop had shut down the executor of the
policy thread (created once in setCamelContext), removed the event notifier
and left the retry flag set. A route created with a shut down policy now
makes it usable again before it takes the leadership: a new executor, the
event notifier added back and the flags reset, and the routes are started
once the CamelContext has started.
An Error from a route start or stop (such as a NoClassDefFoundError) now
counts as a failed start or stop and is tried again, instead of ending the
pass. A VirtualMachineError (also one found as a cause) is rethrown once the
retry is scheduled, and the policy thread logs it once at ERROR. If the
timer
thread of a retry cannot be created (such as an OutOfMemoryError), the retry
flag is reset and the error rethrown, so a later failure schedules a retry
again; before, no retry ran until a restart.
Review: Javadoc on onStart, and restart() clears the failed start counts.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../camel/impl/cluster/ClusteredRoutePolicy.java | 97 ++++-
...lusteredRoutePolicyLateStartAndRestartTest.java | 414 +++++++++++++++++++++
2 files changed, 502 insertions(+), 9 deletions(-)
diff --git
a/core/camel-cluster/src/main/java/org/apache/camel/impl/cluster/ClusteredRoutePolicy.java
b/core/camel-cluster/src/main/java/org/apache/camel/impl/cluster/ClusteredRoutePolicy.java
index 862bc7e607e4..57a70ad4991c 100644
---
a/core/camel-cluster/src/main/java/org/apache/camel/impl/cluster/ClusteredRoutePolicy.java
+++
b/core/camel-cluster/src/main/java/org/apache/camel/impl/cluster/ClusteredRoutePolicy.java
@@ -160,8 +160,7 @@ public final class ClusteredRoutePolicy extends
RoutePolicySupport implements Ca
this.camelContext = camelContext;
this.camelContext.addStartupListener(this.listener);
this.camelContext.getManagementStrategy().addEventNotifier(this.listener);
- this.leadershipExecutor = camelContext.getExecutorServiceManager()
- .newThreadPool(this, THREAD_NAME,
newLeadershipThreadPoolProfile());
+ this.leadershipExecutor = newLeadershipExecutor();
} catch (Exception e) {
throw new RuntimeException(e);
}
@@ -213,6 +212,11 @@ public final class ClusteredRoutePolicy extends
RoutePolicySupport implements Ca
// Increase number of managed routes by this policy, acquire policy
view on first run
retainLock.lock();
try {
+ if (leadershipExecutor == null) {
+ // the CamelContext was stopped, which shut this policy down,
and is started again: the routes are
+ // created again with this policy, so it is made usable again
before it takes the leadership
+ restart();
+ }
this.refCount.retain();
} finally {
retainLock.unlock();
@@ -272,6 +276,22 @@ public final class ClusteredRoutePolicy extends
RoutePolicySupport implements Ca
stoppedRoutes.remove(route);
}
+ /**
+ * Applies the current leadership state to a route that just started. If
this node has lost the leadership before
+ * the route started, the leadership change is applied again so the route
is stopped promptly.
+ */
+ @Override
+ public void onStart(Route route) {
+ super.onStart(route);
+ // A route added to a running CamelContext while this node is the
leader is started by the route controller
+ // (see onInit). If the leadership was lost before the route started,
the policy thread could not stop it, so
+ // it applies the leadership again now (it stops the route once
started, see doStopManagedRoutes).
+ if (!isLeader() && startedRoutes.contains(route)) {
+ reapply.set(true);
+ handOverLeadershipChange();
+ }
+ }
+
@Override
protected void doShutdown() throws Exception {
retainLock.lock();
@@ -292,6 +312,8 @@ public final class ClusteredRoutePolicy extends
RoutePolicySupport implements Ca
camelContext.getManagementStrategy().removeEventNotifier(listener);
ExecutorService executor = leadershipExecutor;
if (executor != null) {
+ // a route of this policy created again (CamelContext started
again) makes it usable again (onInit)
+ leadershipExecutor = null;
camelContext.getExecutorServiceManager().shutdownNow(executor);
}
ScheduledExecutorService scheduler = initialDelayExecutor;
@@ -309,6 +331,27 @@ public final class ClusteredRoutePolicy extends
RoutePolicySupport implements Ca
}
}
+ private void restart() {
+ LOG.debug("ClusteredRoutePolicy for namespace {} is used again after
it was shut down", namespace);
+ // a change queued when the executor was shut down was dropped, and
the CamelContext starts again
+ leadershipChangePending.set(false);
+ reapply.set(false);
+ retryScheduled.set(false);
+ contextStarted.set(false);
+ contextResumed = false;
+ initialDelayElapsed = false;
+ // onRemove already clears the entries of the removed routes; start
the failure counts afresh anyway
+ failedStarts.clear();
+ // the routes are created while the CamelContext initializes: start
them once it has started
+ startManagedRoutesEarly = true;
+ camelContext.getManagementStrategy().addEventNotifier(listener);
+ leadershipExecutor = newLeadershipExecutor();
+ }
+
+ private ExecutorService newLeadershipExecutor() {
+ return camelContext.getExecutorServiceManager().newThreadPool(this,
THREAD_NAME, newLeadershipThreadPoolProfile());
+ }
+
// The view and the cluster service are called without holding the policy
lock. The view holds its own lock while
// it notifies the listeners, and the policy thread holds the policy lock
while it starts or stops routes, which
// needs the CamelContext route lock. onRemove (and so releaseClusterView)
can run while the caller holds that route
@@ -468,9 +511,11 @@ public final class ClusteredRoutePolicy extends
RoutePolicySupport implements Ca
LOG.debug("Starting route '{}'", route.getId());
try {
camelContext.getRouteController().startRoute(route.getId());
- } catch (Exception e) {
+ } catch (Throwable e) {
+ // an Error (such as a NoClassDefFoundError) is a failed
start too
failed = true;
int attempt = failedStarts.merge(route.getId(), 1,
Integer::sum);
+ rethrowIfFatal(e);
handleFailure("Failed to start route " + route.getId() + "
(attempt #" + attempt + "). Trying again in "
+ retryDelay.toMillis() + " millis while
this node is the leader.",
e);
@@ -506,8 +551,14 @@ public final class ClusteredRoutePolicy extends
RoutePolicySupport implements Ca
if (!isRunAllowed() || retryScheduled.getAndSet(true)) {
return;
}
- ScheduledExecutorService scheduler
- =
camelContext.getExecutorServiceManager().newSingleThreadScheduledExecutor(this,
THREAD_NAME + "Retry");
+ ScheduledExecutorService scheduler;
+ try {
+ scheduler =
camelContext.getExecutorServiceManager().newSingleThreadScheduledExecutor(this,
THREAD_NAME + "Retry");
+ } catch (Throwable e) {
+ // no retry is scheduled, so a later failure schedules one
+ retryScheduled.set(false);
+ throw e;
+ }
retryExecutor = scheduler;
try {
scheduler.schedule(() -> {
@@ -523,10 +574,27 @@ public final class ClusteredRoutePolicy extends
RoutePolicySupport implements Ca
} catch (RejectedExecutionException e) {
// the policy is being shut down
LOG.debug("Not trying again as ClusteredRoutePolicy for namespace
{} is shut down", namespace);
+ } catch (Throwable e) {
+ // such as an OutOfMemoryError when the timer thread cannot be
created: no retry is scheduled, so a later
+ // failure schedules one
+ retryExecutor = null;
+ retryScheduled.set(false);
+ camelContext.getExecutorServiceManager().shutdownNow(scheduler);
+ throw e;
+ }
+ }
+
+ // a VirtualMachineError (such as an OutOfMemoryError) is not handled as a
failed start or stop: the leadership is
+ // applied again after the retry delay, and the error is rethrown (logged
once, see applyLeadershipChange)
+ private void rethrowIfFatal(Throwable e) {
+ VirtualMachineError fatal = ObjectHelper.getVirtualMachineError(e);
+ if (fatal != null) {
+ scheduleRetry();
+ throw fatal;
}
}
- private void handleFailure(String message, Exception e) {
+ private void handleFailure(String message, Throwable e) {
if (getExceptionHandler() != null) {
getExceptionHandler().handleException(message, e);
} else {
@@ -553,11 +621,16 @@ public final class ClusteredRoutePolicy extends
RoutePolicySupport implements Ca
// each route on its own, so a route that fails to stop does not keep
the others running
for (Route route : startedRoutes) {
ServiceStatus status = getStatus(route);
- if (status != null && status.isStoppable()) {
+ if (status == ServiceStatus.Starting) {
+ // the route controller is starting it (a route added while
this node was the leader): stop it later
+ LOG.debug("Will stop route '{}' once it has started",
route.getId());
+ stopFailed = true;
+ } else if (status != null && status.isStoppable()) {
LOG.debug("Stopping route '{}'", route.getId());
try {
stopRoute(route);
- } catch (Exception e) {
+ } catch (Throwable e) {
+ rethrowIfFatal(e);
handleFailure("Failed to stop route " + route.getId(), e);
if (getStatus(route).isStoppable()) {
// still running: it stays with the started routes,
and the stop is tried again
@@ -646,7 +719,13 @@ public final class ClusteredRoutePolicy extends
RoutePolicySupport implements Ca
leadershipChangePending.getAndSet(false);
try {
setLeader();
- } catch (Exception e) {
+ } catch (Throwable e) {
+ VirtualMachineError fatal = ObjectHelper.getVirtualMachineError(e);
+ if (fatal != null) {
+ LOG.error("Error applying leadership change of
ClusteredRoutePolicy for namespace {}. The error is rethrown.",
+ namespace, e);
+ throw fatal;
+ }
LOG.warn("Error applying leadership change of ClusteredRoutePolicy
for namespace {}. This exception is ignored.",
namespace, e);
}
diff --git
a/core/camel-core/src/test/java/org/apache/camel/cluster/ClusteredRoutePolicyLateStartAndRestartTest.java
b/core/camel-core/src/test/java/org/apache/camel/cluster/ClusteredRoutePolicyLateStartAndRestartTest.java
new file mode 100644
index 000000000000..f3fae8450a82
--- /dev/null
+++
b/core/camel-core/src/test/java/org/apache/camel/cluster/ClusteredRoutePolicyLateStartAndRestartTest.java
@@ -0,0 +1,414 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.cluster;
+
+import java.time.Duration;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ScheduledExecutorService;
+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.Consumer;
+import org.apache.camel.Endpoint;
+import org.apache.camel.Processor;
+import org.apache.camel.Producer;
+import org.apache.camel.Route;
+import org.apache.camel.ServiceStatus;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.impl.cluster.ClusteredRoutePolicy;
+import org.apache.camel.impl.engine.DefaultExecutorServiceManager;
+import org.apache.camel.impl.engine.DefaultRouteController;
+import org.apache.camel.support.DefaultComponent;
+import org.apache.camel.support.DefaultConsumer;
+import org.apache.camel.support.DefaultEndpoint;
+import org.apache.camel.support.RoutePolicySupport;
+import org.apache.camel.support.cluster.AbstractCamelClusterService;
+import org.apache.camel.support.cluster.AbstractCamelClusterView;
+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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * A route added to a running CamelContext while this node loses the
leadership must not keep running, and a
+ * ClusteredRoutePolicy must work again after the CamelContext was stopped and
started.
+ */
+class ClusteredRoutePolicyLateStartAndRestartTest {
+
+ private CamelContext context;
+
+ @AfterEach
+ void stopContext() {
+ if (context != null) {
+ context.stop();
+ }
+ }
+
+ @Test
+ void routeAddedWhileLeadershipIsLostIsStopped() throws Exception {
+ TestClusterService cs = new TestClusterService("node-1", true);
+ // the policy thread has looked at route foo (not started yet) while
it applied the loss of the leadership
+ CountDownLatch fooChecked = new CountDownLatch(1);
+ context = new DefaultCamelContext();
+ context.setRouteController(new PolicyThreadHook(context, "foo", null,
fooChecked));
+ context.addService(cs);
+ ClusteredRoutePolicy policy =
ClusteredRoutePolicy.forNamespace("my-ns");
+ policy.setRetryDelay(Duration.ofMillis(100));
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+ // keeps the policy running, and is never started
+
from("seda:bar").routeId("bar").autoStartup(false).routePolicy(policy).to("mock:bar");
+ }
+ });
+ context.start();
+
+ // runs right after the onInit of the clustered policy, which found
this node to be the leader
+ RoutePolicySupport loseLeadership = new RoutePolicySupport() {
+ @Override
+ public void onInit(Route route) {
+ super.onInit(route);
+ cs.getView().setLeader(false);
+ try {
+ assertTrue(fooChecked.await(10, TimeUnit.SECONDS), "The
policy did not apply the loss");
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException(e);
+ }
+ }
+ };
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+ from("seda:foo").routeId("foo").routePolicy(policy,
loseLeadership).to("mock:foo");
+ }
+ });
+
+ await().atMost(10, TimeUnit.SECONDS).untilAsserted(
+ () -> assertEquals(ServiceStatus.Stopped,
context.getRouteController().getRouteStatus("foo")));
+ assertEquals(ServiceStatus.Stopped,
context.getRouteController().getRouteStatus("bar"));
+ }
+
+ @Test
+ void routeStartingWhileLeadershipIsLostIsStoppedOnceStarted() throws
Exception {
+ TestClusterService cs = new TestClusterService("node-1", true);
+ // the policy thread has seen route foo starting while it applied the
loss of the leadership
+ CountDownLatch fooSeenStarting = new CountDownLatch(1);
+ context = new DefaultCamelContext();
+ context.setRouteController(new PolicyThreadHook(context, "foo",
ServiceStatus.Starting, fooSeenStarting));
+ context.addService(cs);
+ context.start();
+ ClusteredRoutePolicy policy =
ClusteredRoutePolicy.forNamespace("my-ns");
+ policy.setRetryDelay(Duration.ofMillis(100));
+
+ // its onStart runs after the one of the clustered policy, while the
route is starting
+ RoutePolicySupport loseLeadership = new RoutePolicySupport() {
+ @Override
+ public void onStart(Route route) {
+ super.onStart(route);
+ cs.getView().setLeader(false);
+ try {
+ assertTrue(fooSeenStarting.await(10, TimeUnit.SECONDS),
"The policy did not apply the loss");
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException(e);
+ }
+ }
+ };
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+ from("seda:foo").routeId("foo").routePolicy(policy,
loseLeadership).to("mock:foo");
+ }
+ });
+
+ await().atMost(10, TimeUnit.SECONDS).untilAsserted(
+ () -> assertEquals(ServiceStatus.Stopped,
context.getRouteController().getRouteStatus("foo")));
+ }
+
+ @Test
+ void leaderStartsRoutesAfterCamelContextRestart() throws Exception {
+ TestClusterService cs = new TestClusterService("node-1", true);
+ context = new DefaultCamelContext();
+ context.addService(cs);
+ ClusteredRoutePolicy policy =
ClusteredRoutePolicy.forNamespace("my-ns");
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+
from("seda:foo").routeId("foo").routePolicy(policy).to("mock:foo");
+
from("seda:baz").routeId("baz").autoStartup(false).routePolicy(policy).to("mock:baz");
+ }
+ });
+ context.start();
+ await().atMost(10, TimeUnit.SECONDS).untilAsserted(
+ () -> assertEquals(ServiceStatus.Started,
context.getRouteController().getRouteStatus("foo")));
+
+ context.stop();
+ context.start();
+
+ await().atMost(10, TimeUnit.SECONDS).untilAsserted(
+ () -> assertEquals(ServiceStatus.Started,
context.getRouteController().getRouteStatus("foo")));
+ // a route that is not auto startup stays stopped
+ assertEquals(ServiceStatus.Stopped,
context.getRouteController().getRouteStatus("baz"));
+
+ // and the leadership changes are applied again
+ cs.getView().setLeader(false);
+ await().atMost(10, TimeUnit.SECONDS).untilAsserted(
+ () -> assertEquals(ServiceStatus.Stopped,
context.getRouteController().getRouteStatus("foo")));
+ }
+
+ @Test
+ void leadershipTakenAfterCamelContextRestartStartsRoute() throws Exception
{
+ TestClusterService cs = new TestClusterService("node-1", false);
+ context = new DefaultCamelContext();
+ context.addService(cs);
+ ClusteredRoutePolicy policy =
ClusteredRoutePolicy.forNamespace("my-ns");
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+
from("seda:foo").routeId("foo").routePolicy(policy).to("mock:foo");
+ }
+ });
+ context.start();
+ context.stop();
+ context.start();
+ assertEquals(ServiceStatus.Stopped,
context.getRouteController().getRouteStatus("foo"));
+
+ cs.getView().setLeader(true);
+ await().atMost(10, TimeUnit.SECONDS).untilAsserted(
+ () -> assertEquals(ServiceStatus.Started,
context.getRouteController().getRouteStatus("foo")));
+ }
+
+ @Test
+ void routeStartThrowingErrorIsTriedAgain() throws Exception {
+ TestClusterService cs = new TestClusterService("node-1", false);
+ context = new DefaultCamelContext();
+ context.addService(cs);
+ AtomicInteger errors = new AtomicInteger(1);
+ context.addComponent("erroring", new ErrorOnStartComponent(errors,
true));
+ ClusteredRoutePolicy policy =
ClusteredRoutePolicy.forNamespace("my-ns");
+ policy.setRetryDelay(Duration.ofMillis(100));
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+
from("erroring:foo").routeId("foo").routePolicy(policy).to("mock:foo");
+ }
+ });
+ context.start();
+
+ cs.getView().setLeader(true);
+ // on main the Error escapes the policy thread: look at the route, not
at uncaught exceptions
+ await().dontCatchUncaughtExceptions().atMost(10,
TimeUnit.SECONDS).untilAsserted(
+ () -> assertEquals(ServiceStatus.Started,
context.getRouteController().getRouteStatus("foo")));
+ assertEquals(0, errors.get());
+ }
+
+ @Test
+ void retryTimerThatCannotBeCreatedIsCreatedOnTheNextFailure() throws
Exception {
+ TestClusterService cs = new TestClusterService("node-1", false);
+ context = new DefaultCamelContext();
+ // the first retry timer cannot be created, as when the JVM cannot
create a native thread. Not with an
+ // OutOfMemoryError: it would escape the policy thread and fail the
tests that run at the same time
+ CountDownLatch timerFailed = new CountDownLatch(1);
+ context.setExecutorServiceManager(new
DefaultExecutorServiceManager(context) {
+ @Override
+ public ScheduledExecutorService
newSingleThreadScheduledExecutor(Object source, String name) {
+ if (name.endsWith("Retry") && timerFailed.getCount() > 0) {
+ timerFailed.countDown();
+ throw new IllegalStateException("Simulated: unable to
create the retry timer");
+ }
+ return super.newSingleThreadScheduledExecutor(source, name);
+ }
+ });
+ context.addService(cs);
+ AtomicInteger failures = new AtomicInteger(2);
+ context.addComponent("erroring", new ErrorOnStartComponent(failures,
false));
+ ClusteredRoutePolicy policy =
ClusteredRoutePolicy.forNamespace("my-ns");
+ policy.setRetryDelay(Duration.ofMillis(100));
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+
from("erroring:foo").routeId("foo").routePolicy(policy).to("mock:foo");
+ }
+ });
+ context.start();
+
+ // the first start fails, and its retry cannot be scheduled
+ cs.getView().setLeader(true);
+ assertTrue(timerFailed.await(10, TimeUnit.SECONDS), "The policy did
not try to schedule a retry");
+ // the leadership is lost and taken again: the next start fails too,
and its retry is scheduled (before, the
+ // retry flag stayed set after the timer could not be created, so no
retry ran and the route stayed stopped)
+ cs.getView().setLeader(false);
+ await().atMost(10, TimeUnit.SECONDS).until(() -> !policy.isLeader());
+ cs.getView().setLeader(true);
+ await().atMost(10, TimeUnit.SECONDS).untilAsserted(
+ () -> assertEquals(ServiceStatus.Started,
context.getRouteController().getRouteStatus("foo")));
+ assertEquals(-1, failures.get());
+ }
+
+ // *********************************
+ // Helpers
+ // *********************************
+
+ /**
+ * Counts down the latch when the policy thread reads the status of the
route (and the status is the expected one,
+ * if any).
+ */
+ private static final class PolicyThreadHook extends DefaultRouteController
{
+ private final String routeId;
+ private final ServiceStatus expected;
+ private final CountDownLatch latch;
+
+ PolicyThreadHook(CamelContext context, String routeId, ServiceStatus
expected, CountDownLatch latch) {
+ super(context);
+ this.routeId = routeId;
+ this.expected = expected;
+ this.latch = latch;
+ }
+
+ @Override
+ public ServiceStatus getRouteStatus(String id) {
+ ServiceStatus status = super.getRouteStatus(id);
+ if (routeId.equals(id) &&
Thread.currentThread().getName().contains("ClusteredRoutePolicy")
+ && (expected == null || expected == status)) {
+ latch.countDown();
+ }
+ return status;
+ }
+ }
+
+ private static final class ErrorOnStartComponent extends DefaultComponent {
+ private final AtomicInteger errors;
+ private final boolean linkageError;
+
+ ErrorOnStartComponent(AtomicInteger errors, boolean linkageError) {
+ this.errors = errors;
+ this.linkageError = linkageError;
+ }
+
+ @Override
+ protected Endpoint createEndpoint(String uri, String remaining,
Map<String, Object> parameters) {
+ return new DefaultEndpoint(uri, this) {
+ @Override
+ public Producer createProducer() {
+ throw new UnsupportedOperationException("No producer");
+ }
+
+ @Override
+ public Consumer createConsumer(Processor processor) {
+ return new DefaultConsumer(this, processor) {
+ @Override
+ protected void doStart() throws Exception {
+ if (errors.getAndDecrement() > 0) {
+ if (linkageError) {
+ throw new NoClassDefFoundError("Simulated
linkage error on start");
+ }
+ throw new IllegalStateException("Simulated
failure on start");
+ }
+ super.doStart();
+ }
+ };
+ }
+ };
+ }
+ }
+
+ private static final class TestClusterView extends
AbstractCamelClusterView {
+ private final AtomicBoolean leader;
+
+ TestClusterView(CamelClusterService cluster, String namespace,
AtomicBoolean leader) {
+ super(cluster, namespace);
+ this.leader = leader;
+ }
+
+ @Override
+ public Optional<CamelClusterMember> getLeader() {
+ return leader.get() ? Optional.of(getLocalMember()) :
Optional.empty();
+ }
+
+ @Override
+ public CamelClusterMember getLocalMember() {
+ return new CamelClusterMember() {
+ @Override
+ public boolean isLeader() {
+ return leader.get();
+ }
+
+ @Override
+ public boolean isLocal() {
+ return true;
+ }
+
+ @Override
+ public String getId() {
+ return getClusterService().getId();
+ }
+ };
+ }
+
+ @Override
+ public List<CamelClusterMember> getMembers() {
+ return Collections.emptyList();
+ }
+
+ @Override
+ protected void doStart() {
+ }
+
+ @Override
+ protected void doStop() {
+ }
+
+ void setLeader(boolean value) {
+ leader.set(value);
+ if (isRunAllowed()) {
+ fireLeadershipChangedEvent(getLeader().orElse(null));
+ }
+ }
+ }
+
+ private static final class TestClusterService extends
AbstractCamelClusterService<TestClusterView> {
+ private final AtomicBoolean leader;
+ private volatile TestClusterView view;
+
+ TestClusterService(String id, boolean leader) {
+ super(id);
+ this.leader = new AtomicBoolean(leader);
+ }
+
+ @Override
+ protected TestClusterView createView(String namespace) {
+ if (view == null) {
+ view = new TestClusterView(this, namespace, leader);
+ }
+ return view;
+ }
+
+ TestClusterView getView() {
+ return view;
+ }
+ }
+}