You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iotdb.apache.org by yo...@apache.org on 2025/12/16 05:58:39 UTC
(iotdb) 02/14: [AINode] Implement concurrent inference framework (#16311)
This is an automated email from the ASF dual-hosted git repository.
yongzao pushed a commit to branch cp-ain-to-206
in repository https://gitbox.apache.org/repos/asf/iotdb.git
commit e32ed9bb7d5820f6773a9e372d0cf2a3fff650ce
Author: Leo <16...@users.noreply.github.com>
AuthorDate: Fri Sep 12 22:14:27 2025 +0800
[AINode] Implement concurrent inference framework (#16311)
(cherry picked from commit 7b9ec7ea83d1a315690617e98056564a99dc4aee)
---
.../iotdb/it/env/cluster/node/AINodeWrapper.java | 2 +-
.../ainode/it/AINodeConcurrentInferenceIT.java | 141 ++++++
.../ainode/it/AINodeInstanceManagementIT.java | 212 +++++++++
.../apache/iotdb/ainode/utils/AINodeTestUtils.java | 32 ++
.../java/org/apache/iotdb/rpc/TSStatusCode.java | 1 +
iotdb-core/ainode/iotdb/ainode/core/ai_node.py | 2 +
iotdb-core/ainode/iotdb/ainode/core/constant.py | 9 +-
iotdb-core/ainode/iotdb/ainode/core/exception.py | 4 +-
.../iotdb/ainode/core/inference/pool_controller.py | 509 +++++++++++++++++++++
.../iotdb/ainode/core/inference/pool_group.py | 117 +++++
.../iotdb/ainode/core/manager/model_manager.py | 12 +
.../iotdb/ainode/core/model/model_storage.py | 6 +-
.../ainode/iotdb/ainode/core/util/atmoic_int.py | 66 +++
.../iotdb/ainode/core/util/batch_executor.py | 133 ++++++
.../ainode/iotdb/ainode/core/util/gpu_mapping.py | 93 ++++
.../ainode/iotdb/ainode/core/util/thread_name.py | 22 +
.../org/apache/iotdb/db/qp/sql/IoTDBSqlParser.g4 | 20 +-
.../antlr4/org/apache/iotdb/db/qp/sql/SqlLexer.g4 | 8 +
.../exception/NoAvailableAINodeException.java | 27 ++
.../iotdb/confignode/manager/ConfigManager.java | 37 ++
.../apache/iotdb/confignode/manager/IManager.java | 17 +
.../iotdb/confignode/manager/ModelManager.java | 96 +++-
.../thrift/ConfigNodeRPCServiceProcessor.java | 25 +
.../iotdb/db/protocol/client/ConfigNodeClient.java | 28 ++
.../table/v1/handler/ExecuteStatementHandler.java | 4 +
.../rest/v1/handler/ExecuteStatementHandler.java | 4 +
.../rest/v1/handler/QueryDataSetHandler.java | 4 +
.../rest/v2/handler/ExecuteStatementHandler.java | 4 +
.../rest/v2/handler/QueryDataSetHandler.java | 4 +
.../protocol/thrift/impl/ClientRPCServiceImpl.java | 1 -
.../common/header/DatasetHeaderFactory.java | 8 +
.../iotdb/db/queryengine/plan/Coordinator.java | 8 +
.../execution/config/TableConfigTaskVisitor.java | 32 ++
.../execution/config/TreeConfigTaskVisitor.java | 33 ++
.../config/executor/ClusterConfigTaskExecutor.java | 83 ++++
.../config/executor/IConfigTaskExecutor.java | 8 +
.../config/metadata/ai/LoadModelTask.java | 45 ++
.../config/metadata/ai/ShowAIDevicesTask.java | 64 +++
.../config/metadata/ai/ShowLoadedModelsTask.java | 78 ++++
.../config/metadata/ai/UnloadModelTask.java | 45 ++
.../db/queryengine/plan/parser/ASTVisitor.java | 55 +++
.../plan/relational/sql/ast/AstVisitor.java | 16 +
.../plan/relational/sql/ast/LoadModel.java | 73 +++
.../plan/relational/sql/ast/ShowAIDevices.java | 59 +++
.../plan/relational/sql/ast/ShowLoadedModels.java | 66 +++
.../plan/relational/sql/ast/UnloadModel.java | 72 +++
.../plan/relational/sql/parser/AstBuilder.java | 53 +++
.../plan/statement/StatementVisitor.java | 20 +
.../metadata/model/LoadModelStatement.java | 89 ++++
.../metadata/model/ShowAIDevicesStatement.java | 51 +++
.../metadata/model/ShowLoadedModelsStatement.java | 77 ++++
.../metadata/model/UnloadModelStatement.java | 89 ++++
.../iotdb/commons/client/ainode/AINodeClient.java | 53 +++
.../schema/column/ColumnHeaderConstant.java | 11 +
.../db/relational/grammar/sql/RelationalSql.g4 | 24 +
.../thrift-ainode/src/main/thrift/ainode.thrift | 32 ++
.../src/main/thrift/confignode.thrift | 48 ++
57 files changed, 2907 insertions(+), 25 deletions(-)
diff --git a/integration-test/src/main/java/org/apache/iotdb/it/env/cluster/node/AINodeWrapper.java b/integration-test/src/main/java/org/apache/iotdb/it/env/cluster/node/AINodeWrapper.java
index b9eba67c6e1..359c9d1c921 100644
--- a/integration-test/src/main/java/org/apache/iotdb/it/env/cluster/node/AINodeWrapper.java
+++ b/integration-test/src/main/java/org/apache/iotdb/it/env/cluster/node/AINodeWrapper.java
@@ -59,7 +59,7 @@ public class AINodeWrapper extends AbstractNodeWrapper {
public static final String CONFIG_PATH = "conf";
public static final String SCRIPT_PATH = "sbin";
public static final String BUILT_IN_MODEL_PATH = "data/ainode/models/weights";
- public static final String CACHE_BUILT_IN_MODEL_PATH = "/tmp/data/ainode/models/weights";
+ public static final String CACHE_BUILT_IN_MODEL_PATH = "/data/ainode/models/weights";
private void replaceAttribute(String[] keys, String[] values, String filePath) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) {
diff --git a/integration-test/src/test/java/org/apache/iotdb/ainode/it/AINodeConcurrentInferenceIT.java b/integration-test/src/test/java/org/apache/iotdb/ainode/it/AINodeConcurrentInferenceIT.java
new file mode 100644
index 00000000000..b8ebfa9600b
--- /dev/null
+++ b/integration-test/src/test/java/org/apache/iotdb/ainode/it/AINodeConcurrentInferenceIT.java
@@ -0,0 +1,141 @@
+/*
+ * 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.ainode.it;
+
+import org.apache.iotdb.it.env.EnvFactory;
+import org.apache.iotdb.itbase.env.BaseEnv;
+
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+import static org.apache.iotdb.ainode.utils.AINodeTestUtils.concurrentInference;
+
+public class AINodeConcurrentInferenceIT {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(AINodeConcurrentInferenceIT.class);
+
+ @BeforeClass
+ public static void setUp() throws Exception {
+ // Init 1C1D1A cluster environment
+ EnvFactory.getEnv().initClusterEnvironment(1, 1);
+ prepareDataForTreeModel();
+ prepareDataForTableModel();
+ }
+
+ @AfterClass
+ public static void tearDown() throws Exception {
+ EnvFactory.getEnv().cleanClusterEnvironment();
+ }
+
+ private static void prepareDataForTreeModel() throws SQLException {
+ try (Connection connection = EnvFactory.getEnv().getConnection(BaseEnv.TREE_SQL_DIALECT);
+ Statement statement = connection.createStatement()) {
+ statement.execute("CREATE DATABASE root.AI");
+ statement.execute("CREATE TIMESERIES root.AI.s WITH DATATYPE=DOUBLE, ENCODING=RLE");
+ for (int i = 0; i < 2880; i++) {
+ statement.execute(
+ String.format(
+ "INSERT INTO root.AI(timestamp, s) VALUES(%d, %f)",
+ i, Math.sin(i * Math.PI / 1440)));
+ }
+ }
+ }
+
+ private static void prepareDataForTableModel() throws SQLException {
+ try (Connection connection = EnvFactory.getEnv().getConnection(BaseEnv.TABLE_SQL_DIALECT);
+ Statement statement = connection.createStatement()) {
+ statement.execute("CREATE DATABASE root");
+ statement.execute("CREATE TABLE root.AI (s DOUBLE FIELD)");
+ for (int i = 0; i < 2880; i++) {
+ statement.execute(
+ String.format(
+ "INSERT INTO root.AI(timestamp, s) VALUES(%d, %f)",
+ i, Math.sin(i * Math.PI / 1440)));
+ }
+ }
+ }
+
+ @Test
+ public void concurrentCPUCallInferenceTest() throws SQLException, InterruptedException {
+ try (Connection connection = EnvFactory.getEnv().getConnection(BaseEnv.TREE_SQL_DIALECT);
+ Statement statement = connection.createStatement()) {
+ statement.execute("LOAD MODEL sundial TO DEVICES \"cpu\"");
+ concurrentInference(statement, "CALL INFERENCE(sundial, \"SELECT s FROM root.AI\")", 4, 10);
+ }
+ }
+
+ @Test
+ public void concurrentGPUCallInferenceTest() throws SQLException, InterruptedException {
+ try (Connection connection = EnvFactory.getEnv().getConnection(BaseEnv.TREE_SQL_DIALECT);
+ Statement statement = connection.createStatement()) {
+ statement.execute("LOAD MODEL sundial TO DEVICES \"0,1\"");
+ concurrentInference(statement, "CALL INFERENCE(sundial, \"SELECT s FROM root.AI\")", 10, 100);
+ }
+ }
+
+ @Test
+ public void concurrentCPUForecastTest() throws SQLException, InterruptedException {
+ try (Connection connection = EnvFactory.getEnv().getConnection(BaseEnv.TREE_SQL_DIALECT);
+ Statement statement = connection.createStatement()) {
+ final int threadCnt = 4;
+ final int loop = 10;
+ statement.execute("LOAD MODEL sundial TO DEVICES \"cpu\"");
+ long startTime = System.currentTimeMillis();
+ concurrentInference(
+ statement,
+ "SELECT * FROM FORECAST(model_id=>'sundial', input=>(SELECT time,s FROM root.AI) ORDER BY time)",
+ threadCnt,
+ loop);
+ long endTime = System.currentTimeMillis();
+ LOGGER.info(
+ String.format(
+ "Timer-Sundial concurrent inference %d reqs (%d threads, %d loops) in CPU takes time: %dms",
+ threadCnt * loop, threadCnt, loop, endTime - startTime));
+ }
+ }
+
+ @Test
+ public void concurrentGPUForecastTest() throws SQLException, InterruptedException {
+ try (Connection connection = EnvFactory.getEnv().getConnection(BaseEnv.TREE_SQL_DIALECT);
+ Statement statement = connection.createStatement()) {
+ final int threadCnt = 10;
+ final int loop = 100;
+ statement.execute("LOAD MODEL sundial TO DEVICES \"0,1\"");
+ long startTime = System.currentTimeMillis();
+ concurrentInference(
+ statement,
+ "SELECT * FROM FORECAST(model_id=>'sundial', input=>(SELECT time,s FROM root.AI) ORDER BY time)",
+ threadCnt,
+ loop);
+ long endTime = System.currentTimeMillis();
+ LOGGER.info(
+ String.format(
+ "Timer-Sundial concurrent inference %d reqs (%d threads, %d loops) in GPU takes time: %dms",
+ threadCnt * loop, threadCnt, loop, endTime - startTime));
+ }
+ }
+}
diff --git a/integration-test/src/test/java/org/apache/iotdb/ainode/it/AINodeInstanceManagementIT.java b/integration-test/src/test/java/org/apache/iotdb/ainode/it/AINodeInstanceManagementIT.java
new file mode 100644
index 00000000000..93351c01785
--- /dev/null
+++ b/integration-test/src/test/java/org/apache/iotdb/ainode/it/AINodeInstanceManagementIT.java
@@ -0,0 +1,212 @@
+/*
+ * 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.ainode.it;
+
+import org.apache.iotdb.it.env.EnvFactory;
+import org.apache.iotdb.itbase.env.BaseEnv;
+
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.iotdb.ainode.utils.AINodeTestUtils.checkHeader;
+import static org.apache.iotdb.ainode.utils.AINodeTestUtils.errorTest;
+
+public class AINodeInstanceManagementIT {
+
+ private static final int WAITING_TIME_SEC = 30;
+ private static final Set<String> TARGET_DEVICES = new HashSet<>(Arrays.asList("cpu", "0", "1"));
+
+ @BeforeClass
+ public static void setUp() throws Exception {
+ // Init 1C1D1A cluster environment
+ EnvFactory.getEnv().initClusterEnvironment(1, 1);
+ }
+
+ @AfterClass
+ public static void tearDown() throws Exception {
+ EnvFactory.getEnv().cleanClusterEnvironment();
+ }
+
+ @Test
+ public void basicManagementTestInTreeModel() throws SQLException, InterruptedException {
+ try (Connection connection = EnvFactory.getEnv().getConnection(BaseEnv.TREE_SQL_DIALECT);
+ Statement statement = connection.createStatement()) {
+ basicManagementTest(statement);
+ }
+ }
+
+ @Test
+ public void basicManagementTestInTableModel() throws SQLException, InterruptedException {
+ try (Connection connection = EnvFactory.getEnv().getConnection(BaseEnv.TABLE_SQL_DIALECT);
+ Statement statement = connection.createStatement()) {
+ basicManagementTest(statement);
+ }
+ }
+
+ private void basicManagementTest(Statement statement) throws SQLException, InterruptedException {
+ // Ensure resources
+ try (ResultSet resultSet = statement.executeQuery("SHOW AI_DEVICES")) {
+ ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
+ checkHeader(resultSetMetaData, "DeviceID");
+ final Set<String> resultDevices = new HashSet<>();
+ while (resultSet.next()) {
+ resultDevices.add(resultSet.getString("DeviceID"));
+ }
+ Assert.assertEquals(TARGET_DEVICES, resultDevices);
+ }
+
+ // Load sundial to each device
+ statement.execute("LOAD MODEL sundial TO DEVICES \"cpu,0,1\"");
+ TimeUnit.SECONDS.sleep(WAITING_TIME_SEC);
+ try (ResultSet resultSet = statement.executeQuery("SHOW LOADED MODELS 0")) {
+ ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
+ checkHeader(resultSetMetaData, "DeviceID,ModelType,Count(instances)");
+ while (resultSet.next()) {
+ Assert.assertEquals("0", resultSet.getString("DeviceID"));
+ Assert.assertEquals("Timer-Sundial", resultSet.getString("ModelType"));
+ Assert.assertTrue(resultSet.getInt("Count(instances)") > 1);
+ }
+ }
+ try (ResultSet resultSet = statement.executeQuery("SHOW LOADED MODELS")) {
+ ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
+ checkHeader(resultSetMetaData, "DeviceID,ModelType,Count(instances)");
+ final Set<String> resultDevices = new HashSet<>();
+ while (resultSet.next()) {
+ resultDevices.add(resultSet.getString("DeviceID"));
+ }
+ Assert.assertEquals(TARGET_DEVICES, resultDevices);
+ }
+
+ // Load timer_xl to each device
+ statement.execute("LOAD MODEL timer_xl TO DEVICES \"cpu,0,1\"");
+ TimeUnit.SECONDS.sleep(WAITING_TIME_SEC);
+ try (ResultSet resultSet = statement.executeQuery("SHOW LOADED MODELS")) {
+ ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
+ checkHeader(resultSetMetaData, "DeviceID,ModelType,Count(instances)");
+ final Set<String> resultDevices = new HashSet<>();
+ while (resultSet.next()) {
+ if (resultSet.getString("ModelType").equals("Timer-XL")) {
+ resultDevices.add(resultSet.getString("DeviceID"));
+ }
+ Assert.assertTrue(resultSet.getInt("Count(instances)") > 1);
+ }
+ Assert.assertEquals(TARGET_DEVICES, resultDevices);
+ }
+
+ // Clean every device
+ statement.execute("UNLOAD MODEL sundial FROM DEVICES \"cpu,0,1\"");
+ statement.execute("UNLOAD MODEL timer_xl FROM DEVICES \"cpu,0,1\"");
+ TimeUnit.SECONDS.sleep(WAITING_TIME_SEC);
+ try (ResultSet resultSet = statement.executeQuery("SHOW LOADED MODELS")) {
+ ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
+ checkHeader(resultSetMetaData, "DeviceID,ModelType,Count(instances)");
+ Assert.assertFalse(resultSet.next());
+ }
+ }
+
+ private static final int LOOP_CNT = 10;
+
+ @Test
+ public void repeatLoadAndUnloadTest() throws SQLException, InterruptedException {
+ try (Connection connection = EnvFactory.getEnv().getConnection(BaseEnv.TREE_SQL_DIALECT);
+ Statement statement = connection.createStatement()) {
+ for (int i = 0; i < LOOP_CNT; i++) {
+ statement.execute("LOAD MODEL sundial TO DEVICES \"cpu,0,1\"");
+ TimeUnit.SECONDS.sleep(WAITING_TIME_SEC);
+ try (ResultSet resultSet = statement.executeQuery("SHOW LOADED MODELS")) {
+ ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
+ checkHeader(resultSetMetaData, "DeviceID,ModelType,Count(instances)");
+ final Set<String> resultDevices = new HashSet<>();
+ while (resultSet.next()) {
+ resultDevices.add(resultSet.getString("DeviceID"));
+ }
+ Assert.assertEquals(TARGET_DEVICES, resultDevices);
+ }
+ statement.execute("UNLOAD MODEL sundial FROM DEVICES \"cpu,0,1\"");
+ TimeUnit.SECONDS.sleep(WAITING_TIME_SEC);
+ try (ResultSet resultSet = statement.executeQuery("SHOW LOADED MODELS")) {
+ ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
+ checkHeader(resultSetMetaData, "DeviceID,ModelType,Count(instances)");
+ Assert.assertFalse(resultSet.next());
+ }
+ }
+ }
+ }
+
+ @Test
+ public void concurrentLoadAndUnloadTest() throws SQLException, InterruptedException {
+ try (Connection connection = EnvFactory.getEnv().getConnection(BaseEnv.TABLE_SQL_DIALECT);
+ Statement statement = connection.createStatement()) {
+ for (int i = 0; i < LOOP_CNT; i++) {
+ statement.execute("LOAD MODEL sundial TO DEVICES \"cpu,0,1\"");
+ statement.execute("UNLOAD MODEL sundial FROM DEVICES \"cpu,0,1\"");
+ }
+ TimeUnit.SECONDS.sleep(WAITING_TIME_SEC * LOOP_CNT);
+ try (ResultSet resultSet = statement.executeQuery("SHOW LOADED MODELS")) {
+ ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
+ checkHeader(resultSetMetaData, "DeviceID,ModelType,Count(instances)");
+ Assert.assertFalse(resultSet.next());
+ }
+ }
+ }
+
+ @Test
+ public void failTestInTreeModel() throws SQLException {
+ try (Connection connection = EnvFactory.getEnv().getConnection(BaseEnv.TREE_SQL_DIALECT);
+ Statement statement = connection.createStatement()) {
+ failTest(statement);
+ }
+ }
+
+ @Test
+ public void failTestInTableModel() throws SQLException {
+ try (Connection connection = EnvFactory.getEnv().getConnection(BaseEnv.TABLE_SQL_DIALECT);
+ Statement statement = connection.createStatement()) {
+ failTest(statement);
+ }
+ }
+
+ private void failTest(Statement statement) {
+ errorTest(
+ statement,
+ "LOAD MODEL unknown TO DEVICES \"cpu,0,1\"",
+ "1505: Cannot load model [unknown], because it is neither a built-in nor a fine-tuned model. You can use 'SHOW MODELS' to retrieve the available models.");
+ errorTest(
+ statement,
+ "LOAD MODEL sundial TO DEVICES \"unknown\"",
+ "1507: Device ID [unknown] is not available. You can use 'SHOW AI_DEVICES' to retrieve the available devices.");
+ errorTest(
+ statement,
+ "UNLOAD MODEL sundial FROM DEVICES \"unknown\"",
+ "1507: Device ID [unknown] is not available. You can use 'SHOW AI_DEVICES' to retrieve the available devices.");
+ }
+}
diff --git a/integration-test/src/test/java/org/apache/iotdb/ainode/utils/AINodeTestUtils.java b/integration-test/src/test/java/org/apache/iotdb/ainode/utils/AINodeTestUtils.java
index d3f36e38efe..31e498ae729 100644
--- a/integration-test/src/test/java/org/apache/iotdb/ainode/utils/AINodeTestUtils.java
+++ b/integration-test/src/test/java/org/apache/iotdb/ainode/utils/AINodeTestUtils.java
@@ -25,6 +25,7 @@ import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Objects;
+import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
@@ -59,6 +60,37 @@ public class AINodeTestUtils {
}
}
+ public static void concurrentInference(Statement statement, String sql, int threadCnt, int loop)
+ throws InterruptedException {
+ Thread[] threads = new Thread[threadCnt];
+ for (int i = 0; i < threadCnt; i++) {
+ threads[i] =
+ new Thread(
+ () -> {
+ try {
+ for (int j = 0; j < loop; j++) {
+ try (ResultSet resultSet = statement.executeQuery(sql)) {
+ while (resultSet.next()) {
+ // do nothing
+ }
+ } catch (SQLException e) {
+ fail(e.getMessage());
+ }
+ }
+ } catch (Exception e) {
+ fail(e.getMessage());
+ }
+ });
+ threads[i].start();
+ }
+ for (Thread thread : threads) {
+ thread.join(TimeUnit.MINUTES.toMillis(10));
+ if (thread.isAlive()) {
+ fail("Thread timeout after 10 minutes");
+ }
+ }
+ }
+
public static class FakeModelInfo {
private final String modelId;
diff --git a/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/TSStatusCode.java b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/TSStatusCode.java
index c9828eb4109..98f05176068 100644
--- a/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/TSStatusCode.java
+++ b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/TSStatusCode.java
@@ -250,6 +250,7 @@ public enum TSStatusCode {
NO_REGISTERED_AI_NODE_ERROR(1504),
MODEL_NOT_FOUND_ERROR(1505),
REGISTER_AI_NODE_ERROR(1506),
+ UNAVAILABLE_AI_DEVICE_ERROR(1507),
AI_NODE_INTERNAL_ERROR(1510),
REMOVE_AI_NODE_ERROR(1511),
diff --git a/iotdb-core/ainode/iotdb/ainode/core/ai_node.py b/iotdb-core/ainode/iotdb/ainode/core/ai_node.py
index 4fe2a9b97dc..b323818c155 100644
--- a/iotdb-core/ainode/iotdb/ainode/core/ai_node.py
+++ b/iotdb-core/ainode/iotdb/ainode/core/ai_node.py
@@ -147,6 +147,8 @@ class AINode:
self._stop_event = threading.Event()
signal.signal(signal.SIGTERM, self._handle_signal)
+ self._rpc_service.join()
+
def _handle_signal(self, signum, frame):
signal_name = {signal.SIGTERM: "SIGTERM", signal.SIGINT: "SIGINT"}.get(
signum, f"SIGNAL {signum}"
diff --git a/iotdb-core/ainode/iotdb/ainode/core/constant.py b/iotdb-core/ainode/iotdb/ainode/core/constant.py
index 954380b225f..c351d74db02 100644
--- a/iotdb-core/ainode/iotdb/ainode/core/constant.py
+++ b/iotdb-core/ainode/iotdb/ainode/core/constant.py
@@ -35,11 +35,11 @@ AINODE_SYSTEM_FILE_NAME = "system.properties"
# AINode cluster configuration
AINODE_CLUSTER_NAME = "defaultCluster"
-AINODE_TARGET_CONFIG_NODE_LIST = TEndPoint("127.0.0.1", 10710)
+AINODE_TARGET_CONFIG_NODE_LIST = TEndPoint("127.0.0.1", 10910)
AINODE_RPC_ADDRESS = "127.0.0.1"
-AINODE_RPC_PORT = 10810
+AINODE_RPC_PORT = 20810
AINODE_CLUSTER_INGRESS_ADDRESS = "127.0.0.1"
-AINODE_CLUSTER_INGRESS_PORT = 6667
+AINODE_CLUSTER_INGRESS_PORT = 9667
AINODE_CLUSTER_INGRESS_USERNAME = "root"
AINODE_CLUSTER_INGRESS_PASSWORD = "root"
AINODE_CLUSTER_INGRESS_TIME_ZONE = "UTC+8"
@@ -90,6 +90,9 @@ DEFAULT_CHUNK_SIZE = 8192
class TSStatusCode(Enum):
SUCCESS_STATUS = 200
REDIRECTION_RECOMMEND = 400
+ MODEL_EXIST_ERROR = 1502
+ MODEL_NOT_FOUND_ERROR = 1505
+ UNAVAILABLE_AI_DEVICE_ERROR = 1507
AINODE_INTERNAL_ERROR = 1510
INVALID_URI_ERROR = 1511
INVALID_INFERENCE_CONFIG = 1512
diff --git a/iotdb-core/ainode/iotdb/ainode/core/exception.py b/iotdb-core/ainode/iotdb/ainode/core/exception.py
index 4e09f053b8e..f00900e8d01 100644
--- a/iotdb-core/ainode/iotdb/ainode/core/exception.py
+++ b/iotdb-core/ainode/iotdb/ainode/core/exception.py
@@ -36,8 +36,8 @@ class BadNodeUrlError(_BaseError):
class ModelNotExistError(_BaseError):
- def __init__(self, file_path: str):
- self.message = "Model path is not exists: {} ".format(file_path)
+ def __init__(self, msg: str):
+ self.message = "Model is not exists: {} ".format(msg)
class BadConfigValueError(_BaseError):
diff --git a/iotdb-core/ainode/iotdb/ainode/core/inference/pool_controller.py b/iotdb-core/ainode/iotdb/ainode/core/inference/pool_controller.py
new file mode 100644
index 00000000000..ce04120474e
--- /dev/null
+++ b/iotdb-core/ainode/iotdb/ainode/core/inference/pool_controller.py
@@ -0,0 +1,509 @@
+# 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.
+#
+import concurrent
+import queue
+import random
+import threading
+from concurrent.futures import wait
+from typing import Dict, Optional
+
+import torch
+import torch.multiprocessing as mp
+
+from iotdb.ainode.core.exception import InferenceModelInternalError
+from iotdb.ainode.core.inference.inference_request import (
+ InferenceRequest,
+ InferenceRequestProxy,
+)
+from iotdb.ainode.core.inference.inference_request_pool import (
+ InferenceRequestPool,
+ PoolState,
+)
+from iotdb.ainode.core.inference.pool_group import PoolGroup
+from iotdb.ainode.core.inference.pool_scheduler.basic_pool_scheduler import (
+ BasicPoolScheduler,
+ ScaleActionType,
+)
+from iotdb.ainode.core.log import Logger
+from iotdb.ainode.core.model.sundial.configuration_sundial import SundialConfig
+from iotdb.ainode.core.model.timerxl.configuration_timer import TimerConfig
+from iotdb.ainode.core.util.atmoic_int import AtomicInt
+from iotdb.ainode.core.util.batch_executor import BatchExecutor
+from iotdb.ainode.core.util.decorator import synchronized
+from iotdb.ainode.core.util.thread_name import ThreadName
+
+logger = Logger()
+
+
+class PoolController:
+ """
+ A controller for handling inference request pools.
+ """
+
+ def __init__(self, result_queue: mp.Queue):
+ # structure: {model_id: {device_id: PoolGroup}}
+ self._request_pool_map: Dict[str, Dict[str, PoolGroup]] = {}
+ self._new_pool_id = AtomicInt()
+ self._result_queue = result_queue
+ self._pool_scheduler = BasicPoolScheduler(self._request_pool_map)
+ self._stop_event = threading.Event()
+
+ # for pool instances control
+ self._task_queue = queue.Queue()
+ self._pool_control_worker_thread = threading.Thread(
+ target=self._worker_loop, daemon=True
+ )
+ self._pool_control_worker_thread.start()
+ self._executor = BatchExecutor(
+ thread_name_prefix=ThreadName.INFERENCE_POOL_CONTROLLER.value
+ )
+
+ # =============== Pool Management ===============
+ @synchronized(threading.Lock())
+ def first_req_init(self, model_id: str):
+ """
+ Initialize the pools when the first request for the given model_id arrives.
+ """
+ if not self.has_request_pools(model_id, device.index):
+ # TODO: choose a device based on some strategy
+ device = self.DEFAULT_DEVICE
+ actions = self._pool_scheduler.schedule(model_id, device)
+ for action in actions:
+ if action.action == ScaleActionType.SCALE_UP:
+ # initialize the first pool
+ self._first_pool_init(action.model_id, str(device))
+ # start a background thread to expand pools
+ expand_thread = threading.Thread(
+ target=self._expand_pools_on_device,
+ args=(action.model_id, str(device), action.amount - 1),
+ daemon=True,
+ )
+ expand_thread.start()
+ elif action.action == ScaleActionType.SCALE_DOWN:
+ # TODO: implement scale down logic
+ pass
+
+ def _first_pool_init(self, model_id: str, device_str: str):
+ """
+ Initialize the first pool for the given model_id.
+ Ensure the pool is ready before returning.
+ """
+ device = torch.device(device_str)
+ device_id = device.index
+
+ if model_id == "sundial":
+ config = SundialConfig()
+ elif model_id == "timer_xl":
+ config = TimerConfig()
+ first_queue = mp.Queue()
+ ready_event = mp.Event()
+ first_pool = InferenceRequestPool(
+ pool_id=0,
+ model_id=model_id,
+ device=device_str,
+ config=config,
+ request_queue=first_queue,
+ result_queue=self._result_queue,
+ ready_event=ready_event,
+ )
+ first_pool.start()
+ self._register_pool(model_id, device_str, 0, first_pool, first_queue)
+
+ if not ready_event.wait(timeout=30):
+ self._erase_pool(model_id, device_id, 0)
+ logger.error(
+ f"[Inference][Device-{device}][Pool-0] Pool failed to be ready in time"
+ )
+ else:
+ self.set_state(model_id, device_id, 0, PoolState.RUNNING)
+ logger.info(
+ f"[Inference][Device-{device}][Pool-0] Pool started running for model {model_id}"
+ )
+
+ def load_model(self, model_id: str, device_id_list: list[str]):
+ """
+ Load the model to the specified devices asynchronously.
+ Args:
+ model_id (str): The ID of the model to be loaded.
+ device_id_list (list[str]): List of device_ids where the model should be loaded.
+ """
+ self._task_queue.put((self._load_model_task, (model_id, device_id_list), {}))
+
+ def unload_model(self, model_id: str, device_id_list: list[str]):
+ """
+ Unload the model from the specified devices asynchronously.
+ Args:
+ model_id (str): The ID of the model to be unloaded.
+ device_id_list (list[str]): List of device_ids where the model should be unloaded.
+ """
+ self._task_queue.put((self._unload_model_task, (model_id, device_id_list), {}))
+
+ def show_loaded_models(
+ self, device_id_list: list[str]
+ ) -> Dict[str, Dict[str, int]]:
+ """
+ Show loaded model instances on the specified devices.
+ Args:
+ device_id_list (list[str]): List of device_ids where to examine loaded instances.
+ Return:
+ Dict[str, Dict[str, int]]: Dict[device_id, Dict[model_id, Count(instances)]].
+ """
+ result = {}
+ for device_id in device_id_list:
+ device_models = {}
+ for model_id, device_map in self._request_pool_map.items():
+ if device_id in device_map:
+ pool_group = device_map[device_id]
+ device_models[model_id] = pool_group.get_pool_count()
+ result[device_id] = device_models
+ return result
+
+ def _worker_loop(self):
+ while not self._stop_event.is_set():
+ task = self._task_queue.get()
+ if task is None:
+ self._task_queue.task_done()
+ break
+ task_fn, args, kwargs = task
+ try:
+ task_fn(*args, **kwargs)
+ except Exception as e:
+ logger.error(f"Error executing task: {e}")
+ finally:
+ self._task_queue.task_done()
+
+ def _load_model_task(self, model_id: str, device_id_list: list[str]):
+ def _load_model_on_device_task(device_id: str):
+ if not self.has_request_pools(model_id, device_id):
+ actions = self._pool_scheduler.schedule_load_model_to_device(
+ model_id, device_id
+ )
+ for action in actions:
+ if action.action == ScaleActionType.SCALE_UP:
+ self._expand_pools_on_device(
+ action.model_id, device_id, action.amount
+ )
+ elif action.action == ScaleActionType.SCALE_DOWN:
+ self._shrink_pools_on_device(
+ action.model_id, device_id, action.amount
+ )
+ else:
+ logger.info(
+ f"[Inference][Device-{device_id}] Model {model_id} is already installed."
+ )
+
+ load_model_futures = self._executor.submit_batch(
+ device_id_list, _load_model_on_device_task
+ )
+ concurrent.futures.wait(
+ load_model_futures, return_when=concurrent.futures.ALL_COMPLETED
+ )
+
+ def _unload_model_task(self, model_id: str, device_id_list: list[str]):
+ def _unload_model_on_device_task(device_id: str):
+ if self.has_request_pools(model_id, device_id):
+ actions = self._pool_scheduler.schedule_unload_model_from_device(
+ model_id, device_id
+ )
+ for action in actions:
+ if action.action == ScaleActionType.SCALE_DOWN:
+ self._shrink_pools_on_device(
+ action.model_id, device_id, action.amount
+ )
+ elif action.action == ScaleActionType.SCALE_UP:
+ self._expand_pools_on_device(
+ action.model_id, device_id, action.amount
+ )
+ else:
+ logger.info(
+ f"[Inference][Device-{device_id}] Model {model_id} is not installed."
+ )
+
+ unload_model_futures = self._executor.submit_batch(
+ device_id_list, _unload_model_on_device_task
+ )
+ concurrent.futures.wait(
+ unload_model_futures, return_when=concurrent.futures.ALL_COMPLETED
+ )
+
+ def _expand_pools_on_device(self, model_id: str, device_id: str, count: int):
+ """
+ Expand the pools for the given model_id and device_id sequentially.
+ Args:
+ model_id (str): The ID of the model.
+ device_id (str): The ID of the device.
+ count (int): The number of pools to be expanded.
+ """
+
+ def _expand_pool_on_device(*_):
+ result_queue = mp.Queue()
+ pool_id = self._new_pool_id.get_and_increment()
+ if model_id == "sundial":
+ config = SundialConfig()
+ elif model_id == "timer_xl":
+ config = TimerConfig()
+ pool = InferenceRequestPool(
+ pool_id=pool_id,
+ model_id=model_id,
+ device=device_id,
+ config=config,
+ request_queue=result_queue,
+ result_queue=self._result_queue,
+ ready_event=mp.Event(),
+ )
+ pool.start()
+ self._register_pool(model_id, device_id, pool_id, pool, result_queue)
+ if not pool.ready_event.wait(timeout=30):
+ logger.error(
+ f"[Inference][Device-{device_id}][Pool-{pool_id}] Pool failed to be ready in time"
+ )
+ # TODO: retry or decrease the count? this error should be better handled
+ self._erase_pool(model_id, device_id, pool_id)
+ else:
+ self.set_state(model_id, device_id, pool_id, PoolState.RUNNING)
+ logger.info(
+ f"[Inference][Device-{device_id}][Pool-{pool_id}] Pool started running for model {model_id}"
+ )
+
+ expand_pool_futures = self._executor.submit_batch(
+ [None for _ in range(count)], _expand_pool_on_device
+ )
+ concurrent.futures.wait(
+ expand_pool_futures, return_when=concurrent.futures.ALL_COMPLETED
+ )
+
+ def _shrink_pools_on_device(self, model_id: str, device_id: str, count):
+ """
+ Shrink the pools for the given model_id by count sequentially.
+ TODO: shrink pools in parallel
+ """
+
+ pool_ids = self.get_pool_ids(model_id, device_id)
+ current_count = len(pool_ids)
+ if current_count < count:
+ logger.warning(
+ f"[Inference] Cannot shrink {count} pools for model {model_id}, only {current_count} pools available."
+ )
+
+ # 1. Find pools with zero load and set them to STOP
+ zero_load_pools = [
+ pid for pid in pool_ids if self.get_load(model_id, device_id, pid) == 0
+ ]
+ stop_count = min(len(zero_load_pools), count)
+ pools_to_stop = zero_load_pools[:stop_count]
+
+ for pid in pools_to_stop:
+ self.set_state(
+ model_id, device_id, pid, PoolState.STOPPING
+ ) # Set to STOPPING state
+
+ remaining_to_close = count - len(pools_to_stop)
+ if remaining_to_close <= 0:
+ # close the STOP pools whose load is 0
+ for pid in pools_to_stop:
+ self.get_request_pool(model_id, device_id, pid).stop()
+ self._erase_pool(model_id, device_id, pid)
+ return
+
+ # 2. If not enough, randomly select additional pools to set to STOP
+ candidates = [pid for pid in pool_ids if pid not in pools_to_stop]
+ additional_stop = random.sample(
+ candidates, min(remaining_to_close, len(candidates))
+ ) # TODO: implement better selection strategy
+ for pid in additional_stop:
+ self.set_state(
+ model_id, device_id, pid, PoolState.STOPPING
+ ) # Set to STOPPING state
+
+ # 3. Wait for all STOPPING pools to have zero load, then close them
+ final_stop_pools = pools_to_stop + additional_stop
+ while final_stop_pools and not self._stop_event.is_set():
+ for pid in final_stop_pools[:]: # iterate over a copy of the list
+ if self.get_load(model_id, device_id, pid) == 0:
+ self.get_request_pool(model_id, device_id, pid).stop()
+ self._erase_pool(model_id, device_id, pid)
+ final_stop_pools.remove(pid)
+
+ def _register_pool(
+ self,
+ model_id: str,
+ device_id: str,
+ pool_id: int,
+ request_pool: InferenceRequestPool,
+ request_queue: mp.Queue,
+ ):
+ """
+ Register a new inference request pool for the given model_id, device and pool_id.
+ """
+ self.set_request_pool_map(
+ model_id, device_id, pool_id, request_pool, request_queue
+ )
+ pool_group: PoolGroup = self.get_request_pools_group(model_id, device_id)
+ pool_group.set_state(pool_id, PoolState.INITIALIZING)
+ logger.info(
+ f"[Inference][Device-{device_id}][Pool-{pool_id}] Pool initializing for model {model_id}"
+ )
+
+ def _erase_pool(self, model_id: str, device_id: str, pool_id: int):
+ """
+ Erase the specified inference request pool for the given model_id, device_id and pool_id.
+ """
+ pool_group = self.get_request_pools_group(model_id, device_id)
+ if pool_group:
+ pool_group.remove_pool(pool_id)
+ logger.info(
+ f"[Inference][Device-{device_id}][Pool-{pool_id}] Erase pool for model {model_id}"
+ )
+ # Clean up empty structures
+ if pool_group and not pool_group.get_pool_ids():
+ self._request_pool_map[model_id].pop(device_id, None)
+ if model_id in self._request_pool_map and not self._request_pool_map[model_id]:
+ self._request_pool_map.pop(model_id, None)
+
+ # =============== Request Management ===============
+ def add_request(self, req: InferenceRequest, infer_proxy: InferenceRequestProxy):
+ model_id = req.model_id
+ if not self.has_request_pools(model_id):
+ logger.error(f"[Inference] No pools found for model {model_id}.")
+ infer_proxy.set_result(None)
+ raise InferenceModelInternalError(
+ "Dispatch request failed, because no inference pools are init."
+ )
+ # TODO: Implement adaptive scaling based on requests.(e.g. lazy initialization)
+ # self.first_req_init(model_id)
+
+ device_ids = self.get_device_ids(model_id)
+ device_id = random.choice(
+ device_ids
+ ) # TODO: Implement better device selection strategy
+ self._request_pool_map[model_id][device_id].dispatch_request(req, infer_proxy)
+
+ # =============== Getters / Setters ===============
+ def get_state(self, model_id, device_id, pool_id) -> Optional[PoolState]:
+ """
+ Get the state of the specified pool based on model_id, device_id, and pool_id.
+ """
+ pool_group = self.get_request_pools_group(model_id, device_id)
+ if pool_group:
+ return pool_group.get_state(pool_id)
+ return None
+
+ def set_state(self, model_id, device_id, pool_id, state):
+ """
+ Set the state of the specified pool based on model_id, device_id, and pool_id.
+ """
+ pool_group = self.get_request_pools_group(model_id, device_id)
+ if pool_group:
+ pool_group.set_state(pool_id, state)
+
+ def get_device_ids(self, model_id) -> list[str]:
+ """
+ Get the list of device IDs for the given model_id, where the corresponding instances are loaded.
+ """
+ if model_id in self._request_pool_map:
+ return list(self._request_pool_map[model_id].keys())
+ return []
+
+ def get_pool_ids(self, model_id: str, device_id: str) -> list[int]:
+ """
+ Get the list of pool IDs for the given model_id and device_id.
+ """
+ pool_group = self.get_request_pools_group(model_id, device_id)
+ if pool_group:
+ return pool_group.get_pool_ids()
+ return []
+
+ def has_request_pools(self, model_id: str, device_id: Optional[str] = None) -> bool:
+ """
+ Check if there are request pools for the given model_id and device_id (optional).
+ """
+ if model_id not in self._request_pool_map:
+ return False
+ if device_id is not None:
+ return device_id in self._request_pool_map[model_id]
+ return True
+
+ def get_request_pools_group(
+ self, model_id: str, device_id: str
+ ) -> Optional[PoolGroup]:
+ if (
+ model_id in self._request_pool_map
+ and device_id in self._request_pool_map[model_id]
+ ):
+ return self._request_pool_map[model_id][device_id]
+ else:
+ return None
+
+ def get_request_pool(
+ self, model_id, device_id, pool_id
+ ) -> Optional[InferenceRequestPool]:
+ pool_group = self.get_request_pools_group(model_id, device_id)
+ if pool_group:
+ return pool_group.get_request_pool(pool_id)
+ return None
+
+ def get_request_queue(self, model_id, device_id, pool_id) -> Optional[mp.Queue]:
+ pool_group = self.get_request_pools_group(model_id, device_id)
+ if pool_group:
+ return pool_group.get_request_queue(pool_id)
+ return None
+
+ def set_request_pool_map(
+ self,
+ model_id: str,
+ device_id: str,
+ pool_id: int,
+ request_pool: InferenceRequestPool,
+ request_queue: mp.Queue,
+ ):
+ """
+ Set the request pool map for the given model_id, device and pool_id.
+ """
+ if model_id not in self._request_pool_map:
+ self._request_pool_map[model_id] = {}
+ if device_id not in self._request_pool_map[model_id]:
+ self._request_pool_map[model_id][device_id] = PoolGroup(model_id)
+ self._request_pool_map[model_id][device_id].add_pool(
+ pool_id, request_pool, request_queue
+ )
+ logger.info(
+ f"[Inference][Device-{device_id}][Pool-{pool_id}] Registered pool for model {model_id}"
+ )
+
+ def get_load(self, model_id, device_id, pool_id) -> int:
+ """
+ Get the current load of the specified pool.
+ """
+ pool_group = self.get_request_pools_group(model_id, device_id)
+ if pool_group:
+ return pool_group.get_load(pool_id)
+ return -1
+
+ def shutdown(self):
+ self._stop_event.set()
+
+ # shutdown pool controller
+ self._task_queue.put(None)
+ self._pool_control_worker_thread.join()
+ self._executor.close()
+
+ # shutdown pool instances
+ # TODO: pool instances can be shutdown in parallel
+ for inner in self._request_pool_map.values():
+ for group in inner.values():
+ group.shutdown()
diff --git a/iotdb-core/ainode/iotdb/ainode/core/inference/pool_group.py b/iotdb-core/ainode/iotdb/ainode/core/inference/pool_group.py
new file mode 100644
index 00000000000..a7004549db0
--- /dev/null
+++ b/iotdb-core/ainode/iotdb/ainode/core/inference/pool_group.py
@@ -0,0 +1,117 @@
+# 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.
+#
+from typing import Dict, Tuple
+
+import torch.multiprocessing as mp
+
+from iotdb.ainode.core.exception import (
+ InferenceModelInternalError,
+)
+from iotdb.ainode.core.inference.dispatcher.basic_dispatcher import BasicDispatcher
+from iotdb.ainode.core.inference.inference_request import (
+ InferenceRequest,
+ InferenceRequestProxy,
+)
+from iotdb.ainode.core.inference.inference_request_pool import (
+ InferenceRequestPool,
+ PoolState,
+)
+from iotdb.ainode.core.log import Logger
+from iotdb.ainode.core.util.atmoic_int import AtomicInt
+
+logger = Logger()
+
+
+class PoolGroup:
+ """
+ A group of inference request pools for a specific model.
+ """
+
+ def __init__(self, model_id):
+ # structure: {pool_id: (InferenceRequestPool, waitingQueue)}
+ self.pool_group: Dict[int, Tuple[InferenceRequestPool, mp.Queue]] = {}
+ # structure: {pool_id: PoolState}
+ self.pool_states: Dict[int, PoolState] = {}
+ # structure: {pool_id: remaining_reqs_cnt}
+ self.pool_remaining_reqs: Dict[int, AtomicInt] = {}
+ self.model_id = model_id
+ self.request_dispatcher = BasicDispatcher(self.pool_states)
+
+ def get_pool_group(self) -> Dict[int, Tuple[InferenceRequestPool, mp.Queue]]:
+ return self.pool_group
+
+ def add_pool(
+ self, pool_id: int, request_pool: InferenceRequestPool, request_queue: mp.Queue
+ ):
+ self.pool_group[pool_id] = (request_pool, request_queue)
+ self.pool_remaining_reqs[pool_id] = AtomicInt()
+
+ def remove_pool(self, pool_id: int):
+ self.pool_group.pop(pool_id, None)
+ self.pool_states.pop(pool_id, None)
+ self.pool_remaining_reqs.pop(pool_id, None)
+
+ def get_pool_ids(self) -> list[int]:
+ return list(self.pool_group.keys())
+
+ def get_pool_count(self) -> int:
+ return len(self.pool_group)
+
+ def dispatch_request(
+ self, req: InferenceRequest, infer_proxy: InferenceRequestProxy
+ ):
+ pool_id = self.request_dispatcher.dispatch_request(req, self.get_pool_ids())
+ req_q = self.pool_group[pool_id][1]
+ self.pool_remaining_reqs[pool_id].increment_and_get()
+ infer_proxy.set_counter(self.pool_remaining_reqs[pool_id])
+ req_q.put(req)
+ logger.debug(
+ f"[Inference][Pool-{pool_id}][Req-{req.req_id}] Request is queued for inference"
+ )
+
+ def get_request_pool(self, pool_id) -> InferenceRequestPool:
+ if pool_id not in self.pool_group:
+ raise InferenceModelInternalError(
+ f"[Inference][Pool-{pool_id}] Pool not found for model {self.model_id}"
+ )
+ return self.pool_group[pool_id][0]
+
+ def get_request_queue(self, pool_id) -> mp.Queue:
+ if pool_id not in self.pool_group:
+ raise InferenceModelInternalError(
+ f"[Inference][Pool-{pool_id}] Pool not found for model {self.model_id}"
+ )
+ return self.pool_group[pool_id][1]
+
+ def get_state(self, pool_id) -> PoolState:
+ return self.pool_states[pool_id]
+
+ def set_state(self, pool_id, state):
+ self.pool_states[pool_id] = state
+
+ def get_load(self, pool_id) -> int:
+ """
+ Currently, we use the number of remaining requests in the pool as the load estimation.
+ TODO: we will implement better load estimation in the future.
+ """
+ return self.pool_remaining_reqs[pool_id].get()
+
+ def shutdown(self):
+ for pool_id, (request_pool, _) in self.pool_group.items():
+ logger.info(f"[Inference][Pool-{pool_id}] Shutting down the pool...")
+ request_pool.stop()
diff --git a/iotdb-core/ainode/iotdb/ainode/core/manager/model_manager.py b/iotdb-core/ainode/iotdb/ainode/core/manager/model_manager.py
index 818311ed57f..6917f28065e 100644
--- a/iotdb-core/ainode/iotdb/ainode/core/manager/model_manager.py
+++ b/iotdb-core/ainode/iotdb/ainode/core/manager/model_manager.py
@@ -155,3 +155,15 @@ class ModelManager:
Get the type of the model with the given model_id.
"""
return self.model_storage.get_built_in_model_type(model_id)
+
+ def is_built_in_or_fine_tuned(self, model_id: str) -> bool:
+ """
+ Check if the model_id corresponds to a built-in or fine-tuned model.
+
+ Args:
+ model_id (str): The ID of the model.
+
+ Returns:
+ bool: True if the model is built-in or fine_tuned, False otherwise.
+ """
+ return self.model_storage.is_built_in_or_fine_tuned(model_id)
diff --git a/iotdb-core/ainode/iotdb/ainode/core/model/model_storage.py b/iotdb-core/ainode/iotdb/ainode/core/model/model_storage.py
index 93f695805dd..467c99e00a9 100644
--- a/iotdb-core/ainode/iotdb/ainode/core/model/model_storage.py
+++ b/iotdb-core/ainode/iotdb/ainode/core/model/model_storage.py
@@ -281,7 +281,7 @@ class ModelStorage(object):
and self._model_info_map[model_id].category == ModelCategory.BUILT_IN
)
- def _is_built_in_or_fine_tuned(self, model_id: str) -> bool:
+ def is_built_in_or_fine_tuned(self, model_id: str) -> bool:
"""
Check if the model_id corresponds to a built-in or fine-tuned model.
@@ -306,7 +306,7 @@ class ModelStorage(object):
model: The model instance corresponding to specific model_id
"""
with self._lock_pool.get_lock(model_id).read_lock():
- if self._is_built_in_or_fine_tuned(model_id):
+ if self.is_built_in_or_fine_tuned(model_id):
model_dir = os.path.join(self._builtin_model_dir, f"{model_id}")
return fetch_built_in_model(
get_built_in_model_type(self._model_info_map[model_id].model_type),
@@ -348,7 +348,7 @@ class ModelStorage(object):
Whether saving succeeded
"""
with self._lock_pool.get_lock(model_id).write_lock():
- if self._is_built_in_or_fine_tuned(model_id):
+ if self.is_built_in_or_fine_tuned(model_id):
model_dir = os.path.join(self._builtin_model_dir, f"{model_id}")
model.save_pretrained(model_dir)
else:
diff --git a/iotdb-core/ainode/iotdb/ainode/core/util/atmoic_int.py b/iotdb-core/ainode/iotdb/ainode/core/util/atmoic_int.py
new file mode 100644
index 00000000000..8c55bd8e00c
--- /dev/null
+++ b/iotdb-core/ainode/iotdb/ainode/core/util/atmoic_int.py
@@ -0,0 +1,66 @@
+# 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.
+#
+
+import threading
+
+
+class AtomicInt:
+ def __init__(self, value=0):
+ self._value = value
+ self._lock = threading.Lock()
+
+ def get(self) -> int:
+ with self._lock:
+ return self._value
+
+ def set(self, value):
+ with self._lock:
+ self._value = value
+
+ def get_and_increment(self) -> int:
+ with self._lock:
+ old_value = self._value
+ self._value += 1
+ return old_value
+
+ def increment_and_get(self) -> int:
+ with self._lock:
+ self._value += 1
+ return self._value
+
+ def get_and_decrement(self) -> int:
+ with self._lock:
+ old_value = self._value
+ self._value -= 1
+ return old_value
+
+ def decrement_and_get(self) -> int:
+ with self._lock:
+ self._value -= 1
+ return self._value
+
+ def get_and_add(self, delta=1) -> int:
+ with self._lock:
+ old_value = self._value
+ self._value += delta
+ return old_value
+
+ def add_and_get(self, delta=1) -> int:
+ with self._lock:
+ self._value += delta
+ return self._value
diff --git a/iotdb-core/ainode/iotdb/ainode/core/util/batch_executor.py b/iotdb-core/ainode/iotdb/ainode/core/util/batch_executor.py
new file mode 100644
index 00000000000..0629c893d8c
--- /dev/null
+++ b/iotdb-core/ainode/iotdb/ainode/core/util/batch_executor.py
@@ -0,0 +1,133 @@
+# 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.
+#
+
+import atexit
+import threading
+from concurrent.futures import Future, ThreadPoolExecutor
+from typing import Any, Callable, Iterable, List, Optional
+
+from iotdb.ainode.core.log import Logger
+
+logger = Logger()
+
+
+class BatchExecutor:
+ """
+ Abstract batch concurrent executor.
+ - Default fire-and-forget: automatically logs task exceptions (ignores return values)
+ - Allows customization of completion logic by overriding callback hooks via inheritance
+ - Supports single/batch submission, explicit closure, context management, and exit-time cleanup
+ """
+
+ def __init__(
+ self,
+ max_workers: int = 8,
+ thread_name_prefix: str = "batch-exec",
+ cancel_on_close: bool = False,
+ ):
+ self._executor = ThreadPoolExecutor(
+ max_workers=max_workers, thread_name_prefix=thread_name_prefix
+ )
+ self._closing = threading.Event()
+ self._lock = threading.Lock()
+ self._cancel_on_close = cancel_on_close
+ atexit.register(self._atexit_close)
+
+ def submit(self, fn: Callable[..., Any], *args, **kwargs) -> Optional[Future]:
+ """
+ Submit a single task.
+ Default fire-and-forget: internally attaches a done callback to automatically log exceptions.
+ To take over result handling, inherit and override on_task_done().
+ """
+ if self._closing.is_set():
+ raise RuntimeError("Executor is closing; reject new submissions.")
+
+ fut = self._executor.submit(fn, *args, **kwargs)
+ self._attach_done_callback(fut, item=None)
+ self.on_task_submitted(item=None, future=fut)
+ return fut
+
+ def submit_batch(
+ self, items: Iterable[Any], fn: Callable[[Any], Any]
+ ) -> List[Future]:
+ """
+ Submit a batch of tasks. Executes fn(item) for each item.
+ """
+ if self._closing.is_set():
+ raise RuntimeError("Executor is closing; reject new submissions.")
+
+ futures: List[Future] = []
+ for item in items:
+ fut = self._executor.submit(fn, item)
+ self._attach_done_callback(fut, item=item)
+ self.on_task_submitted(item=item, future=fut)
+ futures.append(fut)
+ return futures
+
+ def close(self, wait: bool = True) -> None:
+ """
+ Close the executor:
+ - wait=True: wait for submitted tasks to complete (default; suitable for graceful shutdown)
+ - wait=False: return quickly; if cancel_on_close=True, attempts to cancel pending tasks
+ """
+ with self._lock:
+ if self._closing.is_set():
+ return
+ self._closing.set()
+ self._executor.shutdown(
+ wait=wait, cancel_futures=(self._cancel_on_close and not wait)
+ )
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc, tb):
+ # Context manager exit: close and wait for tasks to finish
+ self.close(wait=True)
+
+ def on_task_submitted(self, item: Any, future: Future) -> None:
+ # Triggered when a task is submitted. Default does nothing.
+ pass
+
+ def on_task_done(self, item: Any, future: Future) -> None:
+ """
+ Triggered when a task is done. Default logs exceptions (key for fire-and-forget).
+ To customize behavior: inherit and override this method.
+ - If you need the result (which may raise), call future.result() here.
+ """
+ try:
+ _ = future.result()
+ except Exception as e:
+ logger.error(f"Batch task failed (item={item}), because {e}")
+
+ def _attach_done_callback(self, fut: Future, item: Any) -> None:
+ def _cb(f: Future, _item=item, self_ref=self):
+ try:
+ self_ref.on_task_done(_item, f)
+ except Exception as e:
+ logger.error(
+ f"Error in on_task_done callback (item={_item}), because {e}"
+ )
+
+ fut.add_done_callback(_cb)
+
+ def _atexit_close(self) -> None:
+ try:
+ self.close(wait=False)
+ except Exception:
+ pass
diff --git a/iotdb-core/ainode/iotdb/ainode/core/util/gpu_mapping.py b/iotdb-core/ainode/iotdb/ainode/core/util/gpu_mapping.py
new file mode 100644
index 00000000000..72b056adb87
--- /dev/null
+++ b/iotdb-core/ainode/iotdb/ainode/core/util/gpu_mapping.py
@@ -0,0 +1,93 @@
+# 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.
+#
+
+import torch
+
+
+def convert_device_id_to_torch_device(device_id: str) -> torch.device:
+ """
+ Converts a device ID string to a torch.device object.
+
+ Args:
+ device_id (str): The device ID string. It can be "cpu" or a GPU index like "0", "1", etc.
+
+ Returns:
+ torch.device: The corresponding torch.device object.
+
+ Raises:
+ ValueError: If the device_id is not "cpu" or a valid integer string.
+ """
+ if device_id.lower() == "cpu":
+ return torch.device("cpu")
+ try:
+ gpu_index = int(device_id)
+ if gpu_index < 0:
+ raise ValueError
+ return torch.device(f"cuda:{gpu_index}")
+ except ValueError:
+ raise ValueError(
+ f"Invalid device_id '{device_id}'. It should be 'cpu' or a non-negative integer string."
+ )
+
+
+def get_available_gpus() -> list[int]:
+ """
+ Returns a list of available GPU indices if CUDA is available, otherwise returns an empty list.
+ """
+
+ if not torch.cuda.is_available():
+ return []
+ return list(range(torch.cuda.device_count()))
+
+
+def get_available_devices() -> list[str]:
+ """
+ Returns: a list of available device IDs as strings, including "cpu".
+ """
+ device_id_list = get_available_gpus()
+ device_id_list = [str(device_id) for device_id in device_id_list]
+ device_id_list.append("cpu")
+ return device_id_list
+
+
+def parse_devices(devices):
+ """
+ Parses the input string of GPU devices and returns a comma-separated string of valid GPU indices.
+
+ Args:
+ devices (str): A comma-separated string of GPU indices (e.g., "0,1,2").
+ Returns:
+ str: A comma-separated string of valid GPU indices corresponding to the input. All available GPUs if no input is provided.
+ Exceptions:
+ RuntimeError: If no GPUs are available.
+ ValueError: If any of the provided GPU indices are not available.
+ """
+ if devices is None or devices == "":
+ gpu_ids = get_available_gpus()
+ if not gpu_ids:
+ raise RuntimeError("No available GPU")
+ return ",".join(map(str, gpu_ids))
+ else:
+ gpu_ids = [int(gpu) for gpu in devices.split(",")]
+ available_gpus = get_available_gpus()
+ for gpu_id in gpu_ids:
+ if gpu_id not in available_gpus:
+ raise ValueError(
+ f"GPU {gpu_id} is not available, the available choices are: {available_gpus}"
+ )
+ return devices
diff --git a/iotdb-core/ainode/iotdb/ainode/core/util/thread_name.py b/iotdb-core/ainode/iotdb/ainode/core/util/thread_name.py
new file mode 100644
index 00000000000..0b26ed7b8a1
--- /dev/null
+++ b/iotdb-core/ainode/iotdb/ainode/core/util/thread_name.py
@@ -0,0 +1,22 @@
+# 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.
+#
+from enum import Enum
+
+
+class ThreadName(Enum):
+ INFERENCE_POOL_CONTROLLER = "inference-pool-controller"
diff --git a/iotdb-core/antlr/src/main/antlr4/org/apache/iotdb/db/qp/sql/IoTDBSqlParser.g4 b/iotdb-core/antlr/src/main/antlr4/org/apache/iotdb/db/qp/sql/IoTDBSqlParser.g4
index 789fac304a6..7816d9db9da 100644
--- a/iotdb-core/antlr/src/main/antlr4/org/apache/iotdb/db/qp/sql/IoTDBSqlParser.g4
+++ b/iotdb-core/antlr/src/main/antlr4/org/apache/iotdb/db/qp/sql/IoTDBSqlParser.g4
@@ -66,7 +66,8 @@ ddlStatement
| migrateRegion | reconstructRegion | extendRegion | removeRegion | removeDataNode | removeConfigNode | removeAINode
| verifyConnection
// AINode
- | showAINodes | createModel | dropModel | showModels | callInference
+ | showAINodes | createModel | dropModel | showModels | showLoadedModels | showAIDevices
+ | callInference | loadModel | unloadModel
// Quota
| setSpaceQuota | showSpaceQuota | setThrottleQuota | showThrottleQuota
// View
@@ -738,6 +739,14 @@ hparamValue
| windowFunction
;
+loadModel
+ : LOAD MODEL existingModelId=identifier TO DEVICES deviceIdList=STRING_LITERAL
+ ;
+
+unloadModel
+ : UNLOAD MODEL existingModelId=identifier FROM DEVICES deviceIdList=STRING_LITERAL
+ ;
+
// ---- Drop Model
dropModel
: DROP MODEL modelId=identifier
@@ -749,6 +758,15 @@ showModels
| SHOW MODELS modelId=identifier
;
+showLoadedModels
+ : SHOW LOADED MODELS
+ | SHOW LOADED MODELS deviceIdList=STRING_LITERAL
+ ;
+
+showAIDevices
+ : SHOW AI_DEVICES
+ ;
+
// Create Logical View
createLogicalView
: CREATE VIEW viewTargetPaths AS viewSourcePaths
diff --git a/iotdb-core/antlr/src/main/antlr4/org/apache/iotdb/db/qp/sql/SqlLexer.g4 b/iotdb-core/antlr/src/main/antlr4/org/apache/iotdb/db/qp/sql/SqlLexer.g4
index 787412e0812..72b4001390d 100644
--- a/iotdb-core/antlr/src/main/antlr4/org/apache/iotdb/db/qp/sql/SqlLexer.g4
+++ b/iotdb-core/antlr/src/main/antlr4/org/apache/iotdb/db/qp/sql/SqlLexer.g4
@@ -45,6 +45,10 @@ AFTER
: A F T E R
;
+AI_DEVICES
+ : A I '_' D E V I C E S
+ ;
+
ALIAS
: A L I A S
;
@@ -478,6 +482,10 @@ LOAD
: L O A D
;
+LOADED
+ : L O A D E D
+ ;
+
LOCAL
: L O C A L
;
diff --git a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/exception/NoAvailableAINodeException.java b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/exception/NoAvailableAINodeException.java
new file mode 100644
index 00000000000..0737b9f75ac
--- /dev/null
+++ b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/exception/NoAvailableAINodeException.java
@@ -0,0 +1,27 @@
+/*
+ * 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.confignode.exception;
+
+public class NoAvailableAINodeException extends ConfigNodeException {
+ public NoAvailableAINodeException() {
+ super(
+ "There are no available AINodes currently, please use \"show cluster\" to check the cluster status.");
+ }
+}
diff --git a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/ConfigManager.java b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/ConfigManager.java
index 20d706a1252..56d4663094e 100644
--- a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/ConfigManager.java
+++ b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/ConfigManager.java
@@ -210,6 +210,7 @@ import org.apache.iotdb.confignode.rpc.thrift.TGetTimeSlotListResp;
import org.apache.iotdb.confignode.rpc.thrift.TGetTriggerTableResp;
import org.apache.iotdb.confignode.rpc.thrift.TGetUDFTableResp;
import org.apache.iotdb.confignode.rpc.thrift.TGetUdfTableReq;
+import org.apache.iotdb.confignode.rpc.thrift.TLoadModelReq;
import org.apache.iotdb.confignode.rpc.thrift.TMigrateRegionReq;
import org.apache.iotdb.confignode.rpc.thrift.TNodeVersionInfo;
import org.apache.iotdb.confignode.rpc.thrift.TPermissionInfoResp;
@@ -222,6 +223,7 @@ import org.apache.iotdb.confignode.rpc.thrift.TSchemaNodeManagementResp;
import org.apache.iotdb.confignode.rpc.thrift.TSchemaPartitionTableResp;
import org.apache.iotdb.confignode.rpc.thrift.TSetDataNodeStatusReq;
import org.apache.iotdb.confignode.rpc.thrift.TSetSchemaTemplateReq;
+import org.apache.iotdb.confignode.rpc.thrift.TShowAIDevicesResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowAINodesResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowCQResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowClusterResp;
@@ -230,6 +232,8 @@ import org.apache.iotdb.confignode.rpc.thrift.TShowConfigNodesResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowDataNodes4InformationSchemaResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowDataNodesResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowDatabaseResp;
+import org.apache.iotdb.confignode.rpc.thrift.TShowLoadedModelReq;
+import org.apache.iotdb.confignode.rpc.thrift.TShowLoadedModelResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowModelReq;
import org.apache.iotdb.confignode.rpc.thrift.TShowModelResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowPipePluginReq;
@@ -249,6 +253,7 @@ import org.apache.iotdb.confignode.rpc.thrift.TStopPipeReq;
import org.apache.iotdb.confignode.rpc.thrift.TSubscribeReq;
import org.apache.iotdb.confignode.rpc.thrift.TThrottleQuotaResp;
import org.apache.iotdb.confignode.rpc.thrift.TTimeSlotList;
+import org.apache.iotdb.confignode.rpc.thrift.TUnloadModelReq;
import org.apache.iotdb.confignode.rpc.thrift.TUnsetSchemaTemplateReq;
import org.apache.iotdb.confignode.rpc.thrift.TUnsubscribeReq;
import org.apache.iotdb.confignode.rpc.thrift.TUpdateModelInfoReq;
@@ -2731,6 +2736,22 @@ public class ConfigManager implements IManager {
: status;
}
+ @Override
+ public TSStatus loadModel(TLoadModelReq req) {
+ TSStatus status = confirmLeader();
+ return status.getCode() == TSStatusCode.SUCCESS_STATUS.getStatusCode()
+ ? modelManager.loadModel(req)
+ : status;
+ }
+
+ @Override
+ public TSStatus unloadModel(TUnloadModelReq req) {
+ TSStatus status = confirmLeader();
+ return status.getCode() == TSStatusCode.SUCCESS_STATUS.getStatusCode()
+ ? modelManager.unloadModel(req)
+ : status;
+ }
+
@Override
public TShowModelResp showModel(TShowModelReq req) {
TSStatus status = confirmLeader();
@@ -2739,6 +2760,22 @@ public class ConfigManager implements IManager {
: new TShowModelResp(status);
}
+ @Override
+ public TShowLoadedModelResp showLoadedModel(TShowLoadedModelReq req) {
+ TSStatus status = confirmLeader();
+ return status.getCode() == TSStatusCode.SUCCESS_STATUS.getStatusCode()
+ ? modelManager.showLoadedModel(req)
+ : new TShowLoadedModelResp(status, Collections.emptyMap());
+ }
+
+ @Override
+ public TShowAIDevicesResp showAIDevices() {
+ TSStatus status = confirmLeader();
+ return status.getCode() == TSStatusCode.SUCCESS_STATUS.getStatusCode()
+ ? modelManager.showAIDevices()
+ : new TShowAIDevicesResp(status, Collections.emptyList());
+ }
+
@Override
public TGetModelInfoResp getModelInfo(TGetModelInfoReq req) {
TSStatus status = confirmLeader();
diff --git a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/IManager.java b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/IManager.java
index bc080198cb6..348d973adf8 100644
--- a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/IManager.java
+++ b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/IManager.java
@@ -124,6 +124,7 @@ import org.apache.iotdb.confignode.rpc.thrift.TGetTimeSlotListResp;
import org.apache.iotdb.confignode.rpc.thrift.TGetTriggerTableResp;
import org.apache.iotdb.confignode.rpc.thrift.TGetUDFTableResp;
import org.apache.iotdb.confignode.rpc.thrift.TGetUdfTableReq;
+import org.apache.iotdb.confignode.rpc.thrift.TLoadModelReq;
import org.apache.iotdb.confignode.rpc.thrift.TMigrateRegionReq;
import org.apache.iotdb.confignode.rpc.thrift.TPermissionInfoResp;
import org.apache.iotdb.confignode.rpc.thrift.TPipeConfigTransferReq;
@@ -135,6 +136,7 @@ import org.apache.iotdb.confignode.rpc.thrift.TSchemaNodeManagementResp;
import org.apache.iotdb.confignode.rpc.thrift.TSchemaPartitionTableResp;
import org.apache.iotdb.confignode.rpc.thrift.TSetDataNodeStatusReq;
import org.apache.iotdb.confignode.rpc.thrift.TSetSchemaTemplateReq;
+import org.apache.iotdb.confignode.rpc.thrift.TShowAIDevicesResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowAINodesResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowCQResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowClusterResp;
@@ -143,6 +145,8 @@ import org.apache.iotdb.confignode.rpc.thrift.TShowConfigNodesResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowDataNodes4InformationSchemaResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowDataNodesResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowDatabaseResp;
+import org.apache.iotdb.confignode.rpc.thrift.TShowLoadedModelReq;
+import org.apache.iotdb.confignode.rpc.thrift.TShowLoadedModelResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowModelReq;
import org.apache.iotdb.confignode.rpc.thrift.TShowModelResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowPipePluginReq;
@@ -158,6 +162,7 @@ import org.apache.iotdb.confignode.rpc.thrift.TShowVariablesResp;
import org.apache.iotdb.confignode.rpc.thrift.TStartPipeReq;
import org.apache.iotdb.confignode.rpc.thrift.TStopPipeReq;
import org.apache.iotdb.confignode.rpc.thrift.TSubscribeReq;
+import org.apache.iotdb.confignode.rpc.thrift.TUnloadModelReq;
import org.apache.iotdb.confignode.rpc.thrift.TUnsetSchemaTemplateReq;
import org.apache.iotdb.confignode.rpc.thrift.TUnsubscribeReq;
import org.apache.iotdb.consensus.common.DataSet;
@@ -862,9 +867,21 @@ public interface IManager {
/** Drop a model. */
TSStatus dropModel(TDropModelReq req);
+ /** Load the specific model to the specific devices. */
+ TSStatus loadModel(TLoadModelReq req);
+
+ /** Unload the specific model from the specific devices. */
+ TSStatus unloadModel(TUnloadModelReq req);
+
/** Return the model table. */
TShowModelResp showModel(TShowModelReq req);
+ /** Return the loaded model instances. */
+ TShowLoadedModelResp showLoadedModel(TShowLoadedModelReq req);
+
+ /** Return all available AI devices. */
+ TShowAIDevicesResp showAIDevices();
+
/** Update the model state */
TGetModelInfoResp getModelInfo(TGetModelInfoReq req);
diff --git a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/ModelManager.java b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/ModelManager.java
index e9d9ff97510..88143af03e9 100644
--- a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/ModelManager.java
+++ b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/ModelManager.java
@@ -19,12 +19,15 @@
package org.apache.iotdb.confignode.manager;
+import org.apache.iotdb.ainode.rpc.thrift.TShowLoadedModelsReq;
+import org.apache.iotdb.ainode.rpc.thrift.TShowLoadedModelsResp;
import org.apache.iotdb.ainode.rpc.thrift.TShowModelsReq;
import org.apache.iotdb.ainode.rpc.thrift.TShowModelsResp;
import org.apache.iotdb.common.rpc.thrift.TEndPoint;
import org.apache.iotdb.common.rpc.thrift.TSStatus;
import org.apache.iotdb.commons.client.ainode.AINodeClient;
import org.apache.iotdb.commons.client.ainode.AINodeClientManager;
+import org.apache.iotdb.commons.client.exception.ClientManagerException;
import org.apache.iotdb.commons.model.ModelInformation;
import org.apache.iotdb.commons.model.ModelStatus;
import org.apache.iotdb.commons.model.ModelType;
@@ -32,14 +35,20 @@ import org.apache.iotdb.confignode.consensus.request.read.model.GetModelInfoPlan
import org.apache.iotdb.confignode.consensus.request.write.model.CreateModelPlan;
import org.apache.iotdb.confignode.consensus.request.write.model.UpdateModelInfoPlan;
import org.apache.iotdb.confignode.consensus.response.model.GetModelInfoResp;
+import org.apache.iotdb.confignode.exception.NoAvailableAINodeException;
import org.apache.iotdb.confignode.persistence.ModelInfo;
import org.apache.iotdb.confignode.rpc.thrift.TAINodeInfo;
import org.apache.iotdb.confignode.rpc.thrift.TCreateModelReq;
import org.apache.iotdb.confignode.rpc.thrift.TDropModelReq;
import org.apache.iotdb.confignode.rpc.thrift.TGetModelInfoReq;
import org.apache.iotdb.confignode.rpc.thrift.TGetModelInfoResp;
+import org.apache.iotdb.confignode.rpc.thrift.TLoadModelReq;
+import org.apache.iotdb.confignode.rpc.thrift.TShowAIDevicesResp;
+import org.apache.iotdb.confignode.rpc.thrift.TShowLoadedModelReq;
+import org.apache.iotdb.confignode.rpc.thrift.TShowLoadedModelResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowModelReq;
import org.apache.iotdb.confignode.rpc.thrift.TShowModelResp;
+import org.apache.iotdb.confignode.rpc.thrift.TUnloadModelReq;
import org.apache.iotdb.confignode.rpc.thrift.TUpdateModelInfoReq;
import org.apache.iotdb.consensus.exception.ConsensusException;
import org.apache.iotdb.rpc.TSStatusCode;
@@ -92,20 +101,33 @@ public class ModelManager {
return configManager.getProcedureManager().dropModel(req.getModelId());
}
- public TShowModelResp showModel(final TShowModelReq req) {
- List<TAINodeInfo> registeredAINodes =
- configManager.getNodeManager().getRegisteredAINodeInfoList();
- if (registeredAINodes.isEmpty()) {
- return new TShowModelResp()
- .setStatus(
- new TSStatus(TSStatusCode.NO_AVAILABLE_AINODE.getStatusCode())
- .setMessage("Show models failed due to there is no AINode available"));
+ public TSStatus loadModel(TLoadModelReq req) {
+ try (AINodeClient client = getAINodeClient()) {
+ org.apache.iotdb.ainode.rpc.thrift.TLoadModelReq loadModelReq =
+ new org.apache.iotdb.ainode.rpc.thrift.TLoadModelReq(
+ req.existingModelId, req.deviceIdList);
+ return client.loadModel(loadModelReq);
+ } catch (Exception e) {
+ LOGGER.warn("Failed to load model due to", e);
+ return new TSStatus(TSStatusCode.AI_NODE_INTERNAL_ERROR.getStatusCode())
+ .setMessage(e.getMessage());
}
- TAINodeInfo registeredAINode = registeredAINodes.get(0);
- TEndPoint targetAINodeEndPoint =
- new TEndPoint(registeredAINode.getInternalAddress(), registeredAINode.getInternalPort());
- try (AINodeClient client =
- AINodeClientManager.getInstance().borrowClient(targetAINodeEndPoint)) {
+ }
+
+ public TSStatus unloadModel(TUnloadModelReq req) {
+ try (AINodeClient client = getAINodeClient()) {
+ org.apache.iotdb.ainode.rpc.thrift.TUnloadModelReq unloadModelReq =
+ new org.apache.iotdb.ainode.rpc.thrift.TUnloadModelReq(req.modelId, req.deviceIdList);
+ return client.unloadModel(unloadModelReq);
+ } catch (Exception e) {
+ LOGGER.warn("Failed to unload model due to", e);
+ return new TSStatus(TSStatusCode.AI_NODE_INTERNAL_ERROR.getStatusCode())
+ .setMessage(e.getMessage());
+ }
+ }
+
+ public TShowModelResp showModel(final TShowModelReq req) {
+ try (AINodeClient client = getAINodeClient()) {
TShowModelsReq showModelsReq = new TShowModelsReq();
if (req.isSetModelId()) {
showModelsReq.setModelId(req.getModelId());
@@ -122,7 +144,43 @@ public class ModelManager {
LOGGER.warn("Failed to show models due to", e);
return new TShowModelResp()
.setStatus(
- new TSStatus(TSStatusCode.CAN_NOT_CONNECT_AINODE.getStatusCode())
+ new TSStatus(TSStatusCode.AI_NODE_INTERNAL_ERROR.getStatusCode())
+ .setMessage(e.getMessage()));
+ }
+ }
+
+ public TShowLoadedModelResp showLoadedModel(final TShowLoadedModelReq req) {
+ try (AINodeClient client = getAINodeClient()) {
+ TShowLoadedModelsReq showModelsReq =
+ new TShowLoadedModelsReq().setDeviceIdList(req.getDeviceIdList());
+ TShowLoadedModelsResp resp = client.showLoadedModels(showModelsReq);
+ TShowLoadedModelResp res =
+ new TShowLoadedModelResp()
+ .setStatus(new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode()));
+ res.setDeviceLoadedModelsMap(resp.getDeviceLoadedModelsMap());
+ return res;
+ } catch (Exception e) {
+ LOGGER.warn("Failed to show loaded models due to", e);
+ return new TShowLoadedModelResp()
+ .setStatus(
+ new TSStatus(TSStatusCode.AI_NODE_INTERNAL_ERROR.getStatusCode())
+ .setMessage(e.getMessage()));
+ }
+ }
+
+ public TShowAIDevicesResp showAIDevices() {
+ try (AINodeClient client = getAINodeClient()) {
+ org.apache.iotdb.ainode.rpc.thrift.TShowAIDevicesResp resp = client.showAIDevices();
+ TShowAIDevicesResp res =
+ new TShowAIDevicesResp()
+ .setStatus(new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode()));
+ res.setDeviceIdList(resp.getDeviceIdList());
+ return res;
+ } catch (Exception e) {
+ LOGGER.warn("Failed to show AI devices due to", e);
+ return new TShowAIDevicesResp()
+ .setStatus(
+ new TSStatus(TSStatusCode.AI_NODE_INTERNAL_ERROR.getStatusCode())
.setMessage(e.getMessage()));
}
}
@@ -190,6 +248,16 @@ public class ModelManager {
}
}
+ private AINodeClient getAINodeClient() throws NoAvailableAINodeException, ClientManagerException {
+ List<TAINodeInfo> aiNodeInfo = configManager.getNodeManager().getRegisteredAINodeInfoList();
+ if (aiNodeInfo.isEmpty()) {
+ throw new NoAvailableAINodeException();
+ }
+ TEndPoint targetAINodeEndPoint =
+ new TEndPoint(aiNodeInfo.get(0).getInternalAddress(), aiNodeInfo.get(0).getInternalPort());
+ return AINodeClientManager.getInstance().borrowClient(targetAINodeEndPoint);
+ }
+
public List<Integer> getModelDistributions(String modelName) {
return modelInfo.getNodeIds(modelName);
}
diff --git a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/service/thrift/ConfigNodeRPCServiceProcessor.java b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/service/thrift/ConfigNodeRPCServiceProcessor.java
index 958324c0b51..0de826ef542 100644
--- a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/service/thrift/ConfigNodeRPCServiceProcessor.java
+++ b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/service/thrift/ConfigNodeRPCServiceProcessor.java
@@ -173,6 +173,7 @@ import org.apache.iotdb.confignode.rpc.thrift.TGetTimeSlotListResp;
import org.apache.iotdb.confignode.rpc.thrift.TGetTriggerTableResp;
import org.apache.iotdb.confignode.rpc.thrift.TGetUDFTableResp;
import org.apache.iotdb.confignode.rpc.thrift.TGetUdfTableReq;
+import org.apache.iotdb.confignode.rpc.thrift.TLoadModelReq;
import org.apache.iotdb.confignode.rpc.thrift.TLoginReq;
import org.apache.iotdb.confignode.rpc.thrift.TMigrateRegionReq;
import org.apache.iotdb.confignode.rpc.thrift.TPermissionInfoResp;
@@ -190,6 +191,7 @@ import org.apache.iotdb.confignode.rpc.thrift.TSetDataReplicationFactorReq;
import org.apache.iotdb.confignode.rpc.thrift.TSetSchemaReplicationFactorReq;
import org.apache.iotdb.confignode.rpc.thrift.TSetSchemaTemplateReq;
import org.apache.iotdb.confignode.rpc.thrift.TSetTimePartitionIntervalReq;
+import org.apache.iotdb.confignode.rpc.thrift.TShowAIDevicesResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowAINodesResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowCQResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowClusterResp;
@@ -198,6 +200,8 @@ import org.apache.iotdb.confignode.rpc.thrift.TShowConfigNodesResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowDataNodes4InformationSchemaResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowDataNodesResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowDatabaseResp;
+import org.apache.iotdb.confignode.rpc.thrift.TShowLoadedModelReq;
+import org.apache.iotdb.confignode.rpc.thrift.TShowLoadedModelResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowModelReq;
import org.apache.iotdb.confignode.rpc.thrift.TShowModelResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowPipePluginReq;
@@ -221,6 +225,7 @@ import org.apache.iotdb.confignode.rpc.thrift.TSubscribeReq;
import org.apache.iotdb.confignode.rpc.thrift.TSystemConfigurationResp;
import org.apache.iotdb.confignode.rpc.thrift.TTestOperation;
import org.apache.iotdb.confignode.rpc.thrift.TThrottleQuotaResp;
+import org.apache.iotdb.confignode.rpc.thrift.TUnloadModelReq;
import org.apache.iotdb.confignode.rpc.thrift.TUnsetSchemaTemplateReq;
import org.apache.iotdb.confignode.rpc.thrift.TUnsubscribeReq;
import org.apache.iotdb.confignode.rpc.thrift.TUpdateModelInfoReq;
@@ -1323,11 +1328,31 @@ public class ConfigNodeRPCServiceProcessor implements IConfigNodeRPCService.Ifac
return configManager.dropModel(req);
}
+ @Override
+ public TSStatus loadModel(TLoadModelReq req) {
+ return configManager.loadModel(req);
+ }
+
+ @Override
+ public TSStatus unloadModel(TUnloadModelReq req) {
+ return configManager.unloadModel(req);
+ }
+
@Override
public TShowModelResp showModel(TShowModelReq req) {
return configManager.showModel(req);
}
+ @Override
+ public TShowLoadedModelResp showLoadedModel(TShowLoadedModelReq req) {
+ return configManager.showLoadedModel(req);
+ }
+
+ @Override
+ public TShowAIDevicesResp showAIDevices() {
+ return configManager.showAIDevices();
+ }
+
@Override
public TGetModelInfoResp getModelInfo(TGetModelInfoReq req) {
return configManager.getModelInfo(req);
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/client/ConfigNodeClient.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/client/ConfigNodeClient.java
index 6a27ad10f93..a21127b1d7d 100644
--- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/client/ConfigNodeClient.java
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/client/ConfigNodeClient.java
@@ -132,6 +132,7 @@ import org.apache.iotdb.confignode.rpc.thrift.TGetTimeSlotListResp;
import org.apache.iotdb.confignode.rpc.thrift.TGetTriggerTableResp;
import org.apache.iotdb.confignode.rpc.thrift.TGetUDFTableResp;
import org.apache.iotdb.confignode.rpc.thrift.TGetUdfTableReq;
+import org.apache.iotdb.confignode.rpc.thrift.TLoadModelReq;
import org.apache.iotdb.confignode.rpc.thrift.TLoginReq;
import org.apache.iotdb.confignode.rpc.thrift.TMigrateRegionReq;
import org.apache.iotdb.confignode.rpc.thrift.TPermissionInfoResp;
@@ -149,6 +150,7 @@ import org.apache.iotdb.confignode.rpc.thrift.TSetDataReplicationFactorReq;
import org.apache.iotdb.confignode.rpc.thrift.TSetSchemaReplicationFactorReq;
import org.apache.iotdb.confignode.rpc.thrift.TSetSchemaTemplateReq;
import org.apache.iotdb.confignode.rpc.thrift.TSetTimePartitionIntervalReq;
+import org.apache.iotdb.confignode.rpc.thrift.TShowAIDevicesResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowAINodesResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowCQResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowClusterResp;
@@ -157,6 +159,8 @@ import org.apache.iotdb.confignode.rpc.thrift.TShowConfigNodesResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowDataNodes4InformationSchemaResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowDataNodesResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowDatabaseResp;
+import org.apache.iotdb.confignode.rpc.thrift.TShowLoadedModelReq;
+import org.apache.iotdb.confignode.rpc.thrift.TShowLoadedModelResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowModelReq;
import org.apache.iotdb.confignode.rpc.thrift.TShowModelResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowPipePluginReq;
@@ -180,6 +184,7 @@ import org.apache.iotdb.confignode.rpc.thrift.TSubscribeReq;
import org.apache.iotdb.confignode.rpc.thrift.TSystemConfigurationResp;
import org.apache.iotdb.confignode.rpc.thrift.TTestOperation;
import org.apache.iotdb.confignode.rpc.thrift.TThrottleQuotaResp;
+import org.apache.iotdb.confignode.rpc.thrift.TUnloadModelReq;
import org.apache.iotdb.confignode.rpc.thrift.TUnsetSchemaTemplateReq;
import org.apache.iotdb.confignode.rpc.thrift.TUnsubscribeReq;
import org.apache.iotdb.confignode.rpc.thrift.TUpdateModelInfoReq;
@@ -1314,6 +1319,29 @@ public class ConfigNodeClient implements IConfigNodeRPCService.Iface, ThriftClie
() -> client.showModel(req), resp -> !updateConfigNodeLeader(resp.status));
}
+ @Override
+ public TShowLoadedModelResp showLoadedModel(TShowLoadedModelReq req) throws TException {
+ return executeRemoteCallWithRetry(
+ () -> client.showLoadedModel(req), resp -> !updateConfigNodeLeader(resp.status));
+ }
+
+ @Override
+ public TShowAIDevicesResp showAIDevices() throws TException {
+ return executeRemoteCallWithRetry(
+ () -> client.showAIDevices(), resp -> !updateConfigNodeLeader(resp.status));
+ }
+
+ @Override
+ public TSStatus loadModel(TLoadModelReq req) throws TException {
+ return executeRemoteCallWithRetry(
+ () -> client.loadModel(req), status -> !updateConfigNodeLeader(status));
+ }
+
+ public TSStatus unloadModel(TUnloadModelReq req) throws TException {
+ return executeRemoteCallWithRetry(
+ () -> client.unloadModel(req), status -> !updateConfigNodeLeader(status));
+ }
+
@Override
public TGetModelInfoResp getModelInfo(TGetModelInfoReq req) throws TException {
return executeRemoteCallWithRetry(
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/rest/table/v1/handler/ExecuteStatementHandler.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/rest/table/v1/handler/ExecuteStatementHandler.java
index fb706ded2ae..1b273753139 100644
--- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/rest/table/v1/handler/ExecuteStatementHandler.java
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/rest/table/v1/handler/ExecuteStatementHandler.java
@@ -23,6 +23,7 @@ import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.Explain;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ExplainAnalyze;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.Query;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.RelationalAuthorStatement;
+import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowAIDevices;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowAINodes;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowCluster;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowClusterId;
@@ -36,6 +37,7 @@ import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowDataNodes;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowDevice;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowFunctions;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowIndex;
+import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowLoadedModels;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowModels;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowPipePlugins;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowPipes;
@@ -80,6 +82,8 @@ public class ExecuteStatementHandler {
INVALID_STATEMENT_CLASSES.add(ShowFunctions.class);
INVALID_STATEMENT_CLASSES.add(ShowIndex.class);
INVALID_STATEMENT_CLASSES.add(ShowModels.class);
+ INVALID_STATEMENT_CLASSES.add(ShowLoadedModels.class);
+ INVALID_STATEMENT_CLASSES.add(ShowAIDevices.class);
INVALID_STATEMENT_CLASSES.add(ShowPipePlugins.class);
INVALID_STATEMENT_CLASSES.add(ShowPipes.class);
INVALID_STATEMENT_CLASSES.add(ShowQueriesStatement.class);
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/rest/v1/handler/ExecuteStatementHandler.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/rest/v1/handler/ExecuteStatementHandler.java
index 7eec34964bc..f1c621a4aa4 100644
--- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/rest/v1/handler/ExecuteStatementHandler.java
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/rest/v1/handler/ExecuteStatementHandler.java
@@ -22,6 +22,8 @@ import org.apache.iotdb.db.queryengine.plan.statement.StatementType;
import org.apache.iotdb.db.queryengine.plan.statement.crud.QueryStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.GetRegionIdStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.ShowStatement;
+import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.ShowAIDevicesStatement;
+import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.ShowLoadedModelsStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.ShowModelsStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.template.DropSchemaTemplateStatement;
import org.apache.iotdb.db.queryengine.plan.statement.sys.AuthorStatement;
@@ -32,6 +34,8 @@ public class ExecuteStatementHandler {
public static boolean validateStatement(Statement statement) {
return !(statement instanceof QueryStatement)
&& !(statement instanceof ShowModelsStatement)
+ && !(statement instanceof ShowAIDevicesStatement)
+ && !(statement instanceof ShowLoadedModelsStatement)
&& !(statement instanceof ShowStatement
&& !(statement instanceof DropSchemaTemplateStatement))
&& !(statement instanceof AuthorStatement
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/rest/v1/handler/QueryDataSetHandler.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/rest/v1/handler/QueryDataSetHandler.java
index 8accae7991b..55623ecad21 100644
--- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/rest/v1/handler/QueryDataSetHandler.java
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/rest/v1/handler/QueryDataSetHandler.java
@@ -26,6 +26,8 @@ import org.apache.iotdb.db.queryengine.plan.statement.crud.QueryStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.GetRegionIdStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.ShowChildPathsStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.ShowStatement;
+import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.ShowAIDevicesStatement;
+import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.ShowLoadedModelsStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.ShowModelsStatement;
import org.apache.iotdb.db.queryengine.plan.statement.sys.AuthorStatement;
import org.apache.iotdb.rpc.TSStatusCode;
@@ -56,6 +58,8 @@ public class QueryDataSetHandler {
throws IoTDBException {
if (statement instanceof ShowStatement
|| statement instanceof ShowModelsStatement
+ || statement instanceof ShowAIDevicesStatement
+ || statement instanceof ShowLoadedModelsStatement
|| statement instanceof AuthorStatement
|| statement instanceof GetRegionIdStatement) {
return fillShowPlanDataSet(queryExecution, actualRowSizeLimit);
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/rest/v2/handler/ExecuteStatementHandler.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/rest/v2/handler/ExecuteStatementHandler.java
index 53bf7f896a9..00e43d17cce 100644
--- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/rest/v2/handler/ExecuteStatementHandler.java
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/rest/v2/handler/ExecuteStatementHandler.java
@@ -22,6 +22,8 @@ import org.apache.iotdb.db.queryengine.plan.statement.StatementType;
import org.apache.iotdb.db.queryengine.plan.statement.crud.QueryStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.GetRegionIdStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.ShowStatement;
+import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.ShowAIDevicesStatement;
+import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.ShowLoadedModelsStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.ShowModelsStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.template.DropSchemaTemplateStatement;
import org.apache.iotdb.db.queryengine.plan.statement.sys.AuthorStatement;
@@ -32,6 +34,8 @@ public class ExecuteStatementHandler {
public static boolean validateStatement(Statement statement) {
return !(statement instanceof QueryStatement)
&& !(statement instanceof ShowModelsStatement)
+ && !(statement instanceof ShowAIDevicesStatement)
+ && !(statement instanceof ShowLoadedModelsStatement)
&& !(statement instanceof ShowStatement
&& !(statement instanceof DropSchemaTemplateStatement))
&& !(statement instanceof AuthorStatement
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/rest/v2/handler/QueryDataSetHandler.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/rest/v2/handler/QueryDataSetHandler.java
index fed6e3ec80a..b89c4f768a7 100644
--- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/rest/v2/handler/QueryDataSetHandler.java
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/rest/v2/handler/QueryDataSetHandler.java
@@ -26,6 +26,8 @@ import org.apache.iotdb.db.queryengine.plan.statement.crud.QueryStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.GetRegionIdStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.ShowChildPathsStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.ShowStatement;
+import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.ShowAIDevicesStatement;
+import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.ShowLoadedModelsStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.ShowModelsStatement;
import org.apache.iotdb.db.queryengine.plan.statement.sys.AuthorStatement;
import org.apache.iotdb.rpc.TSStatusCode;
@@ -56,6 +58,8 @@ public class QueryDataSetHandler {
throws IoTDBException {
if (statement instanceof ShowStatement
|| statement instanceof ShowModelsStatement
+ || statement instanceof ShowAIDevicesStatement
+ || statement instanceof ShowLoadedModelsStatement
|| statement instanceof AuthorStatement
|| statement instanceof GetRegionIdStatement) {
return fillShowPlanDataSet(queryExecution, actualRowSizeLimit);
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 20cc3dd3c37..4aa87cda1a0 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
@@ -325,7 +325,6 @@ public class ClientRPCServiceImpl implements IClientRPCServiceWithHandler {
ExecutionResult result;
if (clientSession.getSqlDialect() == IClientSession.SqlDialect.TREE) {
Statement s = StatementGenerator.createStatement(statement, clientSession.getZoneId());
-
if (s instanceof SetSqlDialectStatement) {
setSqlDialect = true;
}
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/common/header/DatasetHeaderFactory.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/common/header/DatasetHeaderFactory.java
index c69dee793b9..a9e737ac06e 100644
--- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/common/header/DatasetHeaderFactory.java
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/common/header/DatasetHeaderFactory.java
@@ -211,6 +211,14 @@ public class DatasetHeaderFactory {
return new DatasetHeader(ColumnHeaderConstant.showModelsColumnHeaders, true);
}
+ public static DatasetHeader getShowLoadedModelsHeader() {
+ return new DatasetHeader(ColumnHeaderConstant.showLoadedModelsColumnHeaders, true);
+ }
+
+ public static DatasetHeader getShowAIDevicesHeader() {
+ return new DatasetHeader(ColumnHeaderConstant.showAIDevicesColumnHeaders, true);
+ }
+
public static DatasetHeader getShowLogicalViewHeader() {
return new DatasetHeader(ColumnHeaderConstant.showLogicalViewColumnHeaders, true);
}
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 ca72d2f3151..a1aef5fff60 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
@@ -77,6 +77,7 @@ import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ExtendRegion;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.Flush;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.KillQuery;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.LoadConfiguration;
+import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.LoadModel;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.MigrateRegion;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.PipeStatement;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ReconstructRegion;
@@ -93,6 +94,7 @@ import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.SetProperties;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.SetSqlDialect;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.SetSystemStatus;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.SetTableComment;
+import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowAIDevices;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowAINodes;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowCluster;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowClusterId;
@@ -104,6 +106,7 @@ import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowCurrentUser;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowDB;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowDataNodes;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowFunctions;
+import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowLoadedModels;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowModels;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowRegions;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowTables;
@@ -112,6 +115,7 @@ import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowVersion;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.StartRepairData;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.StopRepairData;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.SubscriptionStatement;
+import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.UnloadModel;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.Use;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.WrappedInsertStatement;
import org.apache.iotdb.db.queryengine.plan.relational.sql.parser.SqlParser;
@@ -461,7 +465,11 @@ public class Coordinator {
|| statement instanceof CreateModel
|| statement instanceof CreateTraining
|| statement instanceof ShowModels
+ || statement instanceof ShowAIDevices
|| statement instanceof DropModel
+ || statement instanceof LoadModel
+ || statement instanceof UnloadModel
+ || statement instanceof ShowLoadedModels
|| statement instanceof RemoveRegion) {
return new ConfigExecution(
queryContext,
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/TableConfigTaskVisitor.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/TableConfigTaskVisitor.java
index b40096a562d..c48f7488cfc 100644
--- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/TableConfigTaskVisitor.java
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/TableConfigTaskVisitor.java
@@ -58,7 +58,11 @@ import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.ShowVariab
import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.ai.CreateModelTask;
import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.ai.CreateTrainingTask;
import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.ai.DropModelTask;
+import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.ai.LoadModelTask;
+import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.ai.ShowAIDevicesTask;
+import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.ai.ShowLoadedModelsTask;
import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.ai.ShowModelsTask;
+import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.ai.UnloadModelTask;
import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.region.ExtendRegionTask;
import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.region.MigrateRegionTask;
import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.region.ReconstructRegionTask;
@@ -154,6 +158,7 @@ import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.Flush;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.KillQuery;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.Literal;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.LoadConfiguration;
+import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.LoadModel;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.LongLiteral;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.MigrateRegion;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.Node;
@@ -173,6 +178,7 @@ import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.SetProperties;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.SetSqlDialect;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.SetSystemStatus;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.SetTableComment;
+import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowAIDevices;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowAINodes;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowCluster;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowClusterId;
@@ -184,6 +190,7 @@ import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowCurrentUser;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowDB;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowDataNodes;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowFunctions;
+import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowLoadedModels;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowModels;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowPipePlugins;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowPipes;
@@ -197,6 +204,7 @@ import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.StartPipe;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.StartRepairData;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.StopPipe;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.StopRepairData;
+import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.UnloadModel;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.Use;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ViewFieldDefinition;
import org.apache.iotdb.db.queryengine.plan.relational.sql.rewrite.StatementRewrite;
@@ -1415,4 +1423,28 @@ public class TableConfigTaskVisitor extends AstVisitor<IConfigTask, MPPQueryCont
context.setQueryType(QueryType.WRITE);
return new DropModelTask(node.getModelId());
}
+
+ @Override
+ protected IConfigTask visitShowLoadedModels(ShowLoadedModels node, MPPQueryContext context) {
+ context.setQueryType(QueryType.READ);
+ return new ShowLoadedModelsTask(node.getDeviceIdList());
+ }
+
+ @Override
+ protected IConfigTask visitShowAIDevices(ShowAIDevices node, MPPQueryContext context) {
+ context.setQueryType(QueryType.READ);
+ return new ShowAIDevicesTask();
+ }
+
+ @Override
+ protected IConfigTask visitLoadModel(LoadModel node, MPPQueryContext context) {
+ context.setQueryType(QueryType.WRITE);
+ return new LoadModelTask(node.getModelId(), node.getDeviceIdList());
+ }
+
+ @Override
+ protected IConfigTask visitUnloadModel(UnloadModel node, MPPQueryContext context) {
+ context.setQueryType(QueryType.WRITE);
+ return new UnloadModelTask(node.getModelId(), node.getDeviceIdList());
+ }
}
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/TreeConfigTaskVisitor.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/TreeConfigTaskVisitor.java
index 5be65a433d8..04ccc59580c 100644
--- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/TreeConfigTaskVisitor.java
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/TreeConfigTaskVisitor.java
@@ -65,7 +65,11 @@ import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.UnSetTTLTa
import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.ai.CreateModelTask;
import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.ai.CreateTrainingTask;
import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.ai.DropModelTask;
+import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.ai.LoadModelTask;
+import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.ai.ShowAIDevicesTask;
+import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.ai.ShowLoadedModelsTask;
import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.ai.ShowModelsTask;
+import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.ai.UnloadModelTask;
import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.region.ExtendRegionTask;
import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.region.MigrateRegionTask;
import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.region.ReconstructRegionTask;
@@ -148,8 +152,12 @@ import org.apache.iotdb.db.queryengine.plan.statement.metadata.UnSetTTLStatement
import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.CreateModelStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.CreateTrainingStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.DropModelStatement;
+import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.LoadModelStatement;
+import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.ShowAIDevicesStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.ShowAINodesStatement;
+import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.ShowLoadedModelsStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.ShowModelsStatement;
+import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.UnloadModelStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.pipe.AlterPipeStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.pipe.CreatePipePluginStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.pipe.CreatePipeStatement;
@@ -811,6 +819,31 @@ public class TreeConfigTaskVisitor extends StatementVisitor<IConfigTask, MPPQuer
return new ShowModelsTask(showModelsStatement.getModelId());
}
+ @Override
+ public IConfigTask visitShowLoadedModels(
+ ShowLoadedModelsStatement showLoadedModelsStatement, MPPQueryContext context) {
+ return new ShowLoadedModelsTask(showLoadedModelsStatement.getDeviceIdList());
+ }
+
+ @Override
+ public IConfigTask visitShowAIDevices(
+ ShowAIDevicesStatement showAIDevicesStatement, MPPQueryContext context) {
+ return new ShowAIDevicesTask();
+ }
+
+ @Override
+ public IConfigTask visitLoadModel(
+ LoadModelStatement loadModelStatement, MPPQueryContext context) {
+ return new LoadModelTask(loadModelStatement.getModelId(), loadModelStatement.getDeviceIdList());
+ }
+
+ @Override
+ public IConfigTask visitUnloadModel(
+ UnloadModelStatement unloadModelStatement, MPPQueryContext context) {
+ return new UnloadModelTask(
+ unloadModelStatement.getModelId(), unloadModelStatement.getDeviceIdList());
+ }
+
@Override
public IConfigTask visitShowCurrentUser(ShowCurrentUserStatement node, MPPQueryContext context) {
return new ShowCurrentUserTask(context.getSession().getUserName());
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/executor/ClusterConfigTaskExecutor.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/executor/ClusterConfigTaskExecutor.java
index 8227d5b4676..aa5f3034703 100644
--- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/executor/ClusterConfigTaskExecutor.java
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/executor/ClusterConfigTaskExecutor.java
@@ -125,18 +125,22 @@ import org.apache.iotdb.confignode.rpc.thrift.TGetTimeSlotListResp;
import org.apache.iotdb.confignode.rpc.thrift.TGetTriggerTableResp;
import org.apache.iotdb.confignode.rpc.thrift.TGetUDFTableResp;
import org.apache.iotdb.confignode.rpc.thrift.TGetUdfTableReq;
+import org.apache.iotdb.confignode.rpc.thrift.TLoadModelReq;
import org.apache.iotdb.confignode.rpc.thrift.TMigrateRegionReq;
import org.apache.iotdb.confignode.rpc.thrift.TPipeConfigTransferReq;
import org.apache.iotdb.confignode.rpc.thrift.TPipeConfigTransferResp;
import org.apache.iotdb.confignode.rpc.thrift.TReconstructRegionReq;
import org.apache.iotdb.confignode.rpc.thrift.TRegionInfo;
import org.apache.iotdb.confignode.rpc.thrift.TRemoveRegionReq;
+import org.apache.iotdb.confignode.rpc.thrift.TShowAIDevicesResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowAINodesResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowCQResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowClusterResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowConfigNodesResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowDataNodesResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowDatabaseResp;
+import org.apache.iotdb.confignode.rpc.thrift.TShowLoadedModelReq;
+import org.apache.iotdb.confignode.rpc.thrift.TShowLoadedModelResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowModelReq;
import org.apache.iotdb.confignode.rpc.thrift.TShowModelResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowPipeInfo;
@@ -156,6 +160,7 @@ import org.apache.iotdb.confignode.rpc.thrift.TSpaceQuotaResp;
import org.apache.iotdb.confignode.rpc.thrift.TStartPipeReq;
import org.apache.iotdb.confignode.rpc.thrift.TStopPipeReq;
import org.apache.iotdb.confignode.rpc.thrift.TThrottleQuotaResp;
+import org.apache.iotdb.confignode.rpc.thrift.TUnloadModelReq;
import org.apache.iotdb.confignode.rpc.thrift.TUnsetSchemaTemplateReq;
import org.apache.iotdb.db.conf.IoTDBDescriptor;
import org.apache.iotdb.db.exception.BatchProcessException;
@@ -199,6 +204,8 @@ import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.ShowRegion
import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.ShowTTLTask;
import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.ShowTriggersTask;
import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.ShowVariablesTask;
+import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.ai.ShowAIDevicesTask;
+import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.ai.ShowLoadedModelsTask;
import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.ai.ShowModelsTask;
import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.region.ExtendRegionTask;
import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.region.MigrateRegionTask;
@@ -3382,6 +3389,82 @@ public class ClusterConfigTaskExecutor implements IConfigTaskExecutor {
return future;
}
+ @Override
+ public SettableFuture<ConfigTaskResult> showLoadedModels(List<String> deviceIdList) {
+ final SettableFuture<ConfigTaskResult> future = SettableFuture.create();
+ try (final ConfigNodeClient client =
+ CONFIG_NODE_CLIENT_MANAGER.borrowClient(ConfigNodeInfo.CONFIG_REGION_ID)) {
+ final TShowLoadedModelReq req = new TShowLoadedModelReq();
+ if (deviceIdList != null) {
+ req.setDeviceIdList(deviceIdList);
+ }
+ final TShowLoadedModelResp resp = client.showLoadedModel(req);
+ if (resp.getStatus().getCode() != TSStatusCode.SUCCESS_STATUS.getStatusCode()) {
+ future.setException(new IoTDBException(resp.getStatus()));
+ return future;
+ }
+ ShowLoadedModelsTask.buildTsBlock(resp, future);
+ } catch (final ClientManagerException | TException e) {
+ future.setException(e);
+ }
+ return future;
+ }
+
+ @Override
+ public SettableFuture<ConfigTaskResult> showAIDevices() {
+ final SettableFuture<ConfigTaskResult> future = SettableFuture.create();
+ try (final ConfigNodeClient client =
+ CONFIG_NODE_CLIENT_MANAGER.borrowClient(ConfigNodeInfo.CONFIG_REGION_ID)) {
+ final TShowAIDevicesResp resp = client.showAIDevices();
+ if (resp.getStatus().getCode() != TSStatusCode.SUCCESS_STATUS.getStatusCode()) {
+ future.setException(new IoTDBException(resp.getStatus()));
+ return future;
+ }
+ ShowAIDevicesTask.buildTsBlock(resp, future);
+ } catch (final ClientManagerException | TException e) {
+ future.setException(e);
+ }
+ return future;
+ }
+
+ @Override
+ public SettableFuture<ConfigTaskResult> loadModel(
+ String existingModelId, List<String> deviceIdList) {
+ final SettableFuture<ConfigTaskResult> future = SettableFuture.create();
+ try (final ConfigNodeClient client =
+ CONFIG_NODE_CLIENT_MANAGER.borrowClient(ConfigNodeInfo.CONFIG_REGION_ID)) {
+ final TLoadModelReq req = new TLoadModelReq(existingModelId, deviceIdList);
+ final TSStatus result = client.loadModel(req);
+ if (TSStatusCode.SUCCESS_STATUS.getStatusCode() != result.getCode()) {
+ future.setException(new IoTDBException(result));
+ } else {
+ future.set(new ConfigTaskResult(TSStatusCode.SUCCESS_STATUS));
+ }
+ } catch (final ClientManagerException | TException e) {
+ future.setException(e);
+ }
+ return future;
+ }
+
+ @Override
+ public SettableFuture<ConfigTaskResult> unloadModel(
+ String existingModelId, List<String> deviceIdList) {
+ final SettableFuture<ConfigTaskResult> future = SettableFuture.create();
+ try (final ConfigNodeClient client =
+ CONFIG_NODE_CLIENT_MANAGER.borrowClient(ConfigNodeInfo.CONFIG_REGION_ID)) {
+ final TUnloadModelReq req = new TUnloadModelReq(existingModelId, deviceIdList);
+ final TSStatus result = client.unloadModel(req);
+ if (TSStatusCode.SUCCESS_STATUS.getStatusCode() != result.getCode()) {
+ future.setException(new IoTDBException(result));
+ } else {
+ future.set(new ConfigTaskResult(TSStatusCode.SUCCESS_STATUS));
+ }
+ } catch (final ClientManagerException | TException e) {
+ future.setException(e);
+ }
+ return future;
+ }
+
@Override
public SettableFuture<ConfigTaskResult> createTraining(
String modelId,
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/executor/IConfigTaskExecutor.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/executor/IConfigTaskExecutor.java
index 8ad06a41c51..69ee3a06f89 100644
--- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/executor/IConfigTaskExecutor.java
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/executor/IConfigTaskExecutor.java
@@ -423,6 +423,14 @@ public interface IConfigTaskExecutor {
SettableFuture<ConfigTaskResult> showModels(String modelId);
+ SettableFuture<ConfigTaskResult> showLoadedModels(List<String> deviceIdList);
+
+ SettableFuture<ConfigTaskResult> showAIDevices();
+
+ SettableFuture<ConfigTaskResult> loadModel(String existingModelId, List<String> deviceIdList);
+
+ SettableFuture<ConfigTaskResult> unloadModel(String existingModelId, List<String> deviceIdList);
+
SettableFuture<ConfigTaskResult> createTraining(
String modelId,
boolean isTableModel,
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/metadata/ai/LoadModelTask.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/metadata/ai/LoadModelTask.java
new file mode 100644
index 00000000000..eac0c737477
--- /dev/null
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/metadata/ai/LoadModelTask.java
@@ -0,0 +1,45 @@
+/*
+ * 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.config.metadata.ai;
+
+import org.apache.iotdb.db.queryengine.plan.execution.config.ConfigTaskResult;
+import org.apache.iotdb.db.queryengine.plan.execution.config.IConfigTask;
+import org.apache.iotdb.db.queryengine.plan.execution.config.executor.IConfigTaskExecutor;
+
+import com.google.common.util.concurrent.ListenableFuture;
+
+import java.util.List;
+
+public class LoadModelTask implements IConfigTask {
+
+ private final String modelId;
+ private final List<String> deviceIdList;
+
+ public LoadModelTask(String modelId, List<String> deviceIdList) {
+ this.modelId = modelId;
+ this.deviceIdList = deviceIdList;
+ }
+
+ @Override
+ public ListenableFuture<ConfigTaskResult> execute(IConfigTaskExecutor configTaskExecutor)
+ throws InterruptedException {
+ return configTaskExecutor.loadModel(modelId, deviceIdList);
+ }
+}
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/metadata/ai/ShowAIDevicesTask.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/metadata/ai/ShowAIDevicesTask.java
new file mode 100644
index 00000000000..d2cdd967595
--- /dev/null
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/metadata/ai/ShowAIDevicesTask.java
@@ -0,0 +1,64 @@
+/*
+ * 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.config.metadata.ai;
+
+import org.apache.iotdb.commons.schema.column.ColumnHeader;
+import org.apache.iotdb.commons.schema.column.ColumnHeaderConstant;
+import org.apache.iotdb.confignode.rpc.thrift.TShowAIDevicesResp;
+import org.apache.iotdb.db.queryengine.common.header.DatasetHeader;
+import org.apache.iotdb.db.queryengine.common.header.DatasetHeaderFactory;
+import org.apache.iotdb.db.queryengine.plan.execution.config.ConfigTaskResult;
+import org.apache.iotdb.db.queryengine.plan.execution.config.IConfigTask;
+import org.apache.iotdb.db.queryengine.plan.execution.config.executor.IConfigTaskExecutor;
+import org.apache.iotdb.rpc.TSStatusCode;
+
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.SettableFuture;
+import org.apache.tsfile.enums.TSDataType;
+import org.apache.tsfile.read.common.block.TsBlockBuilder;
+import org.apache.tsfile.utils.BytesUtils;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class ShowAIDevicesTask implements IConfigTask {
+
+ @Override
+ public ListenableFuture<ConfigTaskResult> execute(IConfigTaskExecutor configTaskExecutor)
+ throws InterruptedException {
+ return configTaskExecutor.showAIDevices();
+ }
+
+ public static void buildTsBlock(
+ TShowAIDevicesResp resp, SettableFuture<ConfigTaskResult> future) {
+ List<TSDataType> outputDataTypes =
+ ColumnHeaderConstant.showAIDevicesColumnHeaders.stream()
+ .map(ColumnHeader::getColumnType)
+ .collect(Collectors.toList());
+ TsBlockBuilder builder = new TsBlockBuilder(outputDataTypes);
+ for (String deviceId : resp.getDeviceIdList()) {
+ builder.getTimeColumnBuilder().writeLong(0L);
+ builder.getColumnBuilder(0).writeBinary(BytesUtils.valueOf(deviceId));
+ builder.declarePosition();
+ }
+ DatasetHeader datasetHeader = DatasetHeaderFactory.getShowAIDevicesHeader();
+ future.set(new ConfigTaskResult(TSStatusCode.SUCCESS_STATUS, builder.build(), datasetHeader));
+ }
+}
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/metadata/ai/ShowLoadedModelsTask.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/metadata/ai/ShowLoadedModelsTask.java
new file mode 100644
index 00000000000..5beb8a6a5aa
--- /dev/null
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/metadata/ai/ShowLoadedModelsTask.java
@@ -0,0 +1,78 @@
+/*
+ * 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.config.metadata.ai;
+
+import org.apache.iotdb.commons.schema.column.ColumnHeader;
+import org.apache.iotdb.commons.schema.column.ColumnHeaderConstant;
+import org.apache.iotdb.confignode.rpc.thrift.TShowLoadedModelResp;
+import org.apache.iotdb.db.queryengine.common.header.DatasetHeader;
+import org.apache.iotdb.db.queryengine.common.header.DatasetHeaderFactory;
+import org.apache.iotdb.db.queryengine.plan.execution.config.ConfigTaskResult;
+import org.apache.iotdb.db.queryengine.plan.execution.config.IConfigTask;
+import org.apache.iotdb.db.queryengine.plan.execution.config.executor.IConfigTaskExecutor;
+import org.apache.iotdb.rpc.TSStatusCode;
+
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.SettableFuture;
+import org.apache.tsfile.enums.TSDataType;
+import org.apache.tsfile.read.common.block.TsBlockBuilder;
+import org.apache.tsfile.utils.BytesUtils;
+
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+public class ShowLoadedModelsTask implements IConfigTask {
+
+ private final List<String> deviceIdList;
+
+ public ShowLoadedModelsTask(List<String> deviceIdList) {
+ this.deviceIdList = deviceIdList;
+ }
+
+ @Override
+ public ListenableFuture<ConfigTaskResult> execute(IConfigTaskExecutor configTaskExecutor)
+ throws InterruptedException {
+ return configTaskExecutor.showLoadedModels(deviceIdList);
+ }
+
+ public static void buildTsBlock(
+ TShowLoadedModelResp resp, SettableFuture<ConfigTaskResult> future) {
+ List<TSDataType> outputDataTypes =
+ ColumnHeaderConstant.showLoadedModelsColumnHeaders.stream()
+ .map(ColumnHeader::getColumnType)
+ .collect(Collectors.toList());
+ TsBlockBuilder builder = new TsBlockBuilder(outputDataTypes);
+ for (String deviceId : resp.getDeviceLoadedModelsMap().keySet()) {
+ for (Map.Entry<String, Integer> instanceEntry :
+ resp.getDeviceLoadedModelsMap().get(deviceId).entrySet()) {
+ String modelId = instanceEntry.getKey();
+ Integer count = instanceEntry.getValue();
+ builder.getTimeColumnBuilder().writeLong(0L);
+ builder.getColumnBuilder(0).writeBinary(BytesUtils.valueOf(deviceId));
+ builder.getColumnBuilder(1).writeBinary(BytesUtils.valueOf(modelId));
+ builder.getColumnBuilder(2).writeInt(count);
+ builder.declarePosition();
+ }
+ }
+ DatasetHeader datasetHeader = DatasetHeaderFactory.getShowLoadedModelsHeader();
+ future.set(new ConfigTaskResult(TSStatusCode.SUCCESS_STATUS, builder.build(), datasetHeader));
+ }
+}
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/metadata/ai/UnloadModelTask.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/metadata/ai/UnloadModelTask.java
new file mode 100644
index 00000000000..528a6c49373
--- /dev/null
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/metadata/ai/UnloadModelTask.java
@@ -0,0 +1,45 @@
+/*
+ * 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.config.metadata.ai;
+
+import org.apache.iotdb.db.queryengine.plan.execution.config.ConfigTaskResult;
+import org.apache.iotdb.db.queryengine.plan.execution.config.IConfigTask;
+import org.apache.iotdb.db.queryengine.plan.execution.config.executor.IConfigTaskExecutor;
+
+import com.google.common.util.concurrent.ListenableFuture;
+
+import java.util.List;
+
+public class UnloadModelTask implements IConfigTask {
+
+ private final String modelId;
+ private final List<String> deviceIdList;
+
+ public UnloadModelTask(String modelId, List<String> deviceIdList) {
+ this.modelId = modelId;
+ this.deviceIdList = deviceIdList;
+ }
+
+ @Override
+ public ListenableFuture<ConfigTaskResult> execute(IConfigTaskExecutor configTaskExecutor)
+ throws InterruptedException {
+ return configTaskExecutor.unloadModel(modelId, deviceIdList);
+ }
+}
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/parser/ASTVisitor.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/parser/ASTVisitor.java
index 328cb6c5e18..73f1bb0ffbe 100644
--- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/parser/ASTVisitor.java
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/parser/ASTVisitor.java
@@ -188,8 +188,12 @@ import org.apache.iotdb.db.queryengine.plan.statement.metadata.UnSetTTLStatement
import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.CreateModelStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.CreateTrainingStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.DropModelStatement;
+import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.LoadModelStatement;
+import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.ShowAIDevicesStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.ShowAINodesStatement;
+import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.ShowLoadedModelsStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.ShowModelsStatement;
+import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.UnloadModelStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.pipe.AlterPipeStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.pipe.CreatePipePluginStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.pipe.CreatePipeStatement;
@@ -267,6 +271,8 @@ import org.apache.tsfile.file.metadata.enums.CompressionType;
import org.apache.tsfile.file.metadata.enums.TSEncoding;
import org.apache.tsfile.read.common.TimeRange;
import org.apache.tsfile.utils.TimeDuration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import java.io.FileNotFoundException;
import java.net.URI;
@@ -314,6 +320,8 @@ import static org.apache.iotdb.db.utils.constant.SqlConstant.SUBSTRING_START;
/** Parse AST to Statement. */
public class ASTVisitor extends IoTDBSqlParserBaseVisitor<Statement> {
+ private static final Logger LOGGER = LoggerFactory.getLogger(ASTVisitor.class);
+
private static final IoTDBConfig CONFIG = IoTDBDescriptor.getInstance().getConfig();
private static final String DELETE_RANGE_ERROR_MSG =
@@ -1367,6 +1375,27 @@ public class ASTVisitor extends IoTDBSqlParserBaseVisitor<Statement> {
}
}
+ private static List<String> convertToDeviceIdList(Token rawDeviceString) {
+ String rawString = rawDeviceString.getText();
+ rawString = rawString.substring(1, rawString.length() - 1);
+ String[] deviceIdList = rawString.split(",");
+ List<String> result = new ArrayList<>();
+ for (String deviceId : deviceIdList) {
+ deviceId = deviceId.trim();
+ if (deviceId.equals("cpu")) {
+ result.add("cpu");
+ continue;
+ }
+ try {
+ Integer.valueOf(deviceId);
+ } catch (NumberFormatException e) {
+ throw new SemanticException("Device id should be 'cpu' or integer");
+ }
+ result.add(deviceId);
+ }
+ return result;
+ }
+
@Override
public Statement visitCreateModel(IoTDBSqlParser.CreateModelContext ctx) {
if (ctx.uriClause() == null) {
@@ -1415,6 +1444,22 @@ public class ASTVisitor extends IoTDBSqlParserBaseVisitor<Statement> {
return createModelStatement;
}
+ @Override
+ public Statement visitLoadModel(IoTDBSqlParser.LoadModelContext ctx) {
+ String modelId = parseIdentifier(ctx.existingModelId.getText());
+ validateModelId(modelId);
+ List<String> deviceIdList = convertToDeviceIdList(ctx.deviceIdList);
+ return new LoadModelStatement(modelId, deviceIdList);
+ }
+
+ @Override
+ public Statement visitUnloadModel(IoTDBSqlParser.UnloadModelContext ctx) {
+ String modelId = parseIdentifier(ctx.existingModelId.getText());
+ validateModelId(modelId);
+ List<String> deviceIdList = convertToDeviceIdList(ctx.deviceIdList);
+ return new UnloadModelStatement(modelId, deviceIdList);
+ }
+
// Drop Model =====================================================================
@Override
public Statement visitDropModel(IoTDBSqlParser.DropModelContext ctx) {
@@ -1431,6 +1476,16 @@ public class ASTVisitor extends IoTDBSqlParserBaseVisitor<Statement> {
return statement;
}
+ @Override
+ public Statement visitShowLoadedModels(IoTDBSqlParser.ShowLoadedModelsContext ctx) {
+ return new ShowLoadedModelsStatement(
+ ctx.deviceIdList != null ? convertToDeviceIdList(ctx.deviceIdList) : null);
+ }
+
+ public Statement visitShowAIDevices(IoTDBSqlParser.ShowAIDevicesContext ctx) {
+ return new ShowAIDevicesStatement();
+ }
+
/** Data Manipulation Language (DML). */
// Select Statement ========================================================================
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/ast/AstVisitor.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/ast/AstVisitor.java
index 80b5642fd6e..546320dbc53 100644
--- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/ast/AstVisitor.java
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/ast/AstVisitor.java
@@ -741,6 +741,22 @@ public abstract class AstVisitor<R, C> {
return visitStatement(node, context);
}
+ protected R visitShowLoadedModels(ShowLoadedModels node, C context) {
+ return visitStatement(node, context);
+ }
+
+ protected R visitShowAIDevices(ShowAIDevices node, C context) {
+ return visitStatement(node, context);
+ }
+
+ protected R visitLoadModel(LoadModel node, C context) {
+ return visitStatement(node, context);
+ }
+
+ protected R visitUnloadModel(UnloadModel node, C context) {
+ return visitStatement(node, context);
+ }
+
protected R visitDropModel(DropModel node, C context) {
return visitStatement(node, context);
}
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/ast/LoadModel.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/ast/LoadModel.java
new file mode 100644
index 00000000000..519510043dc
--- /dev/null
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/ast/LoadModel.java
@@ -0,0 +1,73 @@
+/*
+ * 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.relational.sql.ast;
+
+import java.util.List;
+import java.util.Objects;
+
+public class LoadModel extends Statement {
+
+ private final String modelId;
+ private final List<String> deviceIdList;
+
+ public LoadModel(String modelId, List<String> deviceIdList) {
+ super(null);
+ this.modelId = modelId;
+ this.deviceIdList = deviceIdList;
+ }
+
+ public String getModelId() {
+ return modelId;
+ }
+
+ public List<String> getDeviceIdList() {
+ return deviceIdList;
+ }
+
+ @Override
+ public <R, C> R accept(AstVisitor<R, C> visitor, C context) {
+ return visitor.visitLoadModel(this, context);
+ }
+
+ @Override
+ public List<? extends Node> getChildren() {
+ return null;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ LoadModel loadModel = (LoadModel) o;
+ return Objects.equals(modelId, loadModel.modelId)
+ && Objects.equals(deviceIdList, loadModel.deviceIdList);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(modelId, deviceIdList);
+ }
+
+ @Override
+ public String toString() {
+ return "LoadModel{" + "modelId='" + modelId + '\'' + ", deviceIdList=" + deviceIdList + '}';
+ }
+}
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/ast/ShowAIDevices.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/ast/ShowAIDevices.java
new file mode 100644
index 00000000000..40fec58b2f0
--- /dev/null
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/ast/ShowAIDevices.java
@@ -0,0 +1,59 @@
+/*
+ * 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.relational.sql.ast;
+
+import java.util.List;
+
+import static com.google.common.base.MoreObjects.toStringHelper;
+
+public class ShowAIDevices extends Statement {
+
+ public ShowAIDevices() {
+ super(null);
+ }
+
+ @Override
+ public <R, C> R accept(AstVisitor<R, C> visitor, C context) {
+ return visitor.visitShowAIDevices(this, context);
+ }
+
+ @Override
+ public List<? extends Node> getChildren() {
+ return null;
+ }
+
+ @Override
+ public int hashCode() {
+ return 0;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ return (obj != null) && (getClass() == obj.getClass());
+ }
+
+ @Override
+ public String toString() {
+ return toStringHelper(this).toString();
+ }
+}
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/ast/ShowLoadedModels.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/ast/ShowLoadedModels.java
new file mode 100644
index 00000000000..99dd60afd87
--- /dev/null
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/ast/ShowLoadedModels.java
@@ -0,0 +1,66 @@
+/*
+ * 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.relational.sql.ast;
+
+import java.util.List;
+import java.util.Objects;
+
+public class ShowLoadedModels extends Statement {
+
+ private final List<String> deviceIdList;
+
+ public ShowLoadedModels(List<String> deviceIdList) {
+ super(null);
+ this.deviceIdList = deviceIdList;
+ }
+
+ public List<String> getDeviceIdList() {
+ return deviceIdList;
+ }
+
+ @Override
+ public <R, C> R accept(AstVisitor<R, C> visitor, C context) {
+ return visitor.visitShowLoadedModels(this, context);
+ }
+
+ @Override
+ public List<? extends Node> getChildren() {
+ return null;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ ShowLoadedModels that = (ShowLoadedModels) o;
+ return Objects.equals(deviceIdList, that.deviceIdList);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hashCode(deviceIdList);
+ }
+
+ @Override
+ public String toString() {
+ return "ShowLoadedModels{" + "deviceIdList=" + deviceIdList + '}';
+ }
+}
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/ast/UnloadModel.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/ast/UnloadModel.java
new file mode 100644
index 00000000000..4922d248b59
--- /dev/null
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/ast/UnloadModel.java
@@ -0,0 +1,72 @@
+/*
+ * 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.relational.sql.ast;
+
+import java.util.List;
+import java.util.Objects;
+
+public class UnloadModel extends Statement {
+
+ private final String modelId;
+ private final List<String> deviceIdList;
+
+ public UnloadModel(String modelId, List<String> deviceIdList) {
+ super(null);
+ this.modelId = modelId;
+ this.deviceIdList = deviceIdList;
+ }
+
+ public String getModelId() {
+ return modelId;
+ }
+
+ public List<String> getDeviceIdList() {
+ return deviceIdList;
+ }
+
+ @Override
+ public <R, C> R accept(AstVisitor<R, C> visitor, C context) {
+ return visitor.visitUnloadModel(this, context);
+ }
+
+ @Override
+ public List<? extends Node> getChildren() {
+ return null;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ UnloadModel that = (UnloadModel) o;
+ return Objects.equals(modelId, that.modelId) && Objects.equals(deviceIdList, that.deviceIdList);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(modelId, deviceIdList);
+ }
+
+ @Override
+ public String toString() {
+ return "UnloadModel{" + "modelId='" + modelId + '\'' + ", deviceIdList=" + deviceIdList + '}';
+ }
+}
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/parser/AstBuilder.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/parser/AstBuilder.java
index a24d9a11db9..644a8de0472 100644
--- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/parser/AstBuilder.java
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/parser/AstBuilder.java
@@ -120,6 +120,7 @@ import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.LikePredicate;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.Limit;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.Literal;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.LoadConfiguration;
+import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.LoadModel;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.LoadTsFile;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.LogicalExpression;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.LongLiteral;
@@ -172,6 +173,7 @@ import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.SetProperties;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.SetSqlDialect;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.SetSystemStatus;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.SetTableComment;
+import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowAIDevices;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowAINodes;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowCluster;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowClusterId;
@@ -185,6 +187,7 @@ import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowDataNodes;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowDevice;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowFunctions;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowIndex;
+import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowLoadedModels;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowModels;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowPipePlugins;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowPipes;
@@ -218,6 +221,7 @@ import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.TableSubquery;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.Trim;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.TypeParameter;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.Union;
+import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.UnloadModel;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.Update;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.UpdateAssignment;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.Use;
@@ -3585,6 +3589,25 @@ public class AstBuilder extends RelationalSqlBaseVisitor<Node> {
}
}
+ private static List<String> convertToDeviceIdList(String rawDeviceString) {
+ String[] deviceIdList = rawDeviceString.split(",");
+ List<String> result = new ArrayList<>();
+ for (String deviceId : deviceIdList) {
+ deviceId = deviceId.trim();
+ if (deviceId.equals("cpu")) {
+ result.add("cpu");
+ continue;
+ }
+ try {
+ Integer.valueOf(deviceId);
+ } catch (NumberFormatException e) {
+ throw new SemanticException("Device id should be 'cpu' or integer");
+ }
+ result.add(deviceId);
+ }
+ return result;
+ }
+
@Override
public Node visitCreateModelStatement(RelationalSqlParser.CreateModelStatementContext ctx) {
String modelId = ctx.modelId.getText();
@@ -3614,6 +3637,22 @@ public class AstBuilder extends RelationalSqlBaseVisitor<Node> {
return new CreateModel(modelId, uri);
}
+ @Override
+ public Node visitLoadModelStatement(RelationalSqlParser.LoadModelStatementContext ctx) {
+ List<String> deviceIds = convertToDeviceIdList(unquote(ctx.deviceIdList.getText()));
+ String modelId = ctx.existingModelId.getText();
+ validateModelId(modelId);
+ return new LoadModel(modelId, deviceIds);
+ }
+
+ @Override
+ public Node visitUnloadModelStatement(RelationalSqlParser.UnloadModelStatementContext ctx) {
+ List<String> deviceIds = convertToDeviceIdList(unquote(ctx.deviceIdList.getText()));
+ String modelId = ctx.existingModelId.getText();
+ validateModelId(modelId);
+ return new UnloadModel(modelId, deviceIds);
+ }
+
@Override
public Node visitShowModelsStatement(RelationalSqlParser.ShowModelsStatementContext ctx) {
ShowModels showModels = new ShowModels();
@@ -3625,6 +3664,20 @@ public class AstBuilder extends RelationalSqlBaseVisitor<Node> {
return showModels;
}
+ @Override
+ public Node visitShowLoadedModelsStatement(
+ RelationalSqlParser.ShowLoadedModelsStatementContext ctx) {
+ return new ShowLoadedModels(
+ ctx.deviceIdList != null
+ ? convertToDeviceIdList(unquote(ctx.deviceIdList.getText()))
+ : null);
+ }
+
+ @Override
+ public Node visitShowAIDevicesStatement(RelationalSqlParser.ShowAIDevicesStatementContext ctx) {
+ return new ShowAIDevices();
+ }
+
@Override
public Node visitDropModelStatement(RelationalSqlParser.DropModelStatementContext ctx) {
String modelId = ctx.modelId.getText();
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/statement/StatementVisitor.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/statement/StatementVisitor.java
index 588c4dd9892..d2da4814541 100644
--- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/statement/StatementVisitor.java
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/statement/StatementVisitor.java
@@ -79,8 +79,12 @@ import org.apache.iotdb.db.queryengine.plan.statement.metadata.UnSetTTLStatement
import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.CreateModelStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.CreateTrainingStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.DropModelStatement;
+import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.LoadModelStatement;
+import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.ShowAIDevicesStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.ShowAINodesStatement;
+import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.ShowLoadedModelsStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.ShowModelsStatement;
+import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.UnloadModelStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.pipe.AlterPipeStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.pipe.CreatePipePluginStatement;
import org.apache.iotdb.db.queryengine.plan.statement.metadata.pipe.CreatePipeStatement;
@@ -311,6 +315,22 @@ public abstract class StatementVisitor<R, C> {
return visitStatement(showModelsModelStatement, context);
}
+ public R visitShowLoadedModels(ShowLoadedModelsStatement showLoadedModelsStatement, C context) {
+ return visitStatement(showLoadedModelsStatement, context);
+ }
+
+ public R visitShowAIDevices(ShowAIDevicesStatement showAIDevicesStatement, C context) {
+ return visitStatement(showAIDevicesStatement, context);
+ }
+
+ public R visitLoadModel(LoadModelStatement loadModelStatement, C context) {
+ return visitStatement(loadModelStatement, context);
+ }
+
+ public R visitUnloadModel(UnloadModelStatement unloadModelStatement, C context) {
+ return visitStatement(unloadModelStatement, context);
+ }
+
/** Data Manipulation Language (DML) */
// Select Statement
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/statement/metadata/model/LoadModelStatement.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/statement/metadata/model/LoadModelStatement.java
new file mode 100644
index 00000000000..e3e2e3bc4f4
--- /dev/null
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/statement/metadata/model/LoadModelStatement.java
@@ -0,0 +1,89 @@
+/*
+ * 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.statement.metadata.model;
+
+import org.apache.iotdb.commons.path.PartialPath;
+import org.apache.iotdb.db.queryengine.plan.analyze.QueryType;
+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.StatementVisitor;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+
+public class LoadModelStatement extends Statement implements IConfigStatement {
+
+ private final String modelId;
+ private final List<String> deviceIdList;
+
+ public LoadModelStatement(String modelId, List<String> deviceIdList) {
+ this.modelId = modelId;
+ this.deviceIdList = deviceIdList;
+ }
+
+ public String getModelId() {
+ return modelId;
+ }
+
+ public List<String> getDeviceIdList() {
+ return deviceIdList;
+ }
+
+ @Override
+ public QueryType getQueryType() {
+ return QueryType.WRITE;
+ }
+
+ @Override
+ public List<? extends PartialPath> getPaths() {
+ return Collections.emptyList();
+ }
+
+ @Override
+ public <R, C> R accept(StatementVisitor<R, C> visitor, C context) {
+ return visitor.visitLoadModel(this, context);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ LoadModelStatement that = (LoadModelStatement) o;
+ return Objects.equals(modelId, that.modelId) && Objects.equals(deviceIdList, that.deviceIdList);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(modelId, deviceIdList);
+ }
+
+ @Override
+ public String toString() {
+ return "LoadModelStatement{"
+ + "modelId='"
+ + modelId
+ + '\''
+ + ", deviceIdList="
+ + deviceIdList
+ + '}';
+ }
+}
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/statement/metadata/model/ShowAIDevicesStatement.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/statement/metadata/model/ShowAIDevicesStatement.java
new file mode 100644
index 00000000000..37156c621d7
--- /dev/null
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/statement/metadata/model/ShowAIDevicesStatement.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.db.queryengine.plan.statement.metadata.model;
+
+import org.apache.iotdb.commons.path.PartialPath;
+import org.apache.iotdb.db.queryengine.plan.analyze.QueryType;
+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.StatementVisitor;
+
+import java.util.Collections;
+import java.util.List;
+
+public class ShowAIDevicesStatement extends Statement implements IConfigStatement {
+
+ public ShowAIDevicesStatement() {
+ // Do nothing
+ }
+
+ @Override
+ public <R, C> R accept(StatementVisitor<R, C> visitor, C context) {
+ return visitor.visitShowAIDevices(this, context);
+ }
+
+ @Override
+ public QueryType getQueryType() {
+ return QueryType.READ;
+ }
+
+ @Override
+ public List<? extends PartialPath> getPaths() {
+ return Collections.emptyList();
+ }
+}
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/statement/metadata/model/ShowLoadedModelsStatement.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/statement/metadata/model/ShowLoadedModelsStatement.java
new file mode 100644
index 00000000000..dab7524c10c
--- /dev/null
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/statement/metadata/model/ShowLoadedModelsStatement.java
@@ -0,0 +1,77 @@
+/*
+ * 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.statement.metadata.model;
+
+import org.apache.iotdb.commons.path.PartialPath;
+import org.apache.iotdb.db.queryengine.plan.analyze.QueryType;
+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.StatementVisitor;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+
+public class ShowLoadedModelsStatement extends Statement implements IConfigStatement {
+
+ private final List<String> deviceIdList;
+
+ public ShowLoadedModelsStatement(List<String> deviceIdList) {
+ this.deviceIdList = deviceIdList;
+ }
+
+ public List<String> getDeviceIdList() {
+ return deviceIdList;
+ }
+
+ @Override
+ public QueryType getQueryType() {
+ return QueryType.READ;
+ }
+
+ @Override
+ public List<? extends PartialPath> getPaths() {
+ return Collections.emptyList();
+ }
+
+ @Override
+ public <R, C> R accept(StatementVisitor<R, C> visitor, C context) {
+ return visitor.visitShowLoadedModels(this, context);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ ShowLoadedModelsStatement that = (ShowLoadedModelsStatement) o;
+ return Objects.equals(deviceIdList, that.deviceIdList);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hashCode(deviceIdList);
+ }
+
+ @Override
+ public String toString() {
+ return "ShowLoadedModelsStatement{" + "deviceIdList=" + deviceIdList + '}';
+ }
+}
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/statement/metadata/model/UnloadModelStatement.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/statement/metadata/model/UnloadModelStatement.java
new file mode 100644
index 00000000000..be5057a8f00
--- /dev/null
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/statement/metadata/model/UnloadModelStatement.java
@@ -0,0 +1,89 @@
+/*
+ * 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.statement.metadata.model;
+
+import org.apache.iotdb.commons.path.PartialPath;
+import org.apache.iotdb.db.queryengine.plan.analyze.QueryType;
+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.StatementVisitor;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+
+public class UnloadModelStatement extends Statement implements IConfigStatement {
+
+ private final String modelId;
+ private final List<String> deviceIdList;
+
+ public UnloadModelStatement(String modelId, List<String> deviceIdList) {
+ this.modelId = modelId;
+ this.deviceIdList = deviceIdList;
+ }
+
+ public String getModelId() {
+ return modelId;
+ }
+
+ public List<String> getDeviceIdList() {
+ return deviceIdList;
+ }
+
+ @Override
+ public QueryType getQueryType() {
+ return QueryType.WRITE;
+ }
+
+ @Override
+ public List<? extends PartialPath> getPaths() {
+ return Collections.emptyList();
+ }
+
+ @Override
+ public <R, C> R accept(StatementVisitor<R, C> visitor, C context) {
+ return visitor.visitUnloadModel(this, context);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ UnloadModelStatement that = (UnloadModelStatement) o;
+ return Objects.equals(modelId, that.modelId) && Objects.equals(deviceIdList, that.deviceIdList);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(modelId, deviceIdList);
+ }
+
+ @Override
+ public String toString() {
+ return "UnloadModelStatement{"
+ + "modelId='"
+ + modelId
+ + '\''
+ + ", deviceIdList="
+ + deviceIdList
+ + '}';
+ }
+}
diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/client/ainode/AINodeClient.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/client/ainode/AINodeClient.java
index 99479256664..d82647c141a 100644
--- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/client/ainode/AINodeClient.java
+++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/client/ainode/AINodeClient.java
@@ -26,11 +26,16 @@ import org.apache.iotdb.ainode.rpc.thrift.TForecastReq;
import org.apache.iotdb.ainode.rpc.thrift.TForecastResp;
import org.apache.iotdb.ainode.rpc.thrift.TInferenceReq;
import org.apache.iotdb.ainode.rpc.thrift.TInferenceResp;
+import org.apache.iotdb.ainode.rpc.thrift.TLoadModelReq;
import org.apache.iotdb.ainode.rpc.thrift.TRegisterModelReq;
import org.apache.iotdb.ainode.rpc.thrift.TRegisterModelResp;
+import org.apache.iotdb.ainode.rpc.thrift.TShowAIDevicesResp;
+import org.apache.iotdb.ainode.rpc.thrift.TShowLoadedModelsReq;
+import org.apache.iotdb.ainode.rpc.thrift.TShowLoadedModelsResp;
import org.apache.iotdb.ainode.rpc.thrift.TShowModelsReq;
import org.apache.iotdb.ainode.rpc.thrift.TShowModelsResp;
import org.apache.iotdb.ainode.rpc.thrift.TTrainingReq;
+import org.apache.iotdb.ainode.rpc.thrift.TUnloadModelReq;
import org.apache.iotdb.ainode.rpc.thrift.TWindowParams;
import org.apache.iotdb.common.rpc.thrift.TEndPoint;
import org.apache.iotdb.common.rpc.thrift.TSStatus;
@@ -175,6 +180,30 @@ public class AINodeClient implements AutoCloseable, ThriftClient {
}
}
+ public TSStatus loadModel(TLoadModelReq req) throws TException {
+ try {
+ return client.loadModel(req);
+ } catch (TException e) {
+ logger.warn(
+ "Failed to connect to AINode from ConfigNode when executing {}: {}",
+ Thread.currentThread().getStackTrace()[1].getMethodName(),
+ e.getMessage());
+ throw new TException(MSG_CONNECTION_FAIL);
+ }
+ }
+
+ public TSStatus unloadModel(TUnloadModelReq req) throws TException {
+ try {
+ return client.unloadModel(req);
+ } catch (TException e) {
+ logger.warn(
+ "Failed to connect to AINode from ConfigNode when executing {}: {}",
+ Thread.currentThread().getStackTrace()[1].getMethodName(),
+ e.getMessage());
+ throw new TException(MSG_CONNECTION_FAIL);
+ }
+ }
+
public TShowModelsResp showModels(TShowModelsReq req) throws TException {
try {
return client.showModels(req);
@@ -187,6 +216,30 @@ public class AINodeClient implements AutoCloseable, ThriftClient {
}
}
+ public TShowLoadedModelsResp showLoadedModels(TShowLoadedModelsReq req) throws TException {
+ try {
+ return client.showLoadedModels(req);
+ } catch (TException e) {
+ logger.warn(
+ "Failed to connect to AINode from ConfigNode when executing {}: {}",
+ Thread.currentThread().getStackTrace()[1].getMethodName(),
+ e.getMessage());
+ throw new TException(MSG_CONNECTION_FAIL);
+ }
+ }
+
+ public TShowAIDevicesResp showAIDevices() throws TException {
+ try {
+ return client.showAIDevices();
+ } catch (TException e) {
+ logger.warn(
+ "Failed to connect to AINode from ConfigNode when executing {}: {}",
+ Thread.currentThread().getStackTrace()[1].getMethodName(),
+ e.getMessage());
+ throw new TException(MSG_CONNECTION_FAIL);
+ }
+ }
+
public TInferenceResp inference(
String modelId,
TsBlock inputTsBlock,
diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/schema/column/ColumnHeaderConstant.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/schema/column/ColumnHeaderConstant.java
index ff6e9bc42a6..1e2812fe9b3 100644
--- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/schema/column/ColumnHeaderConstant.java
+++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/schema/column/ColumnHeaderConstant.java
@@ -35,6 +35,7 @@ public class ColumnHeaderConstant {
public static final String ENDTIME = "__endTime";
public static final String VALUE = "Value";
public static final String DEVICE = "Device";
+ public static final String DEVICE_ID = "DeviceID";
public static final String EXPLAIN_ANALYZE = "Explain Analyze";
// column names for schema statement
@@ -80,6 +81,7 @@ public class ColumnHeaderConstant {
public static final String COUNT_NODES = "count(nodes)";
public static final String COUNT_TIMESERIES = "count(timeseries)";
public static final String COUNT_DATABASE = "count(database)";
+ public static final String COUNT_INSTANCES = "Count(instances)";
// column names for show cluster and show cluster details statements
public static final String NODE_ID = "NodeID";
@@ -622,6 +624,15 @@ public class ColumnHeaderConstant {
new ColumnHeader(COLUMN_CATEGORY, TSDataType.TEXT),
new ColumnHeader(STATE, TSDataType.TEXT));
+ public static final List<ColumnHeader> showLoadedModelsColumnHeaders =
+ ImmutableList.of(
+ new ColumnHeader(DEVICE_ID, TSDataType.TEXT),
+ new ColumnHeader(MODEL_TYPE, TSDataType.TEXT),
+ new ColumnHeader(COUNT_INSTANCES, TSDataType.INT32));
+
+ public static final List<ColumnHeader> showAIDevicesColumnHeaders =
+ ImmutableList.of(new ColumnHeader(DEVICE_ID, TSDataType.TEXT));
+
public static final List<ColumnHeader> showLogicalViewColumnHeaders =
ImmutableList.of(
new ColumnHeader(TIMESERIES, TSDataType.TEXT),
diff --git a/iotdb-core/relational-grammar/src/main/antlr4/org/apache/iotdb/db/relational/grammar/sql/RelationalSql.g4 b/iotdb-core/relational-grammar/src/main/antlr4/org/apache/iotdb/db/relational/grammar/sql/RelationalSql.g4
index 8aa8ac380d2..785fddc1ea5 100644
--- a/iotdb-core/relational-grammar/src/main/antlr4/org/apache/iotdb/db/relational/grammar/sql/RelationalSql.g4
+++ b/iotdb-core/relational-grammar/src/main/antlr4/org/apache/iotdb/db/relational/grammar/sql/RelationalSql.g4
@@ -165,6 +165,10 @@ statement
| createModelStatement
| dropModelStatement
| showModelsStatement
+ | showLoadedModelsStatement
+ | showAIDevicesStatement
+ | loadModelStatement
+ | unloadModelStatement
// View, Trigger, CQ, Quota are not supported yet
;
@@ -805,6 +809,23 @@ showModelsStatement
| SHOW MODELS modelId=identifier
;
+showLoadedModelsStatement
+ : SHOW LOADED MODELS
+ | SHOW LOADED MODELS deviceIdList=string
+ ;
+
+showAIDevicesStatement
+ : SHOW AI_DEVICES
+ ;
+
+loadModelStatement
+ : LOAD MODEL existingModelId=identifier TO DEVICES deviceIdList=string
+ ;
+
+unloadModelStatement
+ : UNLOAD MODEL existingModelId=identifier FROM DEVICES deviceIdList=string
+ ;
+
// ------------------------------------------- Query Statement ---------------------------------------------------------
queryStatement
: query #statementDefault
@@ -1380,6 +1401,7 @@ ADMIN: 'ADMIN';
AFTER: 'AFTER';
AINODE: 'AINODE';
AINODES: 'AINODES';
+AI_DEVICES: 'AI_DEVICES';
ALL: 'ALL';
ALTER: 'ALTER';
ANALYZE: 'ANALYZE';
@@ -1556,6 +1578,7 @@ LINEAR: 'LINEAR';
LIST: 'LIST';
LISTAGG: 'LISTAGG';
LOAD: 'LOAD';
+LOADED: 'LOADED';
LOCAL: 'LOCAL';
LOCALTIME: 'LOCALTIME';
LOCALTIMESTAMP: 'LOCALTIMESTAMP';
@@ -1735,6 +1758,7 @@ UNCONDITIONAL: 'UNCONDITIONAL';
UNION: 'UNION';
UNIQUE: 'UNIQUE';
UNKNOWN: 'UNKNOWN';
+UNLOAD: 'UNLOAD';
UNMATCHED: 'UNMATCHED';
UNNEST: 'UNNEST';
UNTIL: 'UNTIL';
diff --git a/iotdb-protocol/thrift-ainode/src/main/thrift/ainode.thrift b/iotdb-protocol/thrift-ainode/src/main/thrift/ainode.thrift
index e09d0360c84..c53b482ef77 100644
--- a/iotdb-protocol/thrift-ainode/src/main/thrift/ainode.thrift
+++ b/iotdb-protocol/thrift-ainode/src/main/thrift/ainode.thrift
@@ -111,6 +111,30 @@ struct TShowModelsResp {
5: optional map<string, string> stateMap
}
+struct TShowLoadedModelsReq {
+ 1: optional list<string> deviceIdList
+}
+
+struct TShowLoadedModelsResp {
+ 1: required common.TSStatus status
+ 2: required map<string, map<string, i32>> deviceLoadedModelsMap
+}
+
+struct TShowAIDevicesResp {
+ 1: required common.TSStatus status
+ 2: required list<string> deviceIdList
+}
+
+struct TLoadModelReq {
+ 1: required string existingModelId
+ 2: required list<string> deviceIdList
+}
+
+struct TUnloadModelReq {
+ 1: required string modelId
+ 2: required list<string> deviceIdList
+}
+
service IAINodeRPCService {
// -------------- For Config Node --------------
@@ -118,6 +142,10 @@ service IAINodeRPCService {
TShowModelsResp showModels(TShowModelsReq req)
+ TShowLoadedModelsResp showLoadedModels(TShowLoadedModelsReq req)
+
+ TShowAIDevicesResp showAIDevices()
+
common.TSStatus deleteModel(TDeleteModelReq req)
TRegisterModelResp registerModel(TRegisterModelReq req)
@@ -126,6 +154,10 @@ service IAINodeRPCService {
common.TSStatus createTrainingTask(TTrainingReq req)
+ common.TSStatus loadModel(TLoadModelReq req)
+
+ common.TSStatus unloadModel(TUnloadModelReq req)
+
// -------------- For Data Node --------------
TInferenceResp inference(TInferenceReq req)
diff --git a/iotdb-protocol/thrift-confignode/src/main/thrift/confignode.thrift b/iotdb-protocol/thrift-confignode/src/main/thrift/confignode.thrift
index b869d29cde3..18655a31a11 100644
--- a/iotdb-protocol/thrift-confignode/src/main/thrift/confignode.thrift
+++ b/iotdb-protocol/thrift-confignode/src/main/thrift/confignode.thrift
@@ -1070,6 +1070,30 @@ struct TShowModelResp {
5: optional map<string, string> stateMap
}
+struct TShowLoadedModelReq {
+ 1: optional list<string> deviceIdList
+}
+
+struct TShowLoadedModelResp {
+ 1: required common.TSStatus status
+ 2: required map<string, map<string, i32>> deviceLoadedModelsMap
+}
+
+struct TShowAIDevicesResp {
+ 1: required common.TSStatus status
+ 2: required list<string> deviceIdList
+}
+
+struct TLoadModelReq {
+ 1: required string existingModelId
+ 2: required list<string> deviceIdList
+}
+
+struct TUnloadModelReq {
+ 1: required string modelId
+ 2: required list<string> deviceIdList
+}
+
struct TGetModelInfoReq {
1: required string modelId
}
@@ -1984,6 +2008,30 @@ service IConfigNodeRPCService {
*/
TShowModelResp showModel(TShowModelReq req)
+ /**
+ * Return the loaded model table
+ */
+ TShowLoadedModelResp showLoadedModel(TShowLoadedModelReq req)
+
+ /**
+ * Return the available ai devices
+ */
+ TShowAIDevicesResp showAIDevices()
+
+ /**
+ * Load an existing model to specific devices
+ *
+ * @return SUCCESS_STATUS if the model loading task was submitted successfully
+ */
+ common.TSStatus loadModel(TLoadModelReq req)
+
+ /**
+ * Unload an existing model to specific devices
+ *
+ * @return SUCCESS_STATUS if the model unloading task was submitted successfully
+ */
+ common.TSStatus unloadModel(TUnloadModelReq req)
+
/**
* Return the model info by model_id
*/