This is an automated email from the ASF dual-hosted git repository.
Caideyipi pushed a commit to branch dev/1.3
in repository https://gitbox.apache.org/repos/asf/iotdb.git
The following commit(s) were added to refs/heads/dev/1.3 by this push:
new 81c504a1dd4 [To dev/1.3] Retry Pipe sinks after transient resource
failures (#19379) (#19401)
81c504a1dd4 is described below
commit 81c504a1dd4152341c6a68750bb2fe66660413ec
Author: Caideyipi <[email protected]>
AuthorDate: Wed Nov 25 18:20:42 2026 +0800
[To dev/1.3] Retry Pipe sinks after transient resource failures (#19379)
(#19401)
* Add RPC auto resizing buffer memory control (#17911)
* ver1
* ver2
* ver3
* ver4
* ver4
* update default config value
* Disable when proportion <= 0
* fix review
* disable mem-control in ITs
* Replace auto_resizing_buffer_memory_proportion with
datanode_memory_proportion
* Add AutoResizingBuffer memory metrics
* Fix it
(cherry picked from commit 1073715a081f4e67d3b2963694a8fca049805d6d)
* Fix RPC buffer memory control activation (#18194)
Avoid activating DataNode RPC buffer memory control during configuration
loading, and bind auto-resizing buffers to the memory account used for their
allocation.
(cherry picked from commit 0d3304a106a4ef2ea168682485ac0b7027f93f95)
* Retry Pipe sinks after transient resource failures (#19379)
* Retry Pipe sinks after transient resource failures
* Restore Pipe sink handshake on connection reset
(cherry picked from commit dbbe38a61197b6a680adcd803c189e2503964944)
---------
Co-authored-by: Jiang Tian <[email protected]>
---
.../db/it/IoTDBAutoResizingBufferMemoryIT.java | 274 +++++++++++++++++++++
.../org/apache/iotdb/db/it/IoTDBLoadTsFileIT.java | 2 +-
.../pipe/it/autocreate/AbstractPipeDualAutoIT.java | 2 +
.../it/autocreate/IoTDBPipeAutoConflictIT.java | 2 +
.../pipe/it/autocreate/IoTDBPipeAutoSplitIT.java | 2 +
.../pipe/it/autocreate/IoTDBPipeClusterIT.java | 2 +
.../pipe/it/autocreate/IoTDBPipeIdempotentIT.java | 2 +
.../pipe/it/autocreate/IoTDBPipeProcessorIT.java | 2 +
.../pipe/it/autocreate/IoTDBPipeProtocolIT.java | 6 +
.../it/autocreate/IoTDBPipeSinkCompressionIT.java | 2 +
.../pipe/it/autocreate/IoTDBPipeSourceIT.java | 2 +
.../pipe/it/autocreate/IoTDBPipeWithLoadIT.java | 2 +
.../pipe/it/manual/AbstractPipeDualManualIT.java | 2 +
.../pipe/it/manual/IoTDBPipeMetaHistoricalIT.java | 2 +
.../it/manual/IoTDBPipeMetaLeaderChangeIT.java | 2 +
.../iotdb/pipe/it/single/AbstractPipeSingleIT.java | 1 +
.../pipe/it/triple/AbstractPipeTripleManualIT.java | 3 +
.../en/org/apache/iotdb/rpc/i18n/RpcMessages.java | 6 +
.../zh/org/apache/iotdb/rpc/i18n/RpcMessages.java | 6 +
.../org/apache/iotdb/rpc/AutoResizingBuffer.java | 70 +++++-
...utoResizingBufferMemoryAllocationException.java | 29 +++
.../iotdb/rpc/AutoResizingBufferMemoryControl.java | 32 +++
.../iotdb/rpc/AutoResizingBufferMemoryManager.java | 161 ++++++++++++
.../iotdb/rpc/AutoScalingBufferReadTransport.java | 18 +-
.../iotdb/rpc/AutoScalingBufferWriteTransport.java | 18 +-
.../rpc/TCompressedElasticFramedTransport.java | 29 ++-
.../apache/iotdb/rpc/TElasticFramedTransport.java | 44 +++-
.../iotdb/rpc/TSnappyElasticFramedTransport.java | 8 +-
.../rpc/TimeoutChangeableTFastFramedTransport.java | 6 +-
.../TimeoutChangeableTSnappyFramedTransport.java | 6 +-
.../apache/iotdb/rpc/AutoResizingBufferTest.java | 223 ++++++++++++++++-
.../apache/iotdb/consensus/ratis/utils/Utils.java | 20 +-
.../java/org/apache/iotdb/db/conf/IoTDBConfig.java | 11 +
.../org/apache/iotdb/db/conf/IoTDBDescriptor.java | 5 +
.../java/org/apache/iotdb/db/service/DataNode.java | 45 ++++
.../db/service/metrics/DataNodeMetricsHelper.java | 2 +
.../task/subtask/sink/PipeSinkSubtaskTest.java | 130 ++++++++++
.../thrift/async/IoTDBDataRegionAsyncSinkTest.java | 89 +++++++
.../conf/iotdb-system.properties.template | 1 +
.../memory/AutoResizingBufferMemoryMetrics.java | 108 ++++++++
.../task/subtask/PipeAbstractSinkSubtask.java | 14 ++
.../commons/pipe/resource/PipeStopStrategy.java | 37 +++
.../iotdb/commons/service/metric/enums/Metric.java | 1 +
.../pipe/resource/PipeStopStrategyTest.java | 121 +++++++++
.../iotdb/rpc/ClientPoolIdleEvictionTest.java | 10 +-
45 files changed, 1514 insertions(+), 46 deletions(-)
diff --git
a/integration-test/src/test/java/org/apache/iotdb/db/it/IoTDBAutoResizingBufferMemoryIT.java
b/integration-test/src/test/java/org/apache/iotdb/db/it/IoTDBAutoResizingBufferMemoryIT.java
new file mode 100644
index 00000000000..ead744f5497
--- /dev/null
+++
b/integration-test/src/test/java/org/apache/iotdb/db/it/IoTDBAutoResizingBufferMemoryIT.java
@@ -0,0 +1,274 @@
+/*
+ * 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.it;
+
+import org.apache.iotdb.commons.conf.CommonConfig;
+import org.apache.iotdb.commons.conf.IoTDBConstant;
+import org.apache.iotdb.isession.SessionConfig;
+import org.apache.iotdb.it.env.EnvFactory;
+import org.apache.iotdb.it.env.cluster.node.AbstractNodeWrapper;
+import org.apache.iotdb.it.env.cluster.node.DataNodeWrapper;
+import org.apache.iotdb.it.framework.IoTDBTestRunner;
+import org.apache.iotdb.itbase.category.LocalStandaloneIT;
+import org.apache.iotdb.rpc.DeepCopyRpcTransportFactory;
+import org.apache.iotdb.rpc.RpcUtils;
+import org.apache.iotdb.service.rpc.thrift.IClientRPCService;
+import org.apache.iotdb.service.rpc.thrift.TSCloseOperationReq;
+import org.apache.iotdb.service.rpc.thrift.TSCloseSessionReq;
+import org.apache.iotdb.service.rpc.thrift.TSExecuteStatementReq;
+import org.apache.iotdb.service.rpc.thrift.TSExecuteStatementResp;
+import org.apache.iotdb.service.rpc.thrift.TSOpenSessionReq;
+import org.apache.iotdb.service.rpc.thrift.TSOpenSessionResp;
+
+import org.apache.thrift.protocol.TBinaryProtocol;
+import org.apache.thrift.transport.TTransport;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.runner.RunWith;
+
+import java.io.File;
+import java.nio.file.Files;
+import java.sql.Connection;
+import java.sql.Statement;
+import java.time.ZoneId;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+@RunWith(IoTDBTestRunner.class)
+@Category({LocalStandaloneIT.class})
+public class IoTDBAutoResizingBufferMemoryIT {
+
+ private static final int DATANODE_MAX_HEAP_SIZE_IN_MB = 256;
+ private static final int AUTO_RESIZING_BUFFER_COUNT_PER_CONNECTION = 2;
+ private static final int CONNECTION_COUNT_OVERFLOW_MARGIN = 1;
+ private static final int INITIAL_GROWING_REQUEST_PAYLOAD_SIZE = 16 * 1024;
+ private static final int MAX_GROWING_REQUEST_PAYLOAD_SIZE =
+ calculateNextPowerOfTwo(calculateAutoResizingBufferMemorySizeInBytes());
+
+ @BeforeClass
+ public static void setUp() throws Exception {
+ EnvFactory.getEnv()
+ .getConfig()
+ .getDataNodeJVMConfig()
+ .setMaxHeapSize(DATANODE_MAX_HEAP_SIZE_IN_MB);
+ EnvFactory.getEnv().initClusterEnvironment();
+ }
+
+ @AfterClass
+ public static void tearDown() throws Exception {
+ EnvFactory.getEnv().cleanClusterEnvironment();
+ }
+
+ @Test
+ public void
testNewConnectionsWithWritesAreRejectedWhenBufferMemoryIsExhausted()
+ throws Exception {
+ List<Connection> heldConnections = new ArrayList<>();
+ boolean rejected = false;
+
+ try {
+ try (Connection connection = EnvFactory.getEnv().getConnection();
+ Statement statement = connection.createStatement()) {
+ statement.execute("CREATE DATABASE root.auto_resizing_buffer_reject");
+ statement.execute(
+ "CREATE TIMESERIES root.auto_resizing_buffer_reject.d1.s1 WITH
DATATYPE=INT32, ENCODING=PLAIN");
+ }
+
+ int connectionCountToExhaustBufferMemory =
+ calculateConnectionCountToExhaustAutoResizingBufferMemory();
+ for (int i = 0; i < connectionCountToExhaustBufferMemory; i++) {
+ try {
+ Connection connection = EnvFactory.getEnv().getConnection();
+ heldConnections.add(connection);
+ try (Statement statement = connection.createStatement()) {
+ statement.execute(
+ String.format(
+ "INSERT INTO root.auto_resizing_buffer_reject.d1(time, s1)
VALUES (%d, %d)",
+ i + 1, i));
+ }
+ } catch (Exception e) {
+ rejected = true;
+ break;
+ }
+ }
+ } finally {
+ for (Connection connection : heldConnections) {
+ closeQuietly(connection);
+ }
+ }
+
+ Assert.assertTrue(
+ "Expected new connections with writes to be rejected after
AutoResizingBuffer memory is exhausted",
+ rejected);
+ }
+
+ @Test
+ public void testGrowingRequestsAreRejectedWhenBufferMemoryIsExhausted()
throws Exception {
+ boolean rejected = false;
+
+ try (Connection connection = EnvFactory.getEnv().getConnection();
+ Statement statement = connection.createStatement()) {
+ statement.execute("CREATE DATABASE
root.auto_resizing_buffer_growing_request");
+ statement.execute(
+ "CREATE TIMESERIES root.auto_resizing_buffer_growing_request.d1.s1
WITH DATATYPE=TEXT, ENCODING=PLAIN");
+ }
+
+ // do not use connection because its inevitable retry will slow down the
test
+ try (ThriftClientContext clientContext = ThriftClientContext.open()) {
+ int payloadSize = INITIAL_GROWING_REQUEST_PAYLOAD_SIZE;
+ while (payloadSize <= MAX_GROWING_REQUEST_PAYLOAD_SIZE) {
+ try {
+ clientContext.executeStatement(
+ String.format(
+ "INSERT INTO
root.auto_resizing_buffer_growing_request.d1(time, s1) VALUES (%d, '%s')",
+ payloadSize, repeat('a', payloadSize)));
+ } catch (Exception e) {
+ rejected = true;
+ clientContext.markBroken();
+ break;
+ }
+ payloadSize = payloadSize << 1;
+ }
+ }
+
+ Assert.assertTrue(
+ "Expected a growing request to be rejected after AutoResizingBuffer
memory is exhausted",
+ rejected);
+ }
+
+ private static void closeQuietly(AutoCloseable closeable) {
+ if (closeable == null) {
+ return;
+ }
+ try {
+ closeable.close();
+ } catch (Exception ignored) {
+ // ignored
+ }
+ }
+
+ private static int
calculateConnectionCountToExhaustAutoResizingBufferMemory() {
+ int autoResizingBufferInitialSizePerConnection =
+ AUTO_RESIZING_BUFFER_COUNT_PER_CONNECTION *
RpcUtils.THRIFT_DEFAULT_BUF_CAPACITY;
+ return (int)
+ (calculateAutoResizingBufferMemorySizeInBytes() /
autoResizingBufferInitialSizePerConnection
+ + CONNECTION_COUNT_OVERFLOW_MARGIN);
+ }
+
+ private static long calculateAutoResizingBufferMemorySizeInBytes() {
+ return (DATANODE_MAX_HEAP_SIZE_IN_MB * 1024L * 1024L * 5 / 100); // 5% of
the max heap size;
+ }
+
+ private static int calculateNextPowerOfTwo(long value) {
+ int result = 1;
+ while (result < value) {
+ result <<= 1;
+ }
+ return result;
+ }
+
+ private static String repeat(char character, int count) {
+ char[] chars = new char[count];
+ Arrays.fill(chars, character);
+ return new String(chars);
+ }
+
+ private static TSOpenSessionReq createOpenSessionReq() {
+ TSOpenSessionReq req = new TSOpenSessionReq();
+ req.setUsername(SessionConfig.DEFAULT_USER);
+ req.setPassword(SessionConfig.DEFAULT_PASSWORD);
+ req.setZoneId(ZoneId.systemDefault().toString());
+ req.putToConfiguration("version",
IoTDBConstant.ClientVersion.V_1_0.toString());
+ req.putToConfiguration("sql_dialect", "tree");
+ return req;
+ }
+
+ private static class ThriftClientContext implements AutoCloseable {
+
+ private final TTransport transport;
+ private final IClientRPCService.Client client;
+ private final long sessionId;
+ private final long statementId;
+ private boolean broken;
+
+ private ThriftClientContext(
+ TTransport transport, IClientRPCService.Client client, long sessionId,
long statementId) {
+ this.transport = transport;
+ this.client = client;
+ this.sessionId = sessionId;
+ this.statementId = statementId;
+ }
+
+ private static ThriftClientContext open() throws Exception {
+ DataNodeWrapper dataNode = EnvFactory.getEnv().getDataNodeWrapper(0);
+ TTransport transport =
+ DeepCopyRpcTransportFactory.INSTANCE.getTransport(
+ dataNode.getIp(), dataNode.getPort(), 0);
+ transport.open();
+ IClientRPCService.Client client =
+ new IClientRPCService.Client(new TBinaryProtocol(transport));
+ TSOpenSessionResp openSessionResp =
client.openSession(createOpenSessionReq());
+ RpcUtils.verifySuccess(openSessionResp.getStatus());
+ long sessionId = openSessionResp.getSessionId();
+ return new ThriftClientContext(
+ transport, client, sessionId, client.requestStatementId(sessionId));
+ }
+
+ private void executeStatement(String sql) throws Exception {
+ TSExecuteStatementResp resp =
+ client.executeStatementV2(new TSExecuteStatementReq(sessionId, sql,
statementId));
+ RpcUtils.verifySuccess(resp.getStatus());
+ }
+
+ private void markBroken() {
+ broken = true;
+ }
+
+ @Override
+ public void close() throws Exception {
+ try {
+ if (!broken) {
+ client.closeOperation(new
TSCloseOperationReq(sessionId).setStatementId(statementId));
+ client.closeSession(new TSCloseSessionReq(sessionId));
+ }
+ } finally {
+ transport.close();
+ }
+ }
+ }
+
+ private static boolean checkConfigFileContains(AbstractNodeWrapper
nodeWrapper, String content) {
+ try {
+ String systemPropertiesPath =
+ nodeWrapper.getNodePath()
+ + File.separator
+ + "conf"
+ + File.separator
+ + CommonConfig.SYSTEM_CONFIG_NAME;
+ return new String(Files.readAllBytes(new
File(systemPropertiesPath).toPath()))
+ .contains(content);
+ } catch (Exception ignore) {
+ return false;
+ }
+ }
+}
diff --git
a/integration-test/src/test/java/org/apache/iotdb/db/it/IoTDBLoadTsFileIT.java
b/integration-test/src/test/java/org/apache/iotdb/db/it/IoTDBLoadTsFileIT.java
index 29905b6f88f..af4ca05bcc0 100644
---
a/integration-test/src/test/java/org/apache/iotdb/db/it/IoTDBLoadTsFileIT.java
+++
b/integration-test/src/test/java/org/apache/iotdb/db/it/IoTDBLoadTsFileIT.java
@@ -109,7 +109,7 @@ public class IoTDBLoadTsFileIT {
EnvFactory.getEnv()
.getConfig()
.getCommonConfig()
- .setDatanodeMemoryProportion("100:1000:100:100:100:100");
+ .setDatanodeMemoryProportion("100:1000:100:100:100:0");
EnvFactory.getEnv()
.getConfig()
.getDataNodeConfig()
diff --git
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/AbstractPipeDualAutoIT.java
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/AbstractPipeDualAutoIT.java
index 7914c7cb4ff..36a1a15ae16 100644
---
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/AbstractPipeDualAutoIT.java
+++
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/AbstractPipeDualAutoIT.java
@@ -46,6 +46,7 @@ abstract class AbstractPipeDualAutoIT {
.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(true)
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setPipeMemoryManagementEnabled(false)
@@ -55,6 +56,7 @@ abstract class AbstractPipeDualAutoIT {
.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(true)
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setPipeMemoryManagementEnabled(false)
diff --git
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeAutoConflictIT.java
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeAutoConflictIT.java
index 6685ca91415..ec94fa67d62 100644
---
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeAutoConflictIT.java
+++
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeAutoConflictIT.java
@@ -56,6 +56,7 @@ public class IoTDBPipeAutoConflictIT extends
AbstractPipeDualAutoIT {
.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(true)
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setDataRegionConsensusProtocolClass(ConsensusFactory.IOT_CONSENSUS)
@@ -65,6 +66,7 @@ public class IoTDBPipeAutoConflictIT extends
AbstractPipeDualAutoIT {
.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(true)
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setDataRegionConsensusProtocolClass(ConsensusFactory.IOT_CONSENSUS)
diff --git
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeAutoSplitIT.java
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeAutoSplitIT.java
index afa30ada696..64edd907dcf 100644
---
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeAutoSplitIT.java
+++
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeAutoSplitIT.java
@@ -61,6 +61,7 @@ public class IoTDBPipeAutoSplitIT extends
AbstractPipeDualAutoIT {
.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(true)
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setPipeMemoryManagementEnabled(false)
@@ -70,6 +71,7 @@ public class IoTDBPipeAutoSplitIT extends
AbstractPipeDualAutoIT {
.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(true)
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setPipeMemoryManagementEnabled(false)
diff --git
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeClusterIT.java
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeClusterIT.java
index 047ba3c5afb..a11e03f0114 100644
---
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeClusterIT.java
+++
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeClusterIT.java
@@ -79,6 +79,7 @@ public class IoTDBPipeClusterIT extends
AbstractPipeDualAutoIT {
.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(true)
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setDataRegionConsensusProtocolClass(ConsensusFactory.IOT_CONSENSUS)
@@ -93,6 +94,7 @@ public class IoTDBPipeClusterIT extends
AbstractPipeDualAutoIT {
.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(true)
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
.setDataReplicationFactor(2)
.setSchemaReplicationFactor(3)
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
diff --git
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeIdempotentIT.java
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeIdempotentIT.java
index 5470abfd528..588c5eb6eb1 100644
---
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeIdempotentIT.java
+++
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeIdempotentIT.java
@@ -60,6 +60,7 @@ public class IoTDBPipeIdempotentIT extends
AbstractPipeDualAutoIT {
.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(true)
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
// Limit the schemaRegion number to 1 to guarantee the after sql
executed on the same region
// of the tested idempotent sql.
.setDefaultSchemaRegionGroupNumPerDatabase(1)
@@ -73,6 +74,7 @@ public class IoTDBPipeIdempotentIT extends
AbstractPipeDualAutoIT {
.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(true)
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
.setSchemaRegionGroupExtensionPolicy("CUSTOM")
.setDataRegionGroupExtensionPolicy("CUSTOM")
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
diff --git
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeProcessorIT.java
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeProcessorIT.java
index d0f9620c61f..970a5e2f2c4 100644
---
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeProcessorIT.java
+++
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeProcessorIT.java
@@ -56,6 +56,7 @@ public class IoTDBPipeProcessorIT extends
AbstractPipeDualAutoIT {
.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(true)
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
.setTimestampPrecision("ms")
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
@@ -65,6 +66,7 @@ public class IoTDBPipeProcessorIT extends
AbstractPipeDualAutoIT {
.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(true)
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setPipeMemoryManagementEnabled(false)
diff --git
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeProtocolIT.java
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeProtocolIT.java
index 3f406091ffe..8f524c1b950 100644
---
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeProtocolIT.java
+++
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeProtocolIT.java
@@ -69,6 +69,7 @@ public class IoTDBPipeProtocolIT extends
AbstractPipeDualAutoIT {
.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(true)
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setDataRegionConsensusProtocolClass(dataRegionConsensus)
@@ -80,6 +81,7 @@ public class IoTDBPipeProtocolIT extends
AbstractPipeDualAutoIT {
.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(true)
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
.setConfigNodeConsensusProtocolClass(configNodeConsensus)
.setSchemaRegionConsensusProtocolClass(schemaRegionConsensus)
.setDataRegionConsensusProtocolClass(dataRegionConsensus)
@@ -167,6 +169,7 @@ public class IoTDBPipeProtocolIT extends
AbstractPipeDualAutoIT {
.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(true)
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setDataRegionConsensusProtocolClass(ConsensusFactory.IOT_CONSENSUS)
@@ -178,6 +181,7 @@ public class IoTDBPipeProtocolIT extends
AbstractPipeDualAutoIT {
.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(true)
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setDataRegionConsensusProtocolClass(ConsensusFactory.IOT_CONSENSUS)
@@ -346,6 +350,7 @@ public class IoTDBPipeProtocolIT extends
AbstractPipeDualAutoIT {
.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(true)
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
.setPipeAirGapReceiverEnabled(true)
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
@@ -361,6 +366,7 @@ public class IoTDBPipeProtocolIT extends
AbstractPipeDualAutoIT {
.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(true)
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
.setPipeAirGapReceiverEnabled(true)
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
diff --git
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeSinkCompressionIT.java
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeSinkCompressionIT.java
index 235e705ed0c..0a82e0aaab4 100644
---
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeSinkCompressionIT.java
+++
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeSinkCompressionIT.java
@@ -66,6 +66,7 @@ public class IoTDBPipeSinkCompressionIT extends
AbstractPipeDualAutoIT {
.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(true)
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setPipeMemoryManagementEnabled(false)
@@ -76,6 +77,7 @@ public class IoTDBPipeSinkCompressionIT extends
AbstractPipeDualAutoIT {
.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(true)
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
.setPipeAirGapReceiverEnabled(true)
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
diff --git
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeSourceIT.java
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeSourceIT.java
index b0428ce674d..0e7d4358f18 100644
---
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeSourceIT.java
+++
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeSourceIT.java
@@ -70,6 +70,7 @@ public class IoTDBPipeSourceIT extends AbstractPipeDualAutoIT
{
.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(true)
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
// Disable sender compaction for tsfile determination in loose range
test
@@ -83,6 +84,7 @@ public class IoTDBPipeSourceIT extends AbstractPipeDualAutoIT
{
.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(true)
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setPipeMemoryManagementEnabled(false)
diff --git
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeWithLoadIT.java
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeWithLoadIT.java
index 72306a3da3f..8261eef3634 100644
---
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeWithLoadIT.java
+++
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/autocreate/IoTDBPipeWithLoadIT.java
@@ -55,6 +55,7 @@ public class IoTDBPipeWithLoadIT extends
AbstractPipeDualAutoIT {
.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(true)
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
// Disable sender compaction to test mods
@@ -67,6 +68,7 @@ public class IoTDBPipeWithLoadIT extends
AbstractPipeDualAutoIT {
.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(true)
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setPipeMemoryManagementEnabled(false)
diff --git
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/manual/AbstractPipeDualManualIT.java
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/manual/AbstractPipeDualManualIT.java
index c31ee76c6ad..974cbd0487b 100644
---
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/manual/AbstractPipeDualManualIT.java
+++
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/manual/AbstractPipeDualManualIT.java
@@ -46,6 +46,7 @@ abstract class AbstractPipeDualManualIT {
.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(false)
+ .setDatanodeMemoryProportion("3:3:1:1:3:0")
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setPipeMemoryManagementEnabled(false)
@@ -56,6 +57,7 @@ abstract class AbstractPipeDualManualIT {
.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(false)
+ .setDatanodeMemoryProportion("3:3:1:1:3:0")
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setPipeMemoryManagementEnabled(false)
diff --git
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/manual/IoTDBPipeMetaHistoricalIT.java
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/manual/IoTDBPipeMetaHistoricalIT.java
index baa295c3578..9a5b1d52b7b 100644
---
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/manual/IoTDBPipeMetaHistoricalIT.java
+++
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/manual/IoTDBPipeMetaHistoricalIT.java
@@ -57,6 +57,7 @@ public class IoTDBPipeMetaHistoricalIT extends
AbstractPipeDualManualIT {
.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(false)
+ .setDatanodeMemoryProportion("3:3:1:1:3:0")
.setDefaultSchemaRegionGroupNumPerDatabase(1)
.setTimestampPrecision("ms")
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
@@ -68,6 +69,7 @@ public class IoTDBPipeMetaHistoricalIT extends
AbstractPipeDualManualIT {
.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(false)
+ .setDatanodeMemoryProportion("3:3:1:1:3:0")
.setTimestampPrecision("ms")
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
diff --git
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/manual/IoTDBPipeMetaLeaderChangeIT.java
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/manual/IoTDBPipeMetaLeaderChangeIT.java
index a3d8ad575a7..95917f10505 100644
---
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/manual/IoTDBPipeMetaLeaderChangeIT.java
+++
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/manual/IoTDBPipeMetaLeaderChangeIT.java
@@ -53,6 +53,7 @@ public class IoTDBPipeMetaLeaderChangeIT extends
AbstractPipeDualManualIT {
senderEnv
.getConfig()
.getCommonConfig()
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setDataRegionConsensusProtocolClass(ConsensusFactory.IOT_CONSENSUS)
@@ -66,6 +67,7 @@ public class IoTDBPipeMetaLeaderChangeIT extends
AbstractPipeDualManualIT {
receiverEnv
.getConfig()
.getCommonConfig()
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
.setPipeMemoryManagementEnabled(false)
.setIsPipeEnableMemoryCheck(false)
.setPipeAutoSplitFullEnabled(false)
diff --git
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/single/AbstractPipeSingleIT.java
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/single/AbstractPipeSingleIT.java
index dded7cbce30..c463c20d9e2 100644
---
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/single/AbstractPipeSingleIT.java
+++
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/single/AbstractPipeSingleIT.java
@@ -38,6 +38,7 @@ abstract class AbstractPipeSingleIT {
env.getConfig().getCommonConfig().setDnConnectionTimeoutMs(600000);
env.getConfig()
.getCommonConfig()
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
.setPipeMemoryManagementEnabled(false)
.setIsPipeEnableMemoryCheck(false)
.setPipeAutoSplitFullEnabled(false);
diff --git
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/triple/AbstractPipeTripleManualIT.java
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/triple/AbstractPipeTripleManualIT.java
index a539f684fe1..08b60a2910c 100644
---
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/triple/AbstractPipeTripleManualIT.java
+++
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/triple/AbstractPipeTripleManualIT.java
@@ -52,6 +52,7 @@ abstract class AbstractPipeTripleManualIT {
env1.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(false)
+ .setDatanodeMemoryProportion("3:3:1:1:3:0")
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setPipeMemoryManagementEnabled(false)
@@ -62,6 +63,7 @@ abstract class AbstractPipeTripleManualIT {
env2.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(false)
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setPipeMemoryManagementEnabled(false)
@@ -71,6 +73,7 @@ abstract class AbstractPipeTripleManualIT {
env3.getConfig()
.getCommonConfig()
.setAutoCreateSchemaEnabled(false)
+ .setDatanodeMemoryProportion("3:3:1:1:1:0")
.setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setPipeMemoryManagementEnabled(false)
diff --git
a/iotdb-client/service-rpc/src/main/i18n/en/org/apache/iotdb/rpc/i18n/RpcMessages.java
b/iotdb-client/service-rpc/src/main/i18n/en/org/apache/iotdb/rpc/i18n/RpcMessages.java
index 97cf48d447d..2021c948174 100644
---
a/iotdb-client/service-rpc/src/main/i18n/en/org/apache/iotdb/rpc/i18n/RpcMessages.java
+++
b/iotdb-client/service-rpc/src/main/i18n/en/org/apache/iotdb/rpc/i18n/RpcMessages.java
@@ -24,6 +24,12 @@ public final class RpcMessages {
"This DataSet is already closed";
public static final String EXCEPTION_UNKNOWN_TIME_PRECISION_ARG_F550A691 =
"Unknown time precision: %s";
+ public static final String
+
EXCEPTION_AUTO_RESIZING_BUFFER_WAS_INTERRUPTED_WHILE_ALLOCATING_ARG_BYTES_516F5DA1
=
+ "AutoResizingBuffer was interrupted while allocating %d bytes";
+ public static final String
+
EXCEPTION_AUTO_RESIZING_BUFFER_FAILED_TO_ALLOCATE_ARG_BYTES_AFTER_ARG_RETRIES_836DB2FD
=
+ "AutoResizingBuffer failed to allocate %d bytes after %d retries";
private RpcMessages() {}
}
diff --git
a/iotdb-client/service-rpc/src/main/i18n/zh/org/apache/iotdb/rpc/i18n/RpcMessages.java
b/iotdb-client/service-rpc/src/main/i18n/zh/org/apache/iotdb/rpc/i18n/RpcMessages.java
index c1be19f5916..812a6095f61 100644
---
a/iotdb-client/service-rpc/src/main/i18n/zh/org/apache/iotdb/rpc/i18n/RpcMessages.java
+++
b/iotdb-client/service-rpc/src/main/i18n/zh/org/apache/iotdb/rpc/i18n/RpcMessages.java
@@ -22,6 +22,12 @@ public final class RpcMessages {
public static final String EXCEPTION_THIS_DATASET_IS_ALREADY_CLOSED_826EDCDB
= "该数据集已关闭";
public static final String EXCEPTION_UNKNOWN_TIME_PRECISION_ARG_F550A691 =
"未知时间精度:%s";
+ public static final String
+
EXCEPTION_AUTO_RESIZING_BUFFER_WAS_INTERRUPTED_WHILE_ALLOCATING_ARG_BYTES_516F5DA1
=
+ "AutoResizingBuffer 分配 %d 字节内存时被中断";
+ public static final String
+
EXCEPTION_AUTO_RESIZING_BUFFER_FAILED_TO_ALLOCATE_ARG_BYTES_AFTER_ARG_RETRIES_836DB2FD
=
+ "AutoResizingBuffer 申请 %d 字节内存失败,已重试 %d 次";
private RpcMessages() {}
}
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 ee86294cced..4249d270cfe 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
@@ -19,6 +19,7 @@
package org.apache.iotdb.rpc;
+import java.io.IOException;
import java.util.Arrays;
/**
@@ -32,7 +33,7 @@ import java.util.Arrays;
* of the required size and current capacity. The required size is bounded
below by the initial
* capacity.
*/
-class AutoResizingBuffer {
+class AutoResizingBuffer implements AutoCloseable {
static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
@@ -40,13 +41,24 @@ class AutoResizingBuffer {
private int bufTooLargeCounter = RpcUtils.MAX_BUFFER_OVERSIZE_TIME;
private final int initialCapacity;
private long lastShrinkTime;
+ private int accountedCapacity;
+ private boolean closed;
+ private AutoResizingBufferMemoryManager.MemoryAccount memoryAccount;
- public AutoResizingBuffer(int initialCapacity) {
- this.array = new byte[initialCapacity];
+ public AutoResizingBuffer(int initialCapacity) throws IOException {
this.initialCapacity = initialCapacity;
+ this.memoryAccount = AutoResizingBufferMemoryManager.createMemoryAccount();
+ memoryAccount.allocate(initialCapacity);
+ try {
+ this.array = new byte[initialCapacity];
+ } catch (RuntimeException | Error e) {
+ memoryAccount.release(initialCapacity);
+ throw e;
+ }
+ this.accountedCapacity = initialCapacity;
}
- public void resizeIfNecessary(int size) {
+ public void resizeIfNecessary(int size) throws IOException {
ensureCapacity(size);
size = Math.max(size, initialCapacity);
final int currentCapacity = this.array.length;
@@ -54,25 +66,25 @@ class AutoResizingBuffer {
if (currentCapacity * loadFactor > size
&& bufTooLargeCounter-- <= 0
&& System.currentTimeMillis() - lastShrinkTime >
RpcUtils.MIN_SHRINK_INTERVAL) {
- array = Arrays.copyOf(array, size + (currentCapacity - size) / 2);
+ resize(size + (currentCapacity - size) / 2);
bufTooLargeCounter = RpcUtils.MAX_BUFFER_OVERSIZE_TIME;
lastShrinkTime = System.currentTimeMillis();
}
}
- void ensureCapacity(int size) {
+ void ensureCapacity(int size) throws IOException {
ensureCapacity(size, MAX_ARRAY_SIZE);
}
- void ensureCapacity(int size, int maxCapacity) {
+ void ensureCapacity(int size, int maxCapacity) throws IOException {
+ reserveCurrentCapacityIfReleased();
int limit = Math.min(maxCapacity, MAX_ARRAY_SIZE);
if (size < 0 || size > limit) {
throw new IllegalArgumentException("Invalid buffer size: " + size);
}
final int currentCapacity = this.array.length;
if (currentCapacity < size) {
- this.array =
- Arrays.copyOf(array, Math.min(calculateNewCapacity(currentCapacity,
size), limit));
+ resize(Math.min(calculateNewCapacity(currentCapacity, size), limit));
bufTooLargeCounter = RpcUtils.MAX_BUFFER_OVERSIZE_TIME;
}
}
@@ -87,4 +99,44 @@ class AutoResizingBuffer {
public byte[] array() {
return this.array;
}
+
+ @Override
+ public void close() {
+ if (!closed) {
+ memoryAccount.release(accountedCapacity);
+ accountedCapacity = 0;
+ closed = true;
+ }
+ }
+
+ private void resize(int newCapacity) throws IOException {
+ final int currentCapacity = array.length;
+ if (newCapacity > currentCapacity) {
+ final int delta = newCapacity - currentCapacity;
+ memoryAccount.allocate(delta);
+ try {
+ array = Arrays.copyOf(array, newCapacity);
+ accountedCapacity += delta;
+ } catch (RuntimeException | Error e) {
+ memoryAccount.release(delta);
+ throw e;
+ }
+ } else if (newCapacity < currentCapacity) {
+ array = Arrays.copyOf(array, newCapacity);
+ final int delta = currentCapacity - newCapacity;
+ memoryAccount.release(delta);
+ accountedCapacity -= delta;
+ }
+ }
+
+ private void reserveCurrentCapacityIfReleased() throws IOException {
+ if (closed) {
+ AutoResizingBufferMemoryManager.MemoryAccount newMemoryAccount =
+ AutoResizingBufferMemoryManager.createMemoryAccount();
+ newMemoryAccount.allocate(array.length);
+ memoryAccount = newMemoryAccount;
+ accountedCapacity = array.length;
+ closed = false;
+ }
+ }
}
diff --git
a/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/AutoResizingBufferMemoryAllocationException.java
b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/AutoResizingBufferMemoryAllocationException.java
new file mode 100644
index 00000000000..8364b7b30d4
--- /dev/null
+++
b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/AutoResizingBufferMemoryAllocationException.java
@@ -0,0 +1,29 @@
+/*
+ * 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.rpc;
+
+import java.io.IOException;
+
+public final class AutoResizingBufferMemoryAllocationException extends
IOException {
+
+ public AutoResizingBufferMemoryAllocationException(final String message) {
+ super(message);
+ }
+}
diff --git
a/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/AutoResizingBufferMemoryControl.java
b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/AutoResizingBufferMemoryControl.java
new file mode 100644
index 00000000000..f4d9bcf9146
--- /dev/null
+++
b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/AutoResizingBufferMemoryControl.java
@@ -0,0 +1,32 @@
+/*
+ * 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.rpc;
+
+/** Memory accounting hook for {@link AutoResizingBuffer}. */
+public interface AutoResizingBufferMemoryControl {
+
+ boolean allocate(long sizeInBytes);
+
+ void release(long sizeInBytes);
+
+ default long getUsedMemoryInBytes() {
+ return 0;
+ }
+}
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
new file mode 100644
index 00000000000..37f659ce023
--- /dev/null
+++
b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/AutoResizingBufferMemoryManager.java
@@ -0,0 +1,161 @@
+/*
+ * 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.rpc;
+
+import org.apache.iotdb.rpc.i18n.RpcMessages;
+
+import java.io.IOException;
+import java.util.Objects;
+import java.util.concurrent.atomic.AtomicLong;
+
+public final class AutoResizingBufferMemoryManager {
+ private static final int MEMORY_ALLOCATE_MAX_RETRIES = 5;
+ private static final long DEFAULT_MEMORY_ALLOCATE_RETRY_INTERVAL_IN_MS =
2_000L;
+
+ private static final AutoResizingBufferMemoryControl NO_OP_MEMORY_CONTROL =
+ new AutoResizingBufferMemoryControl() {
+ @Override
+ public boolean allocate(long sizeInBytes) {
+ return true;
+ }
+
+ @Override
+ public void release(long sizeInBytes) {
+ // Do nothing.
+ }
+
+ @Override
+ public long getUsedMemoryInBytes() {
+ return 0;
+ }
+ };
+
+ private static volatile AutoResizingBufferMemoryControl memoryControl =
NO_OP_MEMORY_CONTROL;
+ private static volatile long memoryTotalSizeInBytes;
+ private static volatile long memoryAllocateRetryIntervalInMs =
+ DEFAULT_MEMORY_ALLOCATE_RETRY_INTERVAL_IN_MS;
+ private static final AtomicLong memoryAllocationCount = new AtomicLong();
+ private static final AtomicLong memoryAllocationFailureCount = new
AtomicLong();
+
+ private AutoResizingBufferMemoryManager() {
+ // Utility class.
+ }
+
+ public static void setMemoryControl(AutoResizingBufferMemoryControl
memoryControl) {
+ setMemoryControl(memoryControl, 0);
+ }
+
+ public static void setMemoryControl(
+ AutoResizingBufferMemoryControl memoryControl, long
memoryTotalSizeInBytes) {
+ AutoResizingBufferMemoryManager.memoryControl =
Objects.requireNonNull(memoryControl);
+ AutoResizingBufferMemoryManager.memoryTotalSizeInBytes = Math.max(0,
memoryTotalSizeInBytes);
+ }
+
+ static void resetMemoryControl() {
+ memoryControl = NO_OP_MEMORY_CONTROL;
+ memoryTotalSizeInBytes = 0;
+ memoryAllocateRetryIntervalInMs =
DEFAULT_MEMORY_ALLOCATE_RETRY_INTERVAL_IN_MS;
+ memoryAllocationCount.set(0);
+ memoryAllocationFailureCount.set(0);
+ }
+
+ static void setMemoryAllocateRetryIntervalInMs(long
memoryAllocateRetryIntervalInMs) {
+ AutoResizingBufferMemoryManager.memoryAllocateRetryIntervalInMs =
+ memoryAllocateRetryIntervalInMs;
+ }
+
+ static MemoryAccount createMemoryAccount() {
+ return new MemoryAccount(memoryControl);
+ }
+
+ private static void allocate(AutoResizingBufferMemoryControl memoryControl,
long sizeInBytes)
+ throws IOException {
+ if (sizeInBytes <= 0) {
+ return;
+ }
+ for (int i = 0; i < MEMORY_ALLOCATE_MAX_RETRIES; i++) {
+ if (memoryControl.allocate(sizeInBytes)) {
+ memoryAllocationCount.incrementAndGet();
+ return;
+ }
+ try {
+ Thread.sleep(memoryAllocateRetryIntervalInMs);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IOException(
+ String.format(
+ RpcMessages
+
.EXCEPTION_AUTO_RESIZING_BUFFER_WAS_INTERRUPTED_WHILE_ALLOCATING_ARG_BYTES_516F5DA1,
+ sizeInBytes),
+ e);
+ }
+ }
+ memoryAllocationFailureCount.incrementAndGet();
+ throw new AutoResizingBufferMemoryAllocationException(
+ String.format(
+ RpcMessages
+
.EXCEPTION_AUTO_RESIZING_BUFFER_FAILED_TO_ALLOCATE_ARG_BYTES_AFTER_ARG_RETRIES_836DB2FD,
+ sizeInBytes,
+ MEMORY_ALLOCATE_MAX_RETRIES));
+ }
+
+ private static void release(AutoResizingBufferMemoryControl memoryControl,
long sizeInBytes) {
+ if (sizeInBytes <= 0) {
+ return;
+ }
+ memoryControl.release(sizeInBytes);
+ }
+
+ public static long getMemoryAllocationCount() {
+ return memoryAllocationCount.get();
+ }
+
+ public static long getMemoryAllocationFailureCount() {
+ return memoryAllocationFailureCount.get();
+ }
+
+ public static long getMemoryTotalSizeInBytes() {
+ return memoryTotalSizeInBytes;
+ }
+
+ public static long getMemoryUsedSizeInBytes() {
+ return memoryControl.getUsedMemoryInBytes();
+ }
+
+ public static long getMemoryAvailableSizeInBytes() {
+ return Math.max(0, memoryTotalSizeInBytes - getMemoryUsedSizeInBytes());
+ }
+
+ static final class MemoryAccount {
+ private final AutoResizingBufferMemoryControl memoryControl;
+
+ private MemoryAccount(AutoResizingBufferMemoryControl memoryControl) {
+ this.memoryControl = memoryControl;
+ }
+
+ void allocate(long sizeInBytes) throws IOException {
+ AutoResizingBufferMemoryManager.allocate(memoryControl, sizeInBytes);
+ }
+
+ void release(long sizeInBytes) {
+ AutoResizingBufferMemoryManager.release(memoryControl, sizeInBytes);
+ }
+ }
+}
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 35833321ba3..035f8753de1 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
@@ -23,18 +23,24 @@ import org.apache.thrift.TConfiguration;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
+import java.io.IOException;
+
public class AutoScalingBufferReadTransport extends NonOpenTransport {
private final AutoResizingBuffer buf;
private int pos = 0;
private int limit = 0;
- public AutoScalingBufferReadTransport(int initialCapacity) {
+ public AutoScalingBufferReadTransport(int initialCapacity) throws
IOException {
this.buf = new AutoResizingBuffer(initialCapacity);
}
public void fill(TTransport inTrans, int length) throws TTransportException {
- buf.resizeIfNecessary(length);
+ try {
+ buf.resizeIfNecessary(length);
+ } catch (IOException e) {
+ throw new TTransportException(e);
+ }
inTrans.readAll(buf.array(), 0, length);
pos = 0;
limit = length;
@@ -89,10 +95,16 @@ public class AutoScalingBufferReadTransport extends
NonOpenTransport {
return limit - pos;
}
- public void resizeIfNecessary(int size) {
+ public void resizeIfNecessary(int size) throws IOException {
buf.resizeIfNecessary(size);
}
+ @Override
+ public void close() {
+ super.close();
+ buf.close();
+ }
+
public void limit(int newLimit) {
this.limit = newLimit;
}
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 c193bd3ea35..830dede7f54 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
@@ -22,6 +22,8 @@ package org.apache.iotdb.rpc;
import org.apache.thrift.TConfiguration;
import org.apache.thrift.transport.TTransportException;
+import java.io.IOException;
+
/**
* Note that this class is mainly copied from class {@link
* org.apache.thrift.transport.AutoExpandingBufferWriteTransport}. since that
class does not support
@@ -32,7 +34,7 @@ public class AutoScalingBufferWriteTransport extends
NonOpenTransport {
private final AutoResizingBuffer buf;
private int pos;
- public AutoScalingBufferWriteTransport(int initialCapacity) {
+ public AutoScalingBufferWriteTransport(int initialCapacity) throws
IOException {
this.buf = new AutoResizingBuffer(initialCapacity);
this.pos = 0;
}
@@ -61,7 +63,11 @@ public class AutoScalingBufferWriteTransport extends
NonOpenTransport {
}
// A small prefix during serialization does not indicate a small frame.
Only the complete
// frame size, supplied after flushing, may trigger shrinking.
- buf.ensureCapacity((int) requiredCapacity, limit);
+ try {
+ buf.ensureCapacity((int) requiredCapacity, limit);
+ } catch (IOException e) {
+ throw new TTransportException(e);
+ }
System.arraycopy(toWrite, off, buf.array(), pos, len);
pos += len;
}
@@ -86,10 +92,16 @@ public class AutoScalingBufferWriteTransport extends
NonOpenTransport {
pos = 0;
}
- public void resizeIfNecessary(int size) {
+ public void resizeIfNecessary(int size) throws IOException {
buf.resizeIfNecessary(size);
}
+ @Override
+ public void close() {
+ super.close();
+ buf.close();
+ }
+
@Override
public byte[] getBuffer() {
return buf.array();
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 ff2037d81af..009d86a8623 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
@@ -34,10 +34,27 @@ public abstract class TCompressedElasticFramedTransport
extends TElasticFramedTr
TTransport underlying,
int thriftDefaultBufferSize,
int thriftMaxFrameSize,
- boolean copyBinary) {
+ boolean copyBinary)
+ throws TTransportException {
super(underlying, thriftDefaultBufferSize, thriftMaxFrameSize, copyBinary);
- writeCompressBuffer = new
AutoScalingBufferWriteTransport(thriftDefaultBufferSize);
- readCompressBuffer = new
AutoScalingBufferReadTransport(thriftDefaultBufferSize);
+ try {
+ writeCompressBuffer = new
AutoScalingBufferWriteTransport(thriftDefaultBufferSize);
+ readCompressBuffer = new
AutoScalingBufferReadTransport(thriftDefaultBufferSize);
+ } catch (IOException e) {
+ closeAllocatedBuffers();
+ throw new TTransportException(e);
+ }
+ }
+
+ @Override
+ protected void closeAllocatedBuffers() {
+ super.closeAllocatedBuffers();
+ if (writeCompressBuffer != null) {
+ writeCompressBuffer.close();
+ }
+ if (readCompressBuffer != null) {
+ readCompressBuffer.close();
+ }
}
@Override
@@ -88,7 +105,11 @@ public abstract class TCompressedElasticFramedTransport
extends TElasticFramedTr
}
writeBuffer.reset();
- writeBuffer.resizeIfNecessary(length);
+ try {
+ writeBuffer.resizeIfNecessary(length);
+ } catch (IOException e) {
+ throw new TTransportException(e);
+ }
underlying.flush();
}
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 beff263faee..40f0db94a53 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
@@ -30,6 +30,7 @@ import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import java.io.EOFException;
+import java.io.IOException;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
@@ -71,7 +72,7 @@ public class TElasticFramedTransport extends TTransport {
}
@Override
- public TTransport getTransport(TTransport trans) {
+ public TTransport getTransport(TTransport trans) throws
TTransportException {
return new TElasticFramedTransport(
trans, thriftDefaultBufferSize, thriftMaxFrameSize, copyBinary);
}
@@ -81,17 +82,23 @@ public class TElasticFramedTransport extends TTransport {
TTransport underlying,
int thriftDefaultBufferSize,
int thriftMaxFrameSize,
- boolean copyBinary) {
+ boolean copyBinary)
+ throws TTransportException {
this.underlying = underlying;
this.thriftDefaultBufferSize = thriftDefaultBufferSize;
this.thriftMaxFrameSize = thriftMaxFrameSize;
this.copyBinary = copyBinary;
- readBuffer = new AutoScalingBufferReadTransport(thriftDefaultBufferSize);
- writeBuffer =
- new AutoScalingBufferWriteTransport(
- Math.min(
- thriftDefaultBufferSize,
- Math.min(thriftMaxFrameSize,
AutoResizingBuffer.MAX_ARRAY_SIZE)));
+ try {
+ readBuffer = new AutoScalingBufferReadTransport(thriftDefaultBufferSize);
+ writeBuffer =
+ new AutoScalingBufferWriteTransport(
+ Math.min(
+ thriftDefaultBufferSize,
+ Math.min(thriftMaxFrameSize,
AutoResizingBuffer.MAX_ARRAY_SIZE)));
+ } catch (IOException e) {
+ closeAllocatedBuffers();
+ throw new TTransportException(e);
+ }
}
protected final int thriftDefaultBufferSize;
@@ -115,7 +122,20 @@ public class TElasticFramedTransport extends TTransport {
@Override
public void close() {
- underlying.close();
+ try {
+ underlying.close();
+ } finally {
+ closeAllocatedBuffers();
+ }
+ }
+
+ protected void closeAllocatedBuffers() {
+ if (readBuffer != null) {
+ readBuffer.close();
+ }
+ if (writeBuffer != null) {
+ writeBuffer.close();
+ }
}
@Override
@@ -263,7 +283,11 @@ public class TElasticFramedTransport extends TTransport {
underlying.write(i32buf, 0, 4);
underlying.write(writeBuffer.getBuffer(), 0, length);
writeBuffer.reset();
- writeBuffer.resizeIfNecessary(length);
+ try {
+ writeBuffer.resizeIfNecessary(length);
+ } catch (IOException e) {
+ throw new TTransportException(e);
+ }
underlying.flush();
}
diff --git
a/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/TSnappyElasticFramedTransport.java
b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/TSnappyElasticFramedTransport.java
index 79ebc7983e3..fd9d4ffbba3 100644
---
a/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/TSnappyElasticFramedTransport.java
+++
b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/TSnappyElasticFramedTransport.java
@@ -20,6 +20,7 @@
package org.apache.iotdb.rpc;
import org.apache.thrift.transport.TTransport;
+import org.apache.thrift.transport.TTransportException;
import org.xerial.snappy.Snappy;
import java.io.IOException;
@@ -41,13 +42,13 @@ public class TSnappyElasticFramedTransport extends
TCompressedElasticFramedTrans
}
@Override
- public TTransport getTransport(TTransport trans) {
+ public TTransport getTransport(TTransport trans) throws
TTransportException {
return new TSnappyElasticFramedTransport(
trans, thriftDefaultBufferSize, thriftMaxFrameSize, copyBinary);
}
}
- public TSnappyElasticFramedTransport(TTransport underlying) {
+ public TSnappyElasticFramedTransport(TTransport underlying) throws
TTransportException {
this(underlying, RpcUtils.THRIFT_DEFAULT_BUF_CAPACITY,
RpcUtils.THRIFT_FRAME_MAX_SIZE, true);
}
@@ -55,7 +56,8 @@ public class TSnappyElasticFramedTransport extends
TCompressedElasticFramedTrans
TTransport underlying,
int thriftDefaultBufferSize,
int thriftMaxFrameSize,
- boolean copyBinary) {
+ boolean copyBinary)
+ throws TTransportException {
super(underlying, thriftDefaultBufferSize, thriftMaxFrameSize, copyBinary);
}
diff --git
a/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/TimeoutChangeableTFastFramedTransport.java
b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/TimeoutChangeableTFastFramedTransport.java
index 77c2bbf6b97..505e1a99405 100644
---
a/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/TimeoutChangeableTFastFramedTransport.java
+++
b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/TimeoutChangeableTFastFramedTransport.java
@@ -21,6 +21,7 @@ package org.apache.iotdb.rpc;
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 java.net.SocketException;
@@ -31,7 +32,8 @@ public class TimeoutChangeableTFastFramedTransport extends
TElasticFramedTranspo
private final TSocket underlyingSocket;
public TimeoutChangeableTFastFramedTransport(
- TSocket underlying, int thriftDefaultBufferSize, int thriftMaxFrameSize,
boolean copyBinary) {
+ TSocket underlying, int thriftDefaultBufferSize, int thriftMaxFrameSize,
boolean copyBinary)
+ throws TTransportException {
super(underlying, thriftDefaultBufferSize, thriftMaxFrameSize, copyBinary);
this.underlyingSocket = underlying;
}
@@ -65,7 +67,7 @@ public class TimeoutChangeableTFastFramedTransport extends
TElasticFramedTranspo
}
@Override
- public TTransport getTransport(TTransport trans) {
+ public TTransport getTransport(TTransport trans) throws
TTransportException {
if (trans instanceof TSocket) {
return new TimeoutChangeableTFastFramedTransport(
(TSocket) trans, thriftDefaultBufferSize, thriftMaxFrameSize,
copyBinary);
diff --git
a/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/TimeoutChangeableTSnappyFramedTransport.java
b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/TimeoutChangeableTSnappyFramedTransport.java
index 168f52662aa..ecd807e38d6 100644
---
a/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/TimeoutChangeableTSnappyFramedTransport.java
+++
b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/TimeoutChangeableTSnappyFramedTransport.java
@@ -21,6 +21,7 @@ package org.apache.iotdb.rpc;
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 java.net.SocketException;
@@ -31,7 +32,8 @@ public class TimeoutChangeableTSnappyFramedTransport extends
TSnappyElasticFrame
private final TSocket underlyingSocket;
public TimeoutChangeableTSnappyFramedTransport(
- TSocket underlying, int thriftDefaultBufferSize, int thriftMaxFrameSize,
boolean copyBinary) {
+ TSocket underlying, int thriftDefaultBufferSize, int thriftMaxFrameSize,
boolean copyBinary)
+ throws TTransportException {
super(underlying, thriftDefaultBufferSize, thriftMaxFrameSize, copyBinary);
this.underlyingSocket = underlying;
}
@@ -65,7 +67,7 @@ public class TimeoutChangeableTSnappyFramedTransport extends
TSnappyElasticFrame
}
@Override
- public TTransport getTransport(TTransport trans) {
+ public TTransport getTransport(TTransport trans) throws
TTransportException {
if (trans instanceof TSocket) {
return new TimeoutChangeableTSnappyFramedTransport(
(TSocket) trans, thriftDefaultBufferSize, thriftMaxFrameSize,
copyBinary);
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 4933a0e0e96..e40dd0af721 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
@@ -21,14 +21,24 @@ package org.apache.iotdb.rpc;
import org.apache.thrift.transport.TMemoryBuffer;
import org.apache.thrift.transport.TTransportException;
+import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
+import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Random;
+import java.util.concurrent.atomic.AtomicLong;
public class AutoResizingBufferTest {
+ private final TestMemoryControl memoryControl = new TestMemoryControl();
+
+ @After
+ public void tearDown() {
+ AutoResizingBufferMemoryManager.resetMemoryControl();
+ }
+
@Test
public void testGrowthNearIntegerLimitKeepsHeadroom() {
Assert.assertEquals(
@@ -41,7 +51,7 @@ public class AutoResizingBufferTest {
}
@Test
- public void testInvalidBufferSizeDoesNotResize() {
+ public void testInvalidBufferSizeDoesNotResize() throws Exception {
AutoResizingBuffer buffer = new AutoResizingBuffer(8);
for (int size : new int[] {-1, Integer.MAX_VALUE}) {
try {
@@ -71,7 +81,7 @@ public class AutoResizingBufferTest {
}
@Test
- public void testGrowthPreservesDataAndHeadroom() {
+ public void testGrowthPreservesDataAndHeadroom() throws Exception {
AutoResizingBuffer buffer = new AutoResizingBuffer(100);
buffer.array()[99] = 42;
buffer.resizeIfNecessary(110);
@@ -243,6 +253,181 @@ public class AutoResizingBufferTest {
}
}
+ @Test
+ public void testAllocateAndReleaseMemoryWhenResizing() throws Exception {
+ AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
+
+ AutoResizingBuffer buffer = new AutoResizingBuffer(100);
+ Assert.assertEquals(100, memoryControl.getUsedMemoryInBytes());
+
+ buffer.resizeIfNecessary(200);
+ Assert.assertEquals(200, buffer.array().length);
+ Assert.assertEquals(200, memoryControl.getUsedMemoryInBytes());
+
+ setLastShrinkTime(buffer, System.currentTimeMillis() -
RpcUtils.MIN_SHRINK_INTERVAL - 1);
+ for (int i = 0; i <= RpcUtils.MAX_BUFFER_OVERSIZE_TIME; i++) {
+ buffer.resizeIfNecessary(101);
+ }
+ Assert.assertEquals(150, buffer.array().length);
+ Assert.assertEquals(150, memoryControl.getUsedMemoryInBytes());
+
+ buffer.close();
+ Assert.assertEquals(0, memoryControl.getUsedMemoryInBytes());
+ }
+
+ @Test
+ public void testThrowIOExceptionWhenMemoryIsInsufficient() throws Exception {
+ memoryControl.setLimit(120);
+ AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
+ AutoResizingBufferMemoryManager.setMemoryAllocateRetryIntervalInMs(1);
+
+ AutoResizingBuffer buffer = new AutoResizingBuffer(100);
+ try {
+ buffer.resizeIfNecessary(200);
+ Assert.fail("Expected IOException");
+ } catch (AutoResizingBufferMemoryAllocationException e) {
+ Assert.assertTrue(e.getMessage().contains("100"));
+ Assert.assertTrue(e.getMessage().contains("5"));
+ } finally {
+ Assert.assertEquals(100, memoryControl.getUsedMemoryInBytes());
+ buffer.close();
+ }
+ }
+
+ @Test
+ public void testInterruptedMemoryAllocationRemainsRegularIOException() {
+ memoryControl.setLimit(0);
+ AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
+ AutoResizingBufferMemoryManager.setMemoryAllocateRetryIntervalInMs(1);
+ final boolean wasInterrupted = Thread.interrupted();
+
+ try {
+ Thread.currentThread().interrupt();
+ new AutoResizingBuffer(100);
+ Assert.fail("Expected allocation interruption");
+ } catch (IOException e) {
+ Assert.assertFalse(e instanceof
AutoResizingBufferMemoryAllocationException);
+ Assert.assertTrue(e.getCause() instanceof InterruptedException);
+ Assert.assertTrue(Thread.currentThread().isInterrupted());
+ } finally {
+ if (wasInterrupted) {
+ Thread.currentThread().interrupt();
+ } else {
+ Thread.interrupted();
+ }
+ }
+ }
+
+ @Test
+ public void testMemoryAllocationMetrics() throws Exception {
+ memoryControl.setLimit(120);
+ AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
+ AutoResizingBufferMemoryManager.setMemoryAllocateRetryIntervalInMs(1);
+
+ AutoResizingBuffer buffer = new AutoResizingBuffer(100);
+ Assert.assertEquals(1,
AutoResizingBufferMemoryManager.getMemoryAllocationCount());
+ Assert.assertEquals(0,
AutoResizingBufferMemoryManager.getMemoryAllocationFailureCount());
+
+ try {
+ buffer.resizeIfNecessary(200);
+ Assert.fail("Expected IOException");
+ } catch (IOException ignored) {
+ Assert.assertEquals(1,
AutoResizingBufferMemoryManager.getMemoryAllocationCount());
+ Assert.assertEquals(1,
AutoResizingBufferMemoryManager.getMemoryAllocationFailureCount());
+ } finally {
+ buffer.close();
+ }
+ }
+
+ @Test
+ public void testElasticFramedTransportReleasesMemoryWhenClosed() throws
Exception {
+ AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
+
+ TElasticFramedTransport transport =
+ new TElasticFramedTransport(new TMemoryBuffer(0), 100, 1024, true);
+ Assert.assertEquals(200, memoryControl.getUsedMemoryInBytes());
+
+ transport.close();
+ Assert.assertEquals(0, memoryControl.getUsedMemoryInBytes());
+ }
+
+ @Test
+ public void testElasticFramedTransportReleasesMemoryWhenConstructorFails() {
+ memoryControl.setLimit(150);
+ AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
+ AutoResizingBufferMemoryManager.setMemoryAllocateRetryIntervalInMs(1);
+
+ try {
+ new TElasticFramedTransport(new TMemoryBuffer(0), 100, 1024, true);
+ Assert.fail("Expected TTransportException");
+ } catch (TTransportException e) {
+ Assert.assertEquals(0, memoryControl.getUsedMemoryInBytes());
+ }
+ }
+
+ @Test
+ public void testSnappyElasticFramedTransportReleasesMemory() throws
Exception {
+ AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
+
+ TSnappyElasticFramedTransport transport =
+ new TSnappyElasticFramedTransport(new TMemoryBuffer(0), 100, 1024,
true);
+ Assert.assertEquals(400, memoryControl.getUsedMemoryInBytes());
+
+ transport.close();
+ Assert.assertEquals(0, memoryControl.getUsedMemoryInBytes());
+ }
+
+ @Test
+ public void
testSnappyElasticFramedTransportReleasesMemoryWhenConstructorFails() {
+ memoryControl.setLimit(350);
+ AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
+ AutoResizingBufferMemoryManager.setMemoryAllocateRetryIntervalInMs(1);
+
+ try {
+ new TSnappyElasticFramedTransport(new TMemoryBuffer(0), 100, 1024, true);
+ Assert.fail("Expected TTransportException");
+ } catch (TTransportException e) {
+ Assert.assertEquals(0, memoryControl.getUsedMemoryInBytes());
+ }
+ }
+
+ @Test
+ public void testBufferReleasesMemoryToTheControlUsedForAllocation() throws
Exception {
+ TestMemoryControl firstMemoryControl = new TestMemoryControl();
+ AutoResizingBufferMemoryManager.setMemoryControl(firstMemoryControl);
+ AutoResizingBuffer firstBuffer = new AutoResizingBuffer(100);
+
+ TestMemoryControl secondMemoryControl = new TestMemoryControl();
+ AutoResizingBufferMemoryManager.setMemoryControl(secondMemoryControl);
+ AutoResizingBuffer secondBuffer = new AutoResizingBuffer(200);
+
+ firstBuffer.close();
+ Assert.assertEquals(0, firstMemoryControl.getUsedMemoryInBytes());
+ Assert.assertEquals(200, secondMemoryControl.getUsedMemoryInBytes());
+
+ secondBuffer.close();
+ Assert.assertEquals(0, secondMemoryControl.getUsedMemoryInBytes());
+ }
+
+ @Test
+ public void testBufferCreatedWithoutControlDoesNotReleaseToNewControl()
throws Exception {
+ AutoResizingBuffer bufferWithoutControl = new AutoResizingBuffer(100);
+
+ AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
+ AutoResizingBuffer bufferWithControl = new AutoResizingBuffer(100);
+
+ bufferWithoutControl.close();
+ Assert.assertEquals(100, memoryControl.getUsedMemoryInBytes());
+
+ bufferWithoutControl.ensureCapacity(100);
+ Assert.assertEquals(200, memoryControl.getUsedMemoryInBytes());
+ bufferWithoutControl.close();
+ Assert.assertEquals(100, memoryControl.getUsedMemoryInBytes());
+
+ bufferWithControl.close();
+ Assert.assertEquals(0, memoryControl.getUsedMemoryInBytes());
+ }
+
private void setLastShrinkTime(AutoResizingBuffer buffer, long
lastShrinkTime) throws Exception {
Field field = AutoResizingBuffer.class.getDeclaredField("lastShrinkTime");
field.setAccessible(true);
@@ -260,4 +445,38 @@ public class AutoResizingBufferTest {
? new TSnappyElasticFramedTransport(new TMemoryBuffer(0), 100, 2048,
true)
: new TElasticFramedTransport(new TMemoryBuffer(0), 100, 2048, true);
}
+
+ private static class TestMemoryControl implements
AutoResizingBufferMemoryControl {
+
+ private final AtomicLong usedMemoryInBytes = new AtomicLong();
+ private long limit = Long.MAX_VALUE;
+
+ @Override
+ public boolean allocate(long sizeInBytes) {
+ while (true) {
+ long currentUsedMemory = usedMemoryInBytes.get();
+ long nextUsedMemory = currentUsedMemory + sizeInBytes;
+ if (nextUsedMemory > limit) {
+ return false;
+ }
+ if (usedMemoryInBytes.compareAndSet(currentUsedMemory,
nextUsedMemory)) {
+ return true;
+ }
+ }
+ }
+
+ @Override
+ public void release(long sizeInBytes) {
+ usedMemoryInBytes.addAndGet(-sizeInBytes);
+ }
+
+ @Override
+ public long getUsedMemoryInBytes() {
+ return usedMemoryInBytes.get();
+ }
+
+ private void setLimit(long limit) {
+ this.limit = limit;
+ }
+ }
}
diff --git
a/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/ratis/utils/Utils.java
b/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/ratis/utils/Utils.java
index 07dac6f8cf2..67540f6d593 100644
---
a/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/ratis/utils/Utils.java
+++
b/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/ratis/utils/Utils.java
@@ -48,7 +48,9 @@ import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.transport.TByteBuffer;
import java.io.File;
+import java.io.IOException;
import java.nio.ByteBuffer;
+import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
@@ -171,11 +173,19 @@ public class Utils {
}
public static ByteBuffer serializeTSStatus(TSStatus status) throws
TException {
- AutoScalingBufferWriteTransport byteBuffer =
- new AutoScalingBufferWriteTransport(TEMP_BUFFER_SIZE);
- TCompactProtocol protocol = new TCompactProtocol(byteBuffer);
- status.write(protocol);
- return ByteBuffer.wrap(byteBuffer.getBuffer());
+ AutoScalingBufferWriteTransport byteBuffer;
+ try {
+ byteBuffer = new AutoScalingBufferWriteTransport(TEMP_BUFFER_SIZE);
+ } catch (IOException e) {
+ throw new TException(e);
+ }
+ try {
+ TCompactProtocol protocol = new TCompactProtocol(byteBuffer);
+ status.write(protocol);
+ return ByteBuffer.wrap(Arrays.copyOf(byteBuffer.getBuffer(),
byteBuffer.getPos()));
+ } finally {
+ byteBuffer.close();
+ }
}
public static TSStatus deserializeFrom(ByteBuffer buffer) throws TException {
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBConfig.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBConfig.java
index 0b3bafb8935..7775d750c22 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBConfig.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBConfig.java
@@ -159,6 +159,9 @@ public class IoTDBConfig {
/** Memory allocated for the pipe */
private long allocateMemoryForPipe = Runtime.getRuntime().maxMemory() / 10;
+ /** Memory allocated for RPC auto-resizing buffers */
+ private long allocateMemoryForAutoResizingBuffer =
Runtime.getRuntime().maxMemory() / 20;
+
private long allocateMemoryPerWalCache = 512 * 1024;
/** Ratio of memory allocated for buffered arrays */
@@ -2231,6 +2234,14 @@ public class IoTDBConfig {
this.allocateMemoryForPipe = allocateMemoryForPipe;
}
+ public long getAllocateMemoryForAutoResizingBuffer() {
+ return allocateMemoryForAutoResizingBuffer;
+ }
+
+ public void setAllocateMemoryForAutoResizingBuffer(long
allocateMemoryForAutoResizingBuffer) {
+ this.allocateMemoryForAutoResizingBuffer =
allocateMemoryForAutoResizingBuffer;
+ }
+
public long getAllocateMemoryPerWalCache() {
return allocateMemoryPerWalCache;
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBDescriptor.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBDescriptor.java
index 30722656ac1..5b572e4a1c9 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBDescriptor.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBDescriptor.java
@@ -2231,6 +2231,11 @@ public class IoTDBDescriptor {
if (proportions.length >= 6) {
conf.setAllocateMemoryForPipe(
maxMemoryAvailable * Integer.parseInt(proportions[4].trim()) /
proportionSum);
+ conf.setAllocateMemoryForAutoResizingBuffer(
+ maxMemoryAvailable
+ * Integer.parseInt(proportions[proportions.length -
1].trim())
+ / proportionSum
+ / 2);
} else {
conf.setAllocateMemoryForPipe(
(maxMemoryAvailable
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/service/DataNode.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/service/DataNode.java
index 89064800061..6dc97242d14 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/service/DataNode.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/service/DataNode.java
@@ -108,6 +108,8 @@ import
org.apache.iotdb.db.trigger.service.TriggerInformationUpdater;
import org.apache.iotdb.db.trigger.service.TriggerManagementService;
import org.apache.iotdb.metrics.config.MetricConfigDescriptor;
import org.apache.iotdb.metrics.utils.InternalReporterType;
+import org.apache.iotdb.rpc.AutoResizingBufferMemoryControl;
+import org.apache.iotdb.rpc.AutoResizingBufferMemoryManager;
import org.apache.iotdb.rpc.TSStatusCode;
import org.apache.iotdb.udf.api.exception.UDFManagementException;
@@ -129,6 +131,7 @@ import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import static org.apache.iotdb.commons.conf.IoTDBConstant.DEFAULT_CLUSTER_NAME;
@@ -138,6 +141,7 @@ public class DataNode extends ServerCommandLine implements
DataNodeMBean {
private static final Logger logger = LoggerFactory.getLogger(DataNode.class);
private static final IoTDBConfig config =
IoTDBDescriptor.getInstance().getConfig();
+ private static boolean autoResizingBufferMemoryControlInitialized;
private final String mbeanName =
String.format(
@@ -229,10 +233,51 @@ public class DataNode extends ServerCommandLine
implements DataNodeMBean {
}
}
+ private static synchronized void activateAutoResizingBufferMemoryControl() {
+ if (autoResizingBufferMemoryControlInitialized) {
+ return;
+ }
+ autoResizingBufferMemoryControlInitialized = true;
+
+ long memoryLimit = config.getAllocateMemoryForAutoResizingBuffer();
+ if (memoryLimit <= 0) {
+ return;
+ }
+
+ AtomicLong usedMemory = new AtomicLong();
+ AutoResizingBufferMemoryManager.setMemoryControl(
+ new AutoResizingBufferMemoryControl() {
+ @Override
+ public boolean allocate(long sizeInBytes) {
+ while (true) {
+ long currentUsedMemory = usedMemory.get();
+ if (sizeInBytes > memoryLimit - currentUsedMemory) {
+ return false;
+ }
+ if (usedMemory.compareAndSet(currentUsedMemory,
currentUsedMemory + sizeInBytes)) {
+ return true;
+ }
+ }
+ }
+
+ @Override
+ public void release(long sizeInBytes) {
+ usedMemory.addAndGet(-sizeInBytes);
+ }
+
+ @Override
+ public long getUsedMemoryInBytes() {
+ return usedMemory.get();
+ }
+ },
+ memoryLimit);
+ }
+
@Override
protected void start() {
boolean isFirstStart;
try {
+ activateAutoResizingBufferMemoryControl();
// Check if this DataNode is start for the first time and do other
pre-checks
isFirstStart = prepareDataNode();
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/service/metrics/DataNodeMetricsHelper.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/service/metrics/DataNodeMetricsHelper.java
index 17463aa357f..afc7bad3a9e 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/service/metrics/DataNodeMetricsHelper.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/service/metrics/DataNodeMetricsHelper.java
@@ -25,6 +25,7 @@ import org.apache.iotdb.commons.concurrent.ThreadName;
import org.apache.iotdb.commons.concurrent.ThreadPoolMetrics;
import org.apache.iotdb.commons.conf.CommonDescriptor;
import org.apache.iotdb.commons.conf.IoTDBConstant;
+import org.apache.iotdb.commons.memory.AutoResizingBufferMemoryMetrics;
import org.apache.iotdb.commons.service.metric.JvmGcMonitorMetrics;
import org.apache.iotdb.commons.service.metric.MetricService;
import org.apache.iotdb.commons.service.metric.PerformanceOverviewMetrics;
@@ -68,6 +69,7 @@ public class DataNodeMetricsHelper {
MetricService.getInstance().addMetricSet(new
DiskMetrics(IoTDBConstant.DN_ROLE));
MetricService.getInstance().addMetricSet(new
NetMetrics(IoTDBConstant.DN_ROLE));
MetricService.getInstance().addMetricSet(ClientManagerMetrics.getInstance());
+ MetricService.getInstance().addMetricSet(new
AutoResizingBufferMemoryMetrics());
initCpuMetrics();
initSystemMetrics();
MetricService.getInstance().addMetricSet(WritingMetrics.getInstance());
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskTest.java
index 86bf4c5b25f..763bf7d24a7 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskTest.java
@@ -24,6 +24,7 @@ import org.apache.iotdb.commons.conf.CommonDescriptor;
import org.apache.iotdb.commons.exception.pipe.PipeRuntimeException;
import
org.apache.iotdb.commons.exception.pipe.PipeRuntimeSinkCriticalException;
import
org.apache.iotdb.commons.exception.pipe.PipeRuntimeSinkNonReportTimeConfigurableException;
+import
org.apache.iotdb.commons.exception.pipe.PipeRuntimeSinkResourceException;
import
org.apache.iotdb.commons.pipe.agent.task.connection.UnboundedBlockingPendingQueue;
import org.apache.iotdb.commons.pipe.agent.task.progress.CommitterKey;
import org.apache.iotdb.commons.pipe.event.EnrichedEvent;
@@ -40,10 +41,13 @@ import
org.apache.iotdb.pipe.api.event.dml.insertion.TabletInsertionEvent;
import org.apache.iotdb.pipe.api.exception.PipeConnectionException;
import org.apache.iotdb.pipe.api.exception.PipeException;
+import org.apache.thrift.transport.TTransportException;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
+import java.io.IOException;
+import java.net.SocketException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
@@ -534,10 +538,124 @@ public class PipeSinkSubtaskTest {
}
}
+ @Test
+ public void
testBrokenPipeFromReceiverResourcePressureDoesNotReportCriticalException() {
+ final long originalSleepIntervalInitMs =
+
CommonDescriptor.getInstance().getConfig().getPipeSinkSubtaskSleepIntervalInitMs();
+ final long originalSleepIntervalMaxMs =
+
CommonDescriptor.getInstance().getConfig().getPipeSinkSubtaskSleepIntervalMaxMs();
+
CommonDescriptor.getInstance().getConfig().setPipeSinkSubtaskSleepIntervalInitMs(1);
+
CommonDescriptor.getInstance().getConfig().setPipeSinkSubtaskSleepIntervalMaxMs(2);
+
+ final PipeConnector connector = mock(PipeConnector.class);
+ final UnboundedBlockingPendingQueue<Event> pendingQueue =
+ mock(UnboundedBlockingPendingQueue.class);
+ final CapturingPipeSinkSubtask subtask = new
CapturingPipeSinkSubtask(pendingQueue, connector);
+
+ try {
+ subtask.handleExceptionForTest(
+ mock(EnrichedEvent.class),
+ new PipeException("transfer failed", new IOException("Broken
pipe")));
+
+ Assert.assertEquals(
+ PipeResourceFailureType.NETWORK_TIMEOUT,
subtask.getReportedResourceFailureType());
+ Assert.assertNull(subtask.getReportedException());
+ } finally {
+ subtask.close();
+ CommonDescriptor.getInstance()
+ .getConfig()
+ .setPipeSinkSubtaskSleepIntervalInitMs(originalSleepIntervalInitMs);
+ CommonDescriptor.getInstance()
+ .getConfig()
+ .setPipeSinkSubtaskSleepIntervalMaxMs(originalSleepIntervalMaxMs);
+ }
+ }
+
+ @Test
+ public void testConnectionResetRetriesLocallyWhenConnectionRetryIsDisabled()
throws Exception {
+ final long originalSleepIntervalInitMs =
+
CommonDescriptor.getInstance().getConfig().getPipeSinkSubtaskSleepIntervalInitMs();
+ final long originalSleepIntervalMaxMs =
+
CommonDescriptor.getInstance().getConfig().getPipeSinkSubtaskSleepIntervalMaxMs();
+ final boolean originalRetryLocallyForConnectionError =
+
CommonDescriptor.getInstance().getConfig().isPipeSinkRetryLocallyForConnectionError();
+
CommonDescriptor.getInstance().getConfig().setPipeSinkSubtaskSleepIntervalInitMs(1);
+
CommonDescriptor.getInstance().getConfig().setPipeSinkSubtaskSleepIntervalMaxMs(2);
+
CommonDescriptor.getInstance().getConfig().setPipeSinkRetryLocallyForConnectionError(false);
+
+ final PipeConnector connector = mock(PipeConnector.class);
+ final UnboundedBlockingPendingQueue<Event> pendingQueue =
+ mock(UnboundedBlockingPendingQueue.class);
+ final CapturingPipeSinkSubtask subtask = new
CapturingPipeSinkSubtask(pendingQueue, connector);
+ final EnrichedEvent event = mock(EnrichedEvent.class);
+ subtask.prepareFailure(event);
+ subtask.allowSubmittingSelf();
+
+ try {
+ subtask.onFailure(
+ new PipeConnectionException(
+ "transfer failed", new TTransportException(new
SocketException("Connection reset"))));
+
+ Assert.assertEquals(
+ PipeResourceFailureType.NETWORK_TIMEOUT,
subtask.getReportedResourceFailureType());
+ Assert.assertNull(subtask.getReportedException());
+ Assert.assertEquals(1, subtask.getRetrySubmissionCount());
+ verify(connector).handshake();
+ } finally {
+ subtask.close();
+ CommonDescriptor.getInstance()
+ .getConfig()
+ .setPipeSinkSubtaskSleepIntervalInitMs(originalSleepIntervalInitMs);
+ CommonDescriptor.getInstance()
+ .getConfig()
+ .setPipeSinkSubtaskSleepIntervalMaxMs(originalSleepIntervalMaxMs);
+ CommonDescriptor.getInstance()
+ .getConfig()
+
.setPipeSinkRetryLocallyForConnectionError(originalRetryLocallyForConnectionError);
+ }
+ }
+
+ @Test
+ public void testForcedRetryQueueResourceFailureRetriesWithoutCriticalStop() {
+ final long originalSleepIntervalInitMs =
+
CommonDescriptor.getInstance().getConfig().getPipeSinkSubtaskSleepIntervalInitMs();
+ final long originalSleepIntervalMaxMs =
+
CommonDescriptor.getInstance().getConfig().getPipeSinkSubtaskSleepIntervalMaxMs();
+
CommonDescriptor.getInstance().getConfig().setPipeSinkSubtaskSleepIntervalInitMs(1);
+
CommonDescriptor.getInstance().getConfig().setPipeSinkSubtaskSleepIntervalMaxMs(2);
+
+ final PipeConnector connector = mock(PipeConnector.class);
+ final UnboundedBlockingPendingQueue<Event> pendingQueue =
+ mock(UnboundedBlockingPendingQueue.class);
+ final CapturingPipeSinkSubtask subtask = new
CapturingPipeSinkSubtask(pendingQueue, connector);
+ final EnrichedEvent event = mock(EnrichedEvent.class);
+ subtask.prepareFailure(event);
+ subtask.allowSubmittingSelf();
+
+ try {
+ subtask.onFailure(
+ new PipeRuntimeSinkResourceException(
+ "retry queue resource failure",
PipeResourceFailureType.NETWORK_TIMEOUT, true));
+
+ Assert.assertNull(subtask.getReportedException());
+ Assert.assertNull(subtask.getReportedResourceFailureType());
+ Assert.assertEquals(1, subtask.getRetrySubmissionCount());
+ } finally {
+ subtask.close();
+ CommonDescriptor.getInstance()
+ .getConfig()
+ .setPipeSinkSubtaskSleepIntervalInitMs(originalSleepIntervalInitMs);
+ CommonDescriptor.getInstance()
+ .getConfig()
+ .setPipeSinkSubtaskSleepIntervalMaxMs(originalSleepIntervalMaxMs);
+ }
+ }
+
private static class CapturingPipeSinkSubtask extends PipeSinkSubtask {
private PipeRuntimeException reportedException;
private PipeResourceFailureType reportedResourceFailureType;
+ private int retrySubmissionCount;
private CapturingPipeSinkSubtask(
final UnboundedBlockingPendingQueue<Event> pendingQueue, final
PipeConnector connector) {
@@ -564,10 +682,22 @@ public class PipeSinkSubtaskTest {
return reportedResourceFailureType;
}
+ private int getRetrySubmissionCount() {
+ return retrySubmissionCount;
+ }
+
private void handleExceptionForTest(final EnrichedEvent event, final
Exception exception) {
handleException(event, exception);
}
+ @Override
+ public void submitSelf() {
+ retrySubmissionCount++;
+ }
+
+ @Override
+ protected void sleepIfNoHighPriorityTask(final long sleepMillis) {}
+
@Override
protected void report(final EnrichedEvent event, final
PipeRuntimeException exception) {
reportedException = exception;
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/sink/protocol/thrift/async/IoTDBDataRegionAsyncSinkTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/sink/protocol/thrift/async/IoTDBDataRegionAsyncSinkTest.java
index fb924b31e30..0af066aa4ea 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/sink/protocol/thrift/async/IoTDBDataRegionAsyncSinkTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/sink/protocol/thrift/async/IoTDBDataRegionAsyncSinkTest.java
@@ -19,11 +19,19 @@
package org.apache.iotdb.db.pipe.sink.protocol.thrift.async;
+import org.apache.iotdb.commons.conf.CommonConfig;
+import org.apache.iotdb.commons.conf.CommonDescriptor;
import
org.apache.iotdb.commons.exception.pipe.PipeRuntimeSinkCriticalException;
+import
org.apache.iotdb.commons.exception.pipe.PipeRuntimeSinkResourceException;
+import org.apache.iotdb.commons.pipe.resource.PipeResourceFailureType;
+import org.apache.iotdb.db.pipe.event.common.heartbeat.PipeHeartbeatEvent;
+import
org.apache.iotdb.db.pipe.event.common.tablet.PipeRawTabletInsertionEvent;
import org.apache.iotdb.db.pipe.event.common.tsfile.PipeTsFileInsertionEvent;
import org.apache.iotdb.pipe.api.event.Event;
+import org.apache.iotdb.pipe.api.exception.PipeConnectionException;
import org.apache.iotdb.pipe.api.exception.PipeException;
+import org.apache.thrift.transport.TTransportException;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
@@ -31,10 +39,19 @@ import org.mockito.Mockito;
import java.io.File;
import java.io.FileNotFoundException;
import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.net.SocketException;
import java.util.Map;
public class IoTDBDataRegionAsyncSinkTest {
+ private static class UnbatchedIoTDBDataRegionAsyncSink extends
IoTDBDataRegionAsyncSink {
+
+ private UnbatchedIoTDBDataRegionAsyncSink() {
+ isTabletBatchModeEnabled = false;
+ }
+ }
+
@Test
public void testRetryQueueFailureMessageIncludesRootCauseAndIsCleared() {
final IoTDBDataRegionAsyncSink sink = new IoTDBDataRegionAsyncSink();
@@ -71,6 +88,78 @@ public class IoTDBDataRegionAsyncSinkTest {
Assert.assertEquals("java.lang.NullPointerException",
sink.getLastRetryFailureMessage());
}
+ @Test
+ public void testConnectionResetIsRetainedAsResourceFailureInRetryQueue()
throws Exception {
+ final IoTDBDataRegionAsyncSink sink = new IoTDBDataRegionAsyncSink();
+ final Event event = Mockito.mock(Event.class);
+ final PipeConnectionException failure =
+ new PipeConnectionException(
+ "transfer failed", new TTransportException(new
SocketException("Connection reset")));
+
+ sink.addFailureEventToRetryQueue(event, failure);
+
+ final Method getRetryQueueResourceFailureType =
+
IoTDBDataRegionAsyncSink.class.getDeclaredMethod("getRetryQueueResourceFailureType");
+ getRetryQueueResourceFailureType.setAccessible(true);
+ Assert.assertEquals(
+ PipeResourceFailureType.NETWORK_TIMEOUT,
getRetryQueueResourceFailureType.invoke(sink));
+ sink.clearRetryEventsReferenceCount();
+ }
+
+ @Test
+ public void testForcedRetryQueueThresholdPreservesTransportResourceFailure()
throws Exception {
+ final CommonConfig config = CommonDescriptor.getInstance().getConfig();
+ final int originalTabletQueueSize =
config.getPipeAsyncSinkForcedRetryTabletEventQueueSize();
+ final int originalTsFileQueueSize =
config.getPipeAsyncSinkForcedRetryTsFileEventQueueSize();
+ final int originalTotalQueueSize =
config.getPipeAsyncSinkForcedRetryTotalEventQueueSize();
+ final long originalRetryExecutionTimeMs =
+ config.getPipeAsyncSinkMaxRetryExecutionTimeMsPerCall();
+ final IoTDBDataRegionAsyncSink sink = new
UnbatchedIoTDBDataRegionAsyncSink();
+ try {
+ config.setPipeAsyncSinkForcedRetryTabletEventQueueSize(2);
+ config.setPipeAsyncSinkForcedRetryTsFileEventQueueSize(1);
+ config.setPipeAsyncSinkForcedRetryTotalEventQueueSize(2);
+ config.setPipeAsyncSinkMaxRetryExecutionTimeMsPerCall(100);
+
+ final PipeRawTabletInsertionEvent blockedEvent =
+ Mockito.mock(PipeRawTabletInsertionEvent.class);
+ Mockito.when(blockedEvent.increaseReferenceCount(Mockito.anyString()))
+ .thenAnswer(
+ invocation -> {
+ Thread.sleep(150);
+ return false;
+ });
+ sink.addFailureEventToRetryQueue(blockedEvent, null);
+
+ final PipeRawTabletInsertionEvent resourceFailureEvent =
+ Mockito.mock(PipeRawTabletInsertionEvent.class);
+ sink.addFailureEventToRetryQueue(resourceFailureEvent, null);
+
+ final Field resourceFailureTypesField =
+
IoTDBDataRegionAsyncSink.class.getDeclaredField("retryEvent2ResourceFailureType");
+ resourceFailureTypesField.setAccessible(true);
+ @SuppressWarnings("unchecked")
+ final Map<Event, PipeResourceFailureType> resourceFailureTypes =
+ (Map<Event, PipeResourceFailureType>)
resourceFailureTypesField.get(sink);
+ resourceFailureTypes.put(resourceFailureEvent,
PipeResourceFailureType.NETWORK_TIMEOUT);
+
+ final PipeRuntimeSinkResourceException failure =
+ Assert.assertThrows(
+ PipeRuntimeSinkResourceException.class,
+ () -> sink.transfer(new PipeHeartbeatEvent("-1", false)));
+
+ Assert.assertEquals(PipeResourceFailureType.NETWORK_TIMEOUT,
failure.getFailureType());
+ Assert.assertTrue(failure.isFailureRecorded());
+ } finally {
+ sink.clearRetryEventsReferenceCount();
+ sink.close();
+
config.setPipeAsyncSinkForcedRetryTabletEventQueueSize(originalTabletQueueSize);
+
config.setPipeAsyncSinkForcedRetryTsFileEventQueueSize(originalTsFileQueueSize);
+
config.setPipeAsyncSinkForcedRetryTotalEventQueueSize(originalTotalQueueSize);
+
config.setPipeAsyncSinkMaxRetryExecutionTimeMsPerCall(originalRetryExecutionTimeMs);
+ }
+ }
+
@Test
@SuppressWarnings("unchecked")
public void testMissingTsFileRetryLimitKeepsEventQueuedAndStopsSink() throws
Exception {
diff --git
a/iotdb-core/node-commons/src/assembly/resources/conf/iotdb-system.properties.template
b/iotdb-core/node-commons/src/assembly/resources/conf/iotdb-system.properties.template
index 48c602ae5cb..3b39b00dbee 100644
---
a/iotdb-core/node-commons/src/assembly/resources/conf/iotdb-system.properties.template
+++
b/iotdb-core/node-commons/src/assembly/resources/conf/iotdb-system.properties.template
@@ -768,6 +768,7 @@ partition_table_recover_max_read_mb_per_sec=10
# Memory Allocation Ratio: StorageEngine, QueryEngine, SchemaEngine,
Consensus, StreamingEngine and Free Memory.
# The parameter form is a:b:c:d:e:f, where a, b, c, d, e and f are integers.
for example: 1:1:1:1:1:1 , 6:2:1:1:1:1
# If you have high level of writing pressure and low level of reading
pressure, please adjust it to for example 6:1:1:1:1:1
+# 50% of Free Memory is used by AutoResizingBuffer memory control.
# effectiveMode: restart
datanode_memory_proportion=3:3:1:1:1:1
diff --git
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/memory/AutoResizingBufferMemoryMetrics.java
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/memory/AutoResizingBufferMemoryMetrics.java
new file mode 100644
index 00000000000..e8300185253
--- /dev/null
+++
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/memory/AutoResizingBufferMemoryMetrics.java
@@ -0,0 +1,108 @@
+/*
+ * 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.commons.memory;
+
+import org.apache.iotdb.commons.service.metric.enums.Metric;
+import org.apache.iotdb.commons.service.metric.enums.Tag;
+import org.apache.iotdb.metrics.AbstractMetricService;
+import org.apache.iotdb.metrics.metricsets.IMetricSet;
+import org.apache.iotdb.metrics.utils.MetricLevel;
+import org.apache.iotdb.metrics.utils.MetricType;
+import org.apache.iotdb.rpc.AutoResizingBufferMemoryManager;
+
+public class AutoResizingBufferMemoryMetrics implements IMetricSet {
+
+ private static final String ALLOCATION_COUNT =
"auto_resizing_buffer_allocation_count";
+ private static final String ALLOCATION_FAILURE_COUNT =
+ "auto_resizing_buffer_allocation_failure_count";
+ private static final String TOTAL_MEMORY =
"auto_resizing_buffer_total_memory";
+ private static final String USED_MEMORY = "auto_resizing_buffer_used_memory";
+ private static final String AVAILABLE_MEMORY =
"auto_resizing_buffer_available_memory";
+
+ public AutoResizingBufferMemoryMetrics() {}
+
+ @Override
+ public void bindTo(AbstractMetricService metricService) {
+ metricService.createAutoGauge(
+ Metric.THRIFT_RPC_MEMORY_USAGE.toString(),
+ MetricLevel.IMPORTANT,
+ AutoResizingBufferMemoryManager.class,
+ ignored -> AutoResizingBufferMemoryManager.getMemoryAllocationCount(),
+ Tag.NAME.toString(),
+ ALLOCATION_COUNT);
+ metricService.createAutoGauge(
+ Metric.THRIFT_RPC_MEMORY_USAGE.toString(),
+ MetricLevel.IMPORTANT,
+ AutoResizingBufferMemoryManager.class,
+ ignored ->
AutoResizingBufferMemoryManager.getMemoryAllocationFailureCount(),
+ Tag.NAME.toString(),
+ ALLOCATION_FAILURE_COUNT);
+ metricService.createAutoGauge(
+ Metric.THRIFT_RPC_MEMORY_USAGE.toString(),
+ MetricLevel.IMPORTANT,
+ AutoResizingBufferMemoryManager.class,
+ ignored -> AutoResizingBufferMemoryManager.getMemoryTotalSizeInBytes(),
+ Tag.NAME.toString(),
+ TOTAL_MEMORY);
+ metricService.createAutoGauge(
+ Metric.THRIFT_RPC_MEMORY_USAGE.toString(),
+ MetricLevel.IMPORTANT,
+ AutoResizingBufferMemoryManager.class,
+ ignored -> AutoResizingBufferMemoryManager.getMemoryUsedSizeInBytes(),
+ Tag.NAME.toString(),
+ USED_MEMORY);
+ metricService.createAutoGauge(
+ Metric.THRIFT_RPC_MEMORY_USAGE.toString(),
+ MetricLevel.IMPORTANT,
+ AutoResizingBufferMemoryManager.class,
+ ignored ->
AutoResizingBufferMemoryManager.getMemoryAvailableSizeInBytes(),
+ Tag.NAME.toString(),
+ AVAILABLE_MEMORY);
+ }
+
+ @Override
+ public void unbindFrom(AbstractMetricService metricService) {
+ metricService.remove(
+ MetricType.AUTO_GAUGE,
+ Metric.THRIFT_RPC_MEMORY_USAGE.toString(),
+ Tag.NAME.toString(),
+ ALLOCATION_COUNT);
+ metricService.remove(
+ MetricType.AUTO_GAUGE,
+ Metric.THRIFT_RPC_MEMORY_USAGE.toString(),
+ Tag.NAME.toString(),
+ ALLOCATION_FAILURE_COUNT);
+ metricService.remove(
+ MetricType.AUTO_GAUGE,
+ Metric.THRIFT_RPC_MEMORY_USAGE.toString(),
+ Tag.NAME.toString(),
+ TOTAL_MEMORY);
+ metricService.remove(
+ MetricType.AUTO_GAUGE,
+ Metric.THRIFT_RPC_MEMORY_USAGE.toString(),
+ Tag.NAME.toString(),
+ USED_MEMORY);
+ metricService.remove(
+ MetricType.AUTO_GAUGE,
+ Metric.THRIFT_RPC_MEMORY_USAGE.toString(),
+ Tag.NAME.toString(),
+ AVAILABLE_MEMORY);
+ }
+}
diff --git
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeAbstractSinkSubtask.java
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeAbstractSinkSubtask.java
index 53415385f8b..5b366077eb4 100644
---
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeAbstractSinkSubtask.java
+++
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeAbstractSinkSubtask.java
@@ -125,6 +125,20 @@ public abstract class PipeAbstractSinkSubtask extends
PipeReportableSubtask {
}
}
+ if (throwable instanceof Exception && !PipeStopStrategy.accept((Exception)
throwable, null)) {
+ final Exception exception = (Exception) throwable;
+ final PipeResourceFailureType failureType =
+ PipeStopStrategy.getResourceFailureType(exception, null);
+ if (lastEvent instanceof EnrichedEvent
+ && !PipeStopStrategy.isResourceFailureRecorded(exception)) {
+ reportResourceFailure((EnrichedEvent) lastEvent, failureType);
+ }
+ super.onFailure(
+ new PipeRuntimeSinkNonReportTimeConfigurableException(
+ throwable.getMessage(), Long.MAX_VALUE));
+ return;
+ }
+
synchronized (this) {
if (tryIgnoreFailure(throwable)) {
return;
diff --git
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/resource/PipeStopStrategy.java
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/resource/PipeStopStrategy.java
index 4535bf57fe5..779fc1eeeb4 100644
---
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/resource/PipeStopStrategy.java
+++
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/resource/PipeStopStrategy.java
@@ -23,10 +23,16 @@ import org.apache.iotdb.common.rpc.thrift.TSStatus;
import org.apache.iotdb.commons.client.exception.ClientManagerException;
import
org.apache.iotdb.commons.exception.pipe.PipeRuntimeOutOfMemoryCriticalException;
import
org.apache.iotdb.commons.exception.pipe.PipeRuntimeSinkResourceException;
+import org.apache.iotdb.rpc.AutoResizingBufferMemoryAllocationException;
import org.apache.iotdb.rpc.TSStatusCode;
+import org.apache.thrift.transport.TTransportException;
+
import javax.annotation.Nullable;
+import java.io.IOException;
+import java.util.Locale;
+
public final class PipeStopStrategy {
private PipeStopStrategy() {}
@@ -50,9 +56,15 @@ public final class PipeStopStrategy {
if (current instanceof PipeRuntimeOutOfMemoryCriticalException) {
return PipeResourceFailureType.MEMORY_TIMEOUT;
}
+ if (current instanceof AutoResizingBufferMemoryAllocationException) {
+ return PipeResourceFailureType.MEMORY_TIMEOUT;
+ }
if (current instanceof ClientManagerException) {
return PipeResourceFailureType.NETWORK_TIMEOUT;
}
+ if (isPeerConnectionClosed(current)) {
+ return PipeResourceFailureType.NETWORK_TIMEOUT;
+ }
current = current.getCause();
}
@@ -63,6 +75,31 @@ public final class PipeStopStrategy {
: null;
}
+ private static boolean isPeerConnectionClosed(final Throwable throwable) {
+ if (throwable instanceof TTransportException
+ && ((TTransportException) throwable).getType() ==
TTransportException.END_OF_FILE) {
+ return true;
+ }
+
+ if (!(throwable instanceof IOException) && !(throwable instanceof
TTransportException)) {
+ return false;
+ }
+
+ final String message = throwable.getMessage();
+ if (message == null) {
+ return false;
+ }
+
+ final String normalizedMessage = message.toLowerCase(Locale.ROOT);
+ return normalizedMessage.contains("broken pipe")
+ || normalizedMessage.contains("connection reset")
+ || normalizedMessage.contains("connection was reset")
+ || normalizedMessage.contains("closed by peer")
+ || normalizedMessage.contains("read call frame size failed")
+ || normalizedMessage.contains("forcibly closed by the remote host")
+ || normalizedMessage.contains("connection was aborted");
+ }
+
public static boolean isResourceFailureRecorded(final @Nullable Exception
exception) {
Throwable current = exception;
while (current != null) {
diff --git
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/service/metric/enums/Metric.java
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/service/metric/enums/Metric.java
index 92ee58b04cb..766162f5ae2 100644
---
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/service/metric/enums/Metric.java
+++
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/service/metric/enums/Metric.java
@@ -49,6 +49,7 @@ public enum Metric {
SESSION_IDLE_TIME("session_idle_time"),
THRIFT_CONNECTIONS("thrift_connections"),
THRIFT_ACTIVE_THREADS("thrift_active_threads"),
+ THRIFT_RPC_MEMORY_USAGE("thrift_rpc_memory_usage"),
CLIENT_MANAGER("client_manager"),
// consensus related
STAGE("stage"),
diff --git
a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/resource/PipeStopStrategyTest.java
b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/resource/PipeStopStrategyTest.java
index b68da403a42..0b01acf7aa6 100644
---
a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/resource/PipeStopStrategyTest.java
+++
b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/resource/PipeStopStrategyTest.java
@@ -23,13 +23,20 @@ import org.apache.iotdb.common.rpc.thrift.TSStatus;
import org.apache.iotdb.commons.client.exception.ClientManagerException;
import
org.apache.iotdb.commons.exception.pipe.PipeRuntimeOutOfMemoryCriticalException;
import
org.apache.iotdb.commons.exception.pipe.PipeRuntimeSinkResourceException;
+import
org.apache.iotdb.commons.exception.pipe.PipeRuntimeSinkRetryTimesConfigurableException;
import org.apache.iotdb.pipe.api.exception.PipeConnectionException;
+import org.apache.iotdb.rpc.AutoResizingBufferMemoryAllocationException;
+import org.apache.iotdb.rpc.TElasticFramedTransport;
import org.apache.iotdb.rpc.TSStatusCode;
+import org.apache.thrift.TConfiguration;
+import org.apache.thrift.transport.TTransport;
+import org.apache.thrift.transport.TTransportException;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
+import java.net.SocketException;
public class PipeStopStrategyTest {
@@ -63,6 +70,78 @@ public class PipeStopStrategyTest {
PipeStopStrategy.getResourceFailureType(null, status));
}
+ @Test
+ public void testAutoResizingBufferAllocationFailureDoesNotStopPipe() {
+ final Exception failure =
+ new TTransportException(
+ new AutoResizingBufferMemoryAllocationException("buffer allocation
failed"));
+
+ Assert.assertFalse(PipeStopStrategy.accept(failure, null));
+ Assert.assertEquals(
+ PipeResourceFailureType.MEMORY_TIMEOUT,
+ PipeStopStrategy.getResourceFailureType(failure, null));
+ }
+
+ @Test
+ public void testBrokenPipeFromReceiverResourcePressureDoesNotStopPipe() {
+ final Exception failure =
+ retryTimesConfigurableFailure(new TTransportException(new
IOException("Broken pipe")));
+
+ Assert.assertFalse(PipeStopStrategy.accept(failure, null));
+ Assert.assertEquals(
+ PipeResourceFailureType.NETWORK_TIMEOUT,
+ PipeStopStrategy.getResourceFailureType(failure, null));
+ }
+
+ @Test
+ public void testPeerClosedTransportDoesNotStopPipe() {
+ final Exception failure =
+ retryTimesConfigurableFailure(
+ new TTransportException(
+ TTransportException.END_OF_FILE, new IOException("Connection
reset")));
+
+ Assert.assertFalse(PipeStopStrategy.accept(failure, null));
+ Assert.assertEquals(
+ PipeResourceFailureType.NETWORK_TIMEOUT,
+ PipeStopStrategy.getResourceFailureType(failure, null));
+ }
+
+ @Test
+ public void testElasticFramedTransportResetRemainsRetryable() throws
Exception {
+ try (TElasticFramedTransport transport =
+ new TElasticFramedTransport(new ConnectionResetTransport(), 100, 1024,
true)) {
+ final TTransportException failure =
+ Assert.assertThrows(TTransportException.class, () ->
transport.read(new byte[1], 0, 1));
+
+ Assert.assertEquals(TTransportException.END_OF_FILE, failure.getType());
+ Assert.assertFalse(PipeStopStrategy.accept(failure, null));
+ Assert.assertEquals(
+ PipeResourceFailureType.NETWORK_TIMEOUT,
+ PipeStopStrategy.getResourceFailureType(failure, null));
+ }
+ }
+
+ @Test
+ public void
testConnectionResetVariantsRemainRetryableThroughCriticalWrapper() {
+ final Exception unixReset =
+ retryTimesConfigurableFailure(
+ new TTransportException(new SocketException("Connection reset")));
+ Assert.assertFalse(PipeStopStrategy.accept(unixReset, null));
+ Assert.assertEquals(
+ PipeResourceFailureType.NETWORK_TIMEOUT,
+ PipeStopStrategy.getResourceFailureType(unixReset, null));
+
+ final Exception windowsReset =
+ retryTimesConfigurableFailure(
+ new TTransportException(
+ new SocketException(
+ "An existing connection was forcibly closed by the remote
host")));
+ Assert.assertFalse(PipeStopStrategy.accept(windowsReset, null));
+ Assert.assertEquals(
+ PipeResourceFailureType.NETWORK_TIMEOUT,
+ PipeStopStrategy.getResourceFailureType(windowsReset, null));
+ }
+
@Test
public void testOtherFailuresKeepExistingStopPolicy() {
Assert.assertTrue(PipeStopStrategy.accept(new IOException("network
disconnected"), null));
@@ -80,4 +159,46 @@ public class PipeStopStrategyTest {
Assert.assertTrue(PipeStopStrategy.isResourceFailureRecorded(failure));
}
+
+ private static class ConnectionResetTransport extends TTransport {
+
+ @Override
+ public boolean isOpen() {
+ return true;
+ }
+
+ @Override
+ public void open() {}
+
+ @Override
+ public void close() {}
+
+ @Override
+ public int read(final byte[] buffer, final int offset, final int length)
+ throws TTransportException {
+ throw new TTransportException(new SocketException("Connection reset"));
+ }
+
+ @Override
+ public void write(final byte[] buffer, final int offset, final int length)
{}
+
+ @Override
+ public TConfiguration getConfiguration() {
+ return new TConfiguration();
+ }
+
+ @Override
+ public void updateKnownMessageSize(final long size) {}
+
+ @Override
+ public void checkReadBytesAvailable(final long numBytes) {}
+ }
+
+ private static PipeRuntimeSinkRetryTimesConfigurableException
retryTimesConfigurableFailure(
+ final Throwable cause) {
+ final PipeRuntimeSinkRetryTimesConfigurableException exception =
+ new PipeRuntimeSinkRetryTimesConfigurableException("transfer failed",
Integer.MAX_VALUE);
+ exception.initCause(cause);
+ return exception;
+ }
}
diff --git
a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/rpc/ClientPoolIdleEvictionTest.java
b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/rpc/ClientPoolIdleEvictionTest.java
index ab5fae70b97..4d6b312bd18 100644
---
a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/rpc/ClientPoolIdleEvictionTest.java
+++
b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/rpc/ClientPoolIdleEvictionTest.java
@@ -33,6 +33,7 @@ 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.Before;
import org.junit.Test;
@@ -169,7 +170,11 @@ public class ClientPoolIdleEvictionTest {
@Override
public TTransport getTransport(TTransport transport) {
serverConnections.add(transport);
- return createTransport(transport);
+ try {
+ return createTransport(transport);
+ } catch (TTransportException e) {
+ throw new RuntimeException(e);
+ }
}
})
.protocolFactory(new TBinaryProtocol.Factory())
@@ -276,7 +281,8 @@ public class ClientPoolIdleEvictionTest {
.getConfig());
}
- private TElasticFramedTransport createTransport(TTransport underlying) {
+ private TElasticFramedTransport createTransport(TTransport underlying)
+ throws TTransportException {
return compression
? new TSnappyElasticFramedTransport(underlying, INITIAL_BUFFER_SIZE,
65536, true)
: new TElasticFramedTransport(underlying, INITIAL_BUFFER_SIZE, 65536,
true);