You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@activemq.apache.org by cl...@apache.org on 2024/06/11 16:03:14 UTC

(activemq-artemis) branch main updated: ARTEMIS-4812 Avoid IntObject accumulation after Page is set as complete

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

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


The following commit(s) were added to refs/heads/main by this push:
     new 178f2e4b4d ARTEMIS-4812 Avoid IntObject accumulation after Page is set as complete
178f2e4b4d is described below

commit 178f2e4b4d8b9ab0ba16750a716179f41e2ec8c5
Author: Clebert Suconic <cl...@apache.org>
AuthorDate: Tue Jun 11 10:22:46 2024 -0400

    ARTEMIS-4812 Avoid IntObject accumulation after Page is set as complete
    
    this could lead to OME if a lazy consumer is there for a long time with all pages being removed.
---
 .../paging/cursor/impl/PageSubscriptionImpl.java   |  91 +++++++---
 .../artemis/tests/leak/FilteredPagingLeakTest.java | 194 +++++++++++++++++++++
 2 files changed, 261 insertions(+), 24 deletions(-)

diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/impl/PageSubscriptionImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/impl/PageSubscriptionImpl.java
index f608dcf62a..08b23efe4e 100644
--- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/impl/PageSubscriptionImpl.java
+++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/cursor/impl/PageSubscriptionImpl.java
@@ -227,6 +227,7 @@ public final class PageSubscriptionImpl implements PageSubscription {
       }
       PageCursorInfo info = new PageCursorInfo(position.getPageNr(), position.getMessageNr());
       info.setCompleteInfo(position);
+      info.clear();
       synchronized (consumedPages) {
          consumedPages.put(position.getPageNr(), info);
       }
