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 06feffca4da4 CAMEL-27506: camel-xmpp - the consumer's delayed start 
tries again after any failure, not only when the server cannot be reached 
(#30830)
06feffca4da4 is described below

commit 06feffca4da424d1b6c1051fe1ce464f3e96765e
Author: allthingssecurity <[email protected]>
AuthorDate: Thu Nov 26 13:32:08 2026 +0530

    CAMEL-27506: camel-xmpp - the consumer's delayed start tries again after 
any failure, not only when the server cannot be reached (#30830)
    
    With testConnectionOnStartup=false the delayed start ran doStart, which
    only scheduled another attempt when getting the connection threw a
    SmackException. Any other failure (a login that fails with an
    XMPPException such as SASL temporary-auth-failure, a room entry refused
    with service-unavailable, a NoResponseException during the join) was
    only logged by the task, and nothing tried again: the route stayed
    Started and consumed nothing, and a room consumer kept the account's
    connection.
    
    The delayed start now has its own method. After any failure it releases
    what the attempt got (listeners, room, its use of the shared connection)
    and tries again after connectionPollDelay, until the consumer is
    stopping. The first failure is logged at WARN and passed to the
    exception handler, the next ones at DEBUG; a start that works after
    failed attempts logs one INFO line. An Error is handled the same way, a
    VirtualMachineError is thrown on. The part of doStart after getting the
    connection moved to subscribe(), used by both starts.
    
    XmppEndpoint.createConnection closes (instantShutdown) a new connection
    whose connect, account creation or login fails: Smack keeps it open and
    nobody else has it, so each retried login would leave one more
    connection open.
    
    New XmppConsumerDelayedStartRetryTest (refused first room entry, failed
    first login) with FakeXmppServer, which gets a constructor for a fixed
    port, switches to refuse room entries and fail logins, and counters.
    
    * CAMEL-27506: camel-xmpp - review follow-up: connection monitor, retry 
scheduling and interrupt flag of the delayed start
    
    - XmppConsumer: the connection monitor is started once the start succeeded
      (after super.doStart()), in both starts, instead of at the end of 
subscribe().
      A delayed start attempt that failed after subscribe() left the monitor 
running
      on the released connection, and the next attempt started a second one.
    - XmppConsumer: the next delayed start attempt is scheduled on the 
consumer's
      executor as read from the field, and not when the stop has cleared or 
shut it
      down (a RejectedExecutionException is ignored). getExecutor() created a 
new
      executor that nothing shuts down when the stop ran between the 
isRunAllowed()
      check and the schedule.
    - XmppConsumer: a delayed start attempt that failed with 
InterruptedException
      restores the interrupt flag, after it released the connection.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../apache/camel/component/xmpp/XmppConsumer.java  |  96 +++++++++++++---
 .../apache/camel/component/xmpp/XmppEndpoint.java  |  37 +++---
 .../camel/component/xmpp/FakeXmppServer.java       |  63 ++++++++++-
 .../xmpp/XmppConsumerDelayedStartRetryTest.java    | 126 +++++++++++++++++++++
 4 files changed, 294 insertions(+), 28 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 36459f6d9d33..1b36eb8823e7 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
@@ -16,6 +16,7 @@
  */
 package org.apache.camel.component.xmpp;
 
+import java.util.concurrent.RejectedExecutionException;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
 
@@ -77,6 +78,8 @@ public class XmppConsumer extends DefaultConsumer implements 
IncomingChatMessage
     // package-private for tests
     XMPPTCPConnection connection;
     private volatile ScheduledExecutorService scheduledExecutor;
+    // the failed attempts of the delayed start (in the connection poller 
thread)
+    private int delayedStartFailures;
 
     public XmppConsumer(XmppEndpoint endpoint, Processor processor) {
         super(endpoint, processor);
@@ -100,6 +103,15 @@ public class XmppConsumer extends DefaultConsumer 
implements IncomingChatMessage
             }
         }
 
