You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@iotdb.apache.org by GitBox <gi...@apache.org> on 2021/01/04 02:41:00 UTC

[GitHub] [iotdb] JackieTien97 commented on a change in pull request #2352: [IOTDB-965] Add timeout in query

JackieTien97 commented on a change in pull request #2352:
URL: https://github.com/apache/iotdb/pull/2352#discussion_r550428530



##########
File path: jdbc/src/main/java/org/apache/iotdb/jdbc/IoTDBStatement.java
##########
@@ -48,7 +48,7 @@
   private ResultSet resultSet = null;
   private IoTDBConnection connection;
   private int fetchSize;
-  private int queryTimeout = 10;
+  private int queryTimeout = 60;

Review comment:
       better to add a comment to indicate the unit is second.

##########
File path: server/src/assembly/resources/conf/iotdb-engine.properties
##########
@@ -367,6 +367,9 @@ compaction_thread_num=10
 # The limit of write throughput merge can reach per second
 merge_write_throughput_mb_per_sec=8
 
+# The max executing time of query.
+query_time_threshold=60000

Review comment:
       Specify the unit in comment.

##########
File path: server/src/main/java/org/apache/iotdb/db/query/dataset/NonAlignEngineDataSet.java
##########
@@ -286,6 +293,11 @@ public TSQueryNonAlignDataSet fillBuffer(int fetchSize, WatermarkEncoder encoder
 
     for (int seriesIndex = 0; seriesIndex < seriesNum; seriesIndex++) {
       if (!noMoreDataInQueueArray[seriesIndex]) {
+        // check the interrupted status of main thread before take next batch
+        if (Thread.interrupted()) {

Review comment:
       The static method `interrupted()` in `Thread` class will clear the interrupt flag, you should call the instance method `isInterrupted()`.

##########
File path: server/src/main/java/org/apache/iotdb/db/query/control/QueryTimeManager.java
##########
@@ -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.
+ */
+package org.apache.iotdb.db.query.control;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import org.apache.iotdb.db.concurrent.IoTDBThreadPoolFactory;
+import org.apache.iotdb.db.exception.query.QueryTimeoutRuntimeException;
+import org.apache.iotdb.db.service.IService;
+import org.apache.iotdb.db.service.ServiceType;
+import org.apache.iotdb.tsfile.utils.Pair;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class is used to monitor the executing time of each query.
+ * </p>
+ * Once one is over the threshold, it will be killed and return the time out exception.
+ */
+public class QueryTimeManager implements IService {
+
+  private static final Logger logger = LoggerFactory.getLogger(QueryTimeManager.class);
+
+  /**
+   * the key of queryStartTimeMap is the query id and the value of queryStartTimeMap is the start
+   * time and the sql of this query.
+   */
+  private Map<Long, Pair<Long, String>> queryInfoMap;
+  /**
+   * the key of queryThreadMap is the query id and the value of queryThreadMap is the executing
+   * thread of this query.
+   * Only main thread is put in this map since the sub threads are maintained by the thread pool.
+   * The thread allocated for readTask will change every time, so we have to access this map
+   * frequently, which will lead to big performance cost.
+   */
+  private Map<Long, Thread> queryThreadMap;
+
+  private ScheduledExecutorService executorService;
+
+  private QueryTimeManager() {
+    queryInfoMap = new ConcurrentHashMap<>();
+    queryThreadMap = new ConcurrentHashMap<>();
+    executorService = IoTDBThreadPoolFactory.newScheduledThreadPool(1,
+        "query-time-manager");
+  }
+
+  public void registerQuery(long queryId, long startTime, String sql, long timeout,
+      Thread queryThread) {
+    queryInfoMap.put(queryId, new Pair<>(startTime, sql));
+    queryThreadMap.put(queryId, queryThread);
+    // submit a scheduled task to judge whether query is still running after timeout
+    executorService.schedule(() -> {
+      if (queryThreadMap.get(queryId) != null) {
+        killQuery(queryId);
+        logger.error(String.format("Query is time out with queryId %d", queryId));
+      }

Review comment:
       It will have some parallel errors. If I manually do the kill operation after the if statement has been judged, then my `kill` operation will successfully remove it from map, but the scheduled thread will cause nullpointerexception in the `killQuery` function, vice versa.

##########
File path: server/src/main/java/org/apache/iotdb/db/qp/executor/PlanExecutor.java
##########
@@ -319,6 +331,25 @@ private void operateCreateSnapshot() {
     IoTDB.metaManager.createMTreeSnapshot();
   }
 
+  private void operateKillQuery(KillQueryPlan killQueryPlan) throws QueryIdNotExsitException {
+    QueryTimeManager queryTimeManager = QueryTimeManager.getInstance();
+    if (killQueryPlan.getQueryId() != -1) {
+      if (queryTimeManager.getQueryThreadMap().get(killQueryPlan.getQueryId()) != null) {
+        queryTimeManager.killQuery(killQueryPlan.getQueryId());
+      } else {
+        throw new QueryIdNotExsitException(String
+            .format("Query Id %d is not exist, please check it.", killQueryPlan.getQueryId()));
+      }
+    } else {
+      // if queryId is not specified, kill all running queries
+      if (!queryTimeManager.getQueryThreadMap().isEmpty()) {
+        for (Long queryId : queryTimeManager.getQueryThreadMap().keySet()) {
+          queryTimeManager.killQuery(queryId);
+        }

Review comment:
       `killQuery` function will change the map while iterating the map keyset. This may cause `ConcurrentModificationException`.

##########
File path: server/src/main/java/org/apache/iotdb/db/query/dataset/RawQueryDataSetWithoutValueFilter.java
##########
@@ -283,7 +296,12 @@ public TSQueryDataSet fillBuffer(int fetchSize, WatermarkEncoder encoder)
           // move next
           cachedBatchDataArray[seriesIndex].next();
 
-          // get next batch if current batch is empty and  still have remaining batch data in queue
+          // check the interrupted status of main thread before taking next batch
+          if (Thread.interrupted()) {

Review comment:
       Same as above

##########
File path: server/src/main/java/org/apache/iotdb/db/query/reader/series/SeriesReader.java
##########
@@ -173,6 +174,10 @@ public boolean isEmpty() throws IOException {
   }
 
   boolean hasNextFile() throws IOException {
+    if (Thread.interrupted()) {

Review comment:
       Same as above

##########
File path: server/src/main/java/org/apache/iotdb/db/query/dataset/NonAlignEngineDataSet.java
##########
@@ -264,7 +271,7 @@ private void init(WatermarkEncoder encoder, int fetchSize) {
       ManagedSeriesReader reader = seriesReaderWithoutValueFilterList.get(i);

Review comment:
       Check the main thread's interrupt flag in the init method.

##########
File path: server/src/main/java/org/apache/iotdb/db/query/reader/series/SeriesReader.java
##########
@@ -351,6 +361,10 @@ void skipCurrentChunk() {
   @SuppressWarnings("squid:S3776")
   // Suppress high Cognitive Complexity warning
   boolean hasNextPage() throws IOException {
+    if (Thread.interrupted()) {

Review comment:
       Same as above.

##########
File path: server/src/main/java/org/apache/iotdb/db/query/dataset/RawQueryDataSetWithoutValueFilter.java
##########
@@ -175,9 +182,15 @@ private void init() throws IOException, InterruptedException {
       reader.setHasRemaining(true);
       reader.setManagedByQueryManager(true);
       TASK_POOL_MANAGER
-          .submit(new ReadTask(reader, blockingQueueArray[i], paths.get(i).getFullPath()));
+          .submit(new ReadTask(reader, blockingQueueArray[i], paths.get(i).getFullPath(),
+              Thread.currentThread()));
     }
     for (int i = 0; i < seriesReaderList.size(); i++) {
+      // check the interrupted status of main thread before taking next batch
+      if (Thread.interrupted()) {

Review comment:
       Same as above.

##########
File path: server/src/main/java/org/apache/iotdb/db/query/dataset/RawQueryDataSetWithoutValueFilter.java
##########
@@ -430,6 +448,11 @@ public RowRecord nextWithoutConstraint() throws IOException {
         // move next
         cachedBatchDataArray[seriesIndex].next();
 
+        // check the interrupted status of main thread before taking next batch
+        if (Thread.interrupted()) {

Review comment:
       Same as above

##########
File path: server/src/main/java/org/apache/iotdb/db/query/control/QueryTimeManager.java
##########
@@ -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.
+ */
+package org.apache.iotdb.db.query.control;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import org.apache.iotdb.db.concurrent.IoTDBThreadPoolFactory;
+import org.apache.iotdb.db.exception.query.QueryTimeoutRuntimeException;
+import org.apache.iotdb.db.service.IService;
+import org.apache.iotdb.db.service.ServiceType;
+import org.apache.iotdb.tsfile.utils.Pair;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class is used to monitor the executing time of each query.
+ * </p>
+ * Once one is over the threshold, it will be killed and return the time out exception.
+ */
+public class QueryTimeManager implements IService {
+
+  private static final Logger logger = LoggerFactory.getLogger(QueryTimeManager.class);
+
+  /**
+   * the key of queryStartTimeMap is the query id and the value of queryStartTimeMap is the start
+   * time and the sql of this query.
+   */
+  private Map<Long, Pair<Long, String>> queryInfoMap;
+  /**
+   * the key of queryThreadMap is the query id and the value of queryThreadMap is the executing
+   * thread of this query.
+   * Only main thread is put in this map since the sub threads are maintained by the thread pool.
+   * The thread allocated for readTask will change every time, so we have to access this map
+   * frequently, which will lead to big performance cost.
+   */
+  private Map<Long, Thread> queryThreadMap;
+
+  private ScheduledExecutorService executorService;
+
+  private QueryTimeManager() {
+    queryInfoMap = new ConcurrentHashMap<>();
+    queryThreadMap = new ConcurrentHashMap<>();
+    executorService = IoTDBThreadPoolFactory.newScheduledThreadPool(1,
+        "query-time-manager");
+  }
+
+  public void registerQuery(long queryId, long startTime, String sql, long timeout,
+      Thread queryThread) {
+    queryInfoMap.put(queryId, new Pair<>(startTime, sql));
+    queryThreadMap.put(queryId, queryThread);
+    // submit a scheduled task to judge whether query is still running after timeout
+    executorService.schedule(() -> {
+      if (queryThreadMap.get(queryId) != null) {
+        killQuery(queryId);
+        logger.error(String.format("Query is time out with queryId %d", queryId));
+      }

Review comment:
       You should try the computeIfPresent() function, it can guarantee atomicity.

##########
File path: server/src/main/java/org/apache/iotdb/db/service/TSServiceImpl.java
##########
@@ -769,17 +779,22 @@ private TSExecuteStatementResp internalExecuteQueryStatement(String statement,
         }
       }
 
+      // remove query info in QueryTimeManager
+      QueryTimeManager.getInstance().unRegisterQuery(queryId);

Review comment:
       Query may not finish in one rpc call, user may call two or more rpc to fetch complete result set. So, you shouldn't remove it after the first call finished.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org