This is an automated email from the ASF dual-hosted git repository.
jt2594838 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/iotdb.git
The following commit(s) were added to refs/heads/master by this push:
new cfa607e6d6f Reclaim idle server RPC buffers under memory pressure
(#19333)
cfa607e6d6f is described below
commit cfa607e6d6f6f2d01146cc667a2fedc59f021207
Author: Caideyipi <[email protected]>
AuthorDate: Thu Nov 26 14:06:10 2026 +0800
Reclaim idle server RPC buffers under memory pressure (#19333)
* Reclaim idle server RPC buffers under memory pressure
* Improve RPC buffer reclamation and retire server pools
* Cache RPC buffer reclamation candidates
* Reuse RPC buffer reclamation snapshots
---
.../org/apache/iotdb/rpc/AutoResizingBuffer.java | 24 +-
.../iotdb/rpc/AutoResizingBufferMemoryManager.java | 408 ++++++++++++++-
.../iotdb/rpc/AutoScalingBufferReadTransport.java | 18 +
.../iotdb/rpc/AutoScalingBufferWriteTransport.java | 16 +
.../rpc/TCompressedElasticFramedTransport.java | 22 +
.../apache/iotdb/rpc/TElasticFramedTransport.java | 64 ++-
.../apache/iotdb/rpc/AutoResizingBufferTest.java | 570 ++++++++++++++++++++-
.../rpc/TCompressedElasticFramedTransportTest.java | 43 +-
.../dataregion/DataRegionStateMachine.java | 6 +
.../schemaregion/SchemaRegionStateMachine.java | 3 +
.../service/AbstractThriftServiceThread.java | 24 +-
.../iotdb/commons/service/ThriftService.java | 12 +-
.../service/ThriftServerBufferReclamationTest.java | 326 ++++++++++++
13 files changed, 1522 insertions(+), 14 deletions(-)
diff --git
a/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/AutoResizingBuffer.java
b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/AutoResizingBuffer.java
index 26c5eb97779..c4e4d07abc6 100644
---
a/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/AutoResizingBuffer.java
+++
b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/AutoResizingBuffer.java
@@ -114,6 +114,27 @@ class AutoResizingBuffer implements AutoCloseable {
lastShrinkTime = System.currentTimeMillis();
}
+ int getAccountedCapacity() {
+ return accountedCapacity;
+ }
+
+ int getReclaimableBytes() {
+ return Math.max(0, accountedCapacity - initialCapacity);
+ }
+
+ long trimToInitialCapacity() {
+ if (closed || array.length <= initialCapacity) {
+ return 0;
+ }
+ long releasedBytes = accountedCapacity - initialCapacity;
+ array = Arrays.copyOf(array, initialCapacity);
+ memoryAccount.release(releasedBytes);
+ accountedCapacity = initialCapacity;
+ bufTooLargeCounter = RpcUtils.MAX_BUFFER_OVERSIZE_TIME;
+ lastShrinkTime = System.currentTimeMillis();
+ return releasedBytes;
+ }
+
@Override
public void close() {
if (!closed) {
@@ -148,8 +169,7 @@ class AutoResizingBuffer implements AutoCloseable {
private void reserveCurrentCapacityIfReleased() throws IOException {
if (closed) {
- AutoResizingBufferMemoryManager.MemoryAccount newMemoryAccount =
- AutoResizingBufferMemoryManager.createMemoryAccount();
+ AutoResizingBufferMemoryManager.MemoryAccount newMemoryAccount =
memoryAccount.reopen();
newMemoryAccount.allocate(array.length);
memoryAccount = newMemoryAccount;
accountedCapacity = array.length;
diff --git
a/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/AutoResizingBufferMemoryManager.java
b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/AutoResizingBufferMemoryManager.java
index a8d7d4fe076..4e53374c006 100644
---
a/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/AutoResizingBufferMemoryManager.java
+++
b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/AutoResizingBufferMemoryManager.java
@@ -21,9 +21,23 @@ package org.apache.iotdb.rpc;
import org.apache.iotdb.rpc.i18n.RpcMessages;
+import org.apache.thrift.transport.TTransport;
+import org.apache.thrift.transport.TTransportException;
+import org.apache.thrift.transport.TTransportFactory;
+
import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Map;
import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
public final class AutoResizingBufferMemoryManager {
private static final int MEMORY_ALLOCATE_MAX_RETRIES = 5;
@@ -47,6 +61,13 @@ public final class AutoResizingBufferMemoryManager {
DEFAULT_MEMORY_ALLOCATE_RETRY_INTERVAL_IN_MS;
private static final AtomicLong memoryAllocationCount = new AtomicLong();
private static final AtomicLong memoryAllocationFailureCount = new
AtomicLong();
+ private static final ThreadLocal<ServerBufferPool>
constructingServerBufferPool =
+ new ThreadLocal<>();
+ private static final AtomicBoolean reclaimingServerBuffers = new
AtomicBoolean();
+ private static final Set<ServerBufferPool> serverBufferPools =
ConcurrentHashMap.newKeySet();
+ private static final AtomicLong serverBufferPoolsVersion = new AtomicLong();
+ private static final AtomicReference<CandidateSnapshot>
otherPoolCandidateSnapshot =
+ new AtomicReference<>();
private AutoResizingBufferMemoryManager() {
// Utility class.
@@ -69,16 +90,28 @@ public final class AutoResizingBufferMemoryManager {
}
static MemoryAccount createMemoryAccount() {
- return new MemoryAccount(memoryControl);
+ return new MemoryAccount(memoryControl,
constructingServerBufferPool.get());
+ }
+
+ public static ServerBufferPool createServerBufferPool() {
+ ServerBufferPool pool = new ServerBufferPool();
+ serverBufferPools.add(pool);
+ serverBufferPoolsVersion.incrementAndGet();
+ otherPoolCandidateSnapshot.set(null);
+ return pool;
}
- private static void allocate(AutoResizingBufferMemoryControl memoryControl,
long sizeInBytes)
+ private static void allocate(
+ AutoResizingBufferMemoryControl memoryControl,
+ long sizeInBytes,
+ ServerBufferPool preferredPool)
throws IOException {
if (sizeInBytes <= 0) {
return;
}
for (int i = 0; i < MEMORY_ALLOCATE_MAX_RETRIES; i++) {
- if (memoryControl.allocate(sizeInBytes)) {
+ if (memoryControl.allocate(sizeInBytes)
+ || tryAllocateAfterReclaim(memoryControl, sizeInBytes,
preferredPool)) {
memoryAllocationCount.incrementAndGet();
return;
}
@@ -98,6 +131,116 @@ public final class AutoResizingBufferMemoryManager {
MEMORY_ALLOCATE_MAX_RETRIES));
}
+ private static boolean tryAllocateAfterReclaim(
+ AutoResizingBufferMemoryControl memoryControl,
+ long sizeInBytes,
+ ServerBufferPool preferredPool) {
+ if (!reclaimingServerBuffers.compareAndSet(false, true)) {
+ return false;
+ }
+ try {
+ if (preferredPool != null && tryAllocateFromPool(memoryControl,
sizeInBytes, preferredPool)) {
+ return true;
+ }
+ return tryAllocateFromOtherPools(memoryControl, sizeInBytes,
preferredPool);
+ } finally {
+ reclaimingServerBuffers.set(false);
+ }
+ }
+
+ private static boolean tryAllocateFromPool(
+ AutoResizingBufferMemoryControl memoryControl, long sizeInBytes,
ServerBufferPool pool) {
+ if (memoryControl.allocate(sizeInBytes)) {
+ return true;
+ }
+ ServerConnectionCandidate candidate;
+ while ((candidate = pool.nextReclamationCandidate()) != null) {
+ candidate.connection().reclaimIdleBuffers(candidate.idleSinceNanos());
+ if (memoryControl.allocate(sizeInBytes)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static boolean tryAllocateFromOtherPools(
+ AutoResizingBufferMemoryControl memoryControl,
+ long sizeInBytes,
+ ServerBufferPool preferredPool) {
+ if (memoryControl.allocate(sizeInBytes)) {
+ return true;
+ }
+ ServerConnectionCandidate candidate;
+ while ((candidate = nextReclamationCandidateFromOtherPools(preferredPool))
!= null) {
+ candidate.connection().reclaimIdleBuffers(candidate.idleSinceNanos());
+ if (memoryControl.allocate(sizeInBytes)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static ServerConnectionCandidate
nextReclamationCandidateFromOtherPools(
+ ServerBufferPool preferredPool) {
+ while (true) {
+ long version = serverBufferPoolsVersion.get();
+ CandidateSnapshot snapshot = otherPoolCandidateSnapshot.get();
+ if (snapshot == null
+ || snapshot.version != version
+ || snapshot.excludedPool != preferredPool) {
+ List<ServerConnectionCandidate> candidates = new ArrayList<>();
+ long now = System.nanoTime();
+ for (ServerBufferPool pool : serverBufferPools) {
+ if (pool != preferredPool) {
+ pool.collectCandidates(candidates, now);
+ }
+ }
+ candidates.sort(ServerConnectionCandidate.RECLAMATION_ORDER);
+ if (version != serverBufferPoolsVersion.get()) {
+ continue;
+ }
+ CandidateSnapshot newSnapshot = new CandidateSnapshot(version,
candidates, preferredPool);
+ if (!otherPoolCandidateSnapshot.compareAndSet(snapshot, newSnapshot)) {
+ continue;
+ }
+ snapshot = newSnapshot;
+ }
+ if (version != serverBufferPoolsVersion.get()) {
+ continue;
+ }
+ return snapshot.nextCandidate();
+ }
+ }
+
+ private static long reclaimIdleBuffers(ServerBufferPool pool, long
targetBytes) {
+ if (targetBytes <= 0 || !reclaimingServerBuffers.compareAndSet(false,
true)) {
+ return 0;
+ }
+ try {
+ return pool.reclaimIdleBuffersInternal(targetBytes);
+ } finally {
+ reclaimingServerBuffers.set(false);
+ }
+ }
+
+ private static long reclaimOneIdleConnection(ServerBufferPool pool) {
+ if (!reclaimingServerBuffers.compareAndSet(false, true)) {
+ return 0;
+ }
+ try {
+ ServerConnectionCandidate candidate;
+ while ((candidate = pool.nextReclamationCandidate()) != null) {
+ long reclaimedBytes =
candidate.connection().reclaimIdleBuffers(candidate.idleSinceNanos());
+ if (reclaimedBytes > 0) {
+ return reclaimedBytes;
+ }
+ }
+ return 0;
+ } finally {
+ reclaimingServerBuffers.set(false);
+ }
+ }
+
private static void release(AutoResizingBufferMemoryControl memoryControl,
long sizeInBytes) {
if (sizeInBytes <= 0) {
return;
@@ -115,13 +258,16 @@ public final class AutoResizingBufferMemoryManager {
static final class MemoryAccount {
private final AutoResizingBufferMemoryControl memoryControl;
+ private final ServerBufferPool serverBufferPool;
- private MemoryAccount(AutoResizingBufferMemoryControl memoryControl) {
+ private MemoryAccount(
+ AutoResizingBufferMemoryControl memoryControl, ServerBufferPool
serverBufferPool) {
this.memoryControl = memoryControl;
+ this.serverBufferPool = serverBufferPool;
}
void allocate(long sizeInBytes) throws IOException {
- AutoResizingBufferMemoryManager.allocate(memoryControl, sizeInBytes);
+ AutoResizingBufferMemoryManager.allocate(memoryControl, sizeInBytes,
serverBufferPool);
}
long allocate(long preferredSizeInBytes, long requiredSizeInBytes) throws
IOException {
@@ -136,8 +282,260 @@ public final class AutoResizingBufferMemoryManager {
return requiredSizeInBytes;
}
+ MemoryAccount reopen() {
+ return new MemoryAccount(AutoResizingBufferMemoryManager.memoryControl,
serverBufferPool);
+ }
+
void release(long sizeInBytes) {
AutoResizingBufferMemoryManager.release(memoryControl, sizeInBytes);
}
}
+
+ public static final class ServerBufferPool implements AutoCloseable {
+ private final Map<TTransport, ServerConnectionState>
connectionsByTransport =
+ new IdentityHashMap<>();
+ private final AtomicLong reclamationCandidatesVersion = new AtomicLong();
+ private volatile CandidateSnapshot candidateSnapshot;
+ private long exhaustedCandidateVersion = Long.MIN_VALUE;
+ private volatile boolean closed;
+ private boolean retired;
+
+ private ServerBufferPool() {}
+
+ /** Reclaims idle buffers from this pool until at least {@code
targetBytes} are released. */
+ public long reclaimIdleBuffers(long targetBytes) {
+ if (closed) {
+ return 0;
+ }
+ return AutoResizingBufferMemoryManager.reclaimIdleBuffers(this,
targetBytes);
+ }
+
+ /** Reclaims buffers from the highest-priority idle connection in this
pool. */
+ public long reclaimOneIdleConnection() {
+ if (closed) {
+ return 0;
+ }
+ return AutoResizingBufferMemoryManager.reclaimOneIdleConnection(this);
+ }
+
+ /** Retires a stopped server while keeping its live connections eligible
for reclamation. */
+ public synchronized void retire() {
+ if (closed) {
+ return;
+ }
+ retired = true;
+ if (connectionsByTransport.isEmpty()) {
+ serverBufferPools.remove(this);
+ }
+ }
+
+ /** Associates initial buffer allocations and subsequent growth with this
server pool. */
+ public TTransportFactory wrapTransportFactory(TTransportFactory factory) {
+ return new TTransportFactory() {
+ @Override
+ public TTransport getTransport(TTransport transport) throws
TTransportException {
+ ServerBufferPool previousPool = constructingServerBufferPool.get();
+ constructingServerBufferPool.set(ServerBufferPool.this);
+ try {
+ TTransport serverTransport = factory.getTransport(transport);
+ if (serverTransport instanceof TElasticFramedTransport
framedTransport) {
+
framedTransport.registerForServerBufferReclamation(ServerBufferPool.this);
+ }
+ return serverTransport;
+ } finally {
+ if (previousPool == null) {
+ constructingServerBufferPool.remove();
+ } else {
+ constructingServerBufferPool.set(previousPool);
+ }
+ }
+ }
+ };
+ }
+
+ synchronized void register(TElasticFramedTransport transport) {
+ if (closed || transport.getServerConnectionState() != null) {
+ return;
+ }
+ ServerConnectionState state =
+ connectionsByTransport.computeIfAbsent(
+ transport.getSocket(), socket -> new
ServerConnectionState(this));
+ state.registerTransport(transport);
+ transport.setServerConnectionState(state);
+ invalidateReclamationCandidates();
+ if (retired) {
+ serverBufferPools.add(this);
+ serverBufferPoolsVersion.incrementAndGet();
+ otherPoolCandidateSnapshot.set(null);
+ }
+ }
+
+ synchronized void unregister(TElasticFramedTransport transport) {
+ ServerConnectionState state = transport.getServerConnectionState();
+ if (state != null && state.unregisterTransport(transport)) {
+ connectionsByTransport.remove(transport.getSocket());
+ if (retired && connectionsByTransport.isEmpty()) {
+ serverBufferPools.remove(this);
+ }
+ }
+ invalidateReclamationCandidates();
+ transport.setServerConnectionState(null);
+ }
+
+ private synchronized void collectCandidates(
+ List<ServerConnectionCandidate> candidates, long now) {
+ if (closed) {
+ return;
+ }
+ for (ServerConnectionState connection : connectionsByTransport.values())
{
+ ServerConnectionCandidate candidate =
connection.getReclamationCandidate(now);
+ if (candidate != null) {
+ candidates.add(candidate);
+ }
+ }
+ }
+
+ private long reclaimIdleBuffersInternal(long targetBytes) {
+ long reclaimedBytes = 0;
+ ServerConnectionCandidate candidate;
+ while (reclaimedBytes < targetBytes && (candidate =
nextReclamationCandidate()) != null) {
+ reclaimedBytes +=
candidate.connection().reclaimIdleBuffers(candidate.idleSinceNanos());
+ }
+ return reclaimedBytes;
+ }
+
+ private synchronized ServerConnectionCandidate nextReclamationCandidate() {
+ long version = reclamationCandidatesVersion.get();
+ if (exhaustedCandidateVersion == version) {
+ return null;
+ }
+ CandidateSnapshot snapshot = candidateSnapshot;
+ if (snapshot == null || snapshot.version != version) {
+ List<ServerConnectionCandidate> candidates = new ArrayList<>();
+ collectCandidates(candidates, System.nanoTime());
+ candidates.sort(ServerConnectionCandidate.RECLAMATION_ORDER);
+ snapshot = new CandidateSnapshot(version, candidates, null);
+ candidateSnapshot = snapshot;
+ }
+ ServerConnectionCandidate candidate = snapshot.nextCandidate();
+ if (candidate == null) {
+ candidateSnapshot = null;
+ exhaustedCandidateVersion = version;
+ }
+ return candidate;
+ }
+
+ private void invalidateReclamationCandidates() {
+ reclamationCandidatesVersion.incrementAndGet();
+ candidateSnapshot = null;
+ serverBufferPoolsVersion.incrementAndGet();
+ otherPoolCandidateSnapshot.set(null);
+ }
+
+ @Override
+ public synchronized void close() {
+ closed = true;
+ connectionsByTransport.clear();
+ invalidateReclamationCandidates();
+ serverBufferPools.remove(this);
+ }
+ }
+
+ static final class ServerConnectionState {
+ private final ServerBufferPool pool;
+ private final Set<TElasticFramedTransport> transports = new HashSet<>();
+ private boolean requestInProgress;
+ private long idleSinceNanos = System.nanoTime();
+
+ private ServerConnectionState(ServerBufferPool pool) {
+ this.pool = pool;
+ }
+
+ private synchronized void registerTransport(TElasticFramedTransport
transport) {
+ transports.add(transport);
+ }
+
+ private synchronized boolean unregisterTransport(TElasticFramedTransport
transport) {
+ transports.remove(transport);
+ return transports.isEmpty();
+ }
+
+ synchronized void setRequestInProgress(boolean requestInProgress) {
+ if (this.requestInProgress != requestInProgress) {
+ if (!requestInProgress) {
+ idleSinceNanos = System.nanoTime();
+ }
+ this.requestInProgress = requestInProgress;
+ pool.invalidateReclamationCandidates();
+ }
+ }
+
+ private synchronized ServerConnectionCandidate
getReclamationCandidate(long now) {
+ if (requestInProgress) {
+ return null;
+ }
+ long reclaimableBytes = 0;
+ long capacityBytes = 0;
+ for (TElasticFramedTransport transport : transports) {
+ reclaimableBytes += transport.getReclaimableBufferBytes();
+ capacityBytes += transport.getAccountedBufferBytes();
+ }
+ if (reclaimableBytes <= 0 || capacityBytes <= 0) {
+ return null;
+ }
+ return new ServerConnectionCandidate(
+ this,
+ idleSinceNanos,
+ Math.max(0, now - idleSinceNanos),
+ reclaimableBytes,
+ (double) reclaimableBytes / capacityBytes);
+ }
+
+ private synchronized long reclaimIdleBuffers(long expectedIdleSinceNanos) {
+ if (pool.closed || requestInProgress || idleSinceNanos !=
expectedIdleSinceNanos) {
+ return 0;
+ }
+ long reclaimedBytes = 0;
+ for (TElasticFramedTransport transport : transports) {
+ reclaimedBytes += transport.trimBuffersForReclamation();
+ }
+ return reclaimedBytes;
+ }
+ }
+
+ private record ServerConnectionCandidate(
+ ServerConnectionState connection,
+ long idleSinceNanos,
+ long idleTimeNanos,
+ long reclaimableBytes,
+ double reclaimableRatio) {
+ private static final Comparator<ServerConnectionCandidate>
RECLAMATION_ORDER =
+ Comparator.comparingLong(ServerConnectionCandidate::idleTimeNanos)
+ .reversed()
+ .thenComparing(
+
Comparator.comparingDouble(ServerConnectionCandidate::reclaimableRatio).reversed())
+ .thenComparing(
+
Comparator.comparingLong(ServerConnectionCandidate::reclaimableBytes).reversed());
+ }
+
+ private static final class CandidateSnapshot {
+ private final long version;
+ private final List<ServerConnectionCandidate> candidates;
+ private final ServerBufferPool excludedPool;
+ private int nextCandidateIndex;
+
+ private CandidateSnapshot(
+ long version, List<ServerConnectionCandidate> candidates,
ServerBufferPool excludedPool) {
+ this.version = version;
+ this.candidates = candidates;
+ this.excludedPool = excludedPool;
+ }
+
+ private synchronized ServerConnectionCandidate nextCandidate() {
+ if (nextCandidateIndex >= candidates.size()) {
+ return null;
+ }
+ return candidates.get(nextCandidateIndex++);
+ }
+ }
}
diff --git
a/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/AutoScalingBufferReadTransport.java
b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/AutoScalingBufferReadTransport.java
index 87a0e93b7d8..7712a145212 100644
---
a/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/AutoScalingBufferReadTransport.java
+++
b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/AutoScalingBufferReadTransport.java
@@ -136,4 +136,22 @@ public class AutoScalingBufferReadTransport extends
NonOpenTransport {
public void position(int newPosition) {
this.pos = newPosition;
}
+
+ int getAccountedBufferBytes() {
+ return buf.getAccountedCapacity();
+ }
+
+ int getReclaimableBufferBytes() {
+ return pos == limit ? buf.getReclaimableBytes() : 0;
+ }
+
+ long trimToInitialCapacity() {
+ if (pos != limit) {
+ return 0;
+ }
+ temporaryBuffer = null;
+ pos = 0;
+ limit = 0;
+ return buf.trimToInitialCapacity();
+ }
}
diff --git
a/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/AutoScalingBufferWriteTransport.java
b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/AutoScalingBufferWriteTransport.java
index 4450d8b6b40..ad87bc8e67b 100644
---
a/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/AutoScalingBufferWriteTransport.java
+++
b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/AutoScalingBufferWriteTransport.java
@@ -177,4 +177,20 @@ public class AutoScalingBufferWriteTransport extends
NonOpenTransport {
public void checkReadBytesAvailable(long numBytes) throws
TTransportException {
// do Nothing
}
+
+ int getAccountedBufferBytes() {
+ return buf.getAccountedCapacity();
+ }
+
+ int getReclaimableBufferBytes() {
+ return pos == 0 ? buf.getReclaimableBytes() : 0;
+ }
+
+ long trimToInitialCapacity() {
+ if (pos != 0) {
+ return 0;
+ }
+ temporaryBuffer = null;
+ return buf.trimToInitialCapacity();
+ }
}
diff --git
a/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/TCompressedElasticFramedTransport.java
b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/TCompressedElasticFramedTransport.java
index aa03783f81e..b05cb132de8 100644
---
a/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/TCompressedElasticFramedTransport.java
+++
b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/TCompressedElasticFramedTransport.java
@@ -77,6 +77,26 @@ public abstract class TCompressedElasticFramedTransport
extends TElasticFramedTr
}
}
+ @Override
+ long getAccountedBufferBytes() {
+ return super.getAccountedBufferBytes()
+ + writeCompressBuffer.getAccountedBufferBytes()
+ + readCompressBuffer.getAccountedBufferBytes();
+ }
+
+ @Override
+ long getReclaimableBufferBytes() {
+ return super.getReclaimableBufferBytes()
+ + writeCompressBuffer.getReclaimableBufferBytes()
+ + readCompressBuffer.getReclaimableBufferBytes();
+ }
+
+ @Override
+ protected long trimAdditionalBuffers() {
+ return (writeCompressBuffer == null ? 0 :
writeCompressBuffer.trimToInitialCapacity())
+ + (readCompressBuffer == null ? 0 :
readCompressBuffer.trimToInitialCapacity());
+ }
+
@Override
protected int getMaxWriteBufferSize() {
// Preserve the wire-size limit: a compressible payload may exceed
thriftMaxFrameSize before
@@ -87,8 +107,10 @@ public abstract class TCompressedElasticFramedTransport
extends TElasticFramedTr
@Override
protected void readFrame() throws TTransportException {
// Discard the previous frame's budget before reading the next frame
header and payload.
+ endServerRequest();
resetMessageSizeAndConsumedBytes();
underlying.readAll(i32buf, 0, 4);
+ beginServerRequest();
int size = TFramedTransport.decodeFrameSize(i32buf);
validateFrame(size);
readBuffer.fill(underlying, size);
diff --git
a/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/TElasticFramedTransport.java
b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/TElasticFramedTransport.java
index 7079b7987ea..5ecde48cab9 100644
---
a/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/TElasticFramedTransport.java
+++
b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/TElasticFramedTransport.java
@@ -19,6 +19,8 @@
package org.apache.iotdb.rpc;
+import org.apache.iotdb.rpc.AutoResizingBufferMemoryManager.ServerBufferPool;
+import
org.apache.iotdb.rpc.AutoResizingBufferMemoryManager.ServerConnectionState;
import org.apache.iotdb.rpc.i18n.RpcMessages;
import org.apache.thrift.TConfiguration;
@@ -146,6 +148,8 @@ public class TElasticFramedTransport extends TTransport {
protected AutoScalingBufferWriteTransport writeBuffer;
protected final byte[] i32buf = new byte[4];
private final boolean copyBinary;
+ private ServerBufferPool serverBufferPool;
+ private volatile ServerConnectionState serverConnectionState;
@Override
public boolean isOpen() {
@@ -153,12 +157,18 @@ public class TElasticFramedTransport extends TTransport {
}
@Override
- public void open() throws TTransportException {
+ public synchronized void open() throws TTransportException {
underlying.open();
+ if (serverBufferPool != null) {
+ serverBufferPool.register(this);
+ }
}
@Override
- public void close() {
+ public synchronized void close() {
+ if (serverBufferPool != null) {
+ serverBufferPool.unregister(this);
+ }
try {
underlying.close();
} finally {
@@ -175,6 +185,54 @@ public class TElasticFramedTransport extends TTransport {
}
}
+ synchronized void registerForServerBufferReclamation(ServerBufferPool pool) {
+ if (serverBufferPool == null) {
+ serverBufferPool = pool;
+ pool.register(this);
+ }
+ }
+
+ public void beginServerRequest() {
+ setServerRequestInProgress(true);
+ }
+
+ public void endServerRequest() {
+ setServerRequestInProgress(false);
+ }
+
+ ServerConnectionState getServerConnectionState() {
+ return serverConnectionState;
+ }
+
+ void setServerConnectionState(ServerConnectionState serverConnectionState) {
+ this.serverConnectionState = serverConnectionState;
+ }
+
+ long getAccountedBufferBytes() {
+ return (long) readBuffer.getAccountedBufferBytes() +
writeBuffer.getAccountedBufferBytes();
+ }
+
+ long getReclaimableBufferBytes() {
+ return (long) readBuffer.getReclaimableBufferBytes() +
writeBuffer.getReclaimableBufferBytes();
+ }
+
+ long trimBuffersForReclamation() {
+ return readBuffer.trimToInitialCapacity()
+ + writeBuffer.trimToInitialCapacity()
+ + trimAdditionalBuffers();
+ }
+
+ protected long trimAdditionalBuffers() {
+ return 0;
+ }
+
+ private void setServerRequestInProgress(boolean requestInProgress) {
+ ServerConnectionState state = serverConnectionState;
+ if (state != null) {
+ state.setRequestInProgress(requestInProgress);
+ }
+ }
+
@Override
public int read(byte[] buf, int off, int len) throws TTransportException {
int got = readBuffer.read(buf, off, len);
@@ -233,8 +291,10 @@ public class TElasticFramedTransport extends TTransport {
protected void readFrame() throws TTransportException {
// Discard the previous frame's budget before reading the next frame
header and payload.
+ endServerRequest();
resetMessageSizeAndConsumedBytes();
underlying.readAll(i32buf, 0, 4);
+ beginServerRequest();
int size = TFramedTransport.decodeFrameSize(i32buf);
validateFrame(size);
readBuffer.fill(underlying, size);
diff --git
a/iotdb-client/service-rpc/src/test/java/org/apache/iotdb/rpc/AutoResizingBufferTest.java
b/iotdb-client/service-rpc/src/test/java/org/apache/iotdb/rpc/AutoResizingBufferTest.java
index 8744d671170..5ad39eac8f6 100644
---
a/iotdb-client/service-rpc/src/test/java/org/apache/iotdb/rpc/AutoResizingBufferTest.java
+++
b/iotdb-client/service-rpc/src/test/java/org/apache/iotdb/rpc/AutoResizingBufferTest.java
@@ -20,16 +20,26 @@
package org.apache.iotdb.rpc;
import org.apache.thrift.transport.TMemoryBuffer;
+import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
+import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Random;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
public class AutoResizingBufferTest {
@@ -112,6 +122,465 @@ public class AutoResizingBufferTest {
Assert.assertEquals(0, memoryControl.getUsedMemoryInBytes());
}
+ @Test
+ public void testMemoryPressureReclaimsIdleServerTransportBuffers() throws
Exception {
+ memoryControl.setLimit(96);
+ AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
+ AutoResizingBufferMemoryManager.setMemoryAllocateRetryIntervalInMs(1);
+
+ try (AutoResizingBufferMemoryManager.ServerBufferPool pool =
+ AutoResizingBufferMemoryManager.createServerBufferPool()) {
+ try (TElasticFramedTransport transport = newServerTransport(pool, new
TMemoryBuffer(0))) {
+ transport.write(new byte[64]);
+ transport.flush();
+ Assert.assertEquals(64, transport.writeBuffer.getBuffer().length);
+ Assert.assertEquals(72, memoryControl.getUsedMemoryInBytes());
+
+ try (TElasticFramedTransport requester = newServerTransport(pool, new
TMemoryBuffer(0))) {
+ requester.write(new byte[32]);
+ requester.flush();
+ Assert.assertEquals(8, transport.writeBuffer.getBuffer().length);
+ Assert.assertEquals(32, requester.writeBuffer.getBuffer().length);
+ Assert.assertEquals(56, memoryControl.getUsedMemoryInBytes());
+ }
+ }
+ }
+ Assert.assertEquals(0, memoryControl.getUsedMemoryInBytes());
+ }
+
+ @Test
+ public void testMemoryPressureReusesPreferredPoolCandidateSnapshot() throws
Exception {
+ AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
+ AutoResizingBufferMemoryManager.setMemoryAllocateRetryIntervalInMs(1);
+
+ try (AutoResizingBufferMemoryManager.ServerBufferPool pool =
+ AutoResizingBufferMemoryManager.createServerBufferPool()) {
+ try (TElasticFramedTransport oldest = newServerTransport(pool, new
TMemoryBuffer(0));
+ TElasticFramedTransport newer = newServerTransport(pool, new
TMemoryBuffer(0));
+ TElasticFramedTransport firstRequester = newServerTransport(pool,
new TMemoryBuffer(0));
+ TElasticFramedTransport secondRequester =
+ newServerTransport(pool, new TMemoryBuffer(0))) {
+ oldest.write(new byte[64]);
+ oldest.flush();
+ Thread.sleep(10);
+ newer.write(new byte[64]);
+ newer.flush();
+ memoryControl.setLimit(memoryControl.getUsedMemoryInBytes());
+
+ firstRequester.write(new byte[16]);
+ firstRequester.flush();
+ Object candidateSnapshot =
+ getFieldValue(
+ pool, AutoResizingBufferMemoryManager.ServerBufferPool.class,
"candidateSnapshot");
+ Assert.assertNotNull(candidateSnapshot);
+
+ memoryControl.setLimit(memoryControl.getUsedMemoryInBytes());
+ secondRequester.write(new byte[16]);
+ secondRequester.flush();
+
+ Assert.assertSame(
+ candidateSnapshot,
+ getFieldValue(
+ pool, AutoResizingBufferMemoryManager.ServerBufferPool.class,
"candidateSnapshot"));
+ Assert.assertEquals(8, oldest.writeBuffer.getBuffer().length);
+ Assert.assertEquals(8, newer.writeBuffer.getBuffer().length);
+ }
+ }
+ Assert.assertEquals(0, memoryControl.getUsedMemoryInBytes());
+ }
+
+ @Test
+ public void testMemoryPressureReusesOtherPoolCandidateSnapshot() throws
Exception {
+ AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
+ AutoResizingBufferMemoryManager.setMemoryAllocateRetryIntervalInMs(1);
+
+ try (AutoResizingBufferMemoryManager.ServerBufferPool pool =
+ AutoResizingBufferMemoryManager.createServerBufferPool()) {
+ try (TElasticFramedTransport oldest = newServerTransport(pool, new
TMemoryBuffer(0));
+ TElasticFramedTransport newer = newServerTransport(pool, new
TMemoryBuffer(0));
+ TElasticFramedTransport firstRequester =
+ new TElasticFramedTransport(new TMemoryBuffer(0), 8, 128, true);
+ TElasticFramedTransport secondRequester =
+ new TElasticFramedTransport(new TMemoryBuffer(0), 8, 128, true))
{
+ oldest.write(new byte[64]);
+ oldest.flush();
+ Thread.sleep(10);
+ newer.write(new byte[64]);
+ newer.flush();
+ memoryControl.setLimit(memoryControl.getUsedMemoryInBytes());
+
+ firstRequester.write(new byte[16]);
+ firstRequester.flush();
+ Object candidateSnapshot =
+ getFieldValue(
+ null, AutoResizingBufferMemoryManager.class,
"otherPoolCandidateSnapshot");
+ Assert.assertNotNull(candidateSnapshot);
+
+ memoryControl.setLimit(memoryControl.getUsedMemoryInBytes());
+ secondRequester.write(new byte[16]);
+ secondRequester.flush();
+
+ Assert.assertSame(
+ candidateSnapshot,
+ getFieldValue(
+ null, AutoResizingBufferMemoryManager.class,
"otherPoolCandidateSnapshot"));
+ Assert.assertEquals(8, oldest.writeBuffer.getBuffer().length);
+ Assert.assertEquals(8, newer.writeBuffer.getBuffer().length);
+ }
+ }
+ Assert.assertEquals(0, memoryControl.getUsedMemoryInBytes());
+ }
+
+ @Test
+ public void testMemoryPressureDoesNotReclaimAnActiveServerTransport() throws
Exception {
+ memoryControl.setLimit(96);
+ AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
+ AutoResizingBufferMemoryManager.setMemoryAllocateRetryIntervalInMs(1);
+
+ try (AutoResizingBufferMemoryManager.ServerBufferPool pool =
+ AutoResizingBufferMemoryManager.createServerBufferPool()) {
+ try (TElasticFramedTransport transport = newServerTransport(pool, new
TMemoryBuffer(0))) {
+ transport.write(new byte[64]);
+ transport.flush();
+ transport.beginServerRequest();
+ try {
+ try (TElasticFramedTransport requester = newServerTransport(pool,
new TMemoryBuffer(0))) {
+ requester.write(new byte[32]);
+ Assert.fail("An active request must keep its buffers reserved");
+ } catch (TTransportException expected) {
+ Assert.assertEquals(
+ 1,
AutoResizingBufferMemoryManager.getMemoryAllocationFailureCount());
+ }
+ Assert.assertEquals(64, transport.writeBuffer.getBuffer().length);
+ Assert.assertEquals(72, memoryControl.getUsedMemoryInBytes());
+ } finally {
+ transport.endServerRequest();
+ }
+
+ try (TElasticFramedTransport requester = newServerTransport(pool, new
TMemoryBuffer(0))) {
+ requester.write(new byte[32]);
+ requester.flush();
+ Assert.assertEquals(8, transport.writeBuffer.getBuffer().length);
+ Assert.assertEquals(56, memoryControl.getUsedMemoryInBytes());
+ }
+ }
+ }
+ Assert.assertEquals(0, memoryControl.getUsedMemoryInBytes());
+ }
+
+ @Test
+ public void testMemoryPressureReclaimsOldestConnectionAndStopsWhenEnough()
throws Exception {
+ AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
+ AutoResizingBufferMemoryManager.setMemoryAllocateRetryIntervalInMs(1);
+
+ try (AutoResizingBufferMemoryManager.ServerBufferPool pool =
+ AutoResizingBufferMemoryManager.createServerBufferPool()) {
+ try (TElasticFramedTransport oldest = newServerTransport(pool, new
TMemoryBuffer(0))) {
+ oldest.write(new byte[32]);
+ oldest.flush();
+ Thread.sleep(10);
+
+ try (TElasticFramedTransport newer = newServerTransport(pool, new
TMemoryBuffer(0))) {
+ newer.write(new byte[64]);
+ newer.flush();
+
+ try (TElasticFramedTransport requester = newServerTransport(pool,
new TMemoryBuffer(0))) {
+ memoryControl.setLimit(memoryControl.getUsedMemoryInBytes());
+ requester.write(new byte[16]);
+ requester.flush();
+
+ Assert.assertEquals(8, oldest.writeBuffer.getBuffer().length);
+ Assert.assertEquals(64, newer.writeBuffer.getBuffer().length);
+ Assert.assertEquals(16, requester.writeBuffer.getBuffer().length);
+ }
+ }
+ }
+ }
+ Assert.assertEquals(0, memoryControl.getUsedMemoryInBytes());
+ }
+
+ @Test
+ public void testMemoryPressureDoesNotReclaimClosedServerPool() throws
Exception {
+ AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
+ AutoResizingBufferMemoryManager.setMemoryAllocateRetryIntervalInMs(1);
+
+ try (AutoResizingBufferMemoryManager.ServerBufferPool requesterPool =
+ AutoResizingBufferMemoryManager.createServerBufferPool();
+ AutoResizingBufferMemoryManager.ServerBufferPool otherPool =
+ AutoResizingBufferMemoryManager.createServerBufferPool()) {
+ try (TElasticFramedTransport otherPoolTransport =
+ newServerTransport(otherPool, new TMemoryBuffer(0));
+ TElasticFramedTransport requester =
+ newServerTransport(requesterPool, new TMemoryBuffer(0))) {
+ otherPoolTransport.write(new byte[64]);
+ otherPoolTransport.flush();
+ otherPool.close();
+ memoryControl.setLimit(memoryControl.getUsedMemoryInBytes());
+
+ try {
+ requester.write(new byte[32]);
+ Assert.fail("An unrelated pool must not be reclaimed");
+ } catch (TTransportException expected) {
+ Assert.assertEquals(64,
otherPoolTransport.writeBuffer.getBuffer().length);
+ Assert.assertEquals(88, memoryControl.getUsedMemoryInBytes());
+ }
+ }
+ }
+ Assert.assertEquals(0, memoryControl.getUsedMemoryInBytes());
+ }
+
+ @Test
+ public void testMemoryPressureFallsBackToAnotherServerPool() throws
Exception {
+ AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
+ AutoResizingBufferMemoryManager.setMemoryAllocateRetryIntervalInMs(1);
+
+ try (AutoResizingBufferMemoryManager.ServerBufferPool requesterPool =
+ AutoResizingBufferMemoryManager.createServerBufferPool();
+ AutoResizingBufferMemoryManager.ServerBufferPool otherPool =
+ AutoResizingBufferMemoryManager.createServerBufferPool()) {
+ try (TElasticFramedTransport otherPoolTransport =
+ newServerTransport(otherPool, new TMemoryBuffer(0));
+ TElasticFramedTransport requester =
+ newServerTransport(requesterPool, new TMemoryBuffer(0))) {
+ otherPoolTransport.write(new byte[64]);
+ otherPoolTransport.flush();
+ memoryControl.setLimit(memoryControl.getUsedMemoryInBytes());
+
+ requester.write(new byte[32]);
+ requester.flush();
+
+ Assert.assertEquals(8,
otherPoolTransport.writeBuffer.getBuffer().length);
+ Assert.assertEquals(32, requester.writeBuffer.getBuffer().length);
+ Assert.assertEquals(56, memoryControl.getUsedMemoryInBytes());
+ }
+ }
+ Assert.assertEquals(0, memoryControl.getUsedMemoryInBytes());
+ }
+
+ @Test
+ public void
testMemoryPressureReclaimsConnectionsRegisteredAfterPoolRetirement()
+ throws Exception {
+ AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
+ AutoResizingBufferMemoryManager.setMemoryAllocateRetryIntervalInMs(1);
+
+ try (AutoResizingBufferMemoryManager.ServerBufferPool pool =
+ AutoResizingBufferMemoryManager.createServerBufferPool()) {
+ pool.retire();
+ try (TElasticFramedTransport serverTransport =
+ newServerTransport(pool, new TMemoryBuffer(0))) {
+ serverTransport.write(new byte[64]);
+ serverTransport.flush();
+ long memoryBeforeClientAllocation =
memoryControl.getUsedMemoryInBytes();
+ memoryControl.setLimit(memoryBeforeClientAllocation);
+
+ try (TElasticFramedTransport clientTransport =
+ new TElasticFramedTransport(new TMemoryBuffer(0), 8, 128, true)) {
+ Assert.assertTrue(memoryControl.getUsedMemoryInBytes() <
memoryBeforeClientAllocation);
+ }
+ }
+ }
+ Assert.assertEquals(0, memoryControl.getUsedMemoryInBytes());
+ }
+
+ @Test
+ public void testMemoryPressureReclaimsExistingConnectionsFromRetiredPool()
throws Exception {
+ AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
+ AutoResizingBufferMemoryManager.setMemoryAllocateRetryIntervalInMs(1);
+
+ try (AutoResizingBufferMemoryManager.ServerBufferPool pool =
+ AutoResizingBufferMemoryManager.createServerBufferPool()) {
+ try (TElasticFramedTransport serverTransport =
+ newServerTransport(pool, new TMemoryBuffer(0))) {
+ serverTransport.write(new byte[64]);
+ serverTransport.flush();
+ pool.retire();
+ long memoryBeforeClientAllocation =
memoryControl.getUsedMemoryInBytes();
+ memoryControl.setLimit(memoryBeforeClientAllocation);
+
+ try (TElasticFramedTransport clientTransport =
+ new TElasticFramedTransport(new TMemoryBuffer(0), 8, 128, true)) {
+ Assert.assertTrue(memoryControl.getUsedMemoryInBytes() <
memoryBeforeClientAllocation);
+ }
+ }
+ }
+ Assert.assertEquals(0, memoryControl.getUsedMemoryInBytes());
+ }
+
+ @Test
+ public void testMemoryPressurePrefersRequestingPoolBeforeOtherPools() throws
Exception {
+ AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
+ AutoResizingBufferMemoryManager.setMemoryAllocateRetryIntervalInMs(1);
+
+ try (AutoResizingBufferMemoryManager.ServerBufferPool otherPool =
+ AutoResizingBufferMemoryManager.createServerBufferPool();
+ AutoResizingBufferMemoryManager.ServerBufferPool preferredPool =
+ AutoResizingBufferMemoryManager.createServerBufferPool()) {
+ try (TElasticFramedTransport otherPoolTransport =
+ newServerTransport(otherPool, new TMemoryBuffer(0))) {
+ otherPoolTransport.write(new byte[64]);
+ otherPoolTransport.flush();
+ Thread.sleep(10);
+
+ try (TElasticFramedTransport preferredPoolTransport =
+ newServerTransport(preferredPool, new TMemoryBuffer(0));
+ TElasticFramedTransport requester =
+ newServerTransport(preferredPool, new TMemoryBuffer(0))) {
+ preferredPoolTransport.write(new byte[32]);
+ preferredPoolTransport.flush();
+ memoryControl.setLimit(memoryControl.getUsedMemoryInBytes());
+
+ requester.write(new byte[16]);
+ requester.flush();
+
+ Assert.assertEquals(64,
otherPoolTransport.writeBuffer.getBuffer().length);
+ Assert.assertEquals(8,
preferredPoolTransport.writeBuffer.getBuffer().length);
+ Assert.assertEquals(16, requester.writeBuffer.getBuffer().length);
+ }
+ }
+ }
+ Assert.assertEquals(0, memoryControl.getUsedMemoryInBytes());
+ }
+
+ @Test
+ public void testClientBufferAllocationCanReclaimIdleServerBuffers() throws
Exception {
+ AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
+ AutoResizingBufferMemoryManager.setMemoryAllocateRetryIntervalInMs(1);
+
+ try (AutoResizingBufferMemoryManager.ServerBufferPool serverPool =
+ AutoResizingBufferMemoryManager.createServerBufferPool()) {
+ try (TElasticFramedTransport serverTransport =
+ newServerTransport(serverPool, new TMemoryBuffer(0));
+ TElasticFramedTransport clientTransport =
+ new TElasticFramedTransport(new TMemoryBuffer(0), 8, 2048,
true)) {
+ serverTransport.write(new byte[64]);
+ serverTransport.flush();
+ memoryControl.setLimit(memoryControl.getUsedMemoryInBytes());
+
+ clientTransport.write(new byte[32]);
+ clientTransport.flush();
+
+ Assert.assertEquals(8, serverTransport.writeBuffer.getBuffer().length);
+ Assert.assertEquals(32,
clientTransport.writeBuffer.getBuffer().length);
+ }
+ }
+ Assert.assertEquals(0, memoryControl.getUsedMemoryInBytes());
+ }
+
+ @Test
+ public void testReclaimOneIdleConnectionKeepsOtherConnectionsUnchanged()
throws Exception {
+ AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
+
+ try (AutoResizingBufferMemoryManager.ServerBufferPool pool =
+ AutoResizingBufferMemoryManager.createServerBufferPool()) {
+ try (TElasticFramedTransport oldest = newServerTransport(pool, new
TMemoryBuffer(0))) {
+ oldest.write(new byte[32]);
+ oldest.flush();
+ Thread.sleep(10);
+
+ try (TElasticFramedTransport newer = newServerTransport(pool, new
TMemoryBuffer(0))) {
+ newer.write(new byte[64]);
+ newer.flush();
+
+ Assert.assertTrue(pool.reclaimOneIdleConnection() > 0);
+ Assert.assertEquals(8, oldest.writeBuffer.getBuffer().length);
+ Assert.assertEquals(64, newer.writeBuffer.getBuffer().length);
+ }
+ }
+ }
+ Assert.assertEquals(0, memoryControl.getUsedMemoryInBytes());
+ }
+
+ @Test
+ public void testReclaimOneIdleConnectionRefreshesCandidateSnapshot() throws
Exception {
+ AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
+
+ try (AutoResizingBufferMemoryManager.ServerBufferPool pool =
+ AutoResizingBufferMemoryManager.createServerBufferPool()) {
+ try (TElasticFramedTransport oldest = newServerTransport(pool, new
TMemoryBuffer(0))) {
+ oldest.write(new byte[32]);
+ oldest.flush();
+ Thread.sleep(10);
+
+ try (TElasticFramedTransport next = newServerTransport(pool, new
TMemoryBuffer(0))) {
+ next.write(new byte[64]);
+ next.flush();
+
+ Assert.assertTrue(pool.reclaimOneIdleConnection() > 0);
+ Assert.assertEquals(8, oldest.writeBuffer.getBuffer().length);
+
+ next.getServerConnectionState().setRequestInProgress(true);
+ try (TElasticFramedTransport newest = newServerTransport(pool, new
TMemoryBuffer(0))) {
+ newest.write(new byte[48]);
+ newest.flush();
+
+ Assert.assertTrue(pool.reclaimOneIdleConnection() > 0);
+ Assert.assertEquals(8, newest.writeBuffer.getBuffer().length);
+
+ next.getServerConnectionState().setRequestInProgress(false);
+ Assert.assertTrue(pool.reclaimOneIdleConnection() > 0);
+ Assert.assertEquals(8, next.writeBuffer.getBuffer().length);
+ }
+ }
+ }
+ }
+ Assert.assertEquals(0, memoryControl.getUsedMemoryInBytes());
+ }
+
+ @Test
+ public void
testMemoryPressureReclaimsBothServerTransportsWhileWaitingForNextFrame()
+ throws Exception {
+ AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
+ AutoResizingBufferMemoryManager.setMemoryAllocateRetryIntervalInMs(1);
+
+ BlockingServerTransport socket = new BlockingServerTransport();
+ try (AutoResizingBufferMemoryManager.ServerBufferPool pool =
+ AutoResizingBufferMemoryManager.createServerBufferPool();
+ TElasticFramedTransport input = newServerTransport(pool, socket);
+ TElasticFramedTransport output = newServerTransport(pool, socket)) {
+
+ byte[] firstFrame = new byte[64];
+ Arrays.fill(firstFrame, (byte) 7);
+ socket.offerFrame(firstFrame);
+ byte[] firstRead = new byte[firstFrame.length];
+ input.readAll(firstRead, 0, firstRead.length);
+ Assert.assertArrayEquals(firstFrame, firstRead);
+ output.write(firstFrame, 0, firstFrame.length);
+ output.flush();
+ Assert.assertEquals(64, input.readBuffer.getBuffer().length);
+ Assert.assertEquals(64, output.writeBuffer.getBuffer().length);
+
+ memoryControl.setLimit(memoryControl.getUsedMemoryInBytes());
+ ExecutorService reader = Executors.newSingleThreadExecutor();
+ try {
+ byte[] secondFrame = new byte[8];
+ Future<byte[]> nextRead =
+ reader.submit(
+ () -> {
+ byte[] result = new byte[secondFrame.length];
+ input.readAll(result, 0, result.length);
+ return result;
+ });
+ Assert.assertTrue(socket.awaitWaitingForNextFrame(5,
TimeUnit.SECONDS));
+
+ try (TElasticFramedTransport requester = newServerTransport(pool, new
TMemoryBuffer(0))) {
+ Assert.assertEquals(8, input.readBuffer.getBuffer().length);
+ Assert.assertEquals(8, output.writeBuffer.getBuffer().length);
+ Assert.assertEquals(0, input.readBuffer.getBufferPosition());
+ Assert.assertEquals(0, input.readBuffer.getBytesRemainingInBuffer());
+ Assert.assertEquals(48, memoryControl.getUsedMemoryInBytes());
+ }
+
+ Arrays.fill(secondFrame, (byte) 9);
+ socket.offerFrame(secondFrame);
+ Assert.assertArrayEquals(secondFrame, nextRead.get(5,
TimeUnit.SECONDS));
+ } finally {
+ reader.shutdownNow();
+ Assert.assertTrue(reader.awaitTermination(5, TimeUnit.SECONDS));
+ }
+ }
+ Assert.assertEquals(0, memoryControl.getUsedMemoryInBytes());
+ }
+
@Test
public void testCrossingReuseThresholdWithinCapacityUsesTemporaryBuffer()
throws Exception {
AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
@@ -685,6 +1154,14 @@ public class AutoResizingBufferTest {
field.set(buffer, lastShrinkTime);
}
+ private Object getFieldValue(Object target, Class<?> declaringClass, String
fieldName)
+ throws Exception {
+ Field field = declaringClass.getDeclaredField(fieldName);
+ field.setAccessible(true);
+ Object value = field.get(target);
+ return value instanceof AtomicReference<?> reference ? reference.get() :
value;
+ }
+
private void setLastShrinkTime(Object transport, long lastShrinkTime) throws
Exception {
Field field = transport.getClass().getDeclaredField("buf");
field.setAccessible(true);
@@ -697,10 +1174,101 @@ public class AutoResizingBufferTest {
: new TElasticFramedTransport(new TMemoryBuffer(0), 100, 2048, true);
}
+ private TElasticFramedTransport newServerTransport(
+ AutoResizingBufferMemoryManager.ServerBufferPool pool, TTransport socket)
+ throws TTransportException {
+ return (TElasticFramedTransport)
+ pool.wrapTransportFactory(new TElasticFramedTransport.Factory(8, 128,
false))
+ .getTransport(socket);
+ }
+
+ private static class BlockingServerTransport extends
org.apache.thrift.transport.TTransport {
+
+ private final BlockingQueue<byte[]> frames = new LinkedBlockingQueue<>();
+ private final ByteArrayOutputStream writes = new ByteArrayOutputStream();
+ private final CountDownLatch waitingForNextFrame = new CountDownLatch(1);
+ private byte[] currentFrame;
+ private int currentFramePosition;
+ private boolean open = true;
+
+ private void offerFrame(byte[] payload) {
+ byte[] frame = new byte[payload.length + Integer.BYTES];
+ frame[0] = (byte) (payload.length >>> 24);
+ frame[1] = (byte) (payload.length >>> 16);
+ frame[2] = (byte) (payload.length >>> 8);
+ frame[3] = (byte) payload.length;
+ System.arraycopy(payload, 0, frame, Integer.BYTES, payload.length);
+ frames.add(frame);
+ }
+
+ private boolean awaitWaitingForNextFrame(long timeout, TimeUnit unit)
+ throws InterruptedException {
+ return waitingForNextFrame.await(timeout, unit);
+ }
+
+ @Override
+ public boolean isOpen() {
+ return open;
+ }
+
+ @Override
+ public void open() {
+ open = true;
+ }
+
+ @Override
+ public void close() {
+ open = false;
+ }
+
+ @Override
+ public int read(byte[] buffer, int offset, int length)
+ throws org.apache.thrift.transport.TTransportException {
+ try {
+ if (currentFrame == null || currentFramePosition ==
currentFrame.length) {
+ if (frames.isEmpty()) {
+ waitingForNextFrame.countDown();
+ }
+ currentFrame = frames.take();
+ currentFramePosition = 0;
+ }
+ int bytesToRead = Math.min(length, currentFrame.length -
currentFramePosition);
+ System.arraycopy(currentFrame, currentFramePosition, buffer, offset,
bytesToRead);
+ currentFramePosition += bytesToRead;
+ return bytesToRead;
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new org.apache.thrift.transport.TTransportException(e);
+ }
+ }
+
+ @Override
+ public void write(byte[] buffer, int offset, int length) {
+ writes.write(buffer, offset, length);
+ }
+
+ @Override
+ public void flush() {}
+
+ @Override
+ public org.apache.thrift.TConfiguration getConfiguration() {
+ return null;
+ }
+
+ @Override
+ public void updateKnownMessageSize(long size) {}
+
+ @Override
+ public void checkReadBytesAvailable(long numBytes) {}
+
+ @Override
+ public void resetMessageSizeAndConsumedBytes(long newSize) {}
+ }
+
private static class TestMemoryControl implements
AutoResizingBufferMemoryControl {
private final AtomicLong usedMemoryInBytes = new AtomicLong();
- private long limit = Long.MAX_VALUE;
+ private volatile long limit = Long.MAX_VALUE;
@Override
public boolean allocate(long sizeInBytes) {
diff --git
a/iotdb-client/service-rpc/src/test/java/org/apache/iotdb/rpc/TCompressedElasticFramedTransportTest.java
b/iotdb-client/service-rpc/src/test/java/org/apache/iotdb/rpc/TCompressedElasticFramedTransportTest.java
index 829dce8a27b..7e956b973e1 100644
---
a/iotdb-client/service-rpc/src/test/java/org/apache/iotdb/rpc/TCompressedElasticFramedTransportTest.java
+++
b/iotdb-client/service-rpc/src/test/java/org/apache/iotdb/rpc/TCompressedElasticFramedTransportTest.java
@@ -47,15 +47,25 @@ public class TCompressedElasticFramedTransportTest {
private static final int MAX_FRAME_SIZE = 4096;
private final AtomicLong usedMemory = new AtomicLong();
+ private final AtomicLong memoryLimit = new AtomicLong(Long.MAX_VALUE);
@Before
public void setUp() {
+ memoryLimit.set(Long.MAX_VALUE);
AutoResizingBufferMemoryManager.setMemoryControl(
new AutoResizingBufferMemoryControl() {
@Override
public boolean allocate(long sizeInBytes) {
- usedMemory.addAndGet(sizeInBytes);
- return true;
+ while (true) {
+ long current = usedMemory.get();
+ long next = current + sizeInBytes;
+ if (next > memoryLimit.get()) {
+ return false;
+ }
+ if (usedMemory.compareAndSet(current, next)) {
+ return true;
+ }
+ }
}
@Override
@@ -255,6 +265,35 @@ public class TCompressedElasticFramedTransportTest {
assertEquals(0, usedMemory.get());
}
+ @Test
+ public void testMemoryPressureReclaimsAllCompressedServerBuffers() throws
Exception {
+ AutoResizingBufferMemoryManager.setMemoryAllocateRetryIntervalInMs(1);
+ try (AutoResizingBufferMemoryManager.ServerBufferPool pool =
+ AutoResizingBufferMemoryManager.createServerBufferPool();
+ TSnappyElasticFramedTransport transport =
+ (TSnappyElasticFramedTransport)
+ pool.wrapTransportFactory(
+ new TSnappyElasticFramedTransport.Factory(
+ INITIAL_CAPACITY, MAX_FRAME_SIZE, false))
+ .getTransport(new TMemoryBuffer(0))) {
+ roundTrip(transport, randomBytes(1024));
+ for (AutoResizingBuffer buffer : reusableBuffers(transport)) {
+ assertTrue(buffer.array().length > INITIAL_CAPACITY);
+ }
+ transport.endServerRequest();
+
+ memoryLimit.set(5L * INITIAL_CAPACITY);
+ assertTrue(pool.reclaimIdleBuffers(INITIAL_CAPACITY) >=
INITIAL_CAPACITY);
+ try (AutoResizingBuffer allocation = new
AutoResizingBuffer(INITIAL_CAPACITY)) {
+ for (AutoResizingBuffer buffer : reusableBuffers(transport)) {
+ assertEquals(INITIAL_CAPACITY, buffer.array().length);
+ }
+ assertEquals(5L * INITIAL_CAPACITY, usedMemory.get());
+ }
+ }
+ assertEquals(0, usedMemory.get());
+ }
+
private void roundTrip(TSnappyElasticFramedTransport transport, byte[]
payload)
throws TTransportException {
transport.write(payload);
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/consensus/statemachine/dataregion/DataRegionStateMachine.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/consensus/statemachine/dataregion/DataRegionStateMachine.java
index ce9663bc886..ffcce91d07b 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/consensus/statemachine/dataregion/DataRegionStateMachine.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/consensus/statemachine/dataregion/DataRegionStateMachine.java
@@ -37,6 +37,7 @@ import org.apache.iotdb.db.pipe.agent.PipeDataNodeAgent;
import
org.apache.iotdb.db.queryengine.execution.fragment.FragmentInstanceManager;
import org.apache.iotdb.db.queryengine.plan.planner.plan.FragmentInstance;
import org.apache.iotdb.db.queryengine.plan.planner.plan.node.write.SearchNode;
+import org.apache.iotdb.db.service.ExternalRPCService;
import org.apache.iotdb.db.storageengine.StorageEngine;
import org.apache.iotdb.db.storageengine.buffer.BloomFilterCache;
import org.apache.iotdb.db.storageengine.buffer.ChunkCache;
@@ -82,6 +83,11 @@ public class DataRegionStateMachine extends BaseStateMachine
{
// do nothing
}
+ @Override
+ public void notifyNotLeader() {
+ ExternalRPCService.getInstance().reclaimOneIdleServerConnection();
+ }
+
@Override
public boolean isReadOnly() {
return CommonDescriptor.getInstance().getConfig().isReadOnly();
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/consensus/statemachine/schemaregion/SchemaRegionStateMachine.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/consensus/statemachine/schemaregion/SchemaRegionStateMachine.java
index 65e58648236..c22a10ecdde 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/consensus/statemachine/schemaregion/SchemaRegionStateMachine.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/consensus/statemachine/schemaregion/SchemaRegionStateMachine.java
@@ -35,6 +35,7 @@ import
org.apache.iotdb.db.queryengine.execution.fragment.FragmentInstanceManage
import org.apache.iotdb.db.queryengine.plan.planner.plan.FragmentInstance;
import org.apache.iotdb.db.schemaengine.schemaregion.ISchemaRegion;
import
org.apache.iotdb.db.schemaengine.schemaregion.attribute.update.GeneralRegionAttributeSecurityService;
+import org.apache.iotdb.db.service.ExternalRPCService;
import org.apache.iotdb.db.tools.schema.SchemaRegionSnapshotParser;
import org.apache.iotdb.rpc.TSStatusCode;
@@ -84,6 +85,8 @@ public class SchemaRegionStateMachine extends
BaseStateMachine {
@Override
public void notifyNotLeader() {
+ ExternalRPCService.getInstance().reclaimOneIdleServerConnection();
+
final int dataNodeId =
IoTDBDescriptor.getInstance().getConfig().getDataNodeId();
logger.info(
DataNodePipeMessages
diff --git
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/service/AbstractThriftServiceThread.java
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/service/AbstractThriftServiceThread.java
index ea4a6445a16..e0bbc82e051 100644
---
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/service/AbstractThriftServiceThread.java
+++
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/service/AbstractThriftServiceThread.java
@@ -24,6 +24,8 @@ import
org.apache.iotdb.commons.concurrent.threadpool.WrappedThreadPoolExecutor;
import org.apache.iotdb.commons.conf.IoTDBConstant;
import org.apache.iotdb.commons.exception.runtime.RPCServiceException;
import org.apache.iotdb.commons.i18n.ServiceMessages;
+import org.apache.iotdb.rpc.AutoResizingBufferMemoryManager;
+import org.apache.iotdb.rpc.AutoResizingBufferMemoryManager.ServerBufferPool;
import org.apache.iotdb.rpc.RpcSslUtils;
import org.apache.thrift.TBaseAsyncProcessor;
@@ -65,6 +67,7 @@ public abstract class AbstractThriftServiceThread extends
Thread {
private TProtocolFactory protocolFactory;
private TTransportFactory transportFactory;
+ private volatile ServerBufferPool serverBufferPool;
// currently, we can reuse the ProtocolFactory instance.
private static TCompactProtocol.Factory compactProtocolFactory = new
TCompactProtocol.Factory();
@@ -238,7 +241,12 @@ public abstract class AbstractThriftServiceThread extends
Thread {
poolArgs.executorService = executorService;
poolArgs.processor(processor);
poolArgs.protocolFactory(protocolFactory);
- poolArgs.transportFactory(getTTransportFactory());
+ TTransportFactory factory = getTTransportFactory();
+ if (factory != null) {
+ serverBufferPool =
AutoResizingBufferMemoryManager.createServerBufferPool();
+ factory = serverBufferPool.wrapTransportFactory(factory);
+ }
+ poolArgs.transportFactory(factory);
return poolArgs;
}
@@ -334,6 +342,10 @@ public abstract class AbstractThriftServiceThread extends
Thread {
}
public synchronized void close() {
+ if (serverBufferPool != null) {
+ serverBufferPool.retire();
+ serverBufferPool = null;
+ }
if (poolServer != null) {
poolServer.setShouldStop(true);
poolServer.stop();
@@ -350,6 +362,16 @@ public abstract class AbstractThriftServiceThread extends
Thread {
}
}
+ public long reclaimIdleServerBuffers(long targetBytes) {
+ ServerBufferPool pool = serverBufferPool;
+ return pool == null ? 0 : pool.reclaimIdleBuffers(targetBytes);
+ }
+
+ public long reclaimOneIdleServerConnection() {
+ ServerBufferPool pool = serverBufferPool;
+ return pool == null ? 0 : pool.reclaimOneIdleConnection();
+ }
+
public boolean isServing() {
if (poolServer != null) {
return poolServer.isServing();
diff --git
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/service/ThriftService.java
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/service/ThriftService.java
index 0edc1461654..a06cf7d61cb 100644
---
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/service/ThriftService.java
+++
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/service/ThriftService.java
@@ -41,7 +41,7 @@ public abstract class ThriftService implements IService {
String.format(
"%s:%s=%s",
IoTDBConstant.IOTDB_SERVICE_JMX_NAME, IoTDBConstant.JMX_TYPE,
getID().getJmxName());
- protected AbstractThriftServiceThread thriftServiceThread;
+ protected volatile AbstractThriftServiceThread thriftServiceThread;
protected TProcessor processor;
private CountDownLatch stopLatch;
@@ -66,6 +66,16 @@ public abstract class ThriftService implements IService {
}
}
+ public long reclaimIdleServerBuffers(long targetBytes) {
+ AbstractThriftServiceThread serviceThread = thriftServiceThread;
+ return serviceThread == null ? 0 :
serviceThread.reclaimIdleServerBuffers(targetBytes);
+ }
+
+ public long reclaimOneIdleServerConnection() {
+ AbstractThriftServiceThread serviceThread = thriftServiceThread;
+ return serviceThread == null ? 0 :
serviceThread.reclaimOneIdleServerConnection();
+ }
+
@Override
public void start() throws StartupException {
JMXService.registerMBean(this, mbeanName);
diff --git
a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/service/ThriftServerBufferReclamationTest.java
b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/service/ThriftServerBufferReclamationTest.java
new file mode 100644
index 00000000000..a6492dadb78
--- /dev/null
+++
b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/service/ThriftServerBufferReclamationTest.java
@@ -0,0 +1,326 @@
+/*
+ * 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
+ * under the Apache License, Version 2.0.
+ * 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.iotdb.commons.service;
+
+import org.apache.iotdb.rpc.AutoResizingBufferMemoryControl;
+import org.apache.iotdb.rpc.AutoResizingBufferMemoryManager;
+import org.apache.iotdb.rpc.AutoResizingBufferMemoryManager.ServerBufferPool;
+import org.apache.iotdb.rpc.TElasticFramedTransport;
+
+import org.apache.thrift.protocol.TBinaryProtocol;
+import org.apache.thrift.server.TThreadPoolServer;
+import org.apache.thrift.transport.TMemoryBuffer;
+import org.apache.thrift.transport.TServerSocket;
+import org.apache.thrift.transport.TSocket;
+import org.apache.thrift.transport.TTransport;
+import org.apache.thrift.transport.TTransportException;
+import org.apache.thrift.transport.TTransportFactory;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.net.InetAddress;
+import java.net.ServerSocket;
+import java.nio.ByteBuffer;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class ThriftServerBufferReclamationTest {
+
+ private final TestMemoryControl memoryControl = new TestMemoryControl();
+
+ @Before
+ public void setUp() {
+ AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
+ }
+
+ @After
+ public void tearDown() {
+ AutoResizingBufferMemoryManager.setMemoryControl(
+ new AutoResizingBufferMemoryControl() {
+ @Override
+ public boolean allocate(long sizeInBytes) {
+ return true;
+ }
+
+ @Override
+ public void release(long sizeInBytes) {}
+ });
+ }
+
+ @Test
+ public void
testNewConnectionReclaimsIdleBuffersAndKeepsOldConnectionUsable() throws
Exception {
+ int port;
+ try (ServerSocket portProbe = new ServerSocket(0)) {
+ port = portProbe.getLocalPort();
+ }
+ TServerSocket serverSocket = new TServerSocket(port);
+ ServerBufferPool serverBufferPool =
AutoResizingBufferMemoryManager.createServerBufferPool();
+ CountDownLatch secondProcessorCall = new CountDownLatch(1);
+ AtomicInteger processorCalls = new AtomicInteger();
+ TThreadPoolServer.Args args =
+ new TThreadPoolServer.Args(serverSocket)
+ .minWorkerThreads(0)
+ .maxWorkerThreads(4)
+ .protocolFactory(new TBinaryProtocol.Factory())
+ .processor(
+ (input, output) -> {
+ if (processorCalls.incrementAndGet() == 2) {
+ secondProcessorCall.countDown();
+ }
+ output.writeBinary(input.readBinary());
+ output.getTransport().flush();
+ })
+ .transportFactory(
+ serverBufferPool.wrapTransportFactory(
+ new TElasticFramedTransport.Factory(8, 2048, true)));
+ ExecutorService workers = Executors.newFixedThreadPool(4);
+ args.executorService(workers);
+ TThreadPoolServer server = new TThreadPoolServer(args);
+ Thread serverThread = new Thread(server::serve);
+ serverThread.setDaemon(true);
+ serverThread.start();
+
+ try {
+ await().atMost(5, TimeUnit.SECONDS).until(server::isServing);
+ try (TElasticFramedTransport first = createClientTransport(port);
+ TElasticFramedTransport second = createClientTransport(port)) {
+ first.open();
+ echo(first, new byte[128]);
+ assertTrue(secondProcessorCall.await(5, TimeUnit.SECONDS));
+ memoryControl.setLimit(memoryControl.getUsedMemoryInBytes());
+
+ second.open();
+ echo(second, new byte[8]);
+ echo(first, new byte[8]);
+ }
+ } finally {
+ server.stop();
+ serverBufferPool.close();
+ serverSocket.close();
+ workers.shutdownNow();
+ assertTrue(workers.awaitTermination(10, TimeUnit.SECONDS));
+ serverThread.join(10_000);
+ assertFalse(serverThread.isAlive());
+ }
+ assertEquals(0, memoryControl.getUsedMemoryInBytes());
+ }
+
+ @Test
+ public void testServiceCloseKeepsAcceptedIdleConnectionReclaimable() throws
Exception {
+ int port;
+ try (ServerSocket portProbe = new ServerSocket(0)) {
+ port = portProbe.getLocalPort();
+ }
+ CountDownLatch waitingForNextFrame = new CountDownLatch(1);
+ AtomicInteger frameReads = new AtomicInteger();
+ TTransportFactory transportFactory =
+ new TTransportFactory() {
+ @Override
+ public TTransport getTransport(TTransport transport) throws
TTransportException {
+ return new TElasticFramedTransport(transport, 8, 2048, true) {
+ @Override
+ protected void readFrame() throws TTransportException {
+ if (frameReads.incrementAndGet() > 1) {
+ endServerRequest();
+ waitingForNextFrame.countDown();
+ }
+ super.readFrame();
+ }
+ };
+ }
+ };
+ ThriftServiceThread server =
+ new ThriftServiceThread(
+ (input, output) -> {
+ ByteBuffer request = input.readBinary();
+ output.writeBinary(request);
+ output.getTransport().flush();
+ },
+ "test-service",
+ "test-service-thread",
+ InetAddress.getLoopbackAddress().getHostAddress(),
+ port,
+ 4,
+ 1,
+ null,
+ false,
+ transportFactory);
+ TElasticFramedTransport client = createClientTransport(port);
+ server.start();
+
+ try {
+ await().atMost(5, TimeUnit.SECONDS).until(server::isServing);
+ client.open();
+ echo(client, new byte[256]);
+ assertTrue(waitingForNextFrame.await(5, TimeUnit.SECONDS));
+ long memoryBeforeClose = memoryControl.getUsedMemoryInBytes();
+ assertTrue(memoryBeforeClose > 0);
+
+ server.close();
+ assertEquals(memoryBeforeClose, memoryControl.getUsedMemoryInBytes());
+ memoryControl.setLimit(memoryBeforeClose);
+ try (TElasticFramedTransport requester =
+ new TElasticFramedTransport(new TMemoryBuffer(0), 8, 2048, true)) {
+ assertTrue(memoryControl.getUsedMemoryInBytes() < memoryBeforeClose);
+ }
+ } finally {
+ server.close();
+ client.close();
+ server.join(10_000);
+ assertFalse(server.isAlive());
+ }
+ await().atMost(5, TimeUnit.SECONDS).until(() ->
memoryControl.getUsedMemoryInBytes() == 0);
+ }
+
+ @Test
+ public void testProcessorExecutionIsProtectedFromBufferReclamation() throws
Exception {
+ int port;
+ try (ServerSocket portProbe = new ServerSocket(0)) {
+ port = portProbe.getLocalPort();
+ }
+ TServerSocket serverSocket = new TServerSocket(port);
+ ServerBufferPool serverBufferPool =
AutoResizingBufferMemoryManager.createServerBufferPool();
+ CountDownLatch processorStarted = new CountDownLatch(1);
+ CountDownLatch allowProcessorToFinish = new CountDownLatch(1);
+ TThreadPoolServer.Args args =
+ new TThreadPoolServer.Args(serverSocket)
+ .minWorkerThreads(0)
+ .maxWorkerThreads(4)
+ .protocolFactory(new TBinaryProtocol.Factory())
+ .processor(
+ (input, output) -> {
+ ByteBuffer request = input.readBinary();
+ processorStarted.countDown();
+ try {
+ if (!allowProcessorToFinish.await(5, TimeUnit.SECONDS)) {
+ throw new TTransportException();
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new TTransportException(e);
+ }
+ output.writeBinary(request);
+ output.getTransport().flush();
+ })
+ .transportFactory(
+ serverBufferPool.wrapTransportFactory(
+ new TElasticFramedTransport.Factory(8, 2048, true)));
+ ExecutorService workers = Executors.newFixedThreadPool(4);
+ ExecutorService clientExecutor = Executors.newSingleThreadExecutor();
+ args.executorService(workers);
+ TThreadPoolServer server = new TThreadPoolServer(args);
+ Thread serverThread = new Thread(server::serve);
+ serverThread.setDaemon(true);
+ serverThread.start();
+ TElasticFramedTransport client = createClientTransport(port);
+
+ try {
+ await().atMost(5, TimeUnit.SECONDS).until(server::isServing);
+ client.open();
+ Future<?> request =
+ clientExecutor.submit(
+ () -> {
+ try {
+ echo(client, new byte[128]);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ });
+ assertTrue(processorStarted.await(5, TimeUnit.SECONDS));
+ assertEquals(0, serverBufferPool.reclaimOneIdleConnection());
+
+ allowProcessorToFinish.countDown();
+ request.get(5, TimeUnit.SECONDS);
+ await()
+ .atMost(5, TimeUnit.SECONDS)
+ .until(() -> serverBufferPool.reclaimOneIdleConnection() > 0);
+ echo(client, new byte[8]);
+ } finally {
+ allowProcessorToFinish.countDown();
+ client.close();
+ server.stop();
+ serverBufferPool.close();
+ serverSocket.close();
+ workers.shutdownNow();
+ clientExecutor.shutdownNow();
+ assertTrue(workers.awaitTermination(10, TimeUnit.SECONDS));
+ assertTrue(clientExecutor.awaitTermination(10, TimeUnit.SECONDS));
+ serverThread.join(10_000);
+ assertFalse(serverThread.isAlive());
+ }
+ assertEquals(0, memoryControl.getUsedMemoryInBytes());
+ }
+
+ private TElasticFramedTransport createClientTransport(int port) throws
Exception {
+ return new TElasticFramedTransport(
+ new TSocket(InetAddress.getLoopbackAddress().getHostAddress(), port,
5000), 8, 2048, true);
+ }
+
+ private void echo(TElasticFramedTransport transport, byte[] payload) throws
Exception {
+ TBinaryProtocol protocol = new TBinaryProtocol(transport);
+ protocol.writeBinary(ByteBuffer.wrap(payload));
+ transport.flush();
+ ByteBuffer response = protocol.readBinary();
+ byte[] actual = new byte[response.remaining()];
+ response.get(actual);
+ assertArrayEquals(payload, actual);
+ }
+
+ private static class TestMemoryControl implements
AutoResizingBufferMemoryControl {
+ private final AtomicLong usedMemoryInBytes = new AtomicLong();
+ private volatile long limit = Long.MAX_VALUE;
+
+ @Override
+ public boolean allocate(long sizeInBytes) {
+ while (true) {
+ long current = usedMemoryInBytes.get();
+ if (current + sizeInBytes > limit) {
+ return false;
+ }
+ if (usedMemoryInBytes.compareAndSet(current, current + sizeInBytes)) {
+ return true;
+ }
+ }
+ }
+
+ @Override
+ public void release(long sizeInBytes) {
+ usedMemoryInBytes.addAndGet(-sizeInBytes);
+ }
+
+ private long getUsedMemoryInBytes() {
+ return usedMemoryInBytes.get();
+ }
+
+ private void setLimit(long limit) {
+ this.limit = limit;
+ }
+ }
+}