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 e1bdcd5aaa6e CAMEL-27090: camel-smpp - a consumer or producer stopped 
while it waits to reconnect no longer leaves the reconnecting thread waiting 
for ever (#30306)
e1bdcd5aaa6e is described below

commit e1bdcd5aaa6ed9561f23c68463846b1c4bad6a29
Author: allthingssecurity <[email protected]>
AuthorDate: Wed Nov 18 15:04:32 2026 +0530

    CAMEL-27090: camel-smpp - a consumer or producer stopped while it waits to 
reconnect no longer leaves the reconnecting thread waiting for ever (#30306)
    
    When the session to the SMSC is lost, jsmpp reports it on its own thread to 
the
    session state listener of the consumer (or producer), which closes the 
session
    and runs the reconnect task on that thread: the task schedules its attempts 
on
    the reconnect service and waits until one of them reconnects. The task has 
no
    time limit, so only an attempt that succeeds, or one that sees the consumer
    stopping, releases the waiting thread.
    
    A stop while the reconnect waits for its next attempt (the SMSC is down; the
    attempts come every 5 s by default) shuts the reconnect service down, which
    cancels the scheduled attempts. No attempt runs any more, and the thread of 
the
    lost session waited for ever, with the task left in the task registry. A 
task
    built after the stop began was scheduled on the shut down service and 
dropped,
    with the same result.
    
    The consumer and the producer now keep the task they run, and their stop
    cancels it after the reconnect service is shut down, which releases the
    waiting thread. A reconnect that publishes its task after the stop looked 
for
    it sees the stop and does not run it. This is what camel-pgevent and
    camel-master do with their reconnect tasks. SmppUtils.newReconnectTask 
returns
    the BackgroundTask (it returned the BlockingTask interface), so that it can 
be
    cancelled.
    
    The stop shuts the reconnect service down, and a start of the same instance 
(such as suspendRoute and resumeRoute,
    as the consumer is not Suspendable) did not create a new one: the next lost 
session scheduled its reconnect task on
    the shut down service, where it never ran. The test of the stop also checks 
that the task registry is empty.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../apache/camel/component/smpp/SmppConsumer.java  |  35 ++++-
 .../apache/camel/component/smpp/SmppProducer.java  |  35 ++++-
 .../org/apache/camel/component/smpp/SmppUtils.java |   4 +-
 .../smpp/SmppStopDuringReconnectTest.java          | 168 +++++++++++++++++++++
 4 files changed, 232 insertions(+), 10 deletions(-)

diff --git 
a/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppConsumer.java
 
b/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppConsumer.java
index a572368a0522..ccd2a950c03c 100644
--- 
a/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppConsumer.java
+++ 
b/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppConsumer.java
@@ -22,7 +22,7 @@ import java.util.concurrent.locks.ReentrantLock;
 
 import org.apache.camel.Processor;
 import org.apache.camel.support.DefaultConsumer;
-import org.apache.camel.support.task.BlockingTask;
+import org.apache.camel.support.task.BackgroundTask;
 import org.jsmpp.DefaultPDUReader;
 import org.jsmpp.DefaultPDUSender;
 import org.jsmpp.SynchronizedPDUSender;
@@ -57,9 +57,12 @@ public class SmppConsumer extends DefaultConsumer {
     private final SessionStateListener internalSessionStateListener;
 
     private final ReentrantLock reconnectLock = new ReentrantLock();
-    private final ScheduledExecutorService reconnectService;
+    // created again by a start after a stop, as the stop shuts it down
+    private volatile ScheduledExecutorService reconnectService;
 
     private SMPPSession session;
+    // the reconnect task that the thread which reported the lost session 
waits for, so that a stop can release it
+    private volatile BackgroundTask reconnectTask;
 
     /**
      * The constructor which gets a smpp endpoint, a smpp configuration and a 
processor
@@ -90,6 +93,7 @@ public class SmppConsumer extends DefaultConsumer {
     @Override
     protected void doStart() throws Exception {
         LOG.debug("Connecting to: {}...", getEndpoint().getConnectionString());
+        restartReconnectService();
 
         super.doStart();
         session = createSession();
@@ -130,9 +134,26 @@ public class SmppConsumer extends DefaultConsumer {
                         .getInstance(configuration));
     }
 
+    /**
+     * A stop shuts down the reconnect service. When this instance is started 
again in place (such as by suspendRoute
+     * and resumeRoute, which stop and start a service that is not 
Suspendable), a lost session would otherwise schedule
+     * its reconnect task on the shut down service, where it never runs.
+     */
+    private void restartReconnectService() {
+        if (reconnectService.isShutdown()) {
+            reconnectService = createExecutor(this, getEndpoint(), 
RECONNECT_TASK_NAME);
+        }
+    }
+
     @Override
     protected void doStop() throws Exception {
         shutdownReconnectService(reconnectService);
+        // the shut down reconnect service no longer runs the reconnect task, 
so nothing else would release the thread
+        // that waits for it
+        BackgroundTask task = reconnectTask;
+        if (task != null) {
+            task.cancel(false);
+        }
 
         LOG.debug("Disconnecting from: {}...", 
getEndpoint().getConnectionString());
 
@@ -187,14 +208,20 @@ public class SmppConsumer extends DefaultConsumer {
 
     private void reconnect() {
         if (reconnectLock.tryLock()) {
-            BlockingTask task = newReconnectTask(reconnectService, 
RECONNECT_TASK_NAME,
+            BackgroundTask task = newReconnectTask(reconnectService, 
RECONNECT_TASK_NAME,
                     configuration.getInitialReconnectDelay(),
                     configuration.getReconnectDelay(),
                     configuration.getMaxReconnect());
 
+            reconnectTask = task;
             try {
-                task.run(getEndpoint().getCamelContext(), this::doReconnect);
+                // a stop that began before the task was published does not 
cancel it, and the task would never run
+                // on the shut down reconnect service
+                if (!isServiceStopping(this)) {
+                    task.run(getEndpoint().getCamelContext(), 
this::doReconnect);
+                }
             } finally {
+                reconnectTask = null;
                 reconnectLock.unlock();
             }
         } else {
diff --git 
a/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppProducer.java
 
b/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppProducer.java
index eff257679df9..a556e6867e4d 100644
--- 
a/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppProducer.java
+++ 
b/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppProducer.java
@@ -23,7 +23,7 @@ import java.util.concurrent.locks.ReentrantLock;
 import org.apache.camel.Exchange;
 import org.apache.camel.Message;
 import org.apache.camel.support.DefaultProducer;
-import org.apache.camel.support.task.BlockingTask;
+import org.apache.camel.support.task.BackgroundTask;
 import org.apache.camel.util.ObjectHelper;
 import org.jsmpp.DefaultPDUReader;
 import org.jsmpp.DefaultPDUSender;
@@ -56,9 +56,12 @@ public class SmppProducer extends DefaultProducer {
     private final SmppConfiguration configuration;
     private final SessionStateListener internalSessionStateListener;
     private final ReentrantLock connectLock = new ReentrantLock();
-    private final ScheduledExecutorService reconnectService;
+    // created again by a start after a stop, as the stop shuts it down
+    private volatile ScheduledExecutorService reconnectService;
 
     private SMPPSession session;
+    // the reconnect task that the thread which reported the lost session 
waits for, so that a stop can release it
+    private volatile BackgroundTask reconnectTask;
 
     public SmppProducer(SmppEndpoint endpoint, SmppConfiguration config) {
         super(endpoint);
@@ -84,6 +87,7 @@ public class SmppProducer extends DefaultProducer {
     @Override
     protected void doStart() throws Exception {
         super.doStart();
+        restartReconnectService();
 
         if (!getConfiguration().isLazySessionCreation()) {
             if (connectLock.tryLock()) {
@@ -184,9 +188,26 @@ public class SmppProducer extends DefaultProducer {
         command.execute(exchange);
     }
 
+    /**
+     * A stop shuts down the reconnect service. When this instance is started 
again in place (such as by suspendRoute
+     * and resumeRoute, which stop and start a service that is not 
Suspendable), a lost session would otherwise schedule
+     * its reconnect task on the shut down service, where it never runs.
+     */
+    private void restartReconnectService() {
+        if (reconnectService.isShutdown()) {
+            reconnectService = createExecutor(this, getEndpoint(), 
RECONNECT_TASK_NAME);
+        }
+    }
+
     @Override
     protected void doStop() throws Exception {
         shutdownReconnectService(reconnectService);
+        // the shut down reconnect service no longer runs the reconnect task, 
so nothing else would release the thread
+        // that waits for it
+        BackgroundTask task = reconnectTask;
+        if (task != null) {
+            task.cancel(false);
+        }
 
         LOG.debug("Disconnecting from: {}...", 
getEndpoint().getConnectionString());
 
@@ -207,13 +228,19 @@ public class SmppProducer extends DefaultProducer {
 
     private void reconnect() {
         if (connectLock.tryLock()) {
-            BlockingTask task = newReconnectTask(reconnectService, 
RECONNECT_TASK_NAME,
+            BackgroundTask task = newReconnectTask(reconnectService, 
RECONNECT_TASK_NAME,
                     configuration.getInitialReconnectDelay(),
                     configuration.getReconnectDelay(), 
configuration.getMaxReconnect());
 
+            reconnectTask = task;
             try {
-                task.run(getEndpoint().getCamelContext(), this::doReconnect);
+                // a stop that began before the task was published does not 
cancel it, and the task would never run
+                // on the shut down reconnect service
+                if (!isServiceStopping(this)) {
+                    task.run(getEndpoint().getCamelContext(), 
this::doReconnect);
+                }
             } finally {
+                reconnectTask = null;
                 connectLock.unlock();
             }
         } else {
diff --git 
a/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppUtils.java
 
b/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppUtils.java
index d87c59b35808..5c2dad5101c8 100644
--- 
a/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppUtils.java
+++ 
b/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppUtils.java
@@ -28,7 +28,7 @@ import java.util.concurrent.TimeUnit;
 import org.apache.camel.Endpoint;
 import org.apache.camel.spi.ExecutorServiceManager;
 import org.apache.camel.support.service.BaseService;
-import org.apache.camel.support.task.BlockingTask;
+import org.apache.camel.support.task.BackgroundTask;
 import org.apache.camel.support.task.Tasks;
 import org.apache.camel.support.task.budget.Budgets;
 import org.jsmpp.bean.Alphabet;
@@ -321,7 +321,7 @@ public final class SmppUtils {
         }
     }
 
-    public static BlockingTask newReconnectTask(
+    public static BackgroundTask newReconnectTask(
             ScheduledExecutorService service, String taskName, long 
initialReconnectDelay,
             long reconnectDelay, int maxReconnect) {
         return Tasks.backgroundTask()
diff --git 
a/components/camel-smpp/src/test/java/org/apache/camel/component/smpp/SmppStopDuringReconnectTest.java
 
b/components/camel-smpp/src/test/java/org/apache/camel/component/smpp/SmppStopDuringReconnectTest.java
new file mode 100644
index 000000000000..eb8519c1e4b5
--- /dev/null
+++ 
b/components/camel-smpp/src/test/java/org/apache/camel/component/smpp/SmppStopDuringReconnectTest.java
@@ -0,0 +1,168 @@
+/*
+ * 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.smpp;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.Consumer;
+import org.apache.camel.RoutesBuilder;
+import org.apache.camel.Service;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.support.PluginHelper;
+import org.apache.camel.test.AvailablePortFinder;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.jsmpp.session.BindRequest;
+import org.jsmpp.session.SMPPServerSession;
+import org.jsmpp.session.SMPPServerSessionListener;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import static org.awaitility.Awaitility.await;
+
+/**
+ * A consumer or producer that is stopped while it waits to reconnect to an 
SMSC that is down must not leave the thread
+ * that reported the lost session waiting for the reconnect task for ever.
+ */
+class SmppStopDuringReconnectTest extends CamelTestSupport {
+
+    @RegisterExtension
+    static AvailablePortFinder.Port port = AvailablePortFinder.find();
+
+    private final List<SMPPServerSession> serverSessions = new 
CopyOnWriteArrayList<>();
+    private SMPPServerSessionListener smsc;
+    private Thread acceptor;
+
+    @BeforeEach
+    void startSmsc() throws IOException {
+        smsc = new SMPPServerSessionListener(port.getPort());
+        acceptor = new Thread(this::acceptBinds, "smsc-acceptor");
+        acceptor.setDaemon(true);
+        acceptor.start();
+    }
+
+    @AfterEach
+    void stopSmsc() throws IOException {
+        smsc.close();
+        serverSessions.forEach(SMPPServerSession::close);
+    }
+
+    private void acceptBinds() {
+        try {
+            while (true) {
+                SMPPServerSession session = smsc.accept();
+                BindRequest bind = session.waitForBind(5000);
+                bind.accept("smsc");
+                serverSessions.add(session);
+            }
+        } catch (Exception e) {
+            // the SMSC is closed
+        }
+    }
+
+    @Test
+    void stopOfConsumerReleasesTheThreadWaitingToReconnect() throws Exception {
+        stopDuringReconnect(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from(uri()).routeId("smpp").to("mock:received");
+            }
+        }, SmppConsumer.class);
+    }
+
+    @Test
+    void stopOfProducerReleasesTheThreadWaitingToReconnect() throws Exception {
+        stopDuringReconnect(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from("direct:send").routeId("smpp").to(uri());
+            }
+        }, SmppProducer.class);
+    }
+
+    private static String uri() {
+        // the stop comes while the reconnect waits for its next attempt (5 s 
by default)
+        return "smpp://smppclient@localhost:" + port.getPort()
+               + 
"?password=password&initialReconnectDelay=60000&reconnectDelay=60000";
+    }
+
+    private void stopDuringReconnect(RoutesBuilder route, Class<?> type) 
throws Exception {
+        context.addRoutes(route);
+        await().atMost(10, TimeUnit.SECONDS).until(() -> serverSessions.size() 
== 1);
+
+        // the SMSC goes down: it closes the session and no longer accepts 
connections
+        smsc.close();
+        serverSessions.get(0).close();
+        await().atMost(10, TimeUnit.SECONDS).until(() -> 
threadsWaitingToReconnect(type) == 1);
+
+        context.getRouteController().stopRoute("smpp");
+
+        await().atMost(10, TimeUnit.SECONDS).until(() -> 
threadsWaitingToReconnect(type) == 0);
+        // the cancelled reconnect task is no longer registered
+        await().atMost(10, TimeUnit.SECONDS)
+                .until(() -> 
PluginHelper.getTaskManagerRegistry(context.getCamelContextExtension()).getSize()
 == 0);
+    }
+
+    @Test
+    void consumerStoppedAndStartedInPlaceStillReconnects() throws Exception {
+        SmppEndpoint endpoint = context.getEndpoint(fastReconnectUri(), 
SmppEndpoint.class);
+        Consumer consumer = endpoint.createConsumer(exchange -> {
+        });
+        reconnectsAfterRestartInPlace(consumer);
+    }
+
+    @Test
+    void producerStoppedAndStartedInPlaceStillReconnects() throws Exception {
+        SmppEndpoint endpoint = context.getEndpoint(fastReconnectUri(), 
SmppEndpoint.class);
+        reconnectsAfterRestartInPlace(endpoint.createProducer());
+    }
+
+    private static String fastReconnectUri() {
+        return "smpp://smppclient@localhost:" + port.getPort()
+               + 
"?password=password&initialReconnectDelay=100&reconnectDelay=100";
+    }
+
+    private void reconnectsAfterRestartInPlace(Service service) throws 
Exception {
+        try {
+            // started, stopped and started again on the same instance (as 
suspendRoute and resumeRoute do for a
+            // service that is not Suspendable)
+            service.start();
+            service.stop();
+            service.start();
+            await().atMost(10, TimeUnit.SECONDS).until(() -> 
serverSessions.size() == 2);
+
+            // the SMSC closes the session, and still accepts connections, so 
the reconnect must bind again
+            serverSessions.get(1).close();
+
+            await().atMost(10, TimeUnit.SECONDS).until(() -> 
serverSessions.size() == 3);
+        } finally {
+            service.stop();
+        }
+    }
+
+    private static long threadsWaitingToReconnect(Class<?> type) {
+        return Thread.getAllStackTraces().values().stream()
+                .filter(stack -> List.of(stack).stream()
+                        .anyMatch(frame -> 
frame.getClassName().equals(type.getName())
+                                && frame.getMethodName().equals("reconnect")))
+                .count();
+    }
+}

Reply via email to