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 b5864d3777b2 CAMEL-27537: camel-xmpp - a route stopped during the
consumer's delayed start is not started again by it (#30915)
b5864d3777b2 is described below
commit b5864d3777b2c746c5a5a63092af56f3659cbf24
Author: allthingssecurity <[email protected]>
AuthorDate: Fri Nov 27 12:42:53 2026 +0530
CAMEL-27537: camel-xmpp - a route stopped during the consumer's delayed
start is not started again by it (#30915)
With testConnectionOnStartup=false the delayed start of the consumer adds
the consumer to the users of the account's shared connection and then
waits for the account's lock, which another consumer or producer of the
account holds while it connects or logs in. ReentrantLock.lock() ignores
the interrupt of shutdownNow. When the route was stopped meanwhile,
doStop had no connection to release yet, and the delayed start went on
with the stopped consumer when it got the lock: a chat consumer listened
on the connection and started a connection monitor on a new executor
(and routed chat messages into the stopped route), and stayed a user of
the connection, so the connection and its session stayed open. A room
consumer was interrupted in the join; before CAMEL-27506 it also stayed
a user of the connection.
Both starts now check isRunAllowed() under a new startLock after they
got the connection, and only then set the connection field, listen on
it, enter the room (subscribe()) and start the monitor; when the
consumer is stopping they release the connection. A delayed start that
fails releases what it got under the same lock, and the next attempt is
only scheduled under the lock while the consumer is not stopping, so no
attempt and no new executor is created after the stop. doStop shuts the
executor down first (cancels a pending delayed start, interrupts a
running one), then takes startLock, so it waits for a delayed start that
is subscribing and shuts down the executor that start created;
super.doStop() now runs after.
New XmppConsumerStopDuringDelayedStartTest (chat and room consumer).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../apache/camel/component/xmpp/XmppConsumer.java | 119 +++++++++++++-----
.../XmppConsumerStopDuringDelayedStartTest.java | 134 +++++++++++++++++++++
2 files changed, 223 insertions(+), 30 deletions(-)
diff --git
a/components/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppConsumer.java
b/components/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppConsumer.java
index 1b36eb8823e7..ee4f9138ad38 100644
---
a/components/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppConsumer.java
+++
b/components/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppConsumer.java
@@ -80,6 +80,10 @@ public class XmppConsumer extends DefaultConsumer implements
IncomingChatMessage
private volatile ScheduledExecutorService scheduledExecutor;
// the failed attempts of the delayed start (in the connection poller
thread)
private int delayedStartFailures;
+ // the start subscribes and starts its connection monitor under this lock,
after it checked that the consumer is not
+ // stopping, and the stop takes it before it releases the connection: the
stop waits for a delayed start that is
+ // subscribing, and a delayed start that got the connection after the stop
began gives it back
+ private final Object startLock = new Object();
public XmppConsumer(XmppEndpoint endpoint, Processor processor) {
super(endpoint, processor);
@@ -88,8 +92,9 @@ public class XmppConsumer extends DefaultConsumer implements
IncomingChatMessage
@Override
protected void doStart() throws Exception {
+ XMPPTCPConnection acquired;
try {
- connection = endpoint.acquireConnection(this);
+ acquired = endpoint.acquireConnection(this);
} catch (SmackException e) {
if (endpoint.isTestConnectionOnStartup()) {
throw new RuntimeCamelException("Could not connect to XMPP
server.", e);
@@ -103,9 +108,26 @@ public class XmppConsumer extends DefaultConsumer
implements IncomingChatMessage
}
}
- subscribe();
- super.doStart();
- startRobustConnectionMonitor();
+ synchronized (startLock) {
+ if (!isRunAllowed()) {
+ releaseStoppedStart();
+ return;
+ }
+ connection = acquired;
+ subscribe();
+ super.doStart();
+ startRobustConnectionMonitor();
+ }
+ }
+
+ /**
+ * Gives back the connection that a start got after the consumer began to
stop: the stop had no connection to
+ * release yet (a delayed start waits for the account's lock while another
consumer or producer of the account
+ * connects or logs in).
+ */
+ private void releaseStoppedStart() {
+ LOG.debug("The XMPP consumer was stopped while it was starting.
Releasing its connection.");
+ endpoint.releaseConnection(this);
}
/**
@@ -146,10 +168,31 @@ public class XmppConsumer extends DefaultConsumer
implements IncomingChatMessage
}
protected void scheduleDelayedStart() {
- LOG.info("Delaying XMPP consumer startup for endpoint {}. Trying again
in {} seconds.",
- URISupport.sanitizeUri(endpoint.getEndpointUri()),
endpoint.getConnectionPollDelay());
delayedStartFailures = 0;
- getExecutor().schedule(this::delayedStart,
endpoint.getConnectionPollDelay(), TimeUnit.SECONDS);
+ if (scheduleDelayedStartAttempt()) {
+ LOG.info("Delaying XMPP consumer startup for endpoint {}. Trying
again in {} seconds.",
+ URISupport.sanitizeUri(endpoint.getEndpointUri()),
endpoint.getConnectionPollDelay());
+ }
+ }
+
+ /**
+ * Schedules the next attempt of the delayed start, unless the consumer is
stopping: under startLock, so that no
+ * attempt (and no new executor) is created after the stop shut the
executor down.
+ */
+ private boolean scheduleDelayedStartAttempt() {
+ synchronized (startLock) {
+ if (!isRunAllowed()) {
+ LOG.debug("Not trying again to start the XMPP consumer, as it
is stopping.");
+ return false;
+ }
+ try {
+ getExecutor().schedule(this::delayedStart,
endpoint.getConnectionPollDelay(), TimeUnit.SECONDS);
+ } catch (RejectedExecutionException e) {
+ LOG.debug("Not trying again to start the XMPP consumer, as it
is stopping.");
+ return false;
+ }
+ return true;
+ }
}
/**
@@ -162,11 +205,26 @@ public class XmppConsumer extends DefaultConsumer
implements IncomingChatMessage
*/
private void delayedStart() {
try {
- connection = endpoint.acquireConnection(this);
- subscribe();
- super.doStart();
- // once the start succeeded: a failed attempt must not leave a
monitor running on the released connection
- startRobustConnectionMonitor();
+ XMPPTCPConnection acquired = endpoint.acquireConnection(this);
+ synchronized (startLock) {
+ if (!isRunAllowed()) {
+ releaseStoppedStart();
+ return;
+ }
+ connection = acquired;
+ try {
+ subscribe();
+ super.doStart();
+ } catch (Throwable e) {
+ // release what this attempt acquired, under startLock so
that a stop waiting for it finds nothing
+ // of it left: the next attempt starts again from the
beginning, and a consumer that is not started
+ // must not keep the account's connection
+ releaseFailedStart();
+ throw e;
+ }
+ // once the start succeeded: a failed attempt must not leave a
monitor running on the released connection
+ startRobustConnectionMonitor();
+ }
if (delayedStartFailures > 0) {
LOG.info("Started the XMPP consumer for endpoint {} after {}
failed attempts.",
URISupport.sanitizeUri(endpoint.getEndpointUri()),
delayedStartFailures);
@@ -174,17 +232,12 @@ public class XmppConsumer extends DefaultConsumer
implements IncomingChatMessage
} catch (VirtualMachineError e) {
throw e;
} catch (Throwable e) {
- // release what this attempt acquired: the next attempt starts
again from the beginning, and a consumer
- // that is not started must not keep the account's connection
- releaseFailedStart();
+ // a failed acquireConnection released the consumer from the
connection's users itself, and a failed
+ // subscribe() released what it got before it was thrown here
if (e instanceof InterruptedException) {
- // after the release, which disconnects the connection when
nobody else uses it
Thread.currentThread().interrupt();
}
- // the executor of this thread: the stop shuts it down and clears
the field, and getExecutor() would then
- // create another one that nothing shuts down
- ScheduledExecutorService executor = scheduledExecutor;
- if (!isRunAllowed() || executor == null || executor.isShutdown()) {
+ if (!isRunAllowed()) {
LOG.debug("Not trying again to start the XMPP consumer, as it
is stopping: {}", e.toString());
return;
}
@@ -199,11 +252,7 @@ public class XmppConsumer extends DefaultConsumer
implements IncomingChatMessage
LOG.debug("Could not start the XMPP consumer for endpoint {}
({} attempts). Trying again in {} seconds.",
uri, delayedStartFailures,
endpoint.getConnectionPollDelay(), e);
}
- try {
- executor.schedule(this::delayedStart,
endpoint.getConnectionPollDelay(), TimeUnit.SECONDS);
- } catch (RejectedExecutionException rejected) {
- LOG.debug("Not trying again to start the XMPP consumer, as it
is stopping: {}", e.toString());
- }
+ scheduleDelayedStartAttempt();
}
}
@@ -313,13 +362,15 @@ public class XmppConsumer extends DefaultConsumer
implements IncomingChatMessage
@Override
protected void doStop() throws Exception {
+ // stop scheduler first: this cancels a pending delayed start and
interrupts a running one
+ shutdownExecutor();
+ synchronized (startLock) {
+ // waits for a delayed start that was subscribing when the stop
began (it started its connection monitor on
+ // a new executor); a delayed start that gets here later sees that
the consumer is stopping
+ shutdownExecutor();
+ }
super.doStop();
- // stop scheduler first
- if (scheduledExecutor != null) {
-
getEndpoint().getCamelContext().getExecutorServiceManager().shutdownNow(scheduledExecutor);
- scheduledExecutor = null;
- }
if (connection != null) {
connection.removeConnectionListener(connectionListener);
}
@@ -338,6 +389,14 @@ public class XmppConsumer extends DefaultConsumer
implements IncomingChatMessage
releaseConnection();
}
+ private void shutdownExecutor() {
+ ScheduledExecutorService executor = scheduledExecutor;
+ if (executor != null) {
+
getEndpoint().getCamelContext().getExecutorServiceManager().shutdownNow(executor);
+ scheduledExecutor = null;
+ }
+ }
+
private void releaseConnection() {
if (connection != null) {
// the connection is shared with the other consumers and producers
of the account: stop listening on it,
diff --git
a/components/camel-xmpp/src/test/java/org/apache/camel/component/xmpp/XmppConsumerStopDuringDelayedStartTest.java
b/components/camel-xmpp/src/test/java/org/apache/camel/component/xmpp/XmppConsumerStopDuringDelayedStartTest.java
new file mode 100644
index 000000000000..50e262d0bb3c
--- /dev/null
+++
b/components/camel-xmpp/src/test/java/org/apache/camel/component/xmpp/XmppConsumerStopDuringDelayedStartTest.java
@@ -0,0 +1,134 @@
+/*
+ * 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.xmpp;
+
+import java.net.InetAddress;
+import java.net.ServerSocket;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.ReentrantLock;
+
+import org.apache.camel.ServiceStatus;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.jivesoftware.smack.ConnectionConfiguration;
+import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
+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.assertNull;
+
+/**
+ * With testConnectionOnStartup=false the consumer starts in the background
when the server cannot be reached at start.
+ * That delayed start waits for the account's lock while another consumer or
producer of the account connects or logs
+ * in. When the route is stopped meanwhile, the delayed start must not start
the stopped consumer when it gets the lock:
+ * no listener on the connection, no connection monitor, and the account's
connection is closed once its other users
+ * released it.
+ */
+class XmppConsumerStopDuringDelayedStartTest {
+
+ private static final String ROOM = "dev@conference." +
FakeXmppServer.DOMAIN;
+
+ private DefaultCamelContext context;
+ private FakeXmppServer server;
+
+ @AfterEach
+ void stop() throws Exception {
+ if (context != null) {
+ context.stop();
+ }
+ if (server != null) {
+ server.close();
+ }
+ }
+
+ @Test
+ void chatConsumerStoppedWhileItsDelayedStartWaitsForTheLockIsNotStarted()
throws Exception {
+ int port = freePort();
+ stopWhileTheDelayedStartWaitsForTheLock(port, "xmpp://127.0.0.1:" +
port + "/bob@" + FakeXmppServer.DOMAIN
+ +
"?connectionConfig=#connectionConfig&connectionPollDelay=3"
+ +
"&testConnectionOnStartup=false");
+ }
+
+ @Test
+ void roomConsumerStoppedWhileItsDelayedStartWaitsForTheLockIsNotStarted()
throws Exception {
+ int port = freePort();
+ stopWhileTheDelayedStartWaitsForTheLock(port, "xmpp://127.0.0.1:" +
port + "?room=" + ROOM + "&nickname=camel"
+ +
"&connectionConfig=#connectionConfig&connectionPollDelay=3"
+ +
"&testConnectionOnStartup=false");
+ assertEquals(0, server.occupants(ROOM), "the stopped consumer entered
its room");
+ }
+
+ private void stopWhileTheDelayedStartWaitsForTheLock(int port, String uri)
throws Exception {
+ startRoute(port, uri);
+ XmppConsumer consumer = (XmppConsumer)
context.getRoute("in").getConsumer();
+ XmppEndpoint endpoint = (XmppEndpoint) consumer.getEndpoint();
+ XmppComponent component = endpoint.getComponent();
+
+ // the server is reachable now; a producer of the account has the
connection, and holds the account's lock (as
+ // while it logs in again) when the delayed start
(connectionPollDelay=3) runs
+ server = new FakeXmppServer(port);
+ Object producer = new Object();
+ component.acquireConnection(endpoint, producer);
+ ReentrantLock lock = component.connectionLock(endpoint);
+ lock.lock();
+ try {
+ await().atMost(10, TimeUnit.SECONDS).until(lock::hasQueuedThreads);
+ context.getRouteController().stopRoute("in");
+ } finally {
+ lock.unlock();
+ }
+ // the producer stops too
+ component.releaseConnection(endpoint, producer);
+
+ // the delayed start gets the lock and the connection, and gives the
connection back
+ await().atMost(10, TimeUnit.SECONDS).until(() -> !lock.isLocked() &&
!lock.hasQueuedThreads()
+ && component.connectionUsers(endpoint) == 0);
+ await().atMost(10, TimeUnit.SECONDS).until(() ->
server.boundSessions() == 0);
+ await().atMost(10, TimeUnit.SECONDS).until(() ->
Thread.getAllStackTraces().keySet().stream()
+ .noneMatch(t -> t.isAlive() &&
t.getName().contains("connectionPoll")));
+ assertNull(consumer.connection, "the stopped consumer holds a
connection");
+ assertEquals(ServiceStatus.Stopped,
context.getRouteController().getRouteStatus("in"));
+ }
+
+ private void startRoute(int port, String uri) throws Exception {
+ context = new DefaultCamelContext();
+ // the test server has no TLS
+ context.getRegistry().bind("connectionConfig",
XMPPTCPConnectionConfiguration.builder()
+ .setHostAddress(InetAddress.getLoopbackAddress())
+ .setPort(port)
+ .setXmppDomain(FakeXmppServer.DOMAIN)
+ .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
+ .performSaslAnonymousAuthentication()
+ .build());
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+ from(uri).routeId("in").to("mock:out");
+ }
+ });
+ // nothing listens on the port yet, so the consumer starts in the
background
+ context.start();
+ }
+
+ private static int freePort() throws Exception {
+ try (ServerSocket socket = new ServerSocket(0, 50,
InetAddress.getLoopbackAddress())) {
+ return socket.getLocalPort();
+ }
+ }
+}