This is an automated email from the ASF dual-hosted git repository.
dakirily pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/qpid-broker-j.git
The following commit(s) were added to refs/heads/main by this push:
new 8c8bfb0670 QPID-8789: [Broker-J] Pooled buffers leaked after a BDB
flow to disk make the broker flow every message to disk until it is restarted
(#468)
8c8bfb0670 is described below
commit 8c8bfb0670c8fdfa3f5a5cf231703ee7bfc3c7d9
Author: Daniil Kirilyuk <[email protected]>
AuthorDate: Wed Nov 18 12:42:45 2026 +0100
QPID-8789: [Broker-J] Pooled buffers leaked after a BDB flow to disk make
the broker flow every message to disk until it is restarted (#468)
---
.../v1_0/store/bdb/BDBFlowToDiskMetaDataTest.java | 50 +++
.../store/jdbc/JDBCFlowToDiskMetaDataTest.java | 69 ++++
.../v1_0/type/messaging/AbstractSection.java | 11 +-
.../v1_0/store/FlowToDiskMetaDataTestCase.java | 312 +++++++++++++++++
.../v1_0/type/messaging/AbstractSectionTest.java | 387 +++++++++++++++++++++
.../messaging/FlowToDiskMessageEncodingTest.java | 114 ++++++
.../org/apache/qpid/tests/utils/BrokerAdmin.java | 16 +
.../utils/EmbeddedBrokerPerClassAdminImpl.java | 12 +
.../tests/utils/LoggingBrokerAdminDecorator.java | 12 +
9 files changed, 979 insertions(+), 4 deletions(-)
diff --git
a/broker-plugins/amqp-1-0-bdb-store/src/test/java/org/apache/qpid/server/protocol/v1_0/store/bdb/BDBFlowToDiskMetaDataTest.java
b/broker-plugins/amqp-1-0-bdb-store/src/test/java/org/apache/qpid/server/protocol/v1_0/store/bdb/BDBFlowToDiskMetaDataTest.java
new file mode 100644
index 0000000000..58498050ff
--- /dev/null
+++
b/broker-plugins/amqp-1-0-bdb-store/src/test/java/org/apache/qpid/server/protocol/v1_0/store/bdb/BDBFlowToDiskMetaDataTest.java
@@ -0,0 +1,50 @@
+/*
+ *
+ * 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.qpid.server.protocol.v1_0.store.bdb;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.File;
+
+import org.junit.jupiter.api.io.TempDir;
+
+import org.apache.qpid.server.protocol.v1_0.store.FlowToDiskMetaDataTestCase;
+import org.apache.qpid.server.store.MessageStore;
+import org.apache.qpid.server.store.berkeleydb.BDBMessageStore;
+import org.apache.qpid.server.virtualhost.berkeleydb.BDBVirtualHost;
+
+class BDBFlowToDiskMetaDataTest extends FlowToDiskMetaDataTestCase
+{
+ @TempDir
+ private File _storeFolder;
+
+ @Override
+ protected MessageStore createMessageStore()
+ {
+ final BDBVirtualHost<?> virtualHost = mock(BDBVirtualHost.class);
+
when(virtualHost.getStorePath()).thenReturn(_storeFolder.getAbsolutePath());
+ final BDBMessageStore store = new BDBMessageStore();
+ store.openMessageStore(virtualHost);
+ return store;
+ }
+}
diff --git
a/broker-plugins/amqp-1-0-jdbc-store/src/test/java/org/apache/qpid/server/protocol/v1_0/store/jdbc/JDBCFlowToDiskMetaDataTest.java
b/broker-plugins/amqp-1-0-jdbc-store/src/test/java/org/apache/qpid/server/protocol/v1_0/store/jdbc/JDBCFlowToDiskMetaDataTest.java
new file mode 100644
index 0000000000..4300fd5cbe
--- /dev/null
+++
b/broker-plugins/amqp-1-0-jdbc-store/src/test/java/org/apache/qpid/server/protocol/v1_0/store/jdbc/JDBCFlowToDiskMetaDataTest.java
@@ -0,0 +1,69 @@
+/*
+ *
+ * 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.qpid.server.protocol.v1_0.store.jdbc;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.sql.DriverManager;
+import java.sql.SQLException;
+
+import org.junit.jupiter.api.AfterEach;
+
+import org.apache.qpid.server.protocol.v1_0.store.FlowToDiskMetaDataTestCase;
+import org.apache.qpid.server.store.MessageStore;
+import org.apache.qpid.server.store.jdbc.GenericJDBCMessageStore;
+import org.apache.qpid.server.virtualhost.jdbc.JDBCVirtualHost;
+
+class JDBCFlowToDiskMetaDataTest extends FlowToDiskMetaDataTestCase
+{
+ private String _connectionUrl;
+ private GenericJDBCMessageStore _store;
+
+ @Override
+ protected MessageStore createMessageStore()
+ {
+ _connectionUrl = "jdbc:derby:memory:/" + getTestName();
+ final JDBCVirtualHost<?> virtualHost = mock(JDBCVirtualHost.class);
+ when(virtualHost.getConnectionUrl()).thenReturn(_connectionUrl +
";create=true");
+ when(virtualHost.getTableNamePrefix()).thenReturn("TEST_");
+ _store = new GenericJDBCMessageStore();
+ _store.openMessageStore(virtualHost);
+ return _store;
+ }
+
+ @AfterEach
+ void dropDatabase()
+ {
+ if (_store != null)
+ {
+ _store.closeMessageStore();
+ }
+ if (_connectionUrl != null)
+ {
+ final SQLException exception = assertThrows(SQLException.class, ()
->
+ DriverManager.getConnection(_connectionUrl +
";drop=true"));
+ assertEquals("08006", exception.getSQLState());
+ }
+ }
+}
diff --git
a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/AbstractSection.java
b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/AbstractSection.java
index 27fc8cd718..055ffe1216 100644
---
a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/AbstractSection.java
+++
b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/AbstractSection.java
@@ -43,6 +43,7 @@ public abstract class AbstractSection<T, S extends
NonEncodingRetainingSection<T
private S _section;
private QpidByteBuffer _encodedForm;
+ private boolean _encodedFormDetached;
// _encodedSize is valid only when _encodedForm is non-null
private long _encodedSize = 0;
private final int _maxNestedObjects;
@@ -128,12 +129,14 @@ public abstract class AbstractSection<T, S extends
NonEncodingRetainingSection<T
@Override
public synchronized void clearEncodedForm()
{
- if (_encodedForm != null)
+ if (_encodedForm != null && !_encodedFormDetached)
{
- _section = decode(createNonEncodingRetainingSectionConstructor());
+ final QpidByteBuffer encodedForm =
QpidByteBuffer.allocate(_encodedForm.remaining());
+ encodedForm.putCopyOf(_encodedForm);
+ encodedForm.flip();
_encodedForm.dispose();
- _encodedForm = null;
- _encodedSize = 0;
+ _encodedForm = encodedForm;
+ _encodedFormDetached = true;
}
}
diff --git
a/broker-plugins/amqp-1-0-protocol/src/test/java/org/apache/qpid/server/protocol/v1_0/store/FlowToDiskMetaDataTestCase.java
b/broker-plugins/amqp-1-0-protocol/src/test/java/org/apache/qpid/server/protocol/v1_0/store/FlowToDiskMetaDataTestCase.java
new file mode 100644
index 0000000000..b49cc9c1c8
--- /dev/null
+++
b/broker-plugins/amqp-1-0-protocol/src/test/java/org/apache/qpid/server/protocol/v1_0/store/FlowToDiskMetaDataTestCase.java
@@ -0,0 +1,312 @@
+/*
+ *
+ * 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.qpid.server.protocol.v1_0.store;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.ArrayList;
+import java.util.HexFormat;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.parallel.Isolated;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
+import org.apache.qpid.server.protocol.v1_0.MessageMetaData_1_0;
+import
org.apache.qpid.server.protocol.v1_0.type.messaging.ApplicationProperties;
+import
org.apache.qpid.server.protocol.v1_0.type.messaging.ApplicationPropertiesSection;
+import org.apache.qpid.server.protocol.v1_0.type.messaging.Header;
+import org.apache.qpid.server.protocol.v1_0.type.messaging.PropertiesSection;
+import org.apache.qpid.server.store.MessageHandle;
+import org.apache.qpid.server.store.MessageStore;
+import org.apache.qpid.server.store.StoredMessage;
+import org.apache.qpid.test.utils.UnitTestBase;
+
+@Isolated("Changes the global QpidByteBuffer pool")
+public abstract class FlowToDiskMetaDataTestCase extends UnitTestBase
+{
+ private static final byte[] PROPERTIES =
HexFormat.of().parseHex("00800000000000000073d00000000400000000");
+ private static final byte[] APPLICATION_PROPERTIES = HexFormat.of()
+
.parseHex("00800000000000000074d10000001000000002b1000000016bb10000000176");
+ private static final byte[] BODY =
HexFormat.of().parseHex("005375b00000000401020304");
+
+ private MessageStore _store;
+ private int _buffersInUse;
+
+ protected abstract MessageStore createMessageStore();
+
+ @BeforeEach
+ public void setUp()
+ {
+ QpidByteBuffer.deinitialisePool();
+ _buffersInUse = QpidByteBuffer.getNumberOfBuffersInUse();
+ QpidByteBuffer.initialisePool(256 * 1024, 16, 0.5);
+ _store = createMessageStore();
+ }
+
+ @AfterEach
+ public void tearDown()
+ {
+ try
+ {
+ if (_store != null)
+ {
+ _store.closeMessageStore();
+ }
+ }
+ finally
+ {
+ QpidByteBuffer.deinitialisePool();
+ assertEquals(_buffersInUse,
QpidByteBuffer.getNumberOfBuffersInUse());
+ }
+ }
+
+ @Test
+ public void heldMetaDataDoesNotLeakAfterFlowToDisk()
+ {
+ final MessageMetaData_1_0 metaData = new MessageMetaData_1_0(new
Header().createEncodingRetainingSection(),
+ null, null, null, new ApplicationProperties(Map.of("key",
"value")).createEncodingRetainingSection(),
+ null, System.currentTimeMillis(), 0);
+ final StoredMessage<MessageMetaData_1_0> message =
_store.addMessage(metaData).allContentAdded();
+ final MessageMetaData_1_0 heldMetaData = message.getMetaData();
+ try
+ {
+ assertTrue(message.flowToDisk());
+ final ApplicationPropertiesSection section =
heldMetaData.getApplicationPropertiesSection();
+ section.dispose();
+ message.remove();
+ assertNoPooledBuffersRetained();
+ }
+ finally
+ {
+ heldMetaData.dispose();
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ public void mixedMetaDataDoesNotLeakAfterFlowToDisk(final boolean
firstFragmentDirect)
+ {
+ final StoredMessage<MessageMetaData_1_0> message;
+ try (final QpidByteBuffer properties = mixedEncoding(PROPERTIES,
firstFragmentDirect);
+ final QpidByteBuffer applicationProperties =
mixedEncoding(APPLICATION_PROPERTIES, firstFragmentDirect))
+ {
+ message = addEncodedMessage(properties, applicationProperties);
+ }
+ final MessageMetaData_1_0 heldMetaData = message.getMetaData();
+ try
+ {
+ assertTrue(message.flowToDisk());
+ assertEquals(0, message.getInMemorySize());
+ assertNoPooledBuffersRetained();
+
+ QpidByteBuffer.initialisePool(256 * 1024, 16, 0.5);
+ assertMessageEncoding(heldMetaData);
+ heldMetaData.reallocate();
+ heldMetaData.clearEncodedForm();
+ assertMessageEncoding(heldMetaData);
+ message.remove();
+ assertNoPooledBuffersRetained();
+ }
+ finally
+ {
+ heldMetaData.dispose();
+ }
+ }
+
+ @Test
+ public void repeatedEvictionPreservesHeldMetadataAndStoredBytes()
+ {
+ final StoredMessage<MessageMetaData_1_0> message = addEncodedMessage();
+ final List<MessageMetaData_1_0> heldMetadata = new ArrayList<>();
+ try
+ {
+ for (int i = 0; i < 20; i++)
+ {
+ final MessageMetaData_1_0 metadata = message.getMetaData();
+ heldMetadata.add(metadata);
+ assertTrue(message.flowToDisk());
+ assertEquals(0, message.getInMemorySize());
+ assertMessageEncoding(metadata);
+ assertEquals("v", metadata.getMessageHeader().getHeader("k"));
+ assertNotSame(metadata, message.getMetaData());
+ assertMessageEncoding(message.getMetaData());
+ try (final QpidByteBuffer content = message.getContent(0,
BODY.length))
+ {
+ assertTrue(message.flowToDisk());
+ assertArrayEquals(BODY, readBytes(content));
+ }
+ }
+ message.remove();
+ for (final MessageMetaData_1_0 metadata : heldMetadata)
+ {
+ assertMessageEncoding(metadata);
+ }
+ assertNoPooledBuffersRetained();
+ }
+ finally
+ {
+ heldMetadata.forEach(MessageMetaData_1_0::dispose);
+ }
+ }
+
+ @Test
+ public void readersOverlapStoreEviction() throws Exception
+ {
+ final StoredMessage<MessageMetaData_1_0> message = addEncodedMessage();
+ final CountDownLatch workersStopped = new CountDownLatch(2);
+ final ThreadFactory threadFactory = Executors.defaultThreadFactory();
+ final ExecutorService executor = Executors.newFixedThreadPool(2,
QpidByteBuffer
+ .createQpidByteBufferTrackingThreadFactory(task ->
threadFactory.newThread(() ->
+ {
+ try
+ {
+ task.run();
+ }
+ finally
+ {
+ workersStopped.countDown();
+ }
+ })));
+ final CountDownLatch metadataHeld = new CountDownLatch(1);
+ final CountDownLatch evicted = new CountDownLatch(1);
+ try
+ {
+ final Future<?> reader = executor.submit(() ->
+ {
+ final MessageMetaData_1_0 metadata = message.getMetaData();
+ metadataHeld.countDown();
+ assertTrue(evicted.await(10, TimeUnit.SECONDS));
+ for (int i = 0; i < 100; i++)
+ {
+ assertMessageEncoding(metadata);
+ }
+ return null;
+ });
+ final Future<?> eviction = executor.submit(() ->
+ {
+ assertTrue(metadataHeld.await(10, TimeUnit.SECONDS));
+ assertTrue(message.flowToDisk());
+ evicted.countDown();
+ for (int i = 0; i < 100; i++)
+ {
+ message.getMetaData();
+ assertTrue(message.flowToDisk());
+ }
+ return null;
+ });
+ reader.get(30, TimeUnit.SECONDS);
+ eviction.get(30, TimeUnit.SECONDS);
+ message.remove();
+ }
+ finally
+ {
+ executor.shutdownNow();
+ assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS));
+ assertTrue(workersStopped.await(10, TimeUnit.SECONDS));
+ }
+ assertNoPooledBuffersRetained();
+ }
+
+ private StoredMessage<MessageMetaData_1_0> addEncodedMessage()
+ {
+ try (final QpidByteBuffer properties =
QpidByteBuffer.allocateDirect(PROPERTIES.length);
+ final QpidByteBuffer applicationProperties =
QpidByteBuffer.allocateDirect(APPLICATION_PROPERTIES.length))
+ {
+ properties.put(PROPERTIES).flip();
+ applicationProperties.put(APPLICATION_PROPERTIES).flip();
+ return addEncodedMessage(properties, applicationProperties);
+ }
+ }
+
+ private StoredMessage<MessageMetaData_1_0> addEncodedMessage(final
QpidByteBuffer properties,
+ final
QpidByteBuffer applicationProperties)
+ {
+ try (final QpidByteBuffer body =
QpidByteBuffer.allocateDirect(BODY.length))
+ {
+ body.put(BODY).flip();
+ final MessageMetaData_1_0 metadata = new MessageMetaData_1_0(null,
null, null,
+ new PropertiesSection(properties), new
ApplicationPropertiesSection(applicationProperties),
+ null, System.currentTimeMillis(), BODY.length);
+ final MessageHandle<MessageMetaData_1_0> handle =
_store.addMessage(metadata);
+ handle.addContent(body);
+ return handle.allContentAdded();
+ }
+ }
+
+ private QpidByteBuffer mixedEncoding(final byte[] bytes, final boolean
firstFragmentDirect)
+ {
+ final int split = bytes.length / 2;
+ try (final QpidByteBuffer first =
QpidByteBuffer.allocate(firstFragmentDirect, split);
+ final QpidByteBuffer second =
QpidByteBuffer.allocate(!firstFragmentDirect, bytes.length - split))
+ {
+ first.put(bytes, 0, split).flip();
+ second.put(bytes, split, bytes.length - split).flip();
+ return QpidByteBuffer.concatenate(first, second);
+ }
+ }
+
+ private void assertMessageEncoding(final MessageMetaData_1_0 metadata)
+ {
+ final PropertiesSection properties = metadata.getPropertiesSection();
+ final ApplicationPropertiesSection applicationProperties =
metadata.getApplicationPropertiesSection();
+ try (final QpidByteBuffer propertiesBytes =
properties.getEncodedForm();
+ final QpidByteBuffer applicationBytes =
applicationProperties.getEncodedForm())
+ {
+ assertArrayEquals(PROPERTIES, readBytes(propertiesBytes));
+ assertArrayEquals(APPLICATION_PROPERTIES,
readBytes(applicationBytes));
+ assertEquals(17 + PROPERTIES.length +
APPLICATION_PROPERTIES.length, metadata.getStorableSize());
+ }
+ finally
+ {
+ properties.dispose();
+ applicationProperties.dispose();
+ }
+ }
+
+ private byte[] readBytes(final QpidByteBuffer buffer)
+ {
+ final byte[] bytes = new byte[buffer.remaining()];
+ buffer.get(bytes);
+ return bytes;
+ }
+
+ private void assertNoPooledBuffersRetained()
+ {
+ QpidByteBuffer.deinitialisePool();
+ assertEquals(_buffersInUse, QpidByteBuffer.getNumberOfBuffersInUse(),
+ "Metadata released by the store must not retain pooled
buffers");
+ }
+}
diff --git
a/broker-plugins/amqp-1-0-protocol/src/test/java/org/apache/qpid/server/protocol/v1_0/type/messaging/AbstractSectionTest.java
b/broker-plugins/amqp-1-0-protocol/src/test/java/org/apache/qpid/server/protocol/v1_0/type/messaging/AbstractSectionTest.java
new file mode 100644
index 0000000000..562aa084c7
--- /dev/null
+++
b/broker-plugins/amqp-1-0-protocol/src/test/java/org/apache/qpid/server/protocol/v1_0/type/messaging/AbstractSectionTest.java
@@ -0,0 +1,387 @@
+/*
+ *
+ * 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.qpid.server.protocol.v1_0.type.messaging;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.HexFormat;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.parallel.Isolated;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
+import org.apache.qpid.server.protocol.v1_0.codec.ValueHandler;
+import org.apache.qpid.server.protocol.v1_0.messaging.SectionDecoderImpl;
+import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
+import
org.apache.qpid.server.protocol.v1_0.type.codec.AMQPDescribedTypeRegistry;
+import
org.apache.qpid.server.protocol.v1_0.type.messaging.codec.EncodingRetaining;
+import org.apache.qpid.server.util.ConnectionScopedRuntimeException;
+import org.apache.qpid.test.utils.UnitTestBase;
+
+@Isolated("Changes the global QpidByteBuffer pool")
+class AbstractSectionTest extends UnitTestBase
+{
+ private static final AMQPDescribedTypeRegistry TYPE_REGISTRY =
AMQPDescribedTypeRegistry
+ .newInstance()
+ .registerTransportLayer()
+ .registerMessagingLayer()
+ .registerTransactionLayer()
+ .registerSecurityLayer();
+
+ private int _buffersInUse;
+
+ @BeforeEach
+ void beforeEach()
+ {
+ QpidByteBuffer.deinitialisePool();
+ _buffersInUse = QpidByteBuffer.getNumberOfBuffersInUse();
+ QpidByteBuffer.initialisePool(256, 16, 0.5);
+ }
+
+ @AfterEach
+ void afterEach()
+ {
+ QpidByteBuffer.deinitialisePool();
+ assertEquals(_buffersInUse, QpidByteBuffer.getNumberOfBuffersInUse());
+ }
+
+ @ParameterizedTest
+ @ValueSource(ints = {1, 255, 256, 257, 4096})
+ void clearReleasesDirectMemoryWithoutRequiringDisposal(final int
payloadSize)
+ {
+ final byte[] bytes = new byte[payloadSize + 8];
+ try (final QpidByteBuffer encoding = QpidByteBuffer.wrap(bytes))
+ {
+ encoding.put((byte) 0).put((byte) 0x53).put((byte)
0x75).put((byte) 0xb0).putInt(payloadSize);
+ }
+ final DataSection section;
+ try (final QpidByteBuffer input =
QpidByteBuffer.allocateDirect(bytes.length))
+ {
+ input.put(bytes).flip();
+ section = new DataSection(input);
+ }
+ try
+ {
+ section.clearEncodedForm();
+ section.getValue();
+ section.reallocate();
+ section.clearEncodedForm();
+ try (final QpidByteBuffer encoding = section.getEncodedForm())
+ {
+ assertArrayEquals(bytes, readBytes(encoding));
+ }
+ QpidByteBuffer.deinitialisePool();
+ assertEquals(_buffersInUse,
QpidByteBuffer.getNumberOfBuffersInUse(),
+ "A detached section must not require an owner to dispose
pooled memory");
+ }
+ finally
+ {
+ section.dispose();
+ }
+ }
+
+ @ParameterizedTest
+ @CsvSource({"false, true", "true, false", "false, false", "true, true"})
+ void clearDetachesFragmentsWithoutRequiringDisposal(final boolean
firstDirect, final boolean secondDirect)
+ {
+ final byte[] bytes =
HexFormat.of().parseHex("00800000000000000073d00000000400000000");
+ final PropertiesSection section;
+ try (final QpidByteBuffer first = QpidByteBuffer.allocate(firstDirect,
9);
+ final QpidByteBuffer second =
QpidByteBuffer.allocate(secondDirect, bytes.length - 9))
+ {
+ first.put(bytes, 0, 9).flip();
+ second.put(bytes, 9, bytes.length - 9).flip();
+ try (final QpidByteBuffer input =
QpidByteBuffer.concatenate(first, second))
+ {
+ section = new PropertiesSection(input);
+ }
+ }
+ try
+ {
+ if (firstDirect || secondDirect)
+ {
+ assertTrue(QpidByteBuffer.getNumberOfBuffersInUse() >
_buffersInUse);
+ }
+ section.clearEncodedForm();
+ QpidByteBuffer.deinitialisePool();
+ assertEquals(_buffersInUse,
QpidByteBuffer.getNumberOfBuffersInUse(),
+ "Detachment must release every pooled fragment before
section disposal");
+
+ QpidByteBuffer.initialisePool(256, 16, 0.5);
+ section.getValue();
+ section.reallocate();
+ section.clearEncodedForm();
+ assertEquals(bytes.length, section.getEncodedSize());
+ final EncodingRetaining copy = section.copy();
+ try (final QpidByteBuffer encoding = section.getEncodedForm();
+ final QpidByteBuffer destination =
QpidByteBuffer.allocate(bytes.length))
+ {
+ assertArrayEquals(bytes, readBytes(encoding));
+ copy.writeTo(destination);
+ destination.flip();
+ assertArrayEquals(bytes, readBytes(destination));
+ QpidByteBuffer.deinitialisePool();
+ assertEquals(_buffersInUse,
QpidByteBuffer.getNumberOfBuffersInUse(),
+ "Reads and repeated detachment must not recreate
pooled ownership");
+ }
+ finally
+ {
+ copy.dispose();
+ }
+ }
+ finally
+ {
+ section.dispose();
+ }
+ }
+
+ @Test
+ void outstandingCopySurvivesClearAndDisposal() throws AmqpErrorException
+ {
+ final byte[] bytes =
HexFormat.of().parseHex("00800000000000000073d00000000400000000");
+ final EncodingRetainingSection<?> section = decode(bytes);
+ final EncodingRetaining beforeClear = section.copy();
+ try
+ {
+ section.clearEncodedForm();
+ final EncodingRetaining afterClear = section.copy();
+ try
+ {
+ section.dispose();
+ QpidByteBuffer.deinitialisePool();
+ assertTrue(QpidByteBuffer.getNumberOfBuffersInUse() >
_buffersInUse,
+ "A copy issued before detachment still owns its
pooled reference");
+ try (final QpidByteBuffer before =
beforeClear.getEncodedForm();
+ final QpidByteBuffer after = afterClear.getEncodedForm())
+ {
+ assertArrayEquals(bytes, readBytes(before));
+ assertArrayEquals(bytes, readBytes(after));
+ }
+ beforeClear.dispose();
+ assertEquals(_buffersInUse,
QpidByteBuffer.getNumberOfBuffersInUse(),
+ "Only the copy issued before detachment should
retain pooled storage");
+ }
+ finally
+ {
+ afterClear.dispose();
+ }
+ }
+ finally
+ {
+ beforeClear.dispose();
+ section.dispose();
+ }
+ }
+
+ @Test
+ void clearPreservesLazyDecodeLimit()
+ {
+ final byte[] bytes = HexFormat.of().parseHex("005377c00501c0020140");
+ try (final QpidByteBuffer input =
QpidByteBuffer.allocateDirect(bytes.length))
+ {
+ input.put(bytes).flip();
+ final AmqpValueSection section = new AmqpValueSection(input, 1);
+ try
+ {
+ section.clearEncodedForm();
+ assertThrows(ConnectionScopedRuntimeException.class,
section::getValue);
+ }
+ finally
+ {
+ section.dispose();
+ }
+ }
+ }
+
+ @Test
+ void clearPreservesZeroWidthArrayLimit()
+ {
+ final byte[] bytes =
HexFormat.of().parseHex("005377f0000000050000000541");
+ try (final QpidByteBuffer input =
QpidByteBuffer.allocateDirect(bytes.length))
+ {
+ input.put(bytes).flip();
+ final ValueHandler handler = new ValueHandler(TYPE_REGISTRY, 64,
2);
+ final AmqpValueSection section = new AmqpValueSection(input,
handler);
+ try
+ {
+ section.clearEncodedForm();
+ assertThrows(ConnectionScopedRuntimeException.class,
section::getValue);
+ }
+ finally
+ {
+ section.dispose();
+ }
+ }
+ }
+
+ @Test
+ void concurrentCopiesAndClearsPreserveBytes() throws Exception
+ {
+ final byte[] bytes = HexFormat.of()
+
.parseHex("00800000000000000074d10000001000000002b1000000016bb10000000176");
+ final EncodingRetainingSection<?> section = decode(bytes);
+ final CountDownLatch workersStopped = new CountDownLatch(2);
+ final ThreadFactory threadFactory = Executors.defaultThreadFactory();
+ final ExecutorService executor = Executors.newFixedThreadPool(2,
+ QpidByteBuffer.createQpidByteBufferTrackingThreadFactory(task
-> threadFactory.newThread(() ->
+ {
+ try
+ {
+ task.run();
+ }
+ finally
+ {
+ workersStopped.countDown();
+ }
+ })));
+ final CountDownLatch start = new CountDownLatch(1);
+ try
+ {
+ final Future<?> clears = executor.submit(() ->
+ {
+ start.await();
+ for (int i = 0; i < 1000; i++)
+ {
+ section.clearEncodedForm();
+ section.reallocate();
+ }
+ return null;
+ });
+ final Future<?> copies = executor.submit(() ->
+ {
+ start.await();
+ for (int i = 0; i < 1000; i++)
+ {
+ final EncodingRetaining copy = section.copy();
+ try (final QpidByteBuffer encoding = copy.getEncodedForm())
+ {
+ assertArrayEquals(bytes, readBytes(encoding));
+ }
+ finally
+ {
+ copy.dispose();
+ }
+ }
+ return null;
+ });
+ start.countDown();
+ clears.get(10, TimeUnit.SECONDS);
+ copies.get(10, TimeUnit.SECONDS);
+ }
+ finally
+ {
+ executor.shutdownNow();
+ assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS));
+ assertTrue(workersStopped.await(10, TimeUnit.SECONDS));
+ section.dispose();
+ }
+ }
+
+ @ParameterizedTest
+ @MethodSource("sectionEncodings")
+ void clearPreservesExactEncoding(final String hex) throws
AmqpErrorException
+ {
+ final byte[] bytes = HexFormat.of().parseHex(hex);
+ final EncodingRetainingSection<?> section = decode(bytes);
+ try
+ {
+ section.clearEncodedForm();
+ assertEquals(bytes.length, section.getEncodedSize());
+ try (final QpidByteBuffer encoded = section.getEncodedForm())
+ {
+ assertFalse(encoded.isDirect());
+ assertArrayEquals(bytes, readBytes(encoded));
+ }
+
+ final EncodingRetaining copy = section.copy();
+ try
+ {
+ section.clearEncodedForm();
+ section.reallocate();
+ try (final QpidByteBuffer destination =
QpidByteBuffer.allocate(bytes.length))
+ {
+ copy.writeTo(destination);
+ destination.flip();
+ assertArrayEquals(bytes, readBytes(destination));
+ }
+ }
+ finally
+ {
+ copy.dispose();
+ }
+ }
+ finally
+ {
+ section.dispose();
+ }
+ }
+
+ private EncodingRetainingSection<?> decode(final byte[] bytes) throws
AmqpErrorException
+ {
+ try (final QpidByteBuffer input =
QpidByteBuffer.allocateDirect(bytes.length))
+ {
+ input.put(bytes).flip();
+ final List<EncodingRetainingSection<?>> sections =
+ new
SectionDecoderImpl(TYPE_REGISTRY.getSectionDecoderRegistry()).parseAll(input);
+ assertEquals(1, sections.size());
+ return sections.get(0);
+ }
+ }
+
+ private byte[] readBytes(final QpidByteBuffer buffer)
+ {
+ final byte[] bytes = new byte[buffer.remaining()];
+ buffer.get(bytes);
+ return bytes;
+ }
+
+ private static Stream<String> sectionEncodings()
+ {
+ return Stream.of("00800000000000000070d00000000400000000",
+
"00800000000000000071d10000001000000002b3000000016bb10000000176",
+
"00800000000000000072d10000001000000002b3000000016bb10000000176",
+ "00800000000000000073d00000000400000000",
+
"00800000000000000074d10000001000000002b1000000016bb10000000176",
+ "00800000000000000075b00000000176",
+ "00800000000000000076d00000000400000000",
+ "00800000000000000077827ff0000000000001",
+
"00800000000000000078d10000001000000002b3000000016bb10000000176",
+
"00a31f616d71703a6170706c69636174696f6e2d70726f706572746965733a6d6170d10000000400000000");
+ }
+}
diff --git
a/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/messaging/FlowToDiskMessageEncodingTest.java
b/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/messaging/FlowToDiskMessageEncodingTest.java
new file mode 100644
index 0000000000..60daa043ae
--- /dev/null
+++
b/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/messaging/FlowToDiskMessageEncodingTest.java
@@ -0,0 +1,114 @@
+/*
+ *
+ * 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.qpid.tests.protocol.v1_0.messaging;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
+
+import java.util.HexFormat;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.Test;
+
+import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
+import org.apache.qpid.server.protocol.v1_0.type.UnsignedInteger;
+import org.apache.qpid.server.protocol.v1_0.type.messaging.Accepted;
+import org.apache.qpid.server.protocol.v1_0.type.transport.Attach;
+import org.apache.qpid.server.protocol.v1_0.type.transport.Begin;
+import org.apache.qpid.server.protocol.v1_0.type.transport.Disposition;
+import org.apache.qpid.server.protocol.v1_0.type.transport.Flow;
+import org.apache.qpid.server.protocol.v1_0.type.transport.ReceiverSettleMode;
+import org.apache.qpid.server.protocol.v1_0.type.transport.Role;
+import org.apache.qpid.server.protocol.v1_0.type.transport.Transfer;
+import org.apache.qpid.tests.protocol.SpecificationTest;
+import org.apache.qpid.tests.protocol.v1_0.FrameTransport;
+import org.apache.qpid.tests.protocol.v1_0.Interaction;
+import org.apache.qpid.tests.utils.BrokerAdmin;
+import org.apache.qpid.tests.utils.BrokerAdminUsingTestBase;
+import org.apache.qpid.tests.utils.ConfigItem;
+
+@ConfigItem(name = "broker.flowToDiskThreshold", value = "1")
+public class FlowToDiskMessageEncodingTest extends BrokerAdminUsingTestBase
+{
+ @Test
+ @SpecificationTest(section = "3.2", description = "The exact encoding of
sections of the bare message " +
+ "MUST NOT be modified")
+ public void bareMessageBytesSurviveFlowToDisk() throws Exception
+ {
+ assumeTrue(getBrokerAdmin().isFlowToDiskSupported(), "Requires a
persistent store and eviction statistics");
+ final long evacuatedBeforeSend =
getBrokerAdmin().getBytesEvacuatedFromMemory();
+ final byte[] bytes = HexFormat.of().parseHex(
+ "00800000000000000073d00000000400000000" +
+
"00800000000000000074d10000001000000002b1000000016bb10000000176" +
+ "00800000000000000075b00000000401020304");
+ getBrokerAdmin().createQueue(BrokerAdmin.TEST_QUEUE_NAME);
+ try (final FrameTransport sender = new
FrameTransport(getBrokerAdmin()).connect();
+ final QpidByteBuffer payload = QpidByteBuffer.wrap(bytes))
+ {
+ final Interaction interaction =
sender.newInteraction().negotiateOpen()
+ .begin().consumeResponse(Begin.class)
+
.attachRole(Role.SENDER).attachTargetAddress(BrokerAdmin.TEST_QUEUE_NAME)
+
.attach().consumeResponse(Attach.class).consumeResponse(Flow.class);
+ final Disposition disposition =
interaction.transferPayload(payload).transferSettled(false).transfer()
+ .consume(Disposition.class, Flow.class);
+ assertInstanceOf(Accepted.class, disposition.getState());
+ interaction.detachEndCloseUnconditionally();
+ }
+
+ assertTrue(getBrokerAdmin().getBytesEvacuatedFromMemory() >
evacuatedBeforeSend,
+ "The message must be evicted before delivery");
+ assertEquals(1,
getBrokerAdmin().getQueueDepthMessages(BrokerAdmin.TEST_QUEUE_NAME));
+
+ try (final FrameTransport receiver = new
FrameTransport(getBrokerAdmin()).connect())
+ {
+ final Interaction interaction =
receiver.newInteraction().negotiateOpen()
+ .begin().consumeResponse(Begin.class)
+
.attachRole(Role.RECEIVER).attachSourceAddress(BrokerAdmin.TEST_QUEUE_NAME)
+
.attachRcvSettleMode(ReceiverSettleMode.FIRST).attach().consumeResponse(Attach.class)
+ .flowIncomingWindow(UnsignedInteger.ONE)
+
.flowNextIncomingIdFromPeerLatestSessionBeginAndDeliveryCount()
+
.flowOutgoingWindow(UnsignedInteger.ZERO).flowNextOutgoingId(UnsignedInteger.ZERO)
+
.flowLinkCredit(UnsignedInteger.ONE).flowHandleFromLinkHandle().flow()
+ .receiveDelivery(Flow.class);
+ final List<Transfer> transfers = interaction.getLatestDelivery();
+ final List<QpidByteBuffer> payloads =
transfers.stream().map(Transfer::getPayload)
+ .collect(Collectors.toList());
+ try (final QpidByteBuffer received =
QpidByteBuffer.concatenate(payloads))
+ {
+ final byte[] actual = new byte[received.remaining()];
+ received.get(actual);
+ assertArrayEquals(bytes, actual);
+ }
+ finally
+ {
+ payloads.forEach(QpidByteBuffer::dispose);
+ transfers.forEach(Transfer::dispose);
+ }
+
interaction.dispositionSettled(true).dispositionState(Accepted.INSTANCE)
+
.dispositionRole(Role.RECEIVER).dispositionFirstFromLatestDelivery().disposition();
+ interaction.detachEndCloseUnconditionally();
+ }
+ }
+}
diff --git
a/systests/systests-utils/src/main/java/org/apache/qpid/tests/utils/BrokerAdmin.java
b/systests/systests-utils/src/main/java/org/apache/qpid/tests/utils/BrokerAdmin.java
index 701b941a53..b920eaf614 100644
---
a/systests/systests-utils/src/main/java/org/apache/qpid/tests/utils/BrokerAdmin.java
+++
b/systests/systests-utils/src/main/java/org/apache/qpid/tests/utils/BrokerAdmin.java
@@ -56,6 +56,22 @@ public interface BrokerAdmin extends Pluggable
boolean isPutMessageOnQueueSupported();
boolean isDeleteQueueSupported();
+ /**
+ * Indicates whether a persistent message store and flow-to-disk
statistics are available.
+ */
+ default boolean isFlowToDiskSupported()
+ {
+ return false;
+ }
+
+ /**
+ * Returns the virtual host's cumulative number of bytes evacuated from
memory by flow-to-disk.
+ */
+ default long getBytesEvacuatedFromMemory()
+ {
+ throw new UnsupportedOperationException("Flow-to-disk statistics are
not supported");
+ }
+
/**
* Indicates whether connection lookup and asynchronous close operations
are available.
*/
diff --git
a/systests/systests-utils/src/main/java/org/apache/qpid/tests/utils/EmbeddedBrokerPerClassAdminImpl.java
b/systests/systests-utils/src/main/java/org/apache/qpid/tests/utils/EmbeddedBrokerPerClassAdminImpl.java
index 42f0c10071..0d30f66ed7 100644
---
a/systests/systests-utils/src/main/java/org/apache/qpid/tests/utils/EmbeddedBrokerPerClassAdminImpl.java
+++
b/systests/systests-utils/src/main/java/org/apache/qpid/tests/utils/EmbeddedBrokerPerClassAdminImpl.java
@@ -390,6 +390,18 @@ public class EmbeddedBrokerPerClassAdminImpl implements
BrokerAdmin
return queue.getQueueDepthMessages();
}
+ @Override
+ public boolean isFlowToDiskSupported()
+ {
+ return _isPersistentStore;
+ }
+
+ @Override
+ public long getBytesEvacuatedFromMemory()
+ {
+ return ((QueueManagingVirtualHost<?>)
_currentVirtualHostNode.getVirtualHost()).getBytesEvacuatedFromMemory();
+ }
+
@Override
public boolean supportsRestart()
{
diff --git
a/systests/systests-utils/src/main/java/org/apache/qpid/tests/utils/LoggingBrokerAdminDecorator.java
b/systests/systests-utils/src/main/java/org/apache/qpid/tests/utils/LoggingBrokerAdminDecorator.java
index fc39eecdb6..dd7bfeb55f 100644
---
a/systests/systests-utils/src/main/java/org/apache/qpid/tests/utils/LoggingBrokerAdminDecorator.java
+++
b/systests/systests-utils/src/main/java/org/apache/qpid/tests/utils/LoggingBrokerAdminDecorator.java
@@ -174,6 +174,18 @@ public class LoggingBrokerAdminDecorator implements
BrokerAdmin
return _delegate.isDeleteQueueSupported();
}
+ @Override
+ public boolean isFlowToDiskSupported()
+ {
+ return _delegate.isFlowToDiskSupported();
+ }
+
+ @Override
+ public long getBytesEvacuatedFromMemory()
+ {
+ return _delegate.getBytesEvacuatedFromMemory();
+ }
+
@Override
public boolean isConnectionManagementSupported()
{
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]