You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@activemq.apache.org by cs...@apache.org on 2026/10/17 20:05:38 UTC

(activemq) branch main updated: Ensure subscriptions are cleaned up on failure (#2680)

This is an automated email from the ASF dual-hosted git repository.

cshannon pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/activemq.git


The following commit(s) were added to refs/heads/main by this push:
     new 91c190c944 Ensure subscriptions are cleaned up on failure (#2680)
91c190c944 is described below

commit 91c190c9441cf1917cfe5636829ea981210fe0ff
Author: Christopher L. Shannon <cs...@apache.org>
AuthorDate: Sat Oct 17 16:05:33 2026 -0400

    Ensure subscriptions are cleaned up on failure (#2680)
    
    Make sure that any exception will cleanup the tracking of subscriptions
    in the broker
---
 .../activemq/broker/region/AbstractRegion.java     |  19 ++-
 .../apache/activemq/JmsTempDestinationTest.java    |  11 +-
 .../region/FailedSubscriptionCleanupTest.java      | 141 +++++++++++++++++++++
 3 files changed, 167 insertions(+), 4 deletions(-)

diff --git a/activemq-broker/src/main/java/org/apache/activemq/broker/region/AbstractRegion.java b/activemq-broker/src/main/java/org/apache/activemq/broker/region/AbstractRegion.java
index 2556c1510e..765d2cb1c1 100644
--- a/activemq-broker/src/main/java/org/apache/activemq/broker/region/AbstractRegion.java
+++ b/activemq-broker/src/main/java/org/apache/activemq/broker/region/AbstractRegion.java
@@ -407,12 +407,25 @@ public abstract class AbstractRegion implements Region {
                 try {
                     dest.addSubscription(context, sub);
                     removeList.add(dest);
-                } catch (SecurityException e){
+                } catch (Exception e){
                     if (sub.isWildcard()) {
-                        LOG.debug("Subscription denied for {} to destination {}: {}",
+                        LOG.debug("Subscription {} for {} to destination {}: {}",
+                                e instanceof SecurityException ? "denied" : "failed",
                                 sub, dest.getActiveMQDestination(), e.getMessage());
                     } else {
-                        // remove partial subscriptions
+                        // Clean up current dest that failed in case it was partially added
+                        // to the destination tracking, and failed after. This might be in a
+                        // bad state and my not need to be cleaned up at all, so just log as debug
+                        try {
+                            dest.removeSubscription(context, sub, info.getLastDeliveredSequenceId());
+                        } catch (Exception ex) {
+                            LOG.debug("Error cleaning up failed subscription {} from {}: {}",
+                                    sub, dest, ex.getMessage(), ex);
+                        }
+
+                        // remove partial subscriptions that were already added on another
+                        // destination before the failure. These previously succeeded so log
+                        // as an error if we can't remove
                         for (Destination remove : removeList) {
                             try {
                                 remove.removeSubscription(context, sub, info.getLastDeliveredSequenceId());
diff --git a/activemq-unit-tests/src/test/java/org/apache/activemq/JmsTempDestinationTest.java b/activemq-unit-tests/src/test/java/org/apache/activemq/JmsTempDestinationTest.java
index f629380af5..06b117c1e6 100644
--- a/activemq-unit-tests/src/test/java/org/apache/activemq/JmsTempDestinationTest.java
+++ b/activemq-unit-tests/src/test/java/org/apache/activemq/JmsTempDestinationTest.java
@@ -39,6 +39,10 @@ import jakarta.jms.TextMessage;
 import java.util.Arrays;
 import java.util.Collection;
 import org.apache.activemq.broker.BrokerService;
+import org.apache.activemq.broker.region.AbstractRegion;
+import org.apache.activemq.broker.region.QueueRegion;
+import org.apache.activemq.broker.region.RegionBroker;
+import org.apache.activemq.broker.region.TopicRegion;
 import org.apache.activemq.broker.region.policy.PolicyEntry;
 import org.apache.activemq.broker.region.policy.PolicyMap;
 import org.apache.activemq.command.ConsumerInfo;
@@ -221,8 +225,13 @@ public class JmsTempDestinationTest {
             assertTrue(((ExceptionResponse) result).getException().getMessage()
                     .contains("created by another connection is not permitted"));
         }
-    }
 
+        // verify the subscription is properly tracked if allowTempDestinationStealing=true
+        // or cleaned up if allowTempDestinationStealing=false
+        RegionBroker rg = (RegionBroker) brokerService.getRegionBroker();
+        AbstractRegion region = (AbstractRegion) (topic ? rg.getTempTopicRegion() : rg.getTempQueueRegion());
+        assertEquals(tempDestStealing, region.getSubscriptions().containsKey(info.getConsumerId()));
+    }
 
     /**
      * Make sure that a temp queue does not drop message if there is an active
diff --git a/activemq-unit-tests/src/test/java/org/apache/activemq/broker/region/FailedSubscriptionCleanupTest.java b/activemq-unit-tests/src/test/java/org/apache/activemq/broker/region/FailedSubscriptionCleanupTest.java
new file mode 100644
index 0000000000..f4770f233c
--- /dev/null
+++ b/activemq-unit-tests/src/test/java/org/apache/activemq/broker/region/FailedSubscriptionCleanupTest.java
@@ -0,0 +1,141 @@
+/*
+ * 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.activemq.broker.region;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
+
+import jakarta.jms.Connection;
+import jakarta.jms.JMSException;
+import jakarta.jms.Session;
+import java.util.Arrays;
+import java.util.Collection;
+import org.apache.activemq.ActiveMQConnectionFactory;
+import org.apache.activemq.broker.BrokerService;
+import org.apache.activemq.broker.ConnectionContext;
+import org.apache.activemq.command.ActiveMQDestination;
+import org.apache.activemq.command.ActiveMQQueue;
+import org.apache.activemq.command.ActiveMQTopic;
+import org.apache.activemq.test.annotations.ParallelTest;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+@RunWith(value = Parameterized.class)
+@Category(ParallelTest.class)
+public class FailedSubscriptionCleanupTest {
+
+    @Parameterized.Parameters(name = "isTopic({0})")
+    public static Collection<Object[]> getTestParameters() {
+        return Arrays.asList(new Object[][]{{Boolean.TRUE}, {Boolean.FALSE}});
+    }
+
+    private final ActiveMQDestination parentDest;
+    private final ActiveMQDestination dest;
+
+    private BrokerService brokerService;
+    private TopicRegion topicRegion;
+    private QueueRegion queueRegion;
+
+    public FailedSubscriptionCleanupTest(boolean topic) {
+        this.parentDest = topic ? new ActiveMQTopic("test.dest.>") : new ActiveMQQueue("test.dest.>");
+        this.dest = topic ? new ActiveMQTopic("test.dest.1") : new ActiveMQQueue("test.dest.1");
+    }
+
+    @Before
+    public void setUp() throws Exception {
+        brokerService = new BrokerService();
+        brokerService.setPersistent(false);
+        brokerService.setUseJmx(false);
+        brokerService.setAdvisorySupport(false);
+        brokerService.setDestinationFactory(new DestinationFactoryImpl(brokerService,
+                brokerService.getTaskRunnerFactory(), brokerService.getPersistenceAdapter()) {
+            @Override
+            public Destination createDestination(ConnectionContext context,
+                    ActiveMQDestination destination, DestinationStatistics destinationStatistics)
+                    throws Exception {
+                return new DestinationFilter(
+                        super.createDestination(context, destination, destinationStatistics)) {
+                    @Override
+                    public void addSubscription(ConnectionContext context, Subscription sub)
+                            throws Exception {
+                        super.addSubscription(context, sub);
+                        if (destination.equals(dest)) {
+                            throw new IllegalStateException("failed");
+                        }
+                    }
+                };
+            }
+        });
+        brokerService.start();
+        brokerService.waitUntilStarted();
+        RegionBroker regionBroker = (RegionBroker) brokerService.getRegionBroker();
+        topicRegion = (TopicRegion) regionBroker.getTopicRegion();
+        queueRegion = (QueueRegion) regionBroker.getQueueRegion();
+    }
+
+    @After
+    public void tearDown() throws Exception {
+        if (brokerService != null) {
+            brokerService.stop();
+            brokerService.waitUntilStopped();
+        }
+    }
+
+    private Connection createConnection() throws Exception {
+        var factory = new ActiveMQConnectionFactory("vm://localhost?create=false");
+        factory.setWatchTopicAdvisories(false);
+        var connection = factory.createConnection();
+        connection.start();
+        return connection;
+    }
+
+    // cleanup for failure adding consumer on single dest
+    @Test
+    public void testFailedSubscriptionCleanup() throws Exception {
+        AbstractRegion region = dest.isTopic() ? topicRegion : queueRegion;
+        Connection connection = createConnection();
+        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+        assertThrows(JMSException.class, () -> session.createConsumer(dest));
+
+        assertEquals(0, brokerService.getDestination(dest)
+                .getDestinationStatistics().getConsumers().getCount());
+        assertTrue(region.getSubscriptions().isEmpty());
+    }
+
+    // check cleanup for failure for multiple matching dests
+    @Test
+    public void testMultipleFailedSubscriptionCleanup() throws Exception {
+        brokerService.getBroker().addDestination(brokerService.getAdminConnectionContext(),
+                parentDest, false);
+
+        AbstractRegion region = dest.isTopic() ? topicRegion : queueRegion;
+        Connection connection = createConnection();
+        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+        assertThrows(JMSException.class, () -> session.createConsumer(dest));
+        assertTrue(region.getSubscriptions().isEmpty());
+        assertEquals(0, brokerService.getDestination(dest)
+                .getDestinationStatistics().getConsumers().getCount());
+        assertEquals(0, brokerService.getDestination(parentDest)
+                .getDestinationStatistics().getConsumers().getCount());
+    }
+
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@activemq.apache.org
For additional commands, e-mail: commits-help@activemq.apache.org
For further information, visit: https://activemq.apache.org/contact