+        subscribe();
+        super.doStart();
+        startRobustConnectionMonitor();
+    }
+
+    /**
+     * Listens on the acquired connection, and enters the room when the 
endpoint has one.
+     */
+    private void subscribe() throws Exception {
         if (endpoint.getRoom() == null && endpoint.hasParticipant()) {
             // the chat manager of the account passes the chat messages of 
every sender to every consumer of the account
             participantJid = 
JidCreate.entityBareFrom(endpoint.resolveParticipant(connection));
@@ -131,24 +143,82 @@ public class XmppConsumer extends DefaultConsumer 
implements IncomingChatMessage
         }
 
         connection.addConnectionListener(connectionListener);
-        this.startRobustConnectionMonitor();
-        super.doStart();
     }
 
     protected void scheduleDelayedStart() {
-        Runnable startRunnable = new Runnable() {
-            @Override
-            public void run() {
-                try {
-                    doStart();
-                } catch (Exception e) {
-                    LOG.warn("Ignoring an exception caught in the startup 
connection poller thread.", e);
-                }
-            }
-        };
         LOG.info("Delaying XMPP consumer startup for endpoint {}. Trying again 
in {} seconds.",
                 URISupport.sanitizeUri(endpoint.getEndpointUri()), 
endpoint.getConnectionPollDelay());
-        getExecutor().schedule(startRunnable, 
endpoint.getConnectionPollDelay(), TimeUnit.SECONDS);
+        delayedStartFailures = 0;
+        getExecutor().schedule(this::delayedStart, 
endpoint.getConnectionPollDelay(), TimeUnit.SECONDS);
+    }
+
+    /**
+     * Starts the consumer in the connection poller thread when the start 
could not connect to the server
+     * (testConnectionOnStartup=false). Every failure is tried again after 
connectionPollDelay until the consumer is
+     * stopped: a server can be reachable before it accepts logins (a 
temporary authentication failure) or before its
+     * rooms can be entered, and nothing else starts the consumer (the 
connection monitor is only started at the end of
+     * a successful start). The first failure is logged at WARN and passed to 
the exception handler, the next ones are
+     * logged at DEBUG.
+     */
+    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();
+            if (delayedStartFailures > 0) {
+                LOG.info("Started the XMPP consumer for endpoint {} after {} 
failed attempts.",
+                        URISupport.sanitizeUri(endpoint.getEndpointUri()), 
delayedStartFailures);
+            }
+        } 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();
+            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()) {
+                LOG.debug("Not trying again to start the XMPP consumer, as it 
is stopping: {}", e.toString());
+                return;
+            }
+            String uri = URISupport.sanitizeUri(endpoint.getEndpointUri());
+            if (++delayedStartFailures == 1) {
+                LOG.warn("Could not start the XMPP consumer for endpoint {}. 
Trying again every {} seconds.", uri,
+                        endpoint.getConnectionPollDelay(), e);
+                if (getExceptionHandler() != null) {
+                    getExceptionHandler().handleException("Could not start the 
XMPP consumer for endpoint " + uri, e);
+                }
+            } else {
+                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());
+            }
+        }
+    }
+
+    private void releaseFailedStart() {
+        try {
+            if (connection != null) {
+                connection.removeConnectionListener(connectionListener);
+            }
+            if (muc != null) {
+                muc.removeMessageListener(this);
+                muc = null;
+            }
+        } finally {
+            releaseConnection();
+        }
     }
 
     private void startRobustConnectionMonitor() {
diff --git 
a/components/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppEndpoint.java
 
b/components/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppEndpoint.java
index e54704139ffb..c6b01ae1b54c 100644
--- 
a/components/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppEndpoint.java
+++ 
b/components/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppEndpoint.java
@@ -243,23 +243,32 @@ public class XmppEndpoint extends DefaultEndpoint 
implements HeaderFilterStrateg
         try {
             LOG.trace("Creating new connection ...");
             XMPPTCPConnection newConnection = createConnectionInternal();
+            boolean created = false;
+            try {
+                newConnection.connect();
+
+                newConnection.addSyncStanzaListener(new XmppLogger("INBOUND"), 
stanza -> true);
+                newConnection.addSyncStanzaListener(new 
XmppLogger("OUTBOUND"), stanza -> true);
+
+                if (!newConnection.isAuthenticated()) {
+                    if (user != null && createAccount) {
+                        AccountManager accountManager = 
AccountManager.getInstance(newConnection);
+                        accountManager.createAccount(Localpart.from(user), 
password);
+                    }
+                    login(newConnection);
+                }
 
-            newConnection.connect();
-
-            newConnection.addSyncStanzaListener(new XmppLogger("INBOUND"), 
stanza -> true);
-            newConnection.addSyncStanzaListener(new XmppLogger("OUTBOUND"), 
stanza -> true);
-
-            if (!newConnection.isAuthenticated()) {
-                if (user != null && createAccount) {
-                    AccountManager accountManager = 
AccountManager.getInstance(newConnection);
-                    accountManager.createAccount(Localpart.from(user), 
password);
+                // okay new connection was created successfully
+                LOG.debug("Created new connection successfully: {}", 
newConnection);
+                created = true;
+                return newConnection;
+            } finally {
+                if (!created) {
+                    // nobody else has the connection to close it: Smack keeps 
a connection whose login failed open
+                    // (its socket, reader and writer threads), so that the 
caller can log in again
+                    newConnection.instantShutdown();
                 }
-                login(newConnection);
             }
-
-            // okay new connection was created successfully
-            LOG.debug("Created new connection successfully: {}", 
newConnection);
-            return newConnection;
         } finally {
             lock.unlock();
         }
diff --git 
a/components/camel-xmpp/src/test/java/org/apache/camel/component/xmpp/FakeXmppServer.java
 
b/components/camel-xmpp/src/test/java/org/apache/camel/component/xmpp/FakeXmppServer.java
index d0a1449c555d..593626a5cf1f 100644
--- 
a/components/camel-xmpp/src/test/java/org/apache/camel/component/xmpp/FakeXmppServer.java
+++ 
b/components/camel-xmpp/src/test/java/org/apache/camel/component/xmpp/FakeXmppServer.java
@@ -20,6 +20,7 @@ import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.net.InetAddress;
+import java.net.InetSocketAddress;
 import java.net.ServerSocket;
 import java.net.Socket;
 import java.nio.charset.StandardCharsets;
@@ -60,10 +61,23 @@ final class FakeXmppServer implements AutoCloseable {
     private final AtomicInteger binds = new AtomicInteger();
     private final AtomicInteger conflicts = new AtomicInteger();
     private final AtomicInteger roomJoins = new AtomicInteger();
+    private final AtomicInteger roomJoinAttempts = new AtomicInteger();
+    private final AtomicInteger rejectRoomJoins = new AtomicInteger();
+    private final AtomicInteger logins = new AtomicInteger();
+    private final AtomicInteger failLogins = new AtomicInteger();
     private volatile boolean running = true;
 
     FakeXmppServer() throws IOException {
-        serverSocket = new ServerSocket(0, 50, 
InetAddress.getLoopbackAddress());
+        this(0);
+    }
+
+    /**
+     * A server on the given port (0 for any free port), to start a server 
where a client already tries to connect.
+     */
+    FakeXmppServer(int port) throws IOException {
+        serverSocket = new ServerSocket();
+        serverSocket.setReuseAddress(true);
+        serverSocket.bind(new 
InetSocketAddress(InetAddress.getLoopbackAddress(), port), 50);
         Thread acceptor = new Thread(this::accept, "fake-xmpp-acceptor");
         acceptor.setDaemon(true);
         acceptor.start();
@@ -73,6 +87,13 @@ final class FakeXmppServer implements AutoCloseable {
         return serverSocket.getLocalPort();
     }
 
+    /**
+     * The number of client connections that are open, also the ones that did 
not log in.
+     */
+    long openConnections() {
+        return sessions.stream().filter(s -> !s.socket.isClosed()).count();
+    }
+
     /**
      * The number of sessions that logged in and bound a resource.
      */
@@ -101,6 +122,34 @@ final class FakeXmppServer implements AutoCloseable {
         return roomJoins.get();
     }
 
+    /**
+     * The number of times a session asked to enter a room, also the ones that 
were rejected.
+     */
+    int roomJoinAttempts() {
+        return roomJoinAttempts.get();
+    }
+
+    /**
+     * Rejects the next given number of room entries with a 
service-unavailable error (the MUC service is not ready).
+     */
+    void rejectRoomJoins(int count) {
+        rejectRoomJoins.set(count);
+    }
+
+    /**
+     * The number of SASL authentications the clients asked for, also the ones 
that failed.
+     */
+    int logins() {
+        return logins.get();
+    }
+
+    /**
+     * Fails the next given number of SASL authentications with 
temporary-auth-failure (the auth backend is not ready).
+     */
+    void failLogins(int count) {
+        failLogins.set(count);
+    }
+
     /**
      * The number of sessions that are occupants of the given room.
      */
@@ -229,6 +278,11 @@ final class FakeXmppServer implements AutoCloseable {
                       + "' from='" + DOMAIN + "' version='1.0' 
xml:lang='en'><stream:features>" + features
                       + "</stream:features>");
             } else if (pattern == AUTH) {
+                logins.incrementAndGet();
+                if (failLogins.getAndUpdate(n -> Math.max(0, n - 1)) > 0) {
+                    write("<failure 
xmlns='urn:ietf:params:xml:ns:xmpp-sasl'><temporary-auth-failure/></failure>");
+                    return;
+                }
                 user = "PLAIN".equals(attribute(MECHANISM, element))
                         ? new 
String(Base64.getDecoder().decode(content(AUTH_DATA, element)), 
StandardCharsets.UTF_8)
                                 .split("\0")[1]
@@ -279,6 +333,13 @@ final class FakeXmppServer implements AutoCloseable {
                           + "<status code='110'/></x></presence>");
                     return;
                 }
+                roomJoinAttempts.incrementAndGet();
+                if (rejectRoomJoins.getAndUpdate(n -> Math.max(0, n - 1)) > 0) 
{
+                    write("<presence from='" + to + "' to='" + jid + "' id='" 
+ attribute(ID, element) + "' type='error'>"
+                          + "<x xmlns='http://jabber.org/protocol/muc'/><error 
type='cancel'>"
+                          + "<service-unavailable 
xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/></error></presence>");
+                    return;
+                }
                 // entering a room: the room answers with the occupant's own 
presence (status 110)
                 room = to.substring(0, to.indexOf('/'));
                 roomJoins.incrementAndGet();
diff --git 
a/components/camel-xmpp/src/test/java/org/apache/camel/component/xmpp/XmppConsumerDelayedStartRetryTest.java
 
b/components/camel-xmpp/src/test/java/org/apache/camel/component/xmpp/XmppConsumerDelayedStartRetryTest.java
new file mode 100644
index 000000000000..66671197d67b
--- /dev/null
+++ 
b/components/camel-xmpp/src/test/java/org/apache/camel/component/xmpp/XmppConsumerDelayedStartRetryTest.java
@@ -0,0 +1,126 @@
+/*
+ * 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 org.apache.camel.ServiceStatus;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+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;
+
+/**
+ * With testConnectionOnStartup=false the consumer starts in the background 
when the server cannot be reached at start.
+ * When the server is reachable again, it can still refuse the first login or 
the first room entry (its authentication
+ * backend or its room service is not ready yet): the delayed start must try 
again, as it does while the server cannot
+ * be reached, until the consumer receives messages.
+ */
+class XmppConsumerDelayedStartRetryTest {
+
+    private static final String ROOM = "dev@conference." + 
FakeXmppServer.DOMAIN;
+    private static final String BOB = "bob@" + 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 roomIsEnteredWhenTheFirstEntryAfterTheDelayedStartWasRefused() throws 
Exception {
+        int port = freePort();
+        startRoute(port, "xmpp://127.0.0.1:" + port + "?room=" + ROOM + 
"&nickname=camel"
+                         + 
"&connectionConfig=#connectionConfig&connectionPollDelay=1&testConnectionOnStartup=false");
+
+        // the server is reachable now, but refuses the first room entry (its 
room service is not ready yet)
+        server = new FakeXmppServer(port);
+        server.rejectRoomJoins(1);
+
+        await().atMost(20, TimeUnit.SECONDS).until(() -> 
server.occupants(ROOM) == 1);
+        assertEquals(2, server.roomJoinAttempts(), "the refused entry, then 
the one that was accepted");
+
+        MockEndpoint mock = context.getEndpoint("mock:out", 
MockEndpoint.class);
+        mock.expectedBodiesReceived("hello");
+        server.sendGroupChat(ROOM, "alice", "hello");
+        MockEndpoint.assertIsSatisfied(context, 10, TimeUnit.SECONDS);
+        assertEquals(ServiceStatus.Started, 
context.getRouteController().getRouteStatus("in"));
+    }
+
+    @Test
+    void chatIsConsumedWhenTheFirstLoginAfterTheDelayedStartFailed() throws 
Exception {
+        int port = freePort();
+        startRoute(port, "xmpp://127.0.0.1:" + port + "/" + BOB
+                         + 
"?connectionConfig=#connectionConfig&connectionPollDelay=1&testConnectionOnStartup=false");
+
+        // the server is reachable now, but its first login fails with a 
temporary authentication failure
+        server = new FakeXmppServer(port);
+        server.failLogins(1);
+
+        await().atMost(20, TimeUnit.SECONDS).until(() -> 
server.boundSessions() == 1);
+        assertEquals(2, server.logins(), "the failed login, then the one that 
worked");
+        // the connection whose login failed is closed, not left open next to 
the one that works
+        await().atMost(10, TimeUnit.SECONDS).until(() -> 
server.openConnections() == 1);
+
+        MockEndpoint mock = context.getEndpoint("mock:out", 
MockEndpoint.class);
+        mock.expectedBodiesReceived("hello");
+        server.sendChat(BOB, "hello");
+        MockEndpoint.assertIsSatisfied(context, 10, TimeUnit.SECONDS);
+    }
+
+    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();
+        assertEquals(ServiceStatus.Started, 
context.getRouteController().getRouteStatus("in"));
+    }
+
+    private static int freePort() throws Exception {
+        try (ServerSocket socket = new ServerSocket(0, 50, 
InetAddress.getLoopbackAddress())) {
+            return socket.getLocalPort();
+        }
+    }
+}

Reply via email to