diff --git a/integration-test/src/test/java/org/apache/iotdb/session/it/IoTDBStagedTestInsertIT.java b/integration-test/src/test/java/org/apache/iotdb/session/it/IoTDBStagedTestInsertIT.java new file mode 100644 index 0000000000000..12d56ad51f695 --- /dev/null +++ b/integration-test/src/test/java/org/apache/iotdb/session/it/IoTDBStagedTestInsertIT.java @@ -0,0 +1,311 @@ +/* + * 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.session.it; + +import org.apache.iotdb.isession.ISession; +import org.apache.iotdb.isession.ITableSession; +import org.apache.iotdb.isession.SessionDataSet; +import org.apache.iotdb.isession.pool.ITableSessionPool; +import org.apache.iotdb.it.env.EnvFactory; +import org.apache.iotdb.it.env.cluster.node.DataNodeWrapper; +import org.apache.iotdb.it.framework.IoTDBTestRunner; +import org.apache.iotdb.itbase.category.ClusterIT; +import org.apache.iotdb.itbase.category.LocalStandaloneIT; +import org.apache.iotdb.rpc.StatementExecutionException; +import org.apache.iotdb.service.rpc.thrift.TestInsertStage; +import org.apache.iotdb.session.TableSessionBuilder; +import org.apache.iotdb.session.pool.TableSessionPoolBuilder; + +import org.apache.tsfile.enums.ColumnCategory; +import org.apache.tsfile.enums.TSDataType; +import org.apache.tsfile.write.record.Tablet; +import org.apache.tsfile.write.schema.MeasurementSchema; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; + +import java.util.Arrays; +import java.util.Collections; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +@RunWith(IoTDBTestRunner.class) +@Category({LocalStandaloneIT.class, ClusterIT.class}) +public class IoTDBStagedTestInsertIT { + @BeforeClass + public static void setUp() throws Exception { + EnvFactory.getEnv().initClusterEnvironment(); + } + + @AfterClass + public static void tearDown() throws Exception { + EnvFactory.getEnv().cleanClusterEnvironment(); + } + + @Test + public void testStagesAndPayloadsLeaveDataUnchanged() throws Exception { + try (ISession session = EnvFactory.getEnv().getSessionConnection()) { + session.executeNonQueryStatement( + "CREATE TIMESERIES root.staged.d.`a.b` WITH DATATYPE=DOUBLE, ENCODING=PLAIN"); + session.executeNonQueryStatement("INSERT INTO root.staged.d(time, `a.b`) VALUES(1, 1)"); + for (TestInsertStage stage : TestInsertStage.values()) { + session.executeNonQueryStatement("CLEAR CACHE"); + session.testInsertRecord( + "root.staged.d", + 2, + Collections.singletonList("`a.b`"), + Collections.singletonList(TSDataType.DOUBLE), + Collections.singletonList(2.0), + stage); + session.testInsertRecord( + "root.staged.d", + 2, + Collections.singletonList("`a.b`"), + Collections.singletonList("2"), + stage); + session.testInsertRecords( + Collections.singletonList("root.staged.d"), + Collections.singletonList(2L), + Collections.singletonList(Collections.singletonList("`a.b`")), + Collections.singletonList(Collections.singletonList(TSDataType.DOUBLE)), + Collections.singletonList(Collections.singletonList(2.0)), + stage); + session.testInsertRecords( + Collections.singletonList("root.staged.d"), + Collections.singletonList(2L), + Collections.singletonList(Collections.singletonList("`a.b`")), + Collections.singletonList(Collections.singletonList("2")), + stage); + Tablet tablet = + new Tablet( + "root.staged.d", + Collections.singletonList(new MeasurementSchema("`a.b`", TSDataType.DOUBLE))); + tablet.addTimestamp(0, 2); + tablet.addValue("`a.b`", 0, 2.0); + session.testInsertTablet(tablet, stage); + session.testInsertTablets(Collections.singletonMap("root.staged.d", tablet), stage); + } + try (SessionDataSet data = + session.executeQueryStatement("SELECT count(`a.b`) FROM root.staged.d")) { + assertEquals(1, data.next().getFields().get(0).getLongV()); + } + session.executeNonQueryStatement( + "CREATE TIMESERIES root.staged_other.d.s WITH DATATYPE=INT64, ENCODING=PLAIN"); + session.executeNonQueryStatement("INSERT INTO root.staged_other.d(time,s) VALUES(1,1)"); + // Each ingress node tests the same multi-region request, exercising local and remote + // reception. + for (DataNodeWrapper node : EnvFactory.getEnv().getDataNodeWrapperList()) { + try (ISession ingress = + EnvFactory.getEnv() + .getSessionConnection(Collections.singletonList(node.getIpAndPortString()))) { + ingress.testInsertRecords( + Arrays.asList("root.staged.d", "root.staged_other.d"), + Arrays.asList(2L, 2L), + Arrays.asList(Collections.singletonList("`a.b`"), Collections.singletonList("s")), + Arrays.asList(Collections.singletonList("2"), Collections.singletonList("2")), + TestInsertStage.UNTIL_WRITE_TARGET_RECEIVED); + } + } + try (SessionDataSet data = + session.executeQueryStatement("SELECT count(s) FROM root.staged_other.d")) { + assertEquals(1, data.next().getFields().get(0).getLongV()); + } + try (SessionDataSet data = + session.executeQueryStatement("SELECT count(`a.b`) FROM root.staged.d")) { + assertEquals(1, data.next().getFields().get(0).getLongV()); + } + // A normal insertion after the tests proves schema locks/resources were released. + session.executeNonQueryStatement("INSERT INTO root.staged.d(time, `a.b`) VALUES(2, 2)"); + try (SessionDataSet data = + session.executeQueryStatement("SELECT count(`a.b`) FROM root.staged.d")) { + assertEquals(2, data.next().getFields().get(0).getLongV()); + } + } + } + + @Test + public void testMissingMetadataAndPartitionAreNotCreated() throws Exception { + try (ISession session = EnvFactory.getEnv().getSessionConnection()) { + session.testInsertRecord( + "root.staged_missing.d", + 1, + Collections.singletonList("s"), + Collections.singletonList("1")); + session.testInsertRecord( + "root.staged_missing.d", + 1, + Collections.singletonList("s"), + Collections.singletonList("1"), + TestInsertStage.UNTIL_DECODED); + assertThrows( + StatementExecutionException.class, + () -> + session.testInsertRecord( + "root.staged_missing.d", + 1, + Collections.singletonList("s"), + Collections.singletonList("1"), + TestInsertStage.UNTIL_ANALYZED)); + try (SessionDataSet data = + session.executeQueryStatement("SHOW DATABASES root.staged_missing")) { + assertFalse(data.hasNext()); + } + session.executeNonQueryStatement( + "CREATE TIMESERIES root.staged_empty.d.s WITH DATATYPE=INT64, ENCODING=PLAIN"); + assertThrows( + StatementExecutionException.class, + () -> + session.testInsertRecord( + "root.staged_empty.d", + 1, + Collections.singletonList("s"), + Collections.singletonList("1"), + TestInsertStage.UNTIL_PLANNED)); + session.executeNonQueryStatement("INSERT INTO root.staged_empty.d(time,s) VALUES(1,1)"); + session.testInsertRecord( + "root.staged_empty.d", + 2, + Collections.singletonList("s"), + Collections.singletonList("2"), + TestInsertStage.UNTIL_WRITE_TARGET_RECEIVED); + try (SessionDataSet data = + session.executeQueryStatement("SELECT count(s) FROM root.staged_empty.d")) { + assertEquals(1, data.next().getFields().get(0).getLongV()); + } + } + } + + @Test + public void testTemplateIsNotActivatedOrExtended() throws Exception { + try (ISession session = EnvFactory.getEnv().getSessionConnection()) { + session.executeNonQueryStatement( + "CREATE SCHEMA TEMPLATE staged_template (s INT64 ENCODING=PLAIN)"); + session.executeNonQueryStatement("CREATE DATABASE root.staged_template"); + session.executeNonQueryStatement( + "SET SCHEMA TEMPLATE staged_template TO root.staged_template"); + assertThrows( + StatementExecutionException.class, + () -> + session.testInsertRecord( + "root.staged_template.d", + 1, + Collections.singletonList("s"), + Collections.singletonList("1"), + TestInsertStage.UNTIL_ANALYZED)); + assertTrue(session.showPathsTemplateUsingOn("staged_template").isEmpty()); + session.executeNonQueryStatement("INSERT INTO root.staged_template.d(time,s) VALUES(1,1)"); + assertThrows( + StatementExecutionException.class, + () -> + session.testInsertRecord( + "root.staged_template.d", + 2, + Collections.singletonList("extra"), + Collections.singletonList("1"), + TestInsertStage.UNTIL_ANALYZED)); + try (SessionDataSet data = + session.executeQueryStatement("SHOW TIMESERIES root.staged_template.d.extra")) { + assertFalse(data.hasNext()); + } + session.testInsertRecord( + "root.staged_template.d", + 2, + Collections.singletonList("s"), + Collections.singletonList("2"), + TestInsertStage.UNTIL_WRITE_TARGET_RECEIVED); + } + } + + @Test + public void testTableDeviceAndAttributeRemainUnchanged() throws Exception { + try (ITableSession session = + new TableSessionBuilder() + .nodeUrls( + Collections.singletonList( + EnvFactory.getEnv().getIP() + ":" + EnvFactory.getEnv().getPort())) + .build()) { + session.executeNonQueryStatement("CREATE DATABASE staged_table"); + session.executeNonQueryStatement("USE staged_table"); + session.executeNonQueryStatement( + "CREATE TABLE t(id STRING TAG, attr STRING ATTRIBUTE, v INT64 FIELD)"); + session.executeNonQueryStatement("INSERT INTO t(time,id,attr,v) VALUES(1,'d','original',1)"); + session.testInsert(tableTablet("d", "original")); + for (TestInsertStage stage : TestInsertStage.values()) { + session.testInsert(tableTablet("d", "original"), stage); + } + try (ITableSessionPool pool = + new TableSessionPoolBuilder() + .nodeUrls( + Collections.singletonList( + EnvFactory.getEnv().getIP() + ":" + EnvFactory.getEnv().getPort())) + .database("staged_table") + .maxSize(1) + .build()) { + try (ITableSession borrowed = pool.getSession()) { + borrowed.testInsert(tableTablet("d", "original")); + for (TestInsertStage stage : TestInsertStage.values()) { + borrowed.testInsert(tableTablet("d", "original"), stage); + } + assertThrows( + StatementExecutionException.class, + () -> + borrowed.testInsert(tableTablet("d", "changed"), TestInsertStage.UNTIL_ANALYZED)); + } + // A statement error leaves the connection usable and returns it to the pool on close. + try (ITableSession borrowed = pool.getSession(); + SessionDataSet data = borrowed.executeQueryStatement("SELECT count(*) FROM t")) { + assertEquals(1, data.next().getFields().get(0).getLongV()); + } + } + + assertThrows( + StatementExecutionException.class, + () -> + session.testInsert( + tableTablet("missing", "original"), TestInsertStage.UNTIL_ANALYZED)); + assertThrows( + StatementExecutionException.class, + () -> session.testInsert(tableTablet("d", "changed"), TestInsertStage.UNTIL_ANALYZED)); + try (SessionDataSet data = session.executeQueryStatement("SELECT id,attr,v FROM t")) { + assertTrue(data.hasNext()); + assertEquals("original", data.next().getFields().get(1).getStringValue()); + assertFalse(data.hasNext()); + } + } + } + + private Tablet tableTablet(String device, String attribute) { + Tablet tablet = + new Tablet( + "t", + Arrays.asList("id", "attr", "v"), + Arrays.asList(TSDataType.STRING, TSDataType.STRING, TSDataType.INT64), + Arrays.asList(ColumnCategory.TAG, ColumnCategory.ATTRIBUTE, ColumnCategory.FIELD)); + tablet.addTimestamp(0, 2); + tablet.addValue("id", 0, device); + tablet.addValue("attr", 0, attribute); + tablet.addValue("v", 0, 2L); + return tablet; + } +} diff --git a/iotdb-client/isession/src/main/java/org/apache/iotdb/isession/ISession.java b/iotdb-client/isession/src/main/java/org/apache/iotdb/isession/ISession.java index 299dff20f4542..5b534801cba1d 100644 --- a/iotdb-client/isession/src/main/java/org/apache/iotdb/isession/ISession.java +++ b/iotdb-client/isession/src/main/java/org/apache/iotdb/isession/ISession.java @@ -29,6 +29,7 @@ import org.apache.iotdb.rpc.StatementExecutionException; import org.apache.iotdb.service.rpc.thrift.TSBackupConfigurationResp; import org.apache.iotdb.service.rpc.thrift.TSConnectionInfoResp; +import org.apache.iotdb.service.rpc.thrift.TestInsertStage; import org.apache.thrift.TException; import org.apache.tsfile.enums.TSDataType; @@ -578,4 +579,54 @@ default boolean isEnableCacheLeader() { */ @Deprecated default void setEnableCacheLeader(boolean enableCacheLeader) {} + + /** + * Tests insertion up to the requested stage without writing data or changing metadata. Analysis + * and later stages require existing schema and data partitions. + */ + void testInsertTablet(Tablet tablet, TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException; + + void testInsertTablet(Tablet tablet, boolean sorted, TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException; + + void testInsertTablets(Map tablets, TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException; + + void testInsertTablets(Map tablets, boolean sorted, TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException; + + void testInsertRecords( + List deviceIds, + List times, + List> measurementsList, + List> valuesList, + TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException; + + void testInsertRecords( + List deviceIds, + List times, + List> measurementsList, + List> typesList, + List> valuesList, + TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException; + + void testInsertRecord( + String deviceId, + long time, + List measurements, + List values, + TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException; + + void testInsertRecord( + String deviceId, + long time, + List measurements, + List types, + List values, + TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException; } diff --git a/iotdb-client/isession/src/main/java/org/apache/iotdb/isession/ITableSession.java b/iotdb-client/isession/src/main/java/org/apache/iotdb/isession/ITableSession.java index 7973749a5bb3a..81a2c9cdab9d9 100644 --- a/iotdb-client/isession/src/main/java/org/apache/iotdb/isession/ITableSession.java +++ b/iotdb-client/isession/src/main/java/org/apache/iotdb/isession/ITableSession.java @@ -21,6 +21,7 @@ import org.apache.iotdb.rpc.IoTDBConnectionException; import org.apache.iotdb.rpc.StatementExecutionException; +import org.apache.iotdb.service.rpc.thrift.TestInsertStage; import org.apache.tsfile.write.record.Tablet; @@ -68,6 +69,34 @@ public interface ITableSession extends AutoCloseable { void insert(Tablet tablet, String database) throws StatementExecutionException, IoTDBConnectionException; + /** + * Tests receiving a table-model tablet without inserting data or changing metadata. + * + * @param tablet the tablet to test + * @throws StatementExecutionException if the server rejects the request or does not support + * staged tests + * @throws IoTDBConnectionException if the connection fails + */ + default void testInsert(Tablet tablet) + throws StatementExecutionException, IoTDBConnectionException { + testInsert(tablet, TestInsertStage.UNTIL_RPC_PROCESSED); + } + + /** + * Tests a table-model tablet up to the requested stage, without inserting data or changing + * metadata. Analysis and later stages require existing schema, devices and data partitions, and + * must not require attribute updates. A successful return acknowledges completion of the + * requested stage. Unsupported servers fail rather than falling back to a normal insertion. + * + * @param tablet the tablet to test + * @param stage the inclusive completion boundary + * @throws StatementExecutionException if a stage fails or the server does not support staged + * tests + * @throws IoTDBConnectionException if the connection fails + */ + void testInsert(Tablet tablet, TestInsertStage stage) + throws StatementExecutionException, IoTDBConnectionException; + /** * Executes a non-query SQL statement, such as a DDL or DML command. * diff --git a/iotdb-client/session/src/main/i18n/en/org/apache/iotdb/session/i18n/SessionMessages.java b/iotdb-client/session/src/main/i18n/en/org/apache/iotdb/session/i18n/SessionMessages.java index f182740533d37..466e1ef729de7 100644 --- a/iotdb-client/session/src/main/i18n/en/org/apache/iotdb/session/i18n/SessionMessages.java +++ b/iotdb-client/session/src/main/i18n/en/org/apache/iotdb/session/i18n/SessionMessages.java @@ -21,6 +21,18 @@ public final class SessionMessages { + public static final String EXCEPTION_SERVER_DID_NOT_ACKNOWLEDGE_THE_REQUESTED_TEST_INSERTION_STAGE_41067D1C = + "Server did not acknowledge the requested test insertion stage"; + + public static final String MESSAGE_SERVER_DOES_NOT_SUPPORT_STAGED_TEST_INSERTION_0127CF25 = + "Server does not support staged test insertion"; + + public static final String EXCEPTION_TEST_INSERTION_HAS_NO_NON_NULL_VALUES_40F5D116 = + "Test insertion has no non-null values"; + + public static final String EXCEPTION_TEST_INSERTION_STAGE_MUST_NOT_BE_NULL_EC9D4E51 = + "Test insertion stage must not be null"; + public static final String EXCEPTION_INTERNAL_NODE_SUPPLIER_MUST_NOT_BE_NULL_C5CAF392 = "Internal node supplier must not be null"; diff --git a/iotdb-client/session/src/main/i18n/zh/org/apache/iotdb/session/i18n/SessionMessages.java b/iotdb-client/session/src/main/i18n/zh/org/apache/iotdb/session/i18n/SessionMessages.java index e956777c5cd42..e46adf6f37735 100644 --- a/iotdb-client/session/src/main/i18n/zh/org/apache/iotdb/session/i18n/SessionMessages.java +++ b/iotdb-client/session/src/main/i18n/zh/org/apache/iotdb/session/i18n/SessionMessages.java @@ -21,6 +21,18 @@ public final class SessionMessages { + public static final String EXCEPTION_SERVER_DID_NOT_ACKNOWLEDGE_THE_REQUESTED_TEST_INSERTION_STAGE_41067D1C = + "服务端未确认完成请求的测试写入阶段"; + + public static final String MESSAGE_SERVER_DOES_NOT_SUPPORT_STAGED_TEST_INSERTION_0127CF25 = + "服务端不支持分阶段测试写入"; + + public static final String EXCEPTION_TEST_INSERTION_HAS_NO_NON_NULL_VALUES_40F5D116 = + "测试写入没有非空值"; + + public static final String EXCEPTION_TEST_INSERTION_STAGE_MUST_NOT_BE_NULL_EC9D4E51 = + "测试写入阶段不能为空"; + public static final String EXCEPTION_INTERNAL_NODE_SUPPLIER_MUST_NOT_BE_NULL_C5CAF392 = "内部节点 supplier 不能为空"; diff --git a/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java b/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java index 217c143490800..31cdd2bc3d8f2 100644 --- a/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java +++ b/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java @@ -59,7 +59,9 @@ import org.apache.iotdb.service.rpc.thrift.TSQueryTemplateReq; import org.apache.iotdb.service.rpc.thrift.TSQueryTemplateResp; import org.apache.iotdb.service.rpc.thrift.TSSetSchemaTemplateReq; +import org.apache.iotdb.service.rpc.thrift.TSTestInsertReq; import org.apache.iotdb.service.rpc.thrift.TSUnsetSchemaTemplateReq; +import org.apache.iotdb.service.rpc.thrift.TestInsertStage; import org.apache.iotdb.session.i18n.SessionMessages; import org.apache.iotdb.session.rpccompress.TabletEncoder; import org.apache.iotdb.session.template.MeasurementNode; @@ -3061,6 +3063,24 @@ private void insertTabletInternal(Tablet tablet, TSInsertTabletReq request) } } + /** + * Tests a table-model tablet without writing data or changing metadata. Analysis and later stages + * require existing schema, devices and partitions, and must not require attribute updates. + */ + public void testInsertRelationalTablet(Tablet tablet, TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException { + Objects.requireNonNull( + stage, SessionMessages.EXCEPTION_TEST_INSERTION_STAGE_MUST_NOT_BE_NULL_EC9D4E51); + TSInsertTabletReq request = genTSInsertTabletReq(tablet, false, false); + if (request == null) { + throw new StatementExecutionException( + SessionMessages.EXCEPTION_TEST_INSERTION_HAS_NO_NON_NULL_VALUES_40F5D116); + } + request.setWriteToTable(true); + getDefaultSessionConnection() + .testInsert(new TSTestInsertReq(0, stage.getValue()).setTablet(request)); + } + /** * insert a relational Tablet. Note: This method is for internal use only, we do not guarantee * compatibility with subsequent versions. @@ -3931,6 +3951,147 @@ public void testInsertRecord( getDefaultSessionConnection().testInsertRecord(request); } + /** Test insertion up to the requested stage without writing data or metadata. */ + @Override + public void testInsertTablet(Tablet tablet, TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException { + testInsertTablet(tablet, false, stage); + } + + /** Test insertion up to the requested stage without writing data or metadata. */ + @Override + public void testInsertTablet(Tablet tablet, boolean sorted, TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException { + Objects.requireNonNull( + stage, SessionMessages.EXCEPTION_TEST_INSERTION_STAGE_MUST_NOT_BE_NULL_EC9D4E51); + TSInsertTabletReq request = genTSInsertTabletReq(tablet, sorted, false); + if (request == null) { + throw new StatementExecutionException( + SessionMessages.EXCEPTION_TEST_INSERTION_HAS_NO_NON_NULL_VALUES_40F5D116); + } + getDefaultSessionConnection() + .testInsert(new TSTestInsertReq(0, stage.getValue()).setTablet(request)); + } + + /** Test insertion up to the requested stage without writing data or metadata. */ + @Override + public void testInsertTablets(Map tablets, TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException { + testInsertTablets(tablets, false, stage); + } + + /** Test insertion up to the requested stage without writing data or metadata. */ + @Override + public void testInsertTablets(Map tablets, boolean sorted, TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException { + Objects.requireNonNull( + stage, SessionMessages.EXCEPTION_TEST_INSERTION_STAGE_MUST_NOT_BE_NULL_EC9D4E51); + TSInsertTabletsReq request = + genTSInsertTabletsReq(new ArrayList<>(tablets.values()), sorted, false); + if (request == null) { + throw new StatementExecutionException( + SessionMessages.EXCEPTION_TEST_INSERTION_HAS_NO_NON_NULL_VALUES_40F5D116); + } + getDefaultSessionConnection() + .testInsert(new TSTestInsertReq(0, stage.getValue()).setTablets(request)); + } + + /** Test insertion up to the requested stage without writing data or metadata. */ + @Override + public void testInsertRecords( + List deviceIds, + List times, + List> measurementsList, + List> valuesList, + TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException { + Objects.requireNonNull( + stage, SessionMessages.EXCEPTION_TEST_INSERTION_STAGE_MUST_NOT_BE_NULL_EC9D4E51); + TSInsertStringRecordsReq request; + try { + request = + filterAndGenTSInsertStringRecordsReq( + deviceIds, times, measurementsList, valuesList, false); + } catch (NoValidValueException e) { + throw new StatementExecutionException( + SessionMessages.EXCEPTION_TEST_INSERTION_HAS_NO_NON_NULL_VALUES_40F5D116); + } + + getDefaultSessionConnection() + .testInsert(new TSTestInsertReq(0, stage.getValue()).setStringRecords(request)); + } + + /** Test insertion up to the requested stage without writing data or metadata. */ + @Override + public void testInsertRecords( + List deviceIds, + List times, + List> measurementsList, + List> typesList, + List> valuesList, + TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException { + Objects.requireNonNull( + stage, SessionMessages.EXCEPTION_TEST_INSERTION_STAGE_MUST_NOT_BE_NULL_EC9D4E51); + TSInsertRecordsReq request; + try { + request = + filterAndGenTSInsertRecordsReq( + deviceIds, times, measurementsList, typesList, valuesList, false); + } catch (NoValidValueException e) { + throw new StatementExecutionException( + SessionMessages.EXCEPTION_TEST_INSERTION_HAS_NO_NON_NULL_VALUES_40F5D116); + } + + getDefaultSessionConnection() + .testInsert(new TSTestInsertReq(0, stage.getValue()).setRecords(request)); + } + + /** Test insertion up to the requested stage without writing data or metadata. */ + @Override + public void testInsertRecord( + String deviceId, + long time, + List measurements, + List values, + TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException { + Objects.requireNonNull( + stage, SessionMessages.EXCEPTION_TEST_INSERTION_STAGE_MUST_NOT_BE_NULL_EC9D4E51); + TSInsertStringRecordReq request; + try { + request = filterAndGenTSInsertStringRecordReq(deviceId, time, measurements, values, false); + } catch (NoValidValueException e) { + throw new StatementExecutionException( + SessionMessages.EXCEPTION_TEST_INSERTION_HAS_NO_NON_NULL_VALUES_40F5D116); + } + getDefaultSessionConnection() + .testInsert(new TSTestInsertReq(0, stage.getValue()).setStringRecord(request)); + } + + /** Test insertion up to the requested stage without writing data or metadata. */ + @Override + public void testInsertRecord( + String deviceId, + long time, + List measurements, + List types, + List values, + TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException { + Objects.requireNonNull( + stage, SessionMessages.EXCEPTION_TEST_INSERTION_STAGE_MUST_NOT_BE_NULL_EC9D4E51); + TSInsertRecordReq request; + try { + request = filterAndGenTSInsertRecordReq(deviceId, time, measurements, types, values, false); + } catch (NoValidValueException e) { + throw new StatementExecutionException( + SessionMessages.EXCEPTION_TEST_INSERTION_HAS_NO_NON_NULL_VALUES_40F5D116); + } + getDefaultSessionConnection() + .testInsert(new TSTestInsertReq(0, stage.getValue()).setRecord(request)); + } + /** * delete a timeseries, including data and schema * diff --git a/iotdb-client/session/src/main/java/org/apache/iotdb/session/SessionConnection.java b/iotdb-client/session/src/main/java/org/apache/iotdb/session/SessionConnection.java index d6598a39983f6..a0d7657e0a8a2 100644 --- a/iotdb-client/session/src/main/java/org/apache/iotdb/session/SessionConnection.java +++ b/iotdb-client/session/src/main/java/org/apache/iotdb/session/SessionConnection.java @@ -67,10 +67,13 @@ import org.apache.iotdb.service.rpc.thrift.TSRawDataQueryReq; import org.apache.iotdb.service.rpc.thrift.TSSetSchemaTemplateReq; import org.apache.iotdb.service.rpc.thrift.TSSetTimeZoneReq; +import org.apache.iotdb.service.rpc.thrift.TSTestInsertReq; +import org.apache.iotdb.service.rpc.thrift.TSTestInsertResp; import org.apache.iotdb.service.rpc.thrift.TSUnsetSchemaTemplateReq; import org.apache.iotdb.session.i18n.SessionMessages; import org.apache.iotdb.session.util.SessionUtils; +import org.apache.thrift.TApplicationException; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TCompactProtocol; @@ -1124,6 +1127,39 @@ private TSStatus deleteDataInternal(TSDeleteDataReq request) throws TException { return client.deleteData(request); } + protected void testInsert(TSTestInsertReq request) + throws IoTDBConnectionException, StatementExecutionException { + RetryResult result = + callWithRetryAndReconnect( + () -> { + request.setSessionId(sessionId); + try { + return client.testInsert(request); + } catch (TApplicationException e) { + if (e.getType() != TApplicationException.UNKNOWN_METHOD) { + throw e; + } + return new TSTestInsertResp( + new TSStatus(TSStatusCode.EXECUTE_STATEMENT_ERROR.getStatusCode()) + .setMessage( + SessionMessages + .MESSAGE_SERVER_DOES_NOT_SUPPORT_STAGED_TEST_INSERTION_0127CF25), + 0); + } + }, + TSTestInsertResp::getStatus); + if (result.getException() != null) { + throw new IoTDBConnectionException(result.getException()); + } + TSTestInsertResp response = result.getResult(); + RpcUtils.verifySuccess(response.getStatus()); + if (response.getCompletedStage() != request.getStage()) { + throw new StatementExecutionException( + SessionMessages + .EXCEPTION_SERVER_DID_NOT_ACKNOWLEDGE_THE_REQUESTED_TEST_INSERTION_STAGE_41067D1C); + } + } + protected void testInsertRecord(TSInsertStringRecordReq request) throws IoTDBConnectionException, StatementExecutionException { final TSStatus status = diff --git a/iotdb-client/session/src/main/java/org/apache/iotdb/session/TableSession.java b/iotdb-client/session/src/main/java/org/apache/iotdb/session/TableSession.java index b51a3a59831d8..4c9b4d0610ceb 100644 --- a/iotdb-client/session/src/main/java/org/apache/iotdb/session/TableSession.java +++ b/iotdb-client/session/src/main/java/org/apache/iotdb/session/TableSession.java @@ -23,6 +23,7 @@ import org.apache.iotdb.isession.SessionDataSet; import org.apache.iotdb.rpc.IoTDBConnectionException; import org.apache.iotdb.rpc.StatementExecutionException; +import org.apache.iotdb.service.rpc.thrift.TestInsertStage; import org.apache.tsfile.write.record.Tablet; @@ -34,6 +35,12 @@ public class TableSession implements ITableSession { this.session = session; } + @Override + public void testInsert(Tablet tablet, TestInsertStage stage) + throws StatementExecutionException, IoTDBConnectionException { + session.testInsertRelationalTablet(tablet, stage); + } + @Override public void insert(Tablet tablet) throws StatementExecutionException, IoTDBConnectionException { session.insertRelationalTablet(tablet); diff --git a/iotdb-client/session/src/main/java/org/apache/iotdb/session/pool/TableSessionWrapper.java b/iotdb-client/session/src/main/java/org/apache/iotdb/session/pool/TableSessionWrapper.java index 96cf6576fada9..91be80bf6a9af 100644 --- a/iotdb-client/session/src/main/java/org/apache/iotdb/session/pool/TableSessionWrapper.java +++ b/iotdb-client/session/src/main/java/org/apache/iotdb/session/pool/TableSessionWrapper.java @@ -23,6 +23,7 @@ import org.apache.iotdb.isession.SessionDataSet; import org.apache.iotdb.rpc.IoTDBConnectionException; import org.apache.iotdb.rpc.StatementExecutionException; +import org.apache.iotdb.service.rpc.thrift.TestInsertStage; import org.apache.iotdb.session.Session; import org.apache.iotdb.session.i18n.SessionMessages; @@ -48,6 +49,17 @@ protected TableSessionWrapper(Session session, SessionPool sessionPool) { this.sessionPool = sessionPool; } + @Override + public synchronized void testInsert(Tablet tablet, TestInsertStage stage) + throws StatementExecutionException, IoTDBConnectionException { + Session currentSession = getOpenSession(); + try { + currentSession.testInsertRelationalTablet(tablet, stage); + } catch (IoTDBConnectionException e) { + throw releaseOnConnectionFailure(e); + } + } + @Override public synchronized void insert(Tablet tablet) throws StatementExecutionException, IoTDBConnectionException { diff --git a/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionConnectionTest.java b/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionConnectionTest.java index c0a15e62a1d22..0a12a841f868a 100644 --- a/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionConnectionTest.java +++ b/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionConnectionTest.java @@ -56,8 +56,13 @@ import org.apache.iotdb.service.rpc.thrift.TSQueryTemplateReq; import org.apache.iotdb.service.rpc.thrift.TSQueryTemplateResp; import org.apache.iotdb.service.rpc.thrift.TSSetSchemaTemplateReq; +import org.apache.iotdb.service.rpc.thrift.TSTestInsertReq; +import org.apache.iotdb.service.rpc.thrift.TSTestInsertResp; import org.apache.iotdb.service.rpc.thrift.TSUnsetSchemaTemplateReq; +import org.apache.iotdb.service.rpc.thrift.TestInsertStage; +import org.apache.iotdb.session.i18n.SessionMessages; +import org.apache.thrift.TApplicationException; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; @@ -100,6 +105,50 @@ public class SessionConnectionTest { @Mock private Session session; + @Test + public void testOldServerRejectsStagedInsertionWithoutFallback() throws Exception { + Mockito.when(client.testInsert(any())) + .thenThrow(new TApplicationException(TApplicationException.UNKNOWN_METHOD, "testInsert")); + StatementExecutionException error = + Assert.assertThrows( + StatementExecutionException.class, + () -> + sessionConnection.testInsert( + new TSTestInsertReq(0, TestInsertStage.UNTIL_PLANNED.getValue()))); + Assert.assertTrue( + error + .getMessage() + .contains( + SessionMessages.MESSAGE_SERVER_DOES_NOT_SUPPORT_STAGED_TEST_INSERTION_0127CF25)); + Mockito.verify(client, Mockito.times(1)).testInsert(any()); + Mockito.verify(client, Mockito.never()).insertTablet(any()); + Mockito.verify(client, Mockito.never()).testInsertTablet(any()); + } + + @Test + public void testStagedInsertionAcknowledgement() throws Exception { + TSTestInsertReq request = new TSTestInsertReq(0, TestInsertStage.UNTIL_PLANNED.getValue()); + Mockito.when(client.testInsert(any())) + .thenReturn( + new TSTestInsertResp( + new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode()), request.getStage())); + sessionConnection.testInsert(request); + Mockito.verify(client).testInsert(request); + Mockito.verify(client, Mockito.never()).insertTablet(any()); + Mockito.when(client.testInsert(any())) + .thenReturn( + new TSTestInsertResp( + new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode()), + TestInsertStage.UNTIL_DECODED.getValue())); + Assert.assertThrows( + StatementExecutionException.class, () -> sessionConnection.testInsert(request)); + Mockito.when(client.testInsert(any())) + .thenReturn( + new TSTestInsertResp(new TSStatus(TSStatusCode.METADATA_ERROR.getStatusCode()), 0)); + Assert.assertThrows( + StatementExecutionException.class, () -> sessionConnection.testInsert(request)); + } + @Before public void setUp() throws IoTDBConnectionException, StatementExecutionException, TException { MockitoAnnotations.initMocks(this); diff --git a/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionTest.java b/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionTest.java index d27a0a53a1767..eaf24080c4340 100644 --- a/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionTest.java +++ b/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionTest.java @@ -28,8 +28,12 @@ import org.apache.iotdb.rpc.IoTDBConnectionException; import org.apache.iotdb.rpc.StatementExecutionException; import org.apache.iotdb.service.rpc.thrift.TSQueryTemplateResp; +import org.apache.iotdb.service.rpc.thrift.TSTestInsertReq; +import org.apache.iotdb.service.rpc.thrift.TestInsertStage; +import org.apache.iotdb.session.i18n.SessionMessages; import org.apache.tsfile.common.conf.TSFileConfig; +import org.apache.tsfile.enums.ColumnCategory; import org.apache.tsfile.enums.TSDataType; import org.apache.tsfile.file.metadata.enums.CompressionType; import org.apache.tsfile.file.metadata.enums.TSEncoding; @@ -42,6 +46,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; @@ -902,6 +907,76 @@ public void testSetSchemaTemplateException() session.setSchemaTemplate("template1", "prefixPath"); } + @Test + public void testStagedTabletsRejectFilteredEmptyRequests() throws Exception { + Tablet tableTablet = + new Tablet( + "t", + Collections.singletonList("v"), + Collections.singletonList(TSDataType.INT64), + Collections.singletonList(ColumnCategory.FIELD)); + tableTablet.addTimestamp(0, 1); + tableTablet.addValue("v", 0, null); + Tablet treeTablet = + new Tablet( + "root.sg.d", Collections.singletonList(new MeasurementSchema("v", TSDataType.INT64))); + treeTablet.addTimestamp(0, 1); + treeTablet.addValue("v", 0, null); + TableSession tableSession = new TableSession((Session) session); + String expectedMessage = + SessionMessages.EXCEPTION_TEST_INSERTION_HAS_NO_NON_NULL_VALUES_40F5D116; + assertEquals( + expectedMessage, + Assert.assertThrows( + StatementExecutionException.class, () -> tableSession.testInsert(tableTablet)) + .getMessage()); + for (TestInsertStage stage : TestInsertStage.values()) { + assertEquals( + expectedMessage, + Assert.assertThrows( + StatementExecutionException.class, + () -> tableSession.testInsert(tableTablet, stage)) + .getMessage()); + assertEquals( + expectedMessage, + Assert.assertThrows( + StatementExecutionException.class, + () -> session.testInsertTablet(treeTablet, stage)) + .getMessage()); + assertEquals( + expectedMessage, + Assert.assertThrows( + StatementExecutionException.class, + () -> + session.testInsertTablets( + Collections.singletonMap("root.sg.d", treeTablet), stage)) + .getMessage()); + } + Mockito.verifyZeroInteractions(sessionConnection); + } + + @Test + public void testStagedTableTabletKeepsFilteredColumnCategories() throws Exception { + Tablet tablet = + new Tablet( + "t", + Arrays.asList("id", "empty", "value"), + Arrays.asList(TSDataType.STRING, TSDataType.INT64, TSDataType.INT64), + Arrays.asList(ColumnCategory.TAG, ColumnCategory.FIELD, ColumnCategory.FIELD)); + tablet.addTimestamp(0, 1); + tablet.addValue("id", 0, "d"); + tablet.addValue("empty", 0, null); + tablet.addValue("value", 0, 1L); + new TableSession((Session) session).testInsert(tablet, TestInsertStage.UNTIL_DECODED); + ArgumentCaptor request = ArgumentCaptor.forClass(TSTestInsertReq.class); + Mockito.verify(sessionConnection).testInsert(request.capture()); + Assert.assertTrue(request.getValue().getTablet().isWriteToTable()); + assertEquals(Arrays.asList("id", "value"), request.getValue().getTablet().getMeasurements()); + assertEquals( + Arrays.asList((byte) ColumnCategory.TAG.ordinal(), (byte) ColumnCategory.FIELD.ordinal()), + request.getValue().getTablet().getColumnCategories()); + } + @Test public void testInsertTablet() throws IoTDBConnectionException, StatementExecutionException { List schemas = new ArrayList<>(); diff --git a/iotdb-client/session/src/test/java/org/apache/iotdb/session/TableSessionTest.java b/iotdb-client/session/src/test/java/org/apache/iotdb/session/TableSessionTest.java new file mode 100644 index 0000000000000..45dc27b0266a5 --- /dev/null +++ b/iotdb-client/session/src/test/java/org/apache/iotdb/session/TableSessionTest.java @@ -0,0 +1,51 @@ +/* + * 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.session; + +import org.apache.iotdb.isession.ITableSession; +import org.apache.iotdb.service.rpc.thrift.TestInsertStage; + +import org.apache.tsfile.write.record.Tablet; +import org.junit.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +public class TableSessionTest { + @Test + public void testInsertionStagesUseOnlyTheTableTestRpc() throws Exception { + Session delegate = mock(Session.class); + Tablet tablet = mock(Tablet.class); + try (ITableSession session = new TableSession(delegate)) { + session.testInsert(tablet); + for (TestInsertStage stage : TestInsertStage.values()) { + session.testInsert(tablet, stage); + } + } + for (TestInsertStage stage : TestInsertStage.values()) { + verify(delegate, times(stage == TestInsertStage.UNTIL_RPC_PROCESSED ? 2 : 1)) + .testInsertRelationalTablet(tablet, stage); + } + verify(delegate, never()).insertRelationalTablet(tablet); + verify(delegate).close(); + } +} diff --git a/iotdb-client/session/src/test/java/org/apache/iotdb/session/pool/TableSessionWrapperTest.java b/iotdb-client/session/src/test/java/org/apache/iotdb/session/pool/TableSessionWrapperTest.java new file mode 100644 index 0000000000000..02741dd1d60be --- /dev/null +++ b/iotdb-client/session/src/test/java/org/apache/iotdb/session/pool/TableSessionWrapperTest.java @@ -0,0 +1,104 @@ +/* + * 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.session.pool; + +import org.apache.iotdb.isession.ITableSession; +import org.apache.iotdb.rpc.IoTDBConnectionException; +import org.apache.iotdb.rpc.StatementExecutionException; +import org.apache.iotdb.service.rpc.thrift.TestInsertStage; +import org.apache.iotdb.session.Session; + +import org.apache.tsfile.write.record.Tablet; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +public class TableSessionWrapperTest { + @Test + public void testDefaultAndExplicitStagesReturnConnectionOnlyOnce() throws Exception { + Session delegate = mock(Session.class); + SessionPool pool = mock(SessionPool.class); + Tablet tablet = mock(Tablet.class); + ITableSession session = new TableSessionWrapper(delegate, pool); + session.testInsert(tablet); + session.testInsert(tablet, TestInsertStage.UNTIL_PLANNED); + session.close(); + session.close(); + assertThrows(IoTDBConnectionException.class, () -> session.testInsert(tablet)); + verify(delegate).testInsertRelationalTablet(tablet, TestInsertStage.UNTIL_RPC_PROCESSED); + verify(delegate).testInsertRelationalTablet(tablet, TestInsertStage.UNTIL_PLANNED); + verify(delegate, never()).insertRelationalTablet(any()); + verify(pool).releaseSession(delegate, true); + verify(pool, never()).releaseSession(any(), eq(false)); + } + + @Test + public void testConnectionFailureDiscardsSessionWithoutMaskingTheErrorOnClose() throws Exception { + Session delegate = mock(Session.class); + SessionPool pool = mock(SessionPool.class); + Tablet tablet = mock(Tablet.class); + IoTDBConnectionException failure = new IoTDBConnectionException("disconnected"); + doThrow(failure) + .when(delegate) + .testInsertRelationalTablet(tablet, TestInsertStage.UNTIL_PLANNED); + IoTDBConnectionException actual = + assertThrows( + IoTDBConnectionException.class, + () -> { + try (ITableSession session = new TableSessionWrapper(delegate, pool)) { + session.testInsert(tablet, TestInsertStage.UNTIL_PLANNED); + } + }); + assertSame(failure, actual); + assertEquals(0, actual.getSuppressed().length); + verify(pool).releaseSession(delegate, false); + verify(pool, never()).releaseSession(any(), eq(true)); + } + + @Test + public void testStatementFailurePreservesConnectionForReuse() throws Exception { + Session delegate = mock(Session.class); + SessionPool pool = mock(SessionPool.class); + Tablet tablet = mock(Tablet.class); + StatementExecutionException failure = new StatementExecutionException("missing partition"); + doThrow(failure) + .when(delegate) + .testInsertRelationalTablet(tablet, TestInsertStage.UNTIL_ANALYZED); + try (ITableSession session = new TableSessionWrapper(delegate, pool)) { + assertSame( + failure, + assertThrows( + StatementExecutionException.class, + () -> session.testInsert(tablet, TestInsertStage.UNTIL_ANALYZED))); + session.testInsert(tablet); + } + verify(delegate).testInsertRelationalTablet(tablet, TestInsertStage.UNTIL_RPC_PROCESSED); + verify(pool, never()).releaseSession(any(), eq(false)); + verify(pool).releaseSession(delegate, true); + } +} diff --git a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java index 5a75dd7bb38cf..cbcbd0a62de86 100644 --- a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java +++ b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java @@ -21,7 +21,12 @@ /** Compile-time i18n constants for DataNode misc subsystems (English). */ public final class DataNodeMiscMessages { + + public static final String MESSAGE_TEST_INSERTION_REQUIRES_A_KNOWN_STAGE_AND_EXACTLY_ONE_INSERTION_PAYLOAD_B0F3D171 = + "Test insertion requires a known stage and exactly one insertion payload"; + public static final String EXCEPTION_INVALID_IOTCONSENSUS_LOG_COMPRESSION_CODEC_ARG_2B9C27F7 = "Invalid IoTConsensus log compression codec: %s"; + public static final String LOG_FAILED_TO_AUTHORIZE_CQ_ARG_FOR_USER_ARG_ARG_B436A81F = "Failed to authorize CQ {} for user {}: {}"; diff --git a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java index b81f80cc5257d..a3a76b8e8276a 100644 --- a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java +++ b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java @@ -20,6 +20,27 @@ package org.apache.iotdb.db.i18n; public final class DataNodeQueryMessages { + + public static final String EXCEPTION_TEST_INSERTION_REQUIRES_AN_EXISTING_DATA_PARTITION_FOR_ARG_AT_ARG_A5AABFF2 = + "Test insertion requires an existing data partition for %s at %s"; + + public static final String EXCEPTION_INVALID_TEST_INSERTION_ACKNOWLEDGEMENT_FROM_ARG_E2F722A6 = + "Invalid test insertion acknowledgement from %s"; + + public static final String MESSAGE_TEST_INSERTION_TARGET_REGION_DOES_NOT_EXIST_A4645EC1 = + "Test insertion target region does not exist"; + + public static final String MESSAGE_TEST_INSERTION_ACCEPTS_ONLY_INSERTION_PLANS_TARGETING_DATA_REGIONS_319E02A6 = + "Test insertion accepts only insertion plans targeting data regions"; + + public static final String EXCEPTION_TEST_INSERTION_REQUIRES_AN_EXISTING_DATABASE_FOR_EVERY_DEVICE_22548137 = + "Test insertion requires an existing database for every device"; + + public static final String EXCEPTION_TEST_INSERTION_HAS_NO_EXECUTABLE_INSERTION_PLAN_803B3A76 = + "Test insertion has no executable insertion plan"; + + public static final String EXCEPTION_TEST_INSERTION_REQUIRES_EXISTING_SCHEMA_DEVICES_AND_ATTRIBUTES_METADATA_CHANGES_ARE_NOT_ALLOWED_8CF4EF1B = + "Test insertion requires existing schema, devices and attributes; metadata changes are not allowed"; public static final String EXCEPTION_QUERY_ATTEMPT_ARG_IS_CLOSED_12143E89 = "Query attempt %s is closed."; public static final String EXCEPTION_QUERY_ATTEMPT_ARG_ADMISSION_EXPIRED_DEADLINE_ARG_NS_NOW_ARG_NS_16A9846C = "Query attempt %s admission expired: deadline=%d ns, now=%d ns."; public static final String EXCEPTION_INVALID_QUERY_ADMISSION_ISSUER_FOR_ATTEMPT_ARG_9D1C4E9C = "Invalid query admission issuer for attempt %s."; diff --git a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java index 485a32e7448d0..6c403fcfd8b7e 100644 --- a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java +++ b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java @@ -21,7 +21,12 @@ /** 编译时国际化常量 - DataNode 杂项子系统(中文)。 */ public final class DataNodeMiscMessages { + + public static final String MESSAGE_TEST_INSERTION_REQUIRES_A_KNOWN_STAGE_AND_EXACTLY_ONE_INSERTION_PAYLOAD_B0F3D171 = + "测试写入需要有效阶段且只能包含一个写入载荷"; + public static final String EXCEPTION_INVALID_IOTCONSENSUS_LOG_COMPRESSION_CODEC_ARG_2B9C27F7 = "无效的 IoTConsensus 日志压缩算法:%s"; + public static final String LOG_FAILED_TO_AUTHORIZE_CQ_ARG_FOR_USER_ARG_ARG_B436A81F = "CQ {} 的用户 {} 鉴权失败:{}"; diff --git a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java index ce300fe8a2ec3..9efab6b8879ab 100644 --- a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java +++ b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java @@ -20,6 +20,27 @@ package org.apache.iotdb.db.i18n; public final class DataNodeQueryMessages { + + public static final String EXCEPTION_TEST_INSERTION_REQUIRES_AN_EXISTING_DATA_PARTITION_FOR_ARG_AT_ARG_A5AABFF2 = + "测试写入要求设备 %s 在时间 %s 的数据分区已存在"; + + public static final String EXCEPTION_INVALID_TEST_INSERTION_ACKNOWLEDGEMENT_FROM_ARG_E2F722A6 = + "来自 %s 的测试写入确认无效"; + + public static final String MESSAGE_TEST_INSERTION_TARGET_REGION_DOES_NOT_EXIST_A4645EC1 = + "测试写入的目标 Region 不存在"; + + public static final String MESSAGE_TEST_INSERTION_ACCEPTS_ONLY_INSERTION_PLANS_TARGETING_DATA_REGIONS_319E02A6 = + "测试写入仅接受以 DataRegion 为目标的写入计划"; + + public static final String EXCEPTION_TEST_INSERTION_REQUIRES_AN_EXISTING_DATABASE_FOR_EVERY_DEVICE_22548137 = + "测试写入要求每个设备所属的数据库已存在"; + + public static final String EXCEPTION_TEST_INSERTION_HAS_NO_EXECUTABLE_INSERTION_PLAN_803B3A76 = + "测试写入没有可执行的写入计划"; + + public static final String EXCEPTION_TEST_INSERTION_REQUIRES_EXISTING_SCHEMA_DEVICES_AND_ATTRIBUTES_METADATA_CHANGES_ARE_NOT_ALLOWED_8CF4EF1B = + "测试写入要求 schema、设备和属性已存在;不允许修改元数据"; public static final String EXCEPTION_QUERY_ATTEMPT_ARG_IS_CLOSED_12143E89 = "查询执行轮次 %s 已关闭。"; public static final String EXCEPTION_QUERY_ATTEMPT_ARG_ADMISSION_EXPIRED_DEADLINE_ARG_NS_NOW_ARG_NS_16A9846C = "查询执行轮次 %s 的接收凭证已过期:截止时间=%d ns,当前时间=%d ns。"; public static final String EXCEPTION_INVALID_QUERY_ADMISSION_ISSUER_FOR_ATTEMPT_ARG_9D1C4E9C = "查询执行轮次 %s 的接收凭证签发节点进程不匹配。"; diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/ClientRPCServiceImpl.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/ClientRPCServiceImpl.java index 14425b0986e57..bb64b45333da9 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/ClientRPCServiceImpl.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/ClientRPCServiceImpl.java @@ -19,6 +19,7 @@ package org.apache.iotdb.db.protocol.thrift.impl; +import org.apache.iotdb.calc.exception.QueryProcessException; import org.apache.iotdb.common.rpc.thrift.TAggregationType; import org.apache.iotdb.common.rpc.thrift.TEndPoint; import org.apache.iotdb.common.rpc.thrift.TRegionReplicaSet; @@ -36,6 +37,7 @@ import org.apache.iotdb.commons.conf.IoTDBConstant; import org.apache.iotdb.commons.exception.IllegalPathException; import org.apache.iotdb.commons.exception.IoTDBException; +import org.apache.iotdb.commons.exception.MetadataException; import org.apache.iotdb.commons.i18n.PipeMessages; import org.apache.iotdb.commons.partition.DataPartition; import org.apache.iotdb.commons.partition.DataPartitionQueryParam; @@ -111,6 +113,7 @@ import org.apache.iotdb.db.queryengine.plan.statement.StatementType; import org.apache.iotdb.db.queryengine.plan.statement.component.Ordering; import org.apache.iotdb.db.queryengine.plan.statement.crud.DeleteDataStatement; +import org.apache.iotdb.db.queryengine.plan.statement.crud.InsertBaseStatement; import org.apache.iotdb.db.queryengine.plan.statement.crud.InsertMultiTabletsStatement; import org.apache.iotdb.db.queryengine.plan.statement.crud.InsertRowStatement; import org.apache.iotdb.db.queryengine.plan.statement.crud.InsertRowsOfOneDeviceStatement; @@ -202,9 +205,12 @@ import org.apache.iotdb.service.rpc.thrift.TSRawDataQueryReq; import org.apache.iotdb.service.rpc.thrift.TSSetSchemaTemplateReq; import org.apache.iotdb.service.rpc.thrift.TSSetTimeZoneReq; +import org.apache.iotdb.service.rpc.thrift.TSTestInsertReq; +import org.apache.iotdb.service.rpc.thrift.TSTestInsertResp; import org.apache.iotdb.service.rpc.thrift.TSUnsetSchemaTemplateReq; import org.apache.iotdb.service.rpc.thrift.TSyncIdentityInfo; import org.apache.iotdb.service.rpc.thrift.TSyncTransportMetaInfo; +import org.apache.iotdb.service.rpc.thrift.TestInsertStage; import io.airlift.units.Duration; import org.apache.thrift.TException; @@ -3130,6 +3136,123 @@ public TSStatus testInsertTablet(TSInsertTabletReq req) { return RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS); } + @Override + public TSTestInsertResp testInsert(TSTestInsertReq req) { + try { + IClientSession session = SESSION_MANAGER.getCurrSessionAndUpdateIdleTime(); + if (!SESSION_MANAGER.checkLogin(session)) { + return new TSTestInsertResp(getNotLoggedInStatus(), 0); + } + TestInsertStage stage = TestInsertStage.findByValue(req.getStage()); + if (stage == null || !hasExactlyOneInsertPayload(req)) { + return new TSTestInsertResp( + RpcUtils.getStatus( + TSStatusCode.ILLEGAL_PARAMETER, + DataNodeMiscMessages + .MESSAGE_TEST_INSERTION_REQUIRES_A_KNOWN_STAGE_AND_EXACTLY_ONE_INSERTION_PAYLOAD_B0F3D171), + 0); + } + if (stage == TestInsertStage.UNTIL_RPC_PROCESSED) { + return new TSTestInsertResp( + RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS), req.getStage()); + } + InsertBaseStatement statement = decodeTestInsert(req); + if (stage == TestInsertStage.UNTIL_DECODED || statement.isEmpty()) { + return new TSTestInsertResp( + RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS), req.getStage()); + } + if (!statement.isWriteToTable()) { + TSStatus permission = + AuthorityChecker.checkAuthority( + statement, + new TreeAccessCheckContext( + session.getUserId(), session.getUsername(), session.getClientAddress())); + if (permission.getCode() != TSStatusCode.SUCCESS_STATUS.getStatusCode()) { + return new TSTestInsertResp(permission, 0); + } + } + TSStatus status = + COORDINATOR.testInsert( + statement, + stage, + SESSION_MANAGER.requestQueryId(), + SESSION_MANAGER.getSessionInfo(session), + relationSqlParser, + metadata, + partitionFetcher, + schemaFetcher); + return new TSTestInsertResp( + status, + status.getCode() == TSStatusCode.SUCCESS_STATUS.getStatusCode() ? req.getStage() : 0); + } catch (Exception e) { + return new TSTestInsertResp( + onQueryException(e, "testInsert", TSStatusCode.EXECUTE_STATEMENT_ERROR), 0); + } finally { + SESSION_MANAGER.updateIdleTime(); + } + } + + private static boolean hasExactlyOneInsertPayload(TSTestInsertReq req) { + int payloadCount = + (req.isSetTablet() ? 1 : 0) + + (req.isSetTablets() ? 1 : 0) + + (req.isSetRecord() ? 1 : 0) + + (req.isSetStringRecord() ? 1 : 0) + + (req.isSetRecords() ? 1 : 0) + + (req.isSetRecordsOfOneDevice() ? 1 : 0) + + (req.isSetStringRecords() ? 1 : 0); + return payloadCount == 1; + } + + private static InsertBaseStatement decodeTestInsert(TSTestInsertReq req) + throws MetadataException, QueryProcessException { + if (req.isSetTablet()) { + TSInsertTabletReq tablet = req.getTablet(); + if (!tablet.isWriteToTable()) { + tablet.setMeasurements( + PathUtils.checkIsLegalSingleMeasurementsAndUpdate(tablet.getMeasurements())); + } + return StatementGenerator.createStatement(tablet); + } + if (req.isSetTablets()) { + TSInsertTabletsReq tablets = req.getTablets(); + tablets.setMeasurementsList( + PathUtils.checkIsLegalSingleMeasurementListsAndUpdate(tablets.getMeasurementsList())); + return StatementGenerator.createStatement(tablets); + } + if (req.isSetRecord()) { + TSInsertRecordReq record = req.getRecord(); + if (!record.isIsWriteToTable()) { + record.setMeasurements( + PathUtils.checkIsLegalSingleMeasurementsAndUpdate(record.getMeasurements())); + } + return StatementGenerator.createStatement(record); + } + if (req.isSetStringRecord()) { + TSInsertStringRecordReq record = req.getStringRecord(); + record.setMeasurements( + PathUtils.checkIsLegalSingleMeasurementsAndUpdate(record.getMeasurements())); + return StatementGenerator.createStatement(record); + } + if (req.isSetRecords()) { + TSInsertRecordsReq records = req.getRecords(); + records.setMeasurementsList( + PathUtils.checkIsLegalSingleMeasurementListsAndUpdate(records.getMeasurementsList())); + return StatementGenerator.createStatement(records); + } + if (req.isSetRecordsOfOneDevice()) { + TSInsertRecordsOfOneDeviceReq records = req.getRecordsOfOneDevice(); + records.setMeasurementsList( + PathUtils.checkIsLegalSingleMeasurementListsAndUpdate(records.getMeasurementsList())); + return StatementGenerator.createStatement(records); + } + // The caller has verified that exactly one payload is set. + TSInsertStringRecordsReq records = req.getStringRecords(); + records.setMeasurementsList( + PathUtils.checkIsLegalSingleMeasurementListsAndUpdate(records.getMeasurementsList())); + return StatementGenerator.createStatement(records); + } + @Override public TSStatus testInsertTablets(TSInsertTabletsReq req) { LOGGER.debug(DataNodeMiscMessages.TEST_INSERT_BATCH_RECEIVE); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/DataNodeInternalRPCServiceImpl.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/DataNodeInternalRPCServiceImpl.java index 20c6800ab677a..6fe4e6c81cd38 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/DataNodeInternalRPCServiceImpl.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/DataNodeInternalRPCServiceImpl.java @@ -154,6 +154,7 @@ import org.apache.iotdb.db.queryengine.plan.analyze.schema.ISchemaFetcher; import org.apache.iotdb.db.queryengine.plan.execution.ExecutionResult; import org.apache.iotdb.db.queryengine.plan.execution.IQueryExecution; +import org.apache.iotdb.db.queryengine.plan.execution.TestInsertPlanValidator; import org.apache.iotdb.db.queryengine.plan.expression.Expression; import org.apache.iotdb.db.queryengine.plan.expression.binary.GreaterEqualExpression; import org.apache.iotdb.db.queryengine.plan.expression.binary.LessThanExpression; @@ -608,6 +609,11 @@ public TSendFragmentInstanceResp sendFragmentInstance(final TSendFragmentInstanc } } + @Override + public TSendBatchPlanNodeResp testInsertPlanNodes(TSendBatchPlanNodeReq req) { + return TestInsertPlanValidator.validate(req); + } + @Override public TSendBatchPlanNodeResp sendBatchPlanNode(TSendBatchPlanNodeReq req) { List responses = diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/common/MPPQueryContext.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/common/MPPQueryContext.java index 6a21809adf4d6..345edcb07713b 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/common/MPPQueryContext.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/common/MPPQueryContext.java @@ -27,6 +27,7 @@ import org.apache.iotdb.commons.audit.AuditLogOperation; import org.apache.iotdb.commons.audit.IAuditEntity; import org.apache.iotdb.commons.auth.entity.PrivilegeType; +import org.apache.iotdb.commons.exception.SemanticException; import org.apache.iotdb.commons.queryengine.common.SessionInfo; import org.apache.iotdb.commons.queryengine.plan.relational.analyzer.NodeRef; import org.apache.iotdb.commons.queryengine.plan.relational.metadata.ColumnSchema; @@ -209,6 +210,24 @@ public enum ExplainType { ConcurrentHashMap.newKeySet(); private final AtomicInteger externalTsFileQueryResourceIndex = new AtomicInteger(); + private boolean testInsert; + + public boolean isTestInsert() { + return testInsert; + } + + public void setTestInsert(boolean testInsert) { + this.testInsert = testInsert; + } + + public void checkSchemaModificationAllowed() { + if (testInsert) { + throw new SemanticException( + DataNodeQueryMessages + .EXCEPTION_TEST_INSERTION_REQUIRES_EXISTING_SCHEMA_DEVICES_AND_ATTRIBUTES_METADATA_CHANGES_ARE_NOT_ALLOWED_8CF4EF1B); + } + } + @TestOnly public MPPQueryContext(QueryId queryId) { this.queryId = queryId; diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/Coordinator.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/Coordinator.java index 0c7a688420223..6db0a37531b49 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/Coordinator.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/Coordinator.java @@ -20,6 +20,7 @@ package org.apache.iotdb.db.queryengine.plan; import org.apache.iotdb.common.rpc.thrift.TEndPoint; +import org.apache.iotdb.common.rpc.thrift.TSStatus; import org.apache.iotdb.commons.client.ClientPoolFactory; import org.apache.iotdb.commons.client.IClientManager; import org.apache.iotdb.commons.client.async.AsyncDataNodeInternalServiceClient; @@ -57,17 +58,23 @@ import org.apache.iotdb.db.queryengine.common.QueryId; import org.apache.iotdb.db.queryengine.execution.QueryIdGenerator; import org.apache.iotdb.db.queryengine.execution.QueryState; +import org.apache.iotdb.db.queryengine.plan.analyze.IAnalysis; import org.apache.iotdb.db.queryengine.plan.analyze.IPartitionFetcher; import org.apache.iotdb.db.queryengine.plan.analyze.lock.DataNodeSchemaLockManager; import org.apache.iotdb.db.queryengine.plan.analyze.schema.ISchemaFetcher; import org.apache.iotdb.db.queryengine.plan.execution.ExecutionResult; import org.apache.iotdb.db.queryengine.plan.execution.IQueryExecution; import org.apache.iotdb.db.queryengine.plan.execution.QueryExecution; +import org.apache.iotdb.db.queryengine.plan.execution.TestInsertPlanValidator; import org.apache.iotdb.db.queryengine.plan.execution.config.ConfigExecution; import org.apache.iotdb.db.queryengine.plan.execution.config.TableConfigTaskVisitor; import org.apache.iotdb.db.queryengine.plan.execution.config.TreeConfigTaskVisitor; +import org.apache.iotdb.db.queryengine.plan.planner.IPlanner; import org.apache.iotdb.db.queryengine.plan.planner.LocalExecutionPlanner; import org.apache.iotdb.db.queryengine.plan.planner.TreeModelPlanner; +import org.apache.iotdb.db.queryengine.plan.planner.plan.DistributedQueryPlan; +import org.apache.iotdb.db.queryengine.plan.planner.plan.FragmentInstance; +import org.apache.iotdb.db.queryengine.plan.planner.plan.LogicalQueryPlan; import org.apache.iotdb.db.queryengine.plan.relational.metadata.Metadata; import org.apache.iotdb.db.queryengine.plan.relational.planner.PlannerContext; import org.apache.iotdb.db.queryengine.plan.relational.planner.TableModelPlanner; @@ -159,10 +166,18 @@ import org.apache.iotdb.db.queryengine.plan.relational.sql.rewrite.StatementRewriteFactory; import org.apache.iotdb.db.queryengine.plan.statement.IConfigStatement; import org.apache.iotdb.db.queryengine.plan.statement.Statement; +import org.apache.iotdb.db.queryengine.plan.statement.crud.InsertBaseStatement; import org.apache.iotdb.db.queryengine.plan.statement.metadata.pipe.ShowPipeMemoryStatement; import org.apache.iotdb.db.queryengine.plan.statement.pipe.PipeEnrichedStatement; import org.apache.iotdb.db.queryengine.udf.InternalQueryExecutor; import org.apache.iotdb.db.utils.SetThreadName; +import org.apache.iotdb.mpp.rpc.thrift.TPlanNode; +import org.apache.iotdb.mpp.rpc.thrift.TSendBatchPlanNodeReq; +import org.apache.iotdb.mpp.rpc.thrift.TSendBatchPlanNodeResp; +import org.apache.iotdb.mpp.rpc.thrift.TSendSinglePlanNodeReq; +import org.apache.iotdb.rpc.RpcUtils; +import org.apache.iotdb.rpc.TSStatusCode; +import org.apache.iotdb.service.rpc.thrift.TestInsertStage; import org.apache.thrift.TBase; import org.apache.tsfile.utils.Accountable; @@ -283,6 +298,115 @@ public class Coordinator { } } + /** Analyze and plan an insertion without scheduling any writes. */ + public TSStatus testInsert( + InsertBaseStatement statement, + TestInsertStage stage, + long queryId, + SessionInfo session, + SqlParser sqlParser, + Metadata metadata, + IPartitionFetcher partitionFetcher, + ISchemaFetcher schemaFetcher) + throws Exception { + MPPQueryContext context = + new MPPQueryContext( + "", + queryIdGenerator.createNextQueryId(), + queryId, + session, + DataNodeEndPoints.LOCAL_HOST_DATA_BLOCK_ENDPOINT, + DataNodeEndPoints.LOCAL_HOST_INTERNAL_ENDPOINT); + context.setTestInsert(true); + context.setStartTime(System.currentTimeMillis()); + context.setTimeOut(CONFIG.getQueryTimeoutThreshold()); + try { + IPlanner planner = + statement.isWriteToTable() + ? new TableModelPlanner( + statement.toRelationalStatement(context), + sqlParser, + metadata, + scheduledExecutor, + SYNC_INTERNAL_SERVICE_CLIENT_MANAGER, + ASYNC_INTERNAL_SERVICE_CLIENT_MANAGER, + statementRewrite, + logicalPlanOptimizers, + distributionPlanOptimizers, + AuthorityChecker.getAccessControl(), + dataNodeLocationSupplier, + Collections.emptyList(), + Collections.emptyMap(), + typeManager) + : new TreeModelPlanner( + statement, + executor, + scheduledExecutor, + partitionFetcher, + schemaFetcher, + SYNC_INTERNAL_SERVICE_CLIENT_MANAGER, + ASYNC_INTERNAL_SERVICE_CLIENT_MANAGER); + IAnalysis analysis = planner.analyze(context); + if (analysis.isFailed()) { + return analysis.getFailStatus(); + } + context.checkTimeOut(); + if (stage == TestInsertStage.UNTIL_ANALYZED) { + return RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS); + } + if (analysis.isFinishQueryAfterAnalyze()) { + throw new SemanticException( + DataNodeQueryMessages + .EXCEPTION_TEST_INSERTION_HAS_NO_EXECUTABLE_INSERTION_PLAN_803B3A76); + } + context.checkTimeOut(); + LogicalQueryPlan logicalPlan = planner.doLogicalPlan(analysis, context); + if (analysis.isFailed()) { + return analysis.getFailStatus(); + } + DistributedQueryPlan plan = planner.doDistributionPlan(analysis, logicalPlan, context); + context.reserveMemoryForFrontEndImmediately(); + if (stage == TestInsertStage.UNTIL_WRITE_TARGET_RECEIVED) { + for (FragmentInstance instance : plan.getInstances()) { + context.checkTimeOut(); + TSendBatchPlanNodeReq request = + new TSendBatchPlanNodeReq( + Collections.singletonList( + new TSendSinglePlanNodeReq( + new TPlanNode( + instance.getFragment().getPlanNodeTree().serializeToByteBuffer()), + instance.getRegionReplicaSet().getRegionId()))); + TEndPoint endpoint = instance.getHostDataNode().getInternalEndPoint(); + TSendBatchPlanNodeResp response; + if (DataNodeEndPoints.LOCAL_HOST_INTERNAL_ENDPOINT.equals(endpoint)) { + response = TestInsertPlanValidator.validate(request); + } else { + try (SyncDataNodeInternalServiceClient client = + SYNC_INTERNAL_SERVICE_CLIENT_MANAGER.borrowClient(endpoint)) { + response = client.testInsertPlanNodes(request); + } + } + if (response.getResponsesSize() != 1) { + throw new SemanticException( + String.format( + DataNodeQueryMessages + .EXCEPTION_INVALID_TEST_INSERTION_ACKNOWLEDGEMENT_FROM_ARG_E2F722A6, + endpoint)); + } + if (!response.getResponses().get(0).isAccepted()) { + return response.getResponses().get(0).getStatus(); + } + RpcUtils.verifySuccess(response.getResponses().get(0).getStatus()); + } + } + context.checkTimeOut(); + return RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS); + } finally { + context.releaseAllMemoryReservedForFrontEnd(); + DataNodeSchemaLockManager.getInstance().releaseReadLock(context); + } + } + private Coordinator() { this.queryExecutionMap = new ConcurrentHashMap<>(); this.typeManager = new InternalTypeManager(); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/analyze/AnalyzeVisitor.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/analyze/AnalyzeVisitor.java index 6dfa31004ee0e..a53828dd9b751 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/analyze/AnalyzeVisitor.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/analyze/AnalyzeVisitor.java @@ -2911,7 +2911,9 @@ public Analysis visitInsertTablet( context, insertTabletStatement, () -> SchemaValidator.validate(schemaFetcher, insertTabletStatement, context), - partitionFetcher::getOrCreateDataPartition, + context.isTestInsert() + ? ClusterPartitionFetcher.getInstance()::getDataPartitionForTestInsert + : partitionFetcher::getOrCreateDataPartition, AnalyzeUtils::computeTreeDataPartitionParams, analysis, true); @@ -2946,13 +2948,17 @@ public Analysis visitInsertRow(InsertRowStatement insertRowStatement, MPPQueryCo analysis, Collections.singletonList(dataPartitionQueryParam), context.getSession().getUserName(), - partitionFetcher::getOrCreateDataPartition); + context.isTestInsert() + ? ClusterPartitionFetcher.getInstance()::getDataPartitionForTestInsert + : partitionFetcher::getOrCreateDataPartition); } else { AnalyzeUtils.analyzeDataPartition( analysis, AnalyzeUtils.computeTreeDataPartitionParams(realInsertStatement, context), context.getSession().getUserName(), - partitionFetcher::getOrCreateDataPartition); + context.isTestInsert() + ? ClusterPartitionFetcher.getInstance()::getDataPartitionForTestInsert + : partitionFetcher::getOrCreateDataPartition); } return analysis; } @@ -2978,7 +2984,9 @@ public Analysis visitInsertRows( analysis, AnalyzeUtils.computeTreeDataPartitionParams(realInsertRowsStatement, context), context.getSession().getUserName(), - partitionFetcher::getOrCreateDataPartition); + context.isTestInsert() + ? ClusterPartitionFetcher.getInstance()::getDataPartitionForTestInsert + : partitionFetcher::getOrCreateDataPartition); return analysis; } @@ -3004,7 +3012,9 @@ public Analysis visitInsertMultiTablets( analysis, AnalyzeUtils.computeTreeDataPartitionParams(realStatement, context), context.getSession().getUserName(), - partitionFetcher::getOrCreateDataPartition); + context.isTestInsert() + ? ClusterPartitionFetcher.getInstance()::getDataPartitionForTestInsert + : partitionFetcher::getOrCreateDataPartition); return analysis; } @@ -3036,13 +3046,17 @@ public Analysis visitInsertRowsOfOneDevice( analysis, Collections.singletonList(dataPartitionQueryParam), context.getSession().getUserName(), - partitionFetcher::getOrCreateDataPartition); + context.isTestInsert() + ? ClusterPartitionFetcher.getInstance()::getDataPartitionForTestInsert + : partitionFetcher::getOrCreateDataPartition); } else { AnalyzeUtils.analyzeDataPartition( analysis, AnalyzeUtils.computeTreeDataPartitionParams(realInsertStatement, context), context.getSession().getUserName(), - partitionFetcher::getOrCreateDataPartition); + context.isTestInsert() + ? ClusterPartitionFetcher.getInstance()::getDataPartitionForTestInsert + : partitionFetcher::getOrCreateDataPartition); } return analysis; } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/analyze/ClusterPartitionFetcher.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/analyze/ClusterPartitionFetcher.java index 81c3145c95d04..ec20e8715d2be 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/analyze/ClusterPartitionFetcher.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/analyze/ClusterPartitionFetcher.java @@ -27,6 +27,7 @@ import org.apache.iotdb.commons.client.exception.ClientManagerException; import org.apache.iotdb.commons.consensus.ConfigRegionId; import org.apache.iotdb.commons.exception.IoTDBRuntimeException; +import org.apache.iotdb.commons.exception.SemanticException; import org.apache.iotdb.commons.partition.DataPartition; import org.apache.iotdb.commons.partition.DataPartitionQueryParam; import org.apache.iotdb.commons.partition.SchemaNodeManagementPartition; @@ -316,6 +317,39 @@ public DataPartition getOrCreateDataPartition( return dataPartition; } + public DataPartition getDataPartitionForTestInsert( + final List params, final String userName) { + final Map> byDatabase = + splitDataPartitionQueryParam(params, false, userName); + if (byDatabase.values().stream().mapToInt(List::size).sum() != params.size()) { + throw new SemanticException( + DataNodeQueryMessages + .EXCEPTION_TEST_INSERTION_REQUIRES_AN_EXISTING_DATABASE_FOR_EVERY_DEVICE_22548137); + } + final DataPartition partition = getDataPartition(byDatabase); + for (Map.Entry> entry : byDatabase.entrySet()) { + for (DataPartitionQueryParam param : entry.getValue()) { + final Map> slots = + partition + .getDataPartitionMap() + .getOrDefault(entry.getKey(), Collections.emptyMap()) + .getOrDefault( + partition.calculateDeviceGroupId(param.getDeviceID()), Collections.emptyMap()); + for (TTimePartitionSlot slot : param.getTimePartitionSlotList()) { + if (!slots.containsKey(slot) || slots.get(slot).isEmpty()) { + throw new SemanticException( + String.format( + DataNodeQueryMessages + .EXCEPTION_TEST_INSERTION_REQUIRES_AN_EXISTING_DATA_PARTITION_FOR_ARG_AT_ARG_A5AABFF2, + param.getDeviceID(), + slot.getStartTime())); + } + } + } + } + return partition; + } + @Override public DataPartition getOrCreateDataPartition( final List dataPartitionQueryParams, final String userName) { diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/analyze/schema/AutoCreateSchemaExecutor.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/analyze/schema/AutoCreateSchemaExecutor.java index 2c5836c96c8f6..c5c68baa6f267 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/analyze/schema/AutoCreateSchemaExecutor.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/analyze/schema/AutoCreateSchemaExecutor.java @@ -84,6 +84,9 @@ class AutoCreateSchemaExecutor { } private ExecutionResult executeStatement(Statement statement, MPPQueryContext context) { + if (context != null) { + context.checkSchemaModificationAllowed(); + } return coordinator.executeForTreeModel( statement, diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/TestInsertPlanValidator.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/TestInsertPlanValidator.java new file mode 100644 index 0000000000000..15b0f7c7bdb45 --- /dev/null +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/TestInsertPlanValidator.java @@ -0,0 +1,80 @@ +/* + * 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.queryengine.plan.execution; + +import org.apache.iotdb.common.rpc.thrift.TConsensusGroupType; +import org.apache.iotdb.common.rpc.thrift.TSStatus; +import org.apache.iotdb.commons.consensus.ConsensusGroupId; +import org.apache.iotdb.commons.queryengine.plan.planner.plan.node.PlanNode; +import org.apache.iotdb.commons.queryengine.plan.planner.plan.node.PlanNodeType; +import org.apache.iotdb.db.i18n.DataNodeQueryMessages; +import org.apache.iotdb.db.protocol.thrift.impl.DataNodeRegionManager; +import org.apache.iotdb.db.queryengine.plan.planner.plan.node.write.InsertNode; +import org.apache.iotdb.mpp.rpc.thrift.TSendBatchPlanNodeReq; +import org.apache.iotdb.mpp.rpc.thrift.TSendBatchPlanNodeResp; +import org.apache.iotdb.mpp.rpc.thrift.TSendSinglePlanNodeReq; +import org.apache.iotdb.mpp.rpc.thrift.TSendSinglePlanNodeResp; +import org.apache.iotdb.rpc.RpcUtils; +import org.apache.iotdb.rpc.TSStatusCode; + +import java.util.ArrayList; +import java.util.List; + +/** Checks reception and routing only; never invokes triggers, consensus or storage writes. */ +public class TestInsertPlanValidator { + private TestInsertPlanValidator() {} + + public static TSendBatchPlanNodeResp validate(TSendBatchPlanNodeReq request) { + List responses = new ArrayList<>(); + for (TSendSinglePlanNodeReq item : request.getRequests()) { + TSStatus status; + try { + PlanNode node = PlanNodeType.deserialize(item.getPlanNode().bufferForBody()); + if (!(node instanceof InsertNode) + || item.getConsensusGroupId().getType() != TConsensusGroupType.DataRegion) { + status = + RpcUtils.getStatus( + TSStatusCode.EXECUTE_STATEMENT_ERROR, + DataNodeQueryMessages + .MESSAGE_TEST_INSERTION_ACCEPTS_ONLY_INSERTION_PLANS_TARGETING_DATA_REGIONS_319E02A6); + } else if (DataNodeRegionManager.getInstance() + .getRegionLock( + ConsensusGroupId.Factory.createFromTConsensusGroupId( + item.getConsensusGroupId())) + == null) { + status = + RpcUtils.getStatus( + TSStatusCode.NO_AVAILABLE_REGION_GROUP, + DataNodeQueryMessages + .MESSAGE_TEST_INSERTION_TARGET_REGION_DOES_NOT_EXIST_A4645EC1); + } else { + status = RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS); + } + } catch (RuntimeException e) { + status = RpcUtils.getStatus(TSStatusCode.EXECUTE_STATEMENT_ERROR, e.getMessage()); + } + TSendSinglePlanNodeResp response = new TSendSinglePlanNodeResp(); + response.setStatus(status); + response.setAccepted(status.getCode() == TSStatusCode.SUCCESS_STATUS.getStatusCode()); + responses.add(response); + } + return new TSendBatchPlanNodeResp(responses); + } +} diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/StatementAnalyzer.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/StatementAnalyzer.java index e10f492797cdd..61c1f38f7d794 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/StatementAnalyzer.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/StatementAnalyzer.java @@ -137,6 +137,7 @@ import org.apache.iotdb.db.queryengine.execution.warnings.IoTDBWarning; import org.apache.iotdb.db.queryengine.execution.warnings.WarningCollector; import org.apache.iotdb.db.queryengine.plan.analyze.AnalyzeUtils; +import org.apache.iotdb.db.queryengine.plan.analyze.ClusterPartitionFetcher; import org.apache.iotdb.db.queryengine.plan.analyze.QueryType; import org.apache.iotdb.db.queryengine.plan.analyze.load.LoadTsFileAnalyzer; import org.apache.iotdb.db.queryengine.plan.analyze.lock.DataNodeSchemaLockManager; @@ -1405,7 +1406,9 @@ private Scope visitInsert(WrappedInsertStatement insert, Optional scope) context, innerInsert, () -> SchemaValidator.validate(metadata, insert, context, accessControl), - metadata::getOrCreateDataPartition, + context.isTestInsert() + ? ClusterPartitionFetcher.getInstance()::getDataPartitionForTestInsert + : metadata::getOrCreateDataPartition, AnalyzeUtils::computeTableDataPartitionParams, analysis, false); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableDeviceSchemaValidator.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableDeviceSchemaValidator.java index 7133c7ff2f924..49cdbe3530340 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableDeviceSchemaValidator.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableDeviceSchemaValidator.java @@ -250,6 +250,9 @@ private void autoCreateOrUpdateDeviceSchema( final List inputDeviceIdList, final List attributeKeyList, final List intPutAttributeValueList) { + if (context != null) { + context.checkSchemaModificationAllowed(); + } final int size = previousValidateResult.missingDeviceIndexList.size() + previousValidateResult.attributeUpdateDeviceIndexList.size(); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableHeaderSchemaValidator.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableHeaderSchemaValidator.java index 49a6fbd972f72..4b0c9ff1e0c2a 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableHeaderSchemaValidator.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableHeaderSchemaValidator.java @@ -546,6 +546,7 @@ private void autoCreateTableFromMeasurementInfo( final MPPQueryContext context, final String database, final InsertNodeMeasurementInfo measurementInfo) { + context.checkSchemaModificationAllowed(); DataNodeSchemaLockManager.getInstance().releaseReadLock(context); final TsTable tsTable = toTsTable(measurementInfo); AuthorityChecker.getAccessControl() @@ -578,6 +579,7 @@ private void autoCreateColumnsFromMeasurements( final InsertNodeMeasurementInfo measurementInfo, final List missingIndices, final MPPQueryContext context) { + context.checkSchemaModificationAllowed(); DataNodeSchemaLockManager.getInstance().releaseReadLock(context); AuthorityChecker.getAccessControl() .checkCanAlterTable( @@ -635,6 +637,7 @@ private void autoCreateColumnsFromMeasurements( private void autoCreateTable( final MPPQueryContext context, final String database, final TableSchema tableSchema) { + context.checkSchemaModificationAllowed(); // Release to avoid deadlock DataNodeSchemaLockManager.getInstance().releaseReadLock(context); final TsTable tsTable = new TsTable(tableSchema.getTableName()); @@ -843,6 +846,7 @@ private void autoCreateColumn( final String tableName, final List inputColumnList, final MPPQueryContext context) { + context.checkSchemaModificationAllowed(); DataNodeSchemaLockManager.getInstance().releaseReadLock(context); AuthorityChecker.getAccessControl() .checkCanAlterTable( diff --git a/iotdb-protocol/thrift-datanode/src/main/thrift/client.thrift b/iotdb-protocol/thrift-datanode/src/main/thrift/client.thrift index 1790f062b97c9..0842e37c12dd6 100644 --- a/iotdb-protocol/thrift-datanode/src/main/thrift/client.thrift +++ b/iotdb-protocol/thrift-datanode/src/main/thrift/client.thrift @@ -577,6 +577,41 @@ struct TSConnectionInfoResp { 1: required list connectionInfoList } +// Staged test insertion never writes data or changes metadata. +// Analysis and later stages require pre-existing metadata and data partitions. +enum TestInsertStage { + // Login, stage and payload-count checks have passed; no Statement has been decoded. + UNTIL_RPC_PROCESSED = 1, + // The insertion payload has been decoded into a Statement. + UNTIL_DECODED = 2, + // Read-only analysis has completed. + UNTIL_ANALYZED = 3, + // Logical and distributed plans have been generated. + UNTIL_PLANNED = 4, + // All plan targets have deserialized the plan and checked its type and target region existence. + // No triggers, consensus or storage writes have been invoked. + UNTIL_WRITE_TARGET_RECEIVED = 5 +} + +// Exactly one payload must be supplied. Separate RPC prevents old servers silently ignoring stages. +struct TSTestInsertReq { + 1: required i64 sessionId + 2: required i32 stage + 3: optional TSInsertTabletReq tablet + 4: optional TSInsertTabletsReq tablets + 5: optional TSInsertRecordReq record + 6: optional TSInsertStringRecordReq stringRecord + 7: optional TSInsertRecordsReq records + 8: optional TSInsertRecordsOfOneDeviceReq recordsOfOneDevice + 9: optional TSInsertStringRecordsReq stringRecords +} + +struct TSTestInsertResp { + 1: required common.TSStatus status + // Zero on failure; otherwise the requested stage has completed. + 2: required i32 completedStage +} + service IClientRPCService { TSExecuteStatementResp executeQueryStatementV2(1:TSExecuteStatementReq req); @@ -658,6 +693,8 @@ service IClientRPCService { common.TSStatus insertStringRecords(1:TSInsertStringRecordsReq req); + TSTestInsertResp testInsert(1:TSTestInsertReq req); + common.TSStatus testInsertTablet(1:TSInsertTabletReq req); common.TSStatus testInsertTablets(1:TSInsertTabletsReq req); diff --git a/iotdb-protocol/thrift-datanode/src/main/thrift/datanode.thrift b/iotdb-protocol/thrift-datanode/src/main/thrift/datanode.thrift index 97416bf33095f..8365c44cea9be 100644 --- a/iotdb-protocol/thrift-datanode/src/main/thrift/datanode.thrift +++ b/iotdb-protocol/thrift-datanode/src/main/thrift/datanode.thrift @@ -978,6 +978,9 @@ service IDataNodeRPCService { */ TSendBatchPlanNodeResp sendBatchPlanNode(TSendBatchPlanNodeReq req); + // Deserialize and validate insertion plans without executing them. + TSendBatchPlanNodeResp testInsertPlanNodes(TSendBatchPlanNodeReq req); + TFragmentInstanceInfoResp fetchFragmentInstanceInfo(TFetchFragmentInstanceInfoReq req); TCancelResp cancelQuery(TCancelQueryReq req);