@@ -295,6 +296,9 @@ public final class PageSubscriptionImpl implements PageSubscription {
                PageCursorInfo info = entry.getValue();
 
                if (info.isDone() && !info.isPendingDelete()) {
+                  if (logger.isDebugEnabled()) {
+                     logger.debug("Complete page {} on queue {} / {}", info, queue.getName(), queue.getID());
+                  }
                   Page currentPage = pageStore.getCurrentPage();
 
                   if (currentPage != null && entry.getKey() == pageStore.getCurrentPage().getPageId()) {
@@ -329,16 +333,19 @@ public final class PageSubscriptionImpl implements PageSubscription {
                }
             }
 
-            // it will delete the page ack records
-            for (PagePosition pos : infoPG.acks.values()) {
-               if (pos.getRecordID() >= 0) {
-                  store.deleteCursorAcknowledgeTransactional(tx.getID(), pos.getRecordID());
-                  if (!persist) {
-                     // only need to set it once
-                     tx.setContainsPersistent();
-                     persist = true;
+            if (infoPG.acks != null) {
+               // it will delete the page ack records
+               for (PagePosition pos : infoPG.acks.values()) {
+                  if (pos.getRecordID() >= 0) {
+                     store.deleteCursorAcknowledgeTransactional(tx.getID(), pos.getRecordID());
+                     if (!persist) {
+                        // only need to set it once
+                        tx.setContainsPersistent();
+                        persist = true;
+                     }
                   }
                }
+               infoPG.clear();
             }
          }
 
@@ -636,10 +643,12 @@ public final class PageSubscriptionImpl implements PageSubscription {
 
          synchronized (consumedPages) {
             for (PageCursorInfo cursor : consumedPages.values()) {
-               for (PagePosition info : cursor.acks.values()) {
-                  if (info.getRecordID() >= 0) {
-                     isPersistent = true;
-                     store.deleteCursorAcknowledgeTransactional(tx, info.getRecordID());
+               if (cursor.acks != null) {
+                  for (PagePosition info : cursor.acks.values()) {
+                     if (info.getRecordID() >= 0) {
+                        isPersistent = true;
+                        store.deleteCursorAcknowledgeTransactional(tx, info.getRecordID());
+                     }
                   }
                }
                PagePosition completeInfo = cursor.getCompleteInfo();
@@ -739,12 +748,14 @@ public final class PageSubscriptionImpl implements PageSubscription {
             }
             info.setCompleteInfo(null);
          }
-         for (PagePosition deleteInfo : info.acks.values()) {
-            if (deleteInfo.getRecordID() >= 0) {
-               try {
-                  store.deleteCursorAcknowledge(deleteInfo.getRecordID());
-               } catch (Exception e) {
-                  ActiveMQServerLogger.LOGGER.errorDeletingPageCompleteRecord(e);
+         if (info.acks != null) {
+            for (PagePosition deleteInfo : info.acks.values()) {
+               if (deleteInfo.getRecordID() >= 0) {
+                  try {
+                     store.deleteCursorAcknowledge(deleteInfo.getRecordID());
+                  } catch (Exception e) {
+                     ActiveMQServerLogger.LOGGER.errorDeletingPageCompleteRecord(e);
+                  }
                }
             }
          }
@@ -907,14 +918,29 @@ public final class PageSubscriptionImpl implements PageSubscription {
 
       @Override
       public synchronized boolean isAck(int messageNumber) {
-         return completePage != null || acks.get(messageNumber) != null;
+         return completePage != null || acks != null && acks.get(messageNumber) != null;
       }
 
       @Override
       public void forEachAck(BiConsumer<Integer, PagePosition> ackConsumer) {
-         acks.forEach(ackConsumer);
+         if (acks != null) {
+            acks.forEach(ackConsumer);
+         }
+      }
+
+      public IntObjectHashMap getAcks() {
+         return acks;
+      }
+
+      public IntObjectHashMap getRemovedReferences() {
+         return removedReferences;
+      }
+
+      public PagePosition getCompletePageInformation() {
+         return completePage;
       }
 
+
       @Override
       public String toString() {
          try {
@@ -953,6 +979,11 @@ public final class PageSubscriptionImpl implements PageSubscription {
          this.numberOfMessages = -1;
       }
 
+      public void clear() {
+         this.removedReferences = null;
+         this.acks = null;
+      }
+
       /**
        * @param completePage
        */
@@ -1006,14 +1037,17 @@ public final class PageSubscriptionImpl implements PageSubscription {
       }
 
       public synchronized boolean isRemoved(final int messageNr) {
-         return removedReferences.get(messageNr) != null;
+         // removed references = null means everything is acked and done, so we just return true here
+         return completePage != null || removedReferences == null || removedReferences.get(messageNr) != null;
       }
 
       public synchronized void remove(final int messageNr) {
          if (logger.isTraceEnabled()) {
             logger.trace("PageCursor Removing messageNr {} on page {}", messageNr, pageId);
          }
-         removedReferences.put(messageNr, DUMMY);
+         if (removedReferences != null) {
+            removedReferences.put(messageNr, DUMMY);
+         }
       }
 
       public void addACK(final PagePosition posACK) {
@@ -1044,8 +1078,17 @@ public final class PageSubscriptionImpl implements PageSubscription {
       }
 
       synchronized boolean internalAddACK(final PagePosition position) {
-         removedReferences.put(position.getMessageNr(), DUMMY);
-         return acks.put(position.getMessageNr(), position) == null;
+         if (logger.isDebugEnabled()) {
+            logger.debug("internalAddACK on queue {} (id={}), position {}", queue.getName(), queue.getID(), position);
+         }
+         if (removedReferences != null) {
+            removedReferences.put(position.getMessageNr(), DUMMY);
+         }
+         if (acks == null) {
+            return false;
+         } else {
+            return acks.put(position.getMessageNr(), position) == null;
+         }
       }
 
       /**
diff --git a/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/FilteredPagingLeakTest.java b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/FilteredPagingLeakTest.java
new file mode 100644
index 0000000000..2ef9d791f4
--- /dev/null
+++ b/tests/leak-tests/src/test/java/org/apache/activemq/artemis/tests/leak/FilteredPagingLeakTest.java
@@ -0,0 +1,194 @@
+/*
+ * 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.artemis.tests.leak;
+
+import javax.jms.BytesMessage;
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Session;
+import java.lang.invoke.MethodHandles;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+import io.github.checkleak.core.CheckLeak;
+import io.netty.util.collection.IntObjectMap;
+import org.apache.activemq.artemis.api.core.QueueConfiguration;
+import org.apache.activemq.artemis.api.core.RoutingType;
+import org.apache.activemq.artemis.core.paging.PagingStore;
+import org.apache.activemq.artemis.core.paging.cursor.impl.PageSubscriptionImpl;
+import org.apache.activemq.artemis.core.protocol.core.impl.RemotingConnectionImpl;
+import org.apache.activemq.artemis.core.server.ActiveMQServer;
+import org.apache.activemq.artemis.core.server.Queue;
+import org.apache.activemq.artemis.core.server.impl.ActiveMQServerImpl;
+import org.apache.activemq.artemis.core.server.impl.AddressInfo;
+import org.apache.activemq.artemis.core.server.impl.ServerStatus;
+import org.apache.activemq.artemis.tests.util.CFUtil;
+import org.apache.activemq.artemis.utils.Wait;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.apache.activemq.artemis.tests.leak.MemoryAssertions.assertMemory;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
+
+/* This test creates a condition where one queue is filtering a lot of data.
+*  Upon completing a page after the ignored filter.
+*  it will then make sure the removed references list and acked list is cleared from the PageInfo map. */
+public class FilteredPagingLeakTest extends AbstractLeakTest {
+
+   private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+   ActiveMQServer server;
+
+   @BeforeAll
+   public static void beforeClass() throws Exception {
+      assumeTrue(CheckLeak.isLoaded());
+   }
+
+   @AfterEach
+   public void validateServer() throws Exception {
+      CheckLeak checkLeak = new CheckLeak();
+
+      // I am doing this check here because the test method might hold a client connection
+      // so this check has to be done after the test, and before the server is stopped
+      assertMemory(checkLeak, 0, RemotingConnectionImpl.class.getName());
+
+      server.stop();
+
+      server = null;
+
+      clearServers();
+      ServerStatus.clear();
+
+      assertMemory(checkLeak, 0, ActiveMQServerImpl.class.getName());
+   }
+
+   @Override
+   @BeforeEach
+   public void setUp() throws Exception {
+      server = createServer(true, createDefaultConfig(1, true));
+      server.getConfiguration().setJournalPoolFiles(4).setJournalMinFiles(2);
+      server.start();
+   }
+
+   @Test
+   public void testCore() throws Exception {
+      doTest("CORE");
+   }
+
+   private void doTest(String protocol) throws Exception {
+      int MESSAGES = 10_000;
+      int MESSAGE_SIZE = 104;
+      int COMMIT_INTERVAL = 100;
+      int FILTERED_A = 100;
+
+      CheckLeak checkLeak = new CheckLeak();
+      int initialMaps = checkLeak.getAllObjects(IntObjectMap.class).length;
+
+      ExecutorService executorService = Executors.newFixedThreadPool(2);
+      runAfter(executorService::shutdownNow);
+
+      ConnectionFactory cf = CFUtil.createConnectionFactory(protocol, "tcp://localhost:61616");
+
+      server.addAddressInfo(new AddressInfo(getName()).addRoutingType(RoutingType.MULTICAST));
+      server.createQueue(QueueConfiguration.of("A").setAddress(getName()).setRoutingType(RoutingType.MULTICAST).setDurable(true).setFilterString("i >= " + (MESSAGES - FILTERED_A)));
+      server.createQueue(QueueConfiguration.of("B").setAddress(getName()).setRoutingType(RoutingType.MULTICAST).setDurable(true));
+
+      final Queue serverQueueA = server.locateQueue("A");
+
+      PagingStore pagingStore = serverQueueA.getPagingStore();
+      pagingStore.startPaging();
+
+      try (Connection connection = cf.createConnection()) {
+         Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
+         MessageProducer producer = session.createProducer(session.createTopic(getName()));
+         connection.start();
+
+         for (int i = 0; i < MESSAGES; i++) {
+            BytesMessage message = session.createBytesMessage();
+            message.writeBytes(new byte[MESSAGE_SIZE]);
+            message.setIntProperty("i", i);
+            producer.send(message);
+            if (i > 0 && i % COMMIT_INTERVAL == 0) {
+               session.commit();
+               pagingStore.forceAnotherPage();
+            }
+         }
+         session.commit();
+      }
+
+      try (Connection connection = cf.createConnection()) {
+         Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
+         MessageConsumer consumer = session.createConsumer(session.createQueue("A"));
+         connection.start();
+
+         for (int i = 0; i < FILTERED_A; i++) {
+            BytesMessage message = (BytesMessage) consumer.receive(5000);
+            Assertions.assertNotNull(message);
+            logger.debug("Received {}", message.getIntProperty("i"));
+            if (i % 100 == 0) {
+               session.commit();
+            }
+         }
+         Assertions.assertNull(consumer.receiveNoWait());
+         session.commit();
+      }
+
+      Future<Boolean> future = serverQueueA.getPagingStore().getCursorProvider().scheduleCleanup();
+      future.get();
+
+      Object[] pageCursorInfos = checkLeak.getAllObjects(PageSubscriptionImpl.PageCursorInfo.class);
+      logger.debug("There are {} PageCursorInfo elements in the heap", pageCursorInfos.length);
+
+      for (Object cursorInfoObject : pageCursorInfos) {
+         PageSubscriptionImpl.PageCursorInfo cursorInfo = (PageSubscriptionImpl.PageCursorInfo) cursorInfoObject;
+         if (cursorInfo.getCompletePageInformation() != null) {
+            // this is asserting if the fix is in place
+            Assertions.assertNull(cursorInfo.getAcks());
+            Assertions.assertNull(cursorInfo.getRemovedReferences());
+         }
+      }
+
+      Assertions.assertTrue(checkLeak.getAllObjects(IntObjectMap.class).length - initialMaps <= 300, () -> "too many instances of IntObjectMap created " + (checkLeak.getAllObjects(IntObjectMap.class).length - initialMaps));
+
+      try (Connection connection = cf.createConnection()) {
+         Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
+         MessageConsumer consumer = session.createConsumer(session.createQueue("B"));
+         connection.start();
+
+         for (int i = 0; i < MESSAGES; i++) {
+            BytesMessage message = (BytesMessage) consumer.receive(5000);
+            Assertions.assertNotNull(message);
+            logger.debug("Received {}", message.getIntProperty("i"));
+            if (i % 100 == 0) {
+               session.commit();
+            }
+         }
+         Assertions.assertNull(consumer.receiveNoWait());
+         session.commit();
+      }
+
+      Wait.assertFalse(serverQueueA.getPagingStore()::isPaging);
+   }
+}
\ No newline at end of file


---------------------------------------------------------------------
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