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 c2ed594d84a Fix RPC buffer accounting during transport and pipe
shutdown (#19504)
c2ed594d84a is described below
commit c2ed594d84a2db0c82984f4440dfebd047c4e53b
Author: Caideyipi <[email protected]>
AuthorDate: Wed Dec 2 22:41:35 2026 +0800
Fix RPC buffer accounting during transport and pipe shutdown (#19504)
---
.../apache/iotdb/rpc/TElasticFramedTransport.java | 20 +++-
.../apache/iotdb/rpc/AutoResizingBufferTest.java | 48 ++++++++
.../apache/iotdb/db/i18n/DataNodePipeMessages.java | 3 +
.../apache/iotdb/db/i18n/DataNodePipeMessages.java | 3 +
.../exchange/sender/TwoStageAggregateSender.java | 72 +++++++++++-
.../sender/TwoStageAggregateSenderTest.java | 127 +++++++++++++++++++++
6 files changed, 264 insertions(+), 9 deletions(-)
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 5ecde48cab9..d092186d792 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
@@ -158,9 +158,23 @@ public class TElasticFramedTransport extends TTransport {
@Override
public synchronized void open() throws TTransportException {
- underlying.open();
- if (serverBufferPool != null) {
- serverBufferPool.register(this);
+ final boolean wasOpen = underlying.isOpen();
+ try {
+ underlying.open();
+ if (serverBufferPool != null) {
+ serverBufferPool.register(this);
+ }
+ } catch (TTransportException | RuntimeException | Error failure) {
+ if (!wasOpen) {
+ try {
+ close();
+ } catch (RuntimeException | Error closeFailure) {
+ if (closeFailure != failure) {
+ failure.addSuppressed(closeFailure);
+ }
+ }
+ }
+ throw failure;
}
}
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 5ad39eac8f6..e111d5a364b 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,6 +20,7 @@
package org.apache.iotdb.rpc;
import org.apache.thrift.transport.TMemoryBuffer;
+import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.junit.After;
@@ -122,6 +123,53 @@ public class AutoResizingBufferTest {
Assert.assertEquals(0, memoryControl.getUsedMemoryInBytes());
}
+ @Test
+ public void testOpenFailureReleasesBufferReservations() throws Exception {
+ AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
+ for (boolean compressed : new boolean[] {false, true}) {
+ TTransportException failure = new
TTransportException(TTransportException.NOT_OPEN);
+ TSocket socket =
+ new TSocket("localhost", 0) {
+ @Override
+ public void open() throws TTransportException {
+ throw failure;
+ }
+ };
+ try (TElasticFramedTransport transport =
+ compressed
+ ? new TSnappyElasticFramedTransport(socket, 32, 128, false)
+ : new TElasticFramedTransport(socket, 32, 128, false)) {
+ Assert.assertEquals(compressed ? 128 : 64,
memoryControl.getUsedMemoryInBytes());
+ Assert.assertSame(failure,
Assert.assertThrows(TTransportException.class, transport::open));
+ Assert.assertEquals(0, memoryControl.getUsedMemoryInBytes());
+ }
+ }
+ }
+
+ @Test
+ public void testOpenFailureDoesNotReleaseAnAlreadyOpenTransport() throws
Exception {
+ AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
+ TSocket socket =
+ new TSocket("localhost", 0) {
+ @Override
+ public boolean isOpen() {
+ return true;
+ }
+
+ @Override
+ public void open() throws TTransportException {
+ throw new TTransportException(TTransportException.ALREADY_OPEN);
+ }
+ };
+ try (TElasticFramedTransport transport = new
TElasticFramedTransport(socket, 32, 128, false)) {
+ Assert.assertEquals(
+ TTransportException.ALREADY_OPEN,
+ Assert.assertThrows(TTransportException.class,
transport::open).getType());
+ Assert.assertEquals(64, memoryControl.getUsedMemoryInBytes());
+ }
+ Assert.assertEquals(0, memoryControl.getUsedMemoryInBytes());
+ }
+
@Test
public void testMemoryPressureReclaimsIdleServerTransportBuffers() throws
Exception {
memoryControl.setLimit(96);
diff --git
a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodePipeMessages.java
b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodePipeMessages.java
index bfe366d7cf9..d976c346503 100644
---
a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodePipeMessages.java
+++
b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodePipeMessages.java
@@ -1614,6 +1614,9 @@ public final class DataNodePipeMessages {
public static final String
EXCEPTION_MISSING_SOURCE_CREDENTIALS_FOR_TWO_STAGE_AGGREGATE_PIPE_ARG_ARG_FF84ED01
=
"Missing source credentials for two-stage aggregate pipe %s-%s.";
+ public static final String
+
EXCEPTION_TWO_STAGE_AGGREGATE_SENDER_FOR_PIPE_ARG_CREATION_TIME_ARG_IS_CLOSED_D76F95EA
=
+ "Two-stage aggregate sender for Pipe %s (creation time %d) is
closed.";
public static final String
EXCEPTION_ONE_OF_ARG_ARG_MUST_BE_SPECIFIED_IN_CONSENSUS_PIPE_DE0285C1 =
"One of %s, %s must be specified in consensus pipe";
public static final String
diff --git
a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodePipeMessages.java
b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodePipeMessages.java
index cd767a1d815..30d90942164 100644
---
a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodePipeMessages.java
+++
b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodePipeMessages.java
@@ -1513,6 +1513,9 @@ public final class DataNodePipeMessages {
public static final String
EXCEPTION_MISSING_SOURCE_CREDENTIALS_FOR_TWO_STAGE_AGGREGATE_PIPE_ARG_ARG_FF84ED01
=
"两阶段聚合 pipe %s-%s 缺少 source 凭据。";
+ public static final String
+
EXCEPTION_TWO_STAGE_AGGREGATE_SENDER_FOR_PIPE_ARG_CREATION_TIME_ARG_IS_CLOSED_D76F95EA
=
+ "Pipe %s(创建时间 %d)的两阶段聚合发送端已关闭。";
public static final String
EXCEPTION_ONE_OF_ARG_ARG_MUST_BE_SPECIFIED_IN_CONSENSUS_PIPE_DE0285C1 =
"Consensus pipe 必须指定 %s、%s 中的一个";
public static final String
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/twostage/exchange/sender/TwoStageAggregateSender.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/twostage/exchange/sender/TwoStageAggregateSender.java
index ce34a959a0c..1954fdaa99f 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/twostage/exchange/sender/TwoStageAggregateSender.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/twostage/exchange/sender/TwoStageAggregateSender.java
@@ -42,6 +42,7 @@ import org.apache.iotdb.service.rpc.thrift.TSOpenSessionResp;
import org.apache.iotdb.service.rpc.thrift.TSProtocolVersion;
import org.apache.thrift.TException;
+import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -51,7 +52,6 @@ import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
@@ -72,9 +72,15 @@ public class TwoStageAggregateSender implements
AutoCloseable {
private static final AtomicReference<Map<Integer, TEndPoint>>
DATANODE_ID_2_END_POINTS =
new AtomicReference<>();
+ private enum State {
+ IDLE,
+ REQUEST_IN_PROGRESS,
+ CLOSED
+ }
+
+ private final AtomicReference<State> state = new
AtomicReference<>(State.IDLE);
private TEndPoint[] endPoints;
- private final Map<TEndPoint, IoTDBSyncClient> endPointIoTDBSyncClientMap =
- new ConcurrentHashMap<>();
+ private final Map<TEndPoint, IoTDBSyncClient> endPointIoTDBSyncClientMap =
new HashMap<>();
public TwoStageAggregateSender(String pipeName, long creationTime) {
this(pipeName, creationTime, null, null);
@@ -90,7 +96,21 @@ public class TwoStageAggregateSender implements
AutoCloseable {
public synchronized TPipeTransferResp request(long watermark,
TPipeTransferReq req)
throws TException {
+ if (!state.compareAndSet(State.IDLE, State.REQUEST_IN_PROGRESS)) {
+ throw closedException();
+ }
+ try {
+ return sendRequest(watermark, req);
+ } finally {
+ if (!state.compareAndSet(State.REQUEST_IN_PROGRESS, State.IDLE)) {
+ closeClients();
+ }
+ }
+ }
+
+ private TPipeTransferResp sendRequest(long watermark, TPipeTransferReq req)
throws TException {
final boolean endPointsChanged = tryFetchEndPointsIfNecessary();
+ checkOpen();
tryConstructClients(endPointsChanged);
final TEndPoint endPoint = endPoints[(int) Math.floorMod(watermark,
endPoints.length)];
@@ -99,11 +119,15 @@ public class TwoStageAggregateSender implements
AutoCloseable {
client = reconstructIoTDBSyncClient(endPoint);
}
+ checkOpen();
LOGGER.info(DataNodePipeMessages.SENDING_REQUEST_WATERMARK_TO, req,
watermark, endPoint);
try {
return client.pipeTransfer(req);
} catch (Exception e) {
+ if (state.get() == State.CLOSED) {
+ throw e;
+ }
LOGGER.warn(
DataNodePipeMessages.FAILED_TO_SEND_REQUEST_WATERMARK_TO, req,
watermark, endPoint, e);
try {
@@ -120,6 +144,22 @@ public class TwoStageAggregateSender implements
AutoCloseable {
}
}
+ private void checkOpen() throws TTransportException {
+ if (state.get() == State.CLOSED) {
+ throw closedException();
+ }
+ }
+
+ private TTransportException closedException() {
+ return new TTransportException(
+ TTransportException.NOT_OPEN,
+ String.format(
+ DataNodePipeMessages
+
.EXCEPTION_TWO_STAGE_AGGREGATE_SENDER_FOR_PIPE_ARG_CREATION_TIME_ARG_IS_CLOSED_D76F95EA,
+ pipeName,
+ creationTime));
+ }
+
private static boolean tryFetchEndPointsIfNecessary() {
final long currentTime = System.currentTimeMillis();
@@ -166,7 +206,7 @@ public class TwoStageAggregateSender implements
AutoCloseable {
return true;
}
- private void tryConstructClients(boolean endPointsChanged) {
+ private void tryConstructClients(boolean endPointsChanged) throws
TTransportException {
if (Objects.nonNull(endPoints) && !endPointsChanged) {
return;
}
@@ -189,6 +229,7 @@ public class TwoStageAggregateSender implements
AutoCloseable {
endPoints);
for (final TEndPoint endPoint : endPoints) {
+ checkOpen();
if (endPointIoTDBSyncClientMap.containsKey(endPoint)) {
continue;
}
@@ -226,6 +267,7 @@ public class TwoStageAggregateSender implements
AutoCloseable {
}
private IoTDBSyncClient constructIoTDBSyncClient(TEndPoint endPoint) throws
TException {
+ checkOpen();
final IoTDBSyncClient client =
new IoTDBSyncClient(
new ThriftClientProperty.Builder()
@@ -237,8 +279,20 @@ public class TwoStageAggregateSender implements
AutoCloseable {
false,
null,
null);
- openSession(client);
- return client;
+ try {
+ checkOpen();
+ openSession(client);
+ return client;
+ } catch (TException | RuntimeException | Error failure) {
+ try {
+ client.close();
+ } catch (Exception | Error closeFailure) {
+ if (closeFailure != failure) {
+ failure.addSuppressed(closeFailure);
+ }
+ }
+ throw failure;
+ }
}
private void openSession(final IoTDBSyncClient client) throws TException {
@@ -274,6 +328,12 @@ public class TwoStageAggregateSender implements
AutoCloseable {
@Override
public void close() {
+ if (state.getAndSet(State.CLOSED) == State.IDLE) {
+ closeClients();
+ }
+ }
+
+ private void closeClients() {
for (final IoTDBSyncClient client : endPointIoTDBSyncClientMap.values()) {
try {
client.close();
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/processor/twostage/exchange/sender/TwoStageAggregateSenderTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/processor/twostage/exchange/sender/TwoStageAggregateSenderTest.java
new file mode 100644
index 00000000000..c23e226a04e
--- /dev/null
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/processor/twostage/exchange/sender/TwoStageAggregateSenderTest.java
@@ -0,0 +1,127 @@
+/*
+ * 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.iotdb.db.pipe.processor.twostage.exchange.sender;
+
+import org.apache.iotdb.common.rpc.thrift.TEndPoint;
+import org.apache.iotdb.commons.pipe.sink.client.IoTDBSyncClient;
+import org.apache.iotdb.pipe.api.exception.PipeException;
+import org.apache.iotdb.service.rpc.thrift.TPipeTransferReq;
+import org.apache.iotdb.service.rpc.thrift.TPipeTransferResp;
+
+import org.apache.thrift.transport.TTransportException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.powermock.reflect.Whitebox;
+
+import java.net.InetSocketAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+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.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class TwoStageAggregateSenderTest {
+
+ @Test
+ public void testCloseDefersClientCleanupUntilRequestFinishes() throws
Exception {
+ final TEndPoint endpoint = new TEndPoint("127.0.0.1", 1);
+ final IoTDBSyncClient client = mock(IoTDBSyncClient.class);
+ final TPipeTransferReq request = new TPipeTransferReq();
+ final TPipeTransferResp response = new TPipeTransferResp();
+ final CountDownLatch entered = new CountDownLatch(1);
+ final CountDownLatch finish = new CountDownLatch(1);
+ when(client.pipeTransfer(request))
+ .thenAnswer(
+ invocation -> {
+ entered.countDown();
+ Assert.assertTrue(finish.await(10, TimeUnit.SECONDS));
+ return response;
+ });
+
+ final AtomicReference<Map<Integer, TEndPoint>> endpoints =
+ Whitebox.getInternalState(TwoStageAggregateSender.class,
"DATANODE_ID_2_END_POINTS");
+ final AtomicLong lastUpdate =
+ Whitebox.getInternalState(
+ TwoStageAggregateSender.class,
"DATANODE_ID_2_END_POINTS_LAST_UPDATE_TIME");
+ final Map<Integer, TEndPoint> previousEndpoints =
endpoints.getAndSet(Map.of(1, endpoint));
+ final long previousUpdate =
lastUpdate.getAndSet(System.currentTimeMillis());
+
+ final TwoStageAggregateSender sender = new
TwoStageAggregateSender("testPipe", 1);
+ final ExecutorService executor = Executors.newFixedThreadPool(2);
+ try {
+ Whitebox.setInternalState(sender, "endPoints", (Object) new TEndPoint[]
{endpoint});
+ final Map<TEndPoint, IoTDBSyncClient> clients =
+ Whitebox.getInternalState(sender, "endPointIoTDBSyncClientMap");
+ clients.put(endpoint, client);
+
+ final Future<TPipeTransferResp> inFlight = executor.submit(() ->
sender.request(0, request));
+ Assert.assertTrue(entered.await(5, TimeUnit.SECONDS));
+ executor.submit(sender::close).get(5, TimeUnit.SECONDS);
+ verify(client, never()).close();
+
+ finish.countDown();
+ Assert.assertSame(response, inFlight.get(5, TimeUnit.SECONDS));
+ sender.close();
+ verify(client).close();
+ Assert.assertTrue(clients.isEmpty());
+ Assert.assertEquals(
+ TTransportException.NOT_OPEN,
+ Assert.assertThrows(TTransportException.class, () ->
sender.request(0, request))
+ .getType());
+ } finally {
+ finish.countDown();
+ executor.shutdownNow();
+ try {
+ Assert.assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
+ } finally {
+ sender.close();
+ endpoints.set(previousEndpoints);
+ lastUpdate.set(previousUpdate);
+ }
+ }
+ }
+
+ @Test
+ public void testSessionSetupFailureClosesUncachedClient() throws Exception {
+ try (TwoStageAggregateSender sender = new
TwoStageAggregateSender("testPipe", 1);
+ ServerSocket listener = new ServerSocket()) {
+ listener.bind(new InetSocketAddress("127.0.0.1", 0));
+ listener.setSoTimeout(5_000);
+ final TEndPoint endpoint = new TEndPoint("127.0.0.1",
listener.getLocalPort());
+ Assert.assertThrows(
+ PipeException.class,
+ () -> Whitebox.invokeMethod(sender, "constructIoTDBSyncClient",
endpoint));
+ try (Socket connection = listener.accept()) {
+ connection.setSoTimeout(5_000);
+ Assert.assertEquals(-1, connection.getInputStream().read());
+ }
+ }
+ }
+}