This is an automated email from the ASF dual-hosted git repository.
JackieTien97 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/iotdb.git
The following commit(s) were added to refs/heads/master by this push:
new 8a67855a7d1 Bound MPP sink notifications by the query deadline
8a67855a7d1 is described below
commit 8a67855a7d19bc9c2bf68021c86a926f96b889ee
Author: Jackie Tien <[email protected]>
AuthorDate: Mon Nov 23 15:54:54 2026 +0800
Bound MPP sink notifications by the query deadline
---
.../iotdb/db/i18n/DataNodeQueryMessages.java | 2 -
.../iotdb/db/i18n/DataNodeQueryMessages.java | 2 -
.../impl/DataNodeInternalRPCServiceImpl.java | 4 +
.../execution/exchange/MPPDataExchangeManager.java | 49 ++-
.../execution/exchange/MPPDataExchangeService.java | 48 +-
.../execution/exchange/sink/SinkChannel.java | 296 ++++++++++---
.../fragment/FragmentInstanceContext.java | 13 +
.../fragment/FragmentInstanceManager.java | 2 +
.../plan/planner/plan/FragmentInstance.java | 12 +
.../spill/DeviceEntryRpcSegmentFetcher.java | 6 +-
.../scheduler/FragmentInstanceDispatcherImpl.java | 41 +-
.../exchange/MPPDataExchangeManagerTest.java | 47 +-
.../exchange/SinkChannelDeadlineTest.java | 487 +++++++++++++++++++++
.../SinkChannelFailurePropagationTest.java | 17 +-
.../execution/exchange/SinkChannelTest.java | 30 +-
.../fragment/FragmentInstanceContextTest.java | 24 +
.../spill/DeviceEntryRpcSegmentFetcherTest.java | 23 +
.../FragmentInstanceDispatcherLifecycleTest.java | 71 +++
.../plan/scheduler/QueryAttemptProtocolTest.java | 2 +
.../apache/iotdb/commons/client/ClientManager.java | 16 +-
.../apache/iotdb/commons/client/ThriftClient.java | 10 +-
.../client/sync/MPPDataExchangeClientManager.java | 77 ++++
.../SyncDataNodeMPPDataExchangeServiceClient.java | 244 +++++++++--
.../iotdb/commons/client/ClientManagerTest.java | 20 +
.../sync/MPPDataExchangeClientManagerTest.java | 221 ++++++++++
.../client/sync/MPPDataExchangeClientTlsTest.java | 330 ++++++++++++++
.../src/main/thrift/datanode.thrift | 2 +
27 files changed, 1905 insertions(+), 191 deletions(-)
diff --git
a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java
b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java
index 20b8e4e8c7b..149e2a90460 100644
---
a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java
+++
b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java
@@ -201,8 +201,6 @@ public final class DataNodeQueryMessages {
"Failed to send new data block event, attempt times: {}";
public static final String FAILED_TO_SEND_END_OF_DATA_BLOCK_EVENT =
"Failed to send end of data block event, attempt times: {}";
- public static final String FAILED_TO_SEND_END_OF_DATA_BLOCK_EVENT_2 =
- "Failed to send end of data block event after all retry";
public static final String SOURCE_HANDLE_IS_BLOCKED =
"Source handle is blocked.";
public static final String RESERVED_DATA_BLOCK_SIZE_IS_NULL =
diff --git
a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java
b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java
index ca31028984b..03e288fa6cd 100644
---
a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java
+++
b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java
@@ -202,8 +202,6 @@ public final class DataNodeQueryMessages {
"发送新数据块事件失败,尝试次数:{}";
public static final String FAILED_TO_SEND_END_OF_DATA_BLOCK_EVENT =
"发送数据块结束事件失败,尝试次数:{}";
- public static final String FAILED_TO_SEND_END_OF_DATA_BLOCK_EVENT_2 =
- "所有重试后仍无法发送数据块结束事件";
public static final String SOURCE_HANDLE_IS_BLOCKED =
"Source handle 已被阻塞。";
public static final String RESERVED_DATA_BLOCK_SIZE_IS_NULL =
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/DataNodeInternalRPCServiceImpl.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/DataNodeInternalRPCServiceImpl.java
index 43f2e412abd..874239c9436 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/DataNodeInternalRPCServiceImpl.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/DataNodeInternalRPCServiceImpl.java
@@ -521,6 +521,7 @@ public class DataNodeInternalRPCServiceImpl implements
IDataNodeRPCService.Iface
@Override
public TSendFragmentInstanceResp sendFragmentInstance(final
TSendFragmentInstanceReq req) {
+ long receivedAtMs = System.currentTimeMillis();
LOGGER.debug(DataNodeMiscMessages.RECEIVE_FRAGMENT_INSTANCE,
req.getConsensusGroupId());
// Deserialize ConsensusGroupId
@@ -565,6 +566,9 @@ public class DataNodeInternalRPCServiceImpl implements
IDataNodeRPCService.Iface
FragmentInstance.deserializeFrom(
fragmentInstanceId, req.fragmentInstance.body));
fragmentInstance.attachUDFQueryScope(queryScope);
+ if (req.isSetRemainingQueryTimeMs()) {
+ fragmentInstance.setQueryDeadlineFromTimeout(receivedAtMs,
req.getRemainingQueryTimeMs());
+ }
if (req.isSetQueryAttemptId() && req.isSetAdmissionToken()) {
fragmentInstance.setQueryAttempt(req.getQueryAttemptId(),
req.getAdmissionToken());
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/MPPDataExchangeManager.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/MPPDataExchangeManager.java
index 61e776d7d9e..2da7718cb8f 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/MPPDataExchangeManager.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/MPPDataExchangeManager.java
@@ -22,6 +22,7 @@ package org.apache.iotdb.db.queryengine.execution.exchange;
import org.apache.iotdb.common.rpc.thrift.TEndPoint;
import org.apache.iotdb.common.rpc.thrift.TSStatus;
import org.apache.iotdb.commons.client.IClientManager;
+import org.apache.iotdb.commons.client.sync.MPPDataExchangeClientManager;
import
org.apache.iotdb.commons.client.sync.SyncDataNodeMPPDataExchangeServiceClient;
import org.apache.iotdb.commons.utils.TestOnly;
import org.apache.iotdb.db.conf.IoTDBDescriptor;
@@ -420,6 +421,10 @@ public class MPPDataExchangeManager implements
IMPPDataExchangeManager {
public interface SinkListener {
void onFinish(ISink sink);
+ /**
+ * Remote channels may publish the end under their monitor before an
outstanding ACK. This
+ * callback must be non-blocking and must not acquire the owning shuffle
handle's lock.
+ */
void onEndOfBlocks(ISink sink);
Optional<Throwable> onAborted(ISink sink);
@@ -692,8 +697,7 @@ public class MPPDataExchangeManager implements
IMPPDataExchangeManager {
private final LocalMemoryManager localMemoryManager;
private final Supplier<TsBlockSerde> tsBlockSerdeFactory;
private final ExecutorService executorService;
- private final IClientManager<TEndPoint,
SyncDataNodeMPPDataExchangeServiceClient>
- mppDataExchangeServiceClientManager;
+ private final MPPDataExchangeClientManager
mppDataExchangeServiceClientManager;
private final Map<TFragmentInstanceId, Map<String, ISourceHandle>>
sourceHandles;
/** Each FI has only one ShuffleSinkHandle. */
@@ -705,8 +709,7 @@ public class MPPDataExchangeManager implements
IMPPDataExchangeManager {
LocalMemoryManager localMemoryManager,
Supplier<TsBlockSerde> tsBlockSerdeFactory,
ExecutorService executorService,
- IClientManager<TEndPoint, SyncDataNodeMPPDataExchangeServiceClient>
- mppDataExchangeServiceClientManager) {
+ MPPDataExchangeClientManager mppDataExchangeServiceClientManager) {
this.localMemoryManager =
Validate.notNull(
localMemoryManager,
@@ -855,23 +858,29 @@ public class MPPDataExchangeManager implements
IMPPDataExchangeManager {
localFragmentInstanceId);
}
- return new SinkChannel(
- remoteEndpoint,
- remoteFragmentInstanceId,
- remotePlanNodeId,
- localPlanNodeId,
- localFragmentInstanceId,
- localMemoryManager,
- executorService,
- tsBlockSerdeFactory.get(),
- new ISinkChannelListenerImpl(
+ SinkChannel channel =
+ new SinkChannel(
+ remoteEndpoint,
+ remoteFragmentInstanceId,
+ remotePlanNodeId,
+ localPlanNodeId,
localFragmentInstanceId,
- instanceContext,
- instanceContext::failed,
- cnt,
- hasChannelFailedOrAborted),
- instanceContext.isHighestPriority(),
- mppDataExchangeServiceClientManager);
+ localMemoryManager,
+ executorService,
+ tsBlockSerdeFactory.get(),
+ new ISinkChannelListenerImpl(
+ localFragmentInstanceId,
+ instanceContext,
+ instanceContext::failed,
+ cnt,
+ hasChannelFailedOrAborted),
+ instanceContext.isHighestPriority(),
+ instanceContext.getExchangeDeadlineMs(),
+ mppDataExchangeServiceClientManager);
+ instanceContext
+ .getStateMachine()
+ .addFinalStateChangeListener(state ->
channel.stopNotifications(state.isFailed()));
+ return channel;
}
@Override
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/MPPDataExchangeService.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/MPPDataExchangeService.java
index 6afcd2a3a91..35c04d3a794 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/MPPDataExchangeService.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/MPPDataExchangeService.java
@@ -20,12 +20,10 @@
package org.apache.iotdb.db.queryengine.execution.exchange;
import org.apache.iotdb.common.rpc.thrift.TEndPoint;
-import org.apache.iotdb.commons.client.ClientPoolFactory;
-import org.apache.iotdb.commons.client.IClientManager;
-import
org.apache.iotdb.commons.client.sync.SyncDataNodeMPPDataExchangeServiceClient;
-import org.apache.iotdb.commons.concurrent.IoTDBThreadPoolFactory;
+import org.apache.iotdb.commons.client.sync.MPPDataExchangeClientManager;
import org.apache.iotdb.commons.concurrent.IoTThreadFactory;
import org.apache.iotdb.commons.concurrent.ThreadName;
+import
org.apache.iotdb.commons.concurrent.threadpool.WrappedThreadPoolExecutor;
import org.apache.iotdb.commons.conf.CommonConfig;
import org.apache.iotdb.commons.conf.CommonDescriptor;
import org.apache.iotdb.commons.exception.runtime.RPCServiceException;
@@ -60,28 +58,36 @@ public class MPPDataExchangeService extends ThriftService
implements MPPDataExch
private final ExecutorService executorService;
private MPPDataExchangeService() {
- IoTDBConfig config = IoTDBDescriptor.getInstance().getConfig();
- executorService =
- IoTDBThreadPoolFactory.newThreadPool(
- config.getMppDataExchangeCorePoolSize(),
- config.getMppDataExchangeMaxPoolSize(),
- config.getMppDataExchangeKeepAliveTimeInMs(),
- TimeUnit.MILLISECONDS,
- // TODO: Use a priority queue.
- new LinkedBlockingQueue<>(),
- new
IoTThreadFactory(ThreadName.MPP_DATA_EXCHANGE_TASK_EXECUTOR.getName()),
- ThreadName.MPP_DATA_EXCHANGE_TASK_EXECUTOR.getName());
+ MPPDataExchangeClientManager clients = new MPPDataExchangeClientManager();
+ executorService = createExchangeExecutor(clients);
this.mppDataExchangeManager =
new MPPDataExchangeManager(
- new LocalMemoryManager(),
- new TsBlockSerdeFactory(),
- executorService,
- new IClientManager.Factory<TEndPoint,
SyncDataNodeMPPDataExchangeServiceClient>()
- .createClientManager(
- new
ClientPoolFactory.SyncDataNodeMPPDataExchangeServiceClientPoolFactory()));
+ new LocalMemoryManager(), new TsBlockSerdeFactory(),
executorService, clients);
LOGGER.info(DataNodeQueryMessages.MPPDATAEXCHANGEMANAGER_INIT_SUCCESSFULLY);
}
+ static ExecutorService createExchangeExecutor(MPPDataExchangeClientManager
clients) {
+ String name = ThreadName.MPP_DATA_EXCHANGE_TASK_EXECUTOR.getName();
+ return new WrappedThreadPoolExecutor(
+ config.getMppDataExchangeCorePoolSize(),
+ config.getMppDataExchangeMaxPoolSize(),
+ config.getMppDataExchangeKeepAliveTimeInMs(),
+ TimeUnit.MILLISECONDS,
+ new LinkedBlockingQueue<>(),
+ new IoTThreadFactory(name),
+ name) {
+ @Override
+ protected void terminated() {
+ // Queued notifications can still borrow clients while shutdown drains
the exchange workers.
+ try {
+ clients.close();
+ } finally {
+ super.terminated();
+ }
+ }
+ };
+ }
+
@Override
public void initTProcessor() {
initSyncedServiceImpl(null);
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/sink/SinkChannel.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/sink/SinkChannel.java
index 4d592771ef2..14fbc805881 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/sink/SinkChannel.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/sink/SinkChannel.java
@@ -20,8 +20,10 @@
package org.apache.iotdb.db.queryengine.execution.exchange.sink;
import org.apache.iotdb.common.rpc.thrift.TEndPoint;
-import org.apache.iotdb.commons.client.IClientManager;
+import org.apache.iotdb.commons.client.exception.ClientManagerException;
+import org.apache.iotdb.commons.client.sync.MPPDataExchangeClientManager;
import
org.apache.iotdb.commons.client.sync.SyncDataNodeMPPDataExchangeServiceClient;
+import org.apache.iotdb.commons.exception.QueryTimeoutException;
import org.apache.iotdb.commons.utils.TestOnly;
import org.apache.iotdb.db.conf.IoTDBDescriptor;
import org.apache.iotdb.db.i18n.DataNodeQueryMessages;
@@ -41,6 +43,7 @@ import org.apache.iotdb.mpp.rpc.thrift.TNewDataBlockEvent;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.ListenableFuture;
import org.apache.thrift.TApplicationException;
+import org.apache.thrift.TException;
import org.apache.tsfile.common.conf.TSFileDescriptor;
import org.apache.tsfile.external.commons.lang3.Validate;
import org.apache.tsfile.read.common.block.TsBlock;
@@ -51,12 +54,15 @@ import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.ByteBuffer;
+import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
+import java.util.Map;
import java.util.Map.Entry;
+import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
-import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.TimeUnit;
import static com.google.common.util.concurrent.Futures.immediateVoidFuture;
import static
com.google.common.util.concurrent.Futures.nonCancellationPropagating;
@@ -99,6 +105,13 @@ public class SinkChannel implements ISinkChannel {
private final SinkListener sinkListener;
private final String threadName;
private long retryIntervalInMs;
+ private final long queryDeadlineMs;
+ // The value records whether this registration received a channel-owned
interrupt.
+ private final Map<Thread, Boolean> runningNotifications = new HashMap<>();
+ // Guarded by runningNotifications.
+ private CompletableFuture<Void> deadlineAlarm;
+ private volatile boolean deadlineExpired;
+ private volatile boolean notificationsStopped;
private static final int DEFAULT_MAX_TSBLOCK_SIZE_IN_BYTES =
TSFileDescriptor.getInstance().getConfig().getMaxTsBlockSizeInBytes();
@@ -111,8 +124,7 @@ public class SinkChannel implements ISinkChannel {
// size for current TsBlock to reserve and free
private long currentTsBlockSize;
- private final IClientManager<TEndPoint,
SyncDataNodeMPPDataExchangeServiceClient>
- mppDataExchangeServiceClientManager;
+ private final MPPDataExchangeClientManager
mppDataExchangeServiceClientManager;
@SuppressWarnings("squid:S3077")
private volatile ListenableFuture<Void> blocked;
@@ -128,7 +140,8 @@ public class SinkChannel implements ISinkChannel {
private boolean noMoreTsBlocks = false;
- private final AtomicBoolean invokedOnFinished = new AtomicBoolean(false);
+ // Guarded by this. Normal finish and notification failure compete for one
terminal callback.
+ private boolean terminalCallbackClaimed;
/** max bytes this SinkChannel can reserve. */
private long maxBytesCanReserve =
@@ -157,8 +170,7 @@ public class SinkChannel implements ISinkChannel {
ExecutorService executorService,
TsBlockSerde serde,
SinkListener sinkListener,
- IClientManager<TEndPoint, SyncDataNodeMPPDataExchangeServiceClient>
- mppDataExchangeServiceClientManager) {
+ MPPDataExchangeClientManager mppDataExchangeServiceClientManager) {
this(
remoteEndpoint,
remoteFragmentInstanceId,
@@ -170,6 +182,7 @@ public class SinkChannel implements ISinkChannel {
serde,
sinkListener,
false,
+ Long.MAX_VALUE,
mppDataExchangeServiceClientManager);
}
@@ -185,8 +198,8 @@ public class SinkChannel implements ISinkChannel {
TsBlockSerde serde,
SinkListener sinkListener,
boolean isHighestPriority,
- IClientManager<TEndPoint, SyncDataNodeMPPDataExchangeServiceClient>
- mppDataExchangeServiceClientManager) {
+ long queryDeadlineMs,
+ MPPDataExchangeClientManager mppDataExchangeServiceClientManager) {
this.remoteEndpoint =
Validate.notNull(
remoteEndpoint,
@@ -224,6 +237,7 @@ public class SinkChannel implements ISinkChannel {
sinkListener,
DataNodeQueryMessages.EXCEPTION_SINKLISTENER_CAN_NOT_BE_NULL_DOT_32C9E7C0);
this.isHighestPriority = isHighestPriority;
+ this.queryDeadlineMs = queryDeadlineMs < 0 ? Long.MAX_VALUE :
queryDeadlineMs;
this.mppDataExchangeServiceClientManager =
mppDataExchangeServiceClientManager;
this.retryIntervalInMs = DEFAULT_RETRY_INTERVAL_IN_MS;
this.threadName =
@@ -319,6 +333,8 @@ public class SinkChannel implements ISinkChannel {
if (aborted || closed) {
return false;
}
+ terminalCallbackClaimed = true;
+ stopNotifications(true);
sequenceIdToTsBlock.clear();
if (blocked != null) {
bufferRetainedSizeInBytes -=
localMemoryManager.getQueryPool().tryCancel(blocked);
@@ -349,6 +365,7 @@ public class SinkChannel implements ISinkChannel {
if (closed || aborted) {
return false;
}
+ stopNotifications(!terminalCallbackClaimed);
sequenceIdToTsBlock.clear();
if (blocked != null) {
bufferRetainedSizeInBytes -=
localMemoryManager.getQueryPool().tryCancel(blocked);
@@ -372,11 +389,51 @@ public class SinkChannel implements ISinkChannel {
}
private void invokeOnFinished() {
- if (invokedOnFinished.compareAndSet(false, true)) {
+ if (claimFinish()) {
sinkListener.onFinish(this);
}
}
+ private synchronized boolean claimFinish() {
+ if (terminalCallbackClaimed) {
+ return false;
+ }
+ terminalCallbackClaimed = true;
+ stopNotifications(false);
+ return true;
+ }
+
+ private synchronized boolean claimFailure() {
+ synchronized (runningNotifications) {
+ if (terminalCallbackClaimed || notificationsStopped) {
+ return false;
+ }
+ terminalCallbackClaimed = true;
+ stopNotifications(true);
+ return true;
+ }
+ }
+
+ private void endOfBlocksSent() {
+ synchronized (this) {
+ if (notificationsStopped || noMoreTsBlocks) {
+ return;
+ }
+ noMoreTsBlocks = true;
+ if (!sequenceIdToTsBlock.isEmpty()) {
+ // The final ACK can still finish this channel. Publish the end before
a failure can win.
+ sinkListener.onEndOfBlocks(this);
+ return;
+ }
+ if (!claimFinish()) {
+ return;
+ }
+ }
+ // onFinish may re-enter the owning shuffle handle and close other
channels.
+ sinkListener.onFinish(this);
+ sinkListener.onEndOfBlocks(this);
+ }
+
@Override
public boolean isClosed() {
return closed;
@@ -581,6 +638,166 @@ public class SinkChannel implements ISinkChannel {
// endregion
+ @FunctionalInterface
+ private interface Notification {
+ void send(SyncDataNodeMPPDataExchangeServiceClient client) throws
TException;
+ }
+
+ private void checkNotificationActive(Exception previousFailure) throws
InterruptedException {
+ if (deadlineReached()) {
+ throw queryTimeout(previousFailure);
+ }
+ if (notificationsStopped || Thread.currentThread().isInterrupted()) {
+ InterruptedException interrupted = new InterruptedException();
+ interrupted.initCause(previousFailure);
+ throw interrupted;
+ }
+ }
+
+ private static QueryTimeoutException queryTimeout(Exception cause) {
+ if (cause instanceof QueryTimeoutException timeout) {
+ return timeout;
+ }
+ QueryTimeoutException timeout = new QueryTimeoutException();
+ timeout.initCause(cause);
+ return timeout;
+ }
+
+ private boolean deadlineReached() {
+ return deadlineExpired || System.currentTimeMillis() >= queryDeadlineMs;
+ }
+
+ private void registerNotification() throws InterruptedException {
+ synchronized (runningNotifications) {
+ checkNotificationActive(null);
+ if (queryDeadlineMs != Long.MAX_VALUE && deadlineAlarm == null) {
+ deadlineAlarm = new CompletableFuture<>();
+ deadlineAlarm
+ .orTimeout(
+ MPPDataExchangeClientManager.remainingMillis(queryDeadlineMs),
+ TimeUnit.MILLISECONDS)
+ .whenComplete(
+ (unused, failure) -> {
+ if (failure != null) {
+ deadlineExpired = true;
+ interruptNotifications();
+ }
+ });
+ }
+ runningNotifications.put(Thread.currentThread(), false);
+ }
+ }
+
+ private void interruptNotifications() {
+ synchronized (runningNotifications) {
+ for (Entry<Thread, Boolean> registration :
runningNotifications.entrySet()) {
+ Thread worker = registration.getKey();
+ if (!worker.isInterrupted()) {
+ registration.setValue(true);
+ worker.interrupt();
+ }
+ }
+ }
+ }
+
+ /**
+ * Stop new attempts. On normal completion, in-flight RPCs can return their
sockets to the pool.
+ */
+ public void stopNotifications(boolean interruptRunning) {
+ synchronized (runningNotifications) {
+ notificationsStopped = true;
+ if (interruptRunning || runningNotifications.isEmpty()) {
+ cancelDeadlineAlarm();
+ }
+ if (interruptRunning) {
+ interruptNotifications();
+ }
+ }
+ }
+
+ private void cancelDeadlineAlarm() {
+ if (deadlineAlarm != null) {
+ deadlineAlarm.complete(null);
+ }
+ }
+
+ private boolean sendNotification(Notification notification, int blockCount) {
+ if (notificationsStopped) {
+ return false;
+ }
+ try {
+ registerNotification();
+ try {
+ sendWithRetry(notification, blockCount);
+ } finally {
+ synchronized (runningNotifications) {
+ if
(Boolean.TRUE.equals(runningNotifications.remove(Thread.currentThread()))) {
+ // Only consume a wakeup we issued. An independently interrupted
worker keeps its flag.
+ Thread.interrupted();
+ }
+ if (notificationsStopped && runningNotifications.isEmpty()) {
+ cancelDeadlineAlarm();
+ }
+ }
+ }
+ checkNotificationActive(null);
+ return true;
+ } catch (Exception e) {
+ if (claimFailure()) {
+ sinkListener.onFailure(this, deadlineReached() ? queryTimeout(e) : e);
+ }
+ return false;
+ }
+ }
+
+ private void sendWithRetry(Notification notification, int blockCount)
+ throws ClientManagerException, InterruptedException, TException {
+ Exception previousFailure = null;
+ for (int attempt = 1; ; attempt++) {
+ checkNotificationActive(previousFailure);
+ long startTime = System.nanoTime();
+ try (SyncDataNodeMPPDataExchangeServiceClient client =
+ mppDataExchangeServiceClientManager.borrowClient(remoteEndpoint,
queryDeadlineMs)) {
+ checkNotificationActive(previousFailure);
+ notification.send(client);
+ checkNotificationActive(null);
+ return;
+ } catch (ClientManagerException | TException | RuntimeException failure)
{
+ checkNotificationActive(failure);
+ LOGGER.warn(
+ blockCount == 0
+ ? DataNodeQueryMessages.FAILED_TO_SEND_END_OF_DATA_BLOCK_EVENT
+ :
DataNodeQueryMessages.FAILED_TO_SEND_NEW_DATA_BLOCK_EVENT_ATTEMPT,
+ attempt,
+ failure);
+ if (attempt == MAX_ATTEMPT_TIMES
+ || (blockCount > 0 && containsTApplicationException(failure))) {
+ throw failure;
+ }
+ previousFailure = failure;
+ waitBeforeRetry(failure);
+ } finally {
+ if (blockCount > 0) {
+ DATA_EXCHANGE_COST_METRIC_SET.recordDataExchangeCost(
+ SEND_NEW_DATA_BLOCK_EVENT_TASK_CALLER, System.nanoTime() -
startTime);
+ DATA_EXCHANGE_COUNT_METRIC_SET.recordDataBlockNum(
+ SEND_NEW_DATA_BLOCK_NUM_CALLER, blockCount);
+ }
+ }
+ }
+ }
+
+ private void waitBeforeRetry(Exception failure) throws InterruptedException {
+ long remaining = Math.max(0, queryDeadlineMs - System.currentTimeMillis());
+ try {
+ Thread.sleep(Math.min(retryIntervalInMs, remaining));
+ } catch (InterruptedException interrupted) {
+ Thread.currentThread().interrupt();
+ interrupted.initCause(failure);
+ throw interrupted;
+ }
+ }
+
// region ============ inner class ============
/**
* Send a {@link org.apache.iotdb.mpp.rpc.thrift.TNewDataBlockEvent} to
downstream fragment
@@ -613,7 +830,6 @@ public class SinkChannel implements ISinkChannel {
remoteFragmentInstanceId,
remotePlanNodeId);
}
- int attempt = 0;
TNewDataBlockEvent newDataBlockEvent =
new TNewDataBlockEvent(
remoteFragmentInstanceId,
@@ -621,33 +837,8 @@ public class SinkChannel implements ISinkChannel {
localFragmentInstanceId,
startSequenceId,
blockSizes);
- while (attempt < MAX_ATTEMPT_TIMES) {
- attempt += 1;
- long startTime = System.nanoTime();
- try (SyncDataNodeMPPDataExchangeServiceClient client =
-
mppDataExchangeServiceClientManager.borrowClient(remoteEndpoint)) {
- client.onNewDataBlockEvent(newDataBlockEvent);
- break;
- } catch (Exception e) {
- LOGGER.warn(
-
DataNodeQueryMessages.FAILED_TO_SEND_NEW_DATA_BLOCK_EVENT_ATTEMPT, attempt, e);
- if (containsTApplicationException(e) || attempt ==
MAX_ATTEMPT_TIMES) {
- sinkListener.onFailure(SinkChannel.this, e);
- return;
- }
- try {
- Thread.sleep(retryIntervalInMs);
- } catch (InterruptedException ex) {
- Thread.currentThread().interrupt();
- sinkListener.onFailure(SinkChannel.this, e);
- }
- } finally {
- DATA_EXCHANGE_COST_METRIC_SET.recordDataExchangeCost(
- SEND_NEW_DATA_BLOCK_EVENT_TASK_CALLER, System.nanoTime() -
startTime);
- DATA_EXCHANGE_COUNT_METRIC_SET.recordDataBlockNum(
- SEND_NEW_DATA_BLOCK_NUM_CALLER, blockSizes.size());
- }
- }
+ sendNotification(
+ client -> client.onNewDataBlockEvent(newDataBlockEvent),
blockSizes.size());
}
}
}
@@ -664,39 +855,16 @@ public class SinkChannel implements ISinkChannel {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(DataNodeQueryMessages.NOTIFY_NO_MORE_TSBLOCK);
}
- int attempt = 0;
TEndOfDataBlockEvent endOfDataBlockEvent =
new TEndOfDataBlockEvent(
remoteFragmentInstanceId,
remotePlanNodeId,
localFragmentInstanceId,
nextSequenceId - 1);
- while (attempt < MAX_ATTEMPT_TIMES) {
- attempt += 1;
- try (SyncDataNodeMPPDataExchangeServiceClient client =
-
mppDataExchangeServiceClientManager.borrowClient(remoteEndpoint)) {
- client.onEndOfDataBlockEvent(endOfDataBlockEvent);
- break;
- } catch (Exception e) {
-
LOGGER.warn(DataNodeQueryMessages.FAILED_TO_SEND_END_OF_DATA_BLOCK_EVENT,
attempt, e);
- if (attempt == MAX_ATTEMPT_TIMES) {
-
LOGGER.warn(DataNodeQueryMessages.FAILED_TO_SEND_END_OF_DATA_BLOCK_EVENT_2, e);
- sinkListener.onFailure(SinkChannel.this, e);
- return;
- }
- try {
- Thread.sleep(retryIntervalInMs);
- } catch (InterruptedException ex) {
- Thread.currentThread().interrupt();
- sinkListener.onFailure(SinkChannel.this, e);
- }
- }
- }
- noMoreTsBlocks = true;
- if (isFinished()) {
- invokeOnFinished();
+ if (!sendNotification(client ->
client.onEndOfDataBlockEvent(endOfDataBlockEvent), 0)) {
+ return;
}
- sinkListener.onEndOfBlocks(SinkChannel.this);
+ endOfBlocksSent();
}
}
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/fragment/FragmentInstanceContext.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/fragment/FragmentInstanceContext.java
index 6d33ea28a60..a1369225235 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/fragment/FragmentInstanceContext.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/fragment/FragmentInstanceContext.java
@@ -181,6 +181,7 @@ public class FragmentInstanceContext extends QueryContext {
// Outer query deadline (startTime + timeout) for IoTDBLocal UDF
private long outerQueryDeadlineMs = -1L;
+ private long exchangeDeadlineMs = -1L;
private QueryAttemptRegistry.Registration queryAttemptRegistration;
private boolean executionInitialized;
@@ -662,6 +663,18 @@ public class FragmentInstanceContext extends QueryContext {
return outerQueryDeadlineMs;
}
+ void setExchangeDeadlineMs(long deadlineMs) {
+ exchangeDeadlineMs = deadlineMs;
+ }
+
+ public long getExchangeDeadlineMs() {
+ // Legacy coordinators only send the remaining FI timeout. Also honor an
earlier local FI limit.
+ if (exchangeDeadlineMs < 0 || outerQueryDeadlineMs < 0) {
+ return Math.max(exchangeDeadlineMs, outerQueryDeadlineMs);
+ }
+ return Math.min(outerQueryDeadlineMs, exchangeDeadlineMs);
+ }
+
public Optional<Throwable> getFailureCause() {
return Optional.ofNullable(
stateMachine.getFailureCauses().stream()
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/fragment/FragmentInstanceManager.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/fragment/FragmentInstanceManager.java
index 7926d2b501a..2f7b4d5ff5f 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/fragment/FragmentInstanceManager.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/fragment/FragmentInstanceManager.java
@@ -180,6 +180,7 @@ public class FragmentInstanceManager {
DriverTask.computeDeadlineTimeInMs(instance.getTimeOut()),
instance.isDebug(),
instance.isVerbose());
+
createdContext.setExchangeDeadlineMs(instance.getQueryDeadlineMs());
createdContext.adoptUDFQueryScope(instance.claimUDFQueryScope());
return createdContext;
} catch (Throwable t) {
@@ -356,6 +357,7 @@ public class FragmentInstanceManager {
DriverTask.computeDeadlineTimeInMs(instance.getTimeOut()),
instance.isDebug(),
instance.isVerbose());
+
createdContext.setExchangeDeadlineMs(instance.getQueryDeadlineMs());
createdContext.adoptUDFQueryScope(instance.claimUDFQueryScope());
return createdContext;
} catch (Throwable t) {
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/FragmentInstance.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/FragmentInstance.java
index 477a48ad56c..2d8f93f68f5 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/FragmentInstance.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/FragmentInstance.java
@@ -46,6 +46,8 @@ import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Objects;
+import static com.google.common.math.LongMath.saturatedAdd;
+
public class FragmentInstance implements IConsensusRequest {
private static final Logger LOGGER =
LoggerFactory.getLogger(FragmentInstance.class);
@@ -65,6 +67,8 @@ public class FragmentInstance implements IConsensusRequest {
private final TimePredicate globalTimePredicate;
private final long timeOut;
+ // Process-local deadline. The dispatch envelope carries only the remaining
duration.
+ private long queryDeadlineMs = -1;
private boolean isRoot;
@@ -364,6 +368,14 @@ public class FragmentInstance implements IConsensusRequest
{
return hostDataNode;
}
+ public void setQueryDeadlineFromTimeout(long localStartMs, long timeoutMs) {
+ queryDeadlineMs = saturatedAdd(localStartMs, Math.max(0, timeoutMs));
+ }
+
+ public long getQueryDeadlineMs() {
+ return queryDeadlineMs;
+ }
+
public long getTimeOut() {
return timeOut;
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/spill/DeviceEntryRpcSegmentFetcher.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/spill/DeviceEntryRpcSegmentFetcher.java
index 6a1dbad39c2..8bd100a4be8 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/spill/DeviceEntryRpcSegmentFetcher.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/spill/DeviceEntryRpcSegmentFetcher.java
@@ -72,7 +72,8 @@ public final class DeviceEntryRpcSegmentFetcher implements
DeviceEntrySegmentFet
}
} catch (ClientManagerException | TException e) {
failure = new IOException(e);
- if (System.nanoTime() - startTime > RETRY_TIMEOUT_NANOS) {
+ if (Thread.currentThread().isInterrupted()
+ || System.nanoTime() - startTime > RETRY_TIMEOUT_NANOS) {
throw failure;
}
continue;
@@ -105,7 +106,8 @@ public final class DeviceEntryRpcSegmentFetcher implements
DeviceEntrySegmentFet
return;
} catch (ClientManagerException | TException e) {
// Cleanup notification is best effort and must not fail the query.
- if (System.nanoTime() - startTime > RETRY_TIMEOUT_NANOS) {
+ if (Thread.currentThread().isInterrupted()
+ || System.nanoTime() - startTime > RETRY_TIMEOUT_NANOS) {
return;
}
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/scheduler/FragmentInstanceDispatcherImpl.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/scheduler/FragmentInstanceDispatcherImpl.java
index 35b8c70b328..229926e266e 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/scheduler/FragmentInstanceDispatcherImpl.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/scheduler/FragmentInstanceDispatcherImpl.java
@@ -508,15 +508,40 @@ public class FragmentInstanceDispatcherImpl implements
IFragInstanceDispatcher {
private void dispatchOneInstance(FragmentInstance instance)
throws FragmentInstanceDispatchException, TException {
checkNotAborted();
+ if (queryContext.getTimeOut() > 0) {
+ instance.setQueryDeadlineFromTimeout(queryContext.getStartTime(),
queryContext.getTimeOut());
+ }
+ remainingQueryTimeMs(instance);
TEndPoint endPoint = instance.getHostDataNode().getInternalEndPoint();
if (isDispatchedToLocal(endPoint)) {
prepareAdmission(instance, endPoint, null);
+ remainingQueryTimeMs(instance);
dispatchLocally(instance);
} else {
dispatchRemote(instance, endPoint);
}
}
+ private long remainingQueryTimeMs(FragmentInstance instance)
+ throws FragmentInstanceDispatchException {
+ long deadline = instance.getQueryDeadlineMs();
+ if (deadline < 0 || deadline == Long.MAX_VALUE) {
+ return deadline;
+ }
+ long now = System.currentTimeMillis();
+ if (now >= deadline) {
+ throw new FragmentInstanceDispatchException(
+ RpcUtils.getStatus(
+ TSStatusCode.QUERY_TIMEOUT,
+ String.format(
+ QueryTimeoutRuntimeException.QUERY_TIMEOUT_EXCEPTION_MESSAGE,
+ queryContext.getStartTime(),
+ deadline,
+ now)));
+ }
+ return deadline - now;
+ }
+
private boolean isDispatchedToLocal(TEndPoint endPoint) {
return this.localhostIpAddr.equals(endPoint.getIp()) &&
localhostInternalPort == endPoint.port;
}
@@ -549,6 +574,10 @@ public class FragmentInstanceDispatcherImpl implements
IFragInstanceDispatcher {
sendFragmentInstanceReq.setConsensusGroupId(
instance.getRegionReplicaSet().getRegionId());
}
+ long remainingMs = remainingQueryTimeMs(instance);
+ if (remainingMs >= 0) {
+ sendFragmentInstanceReq.setRemainingQueryTimeMs(remainingMs);
+ }
final TSendFragmentInstanceResp sendFragmentInstanceResp =
client.sendFragmentInstance(sendFragmentInstanceReq);
if (!sendFragmentInstanceResp.accepted) {
@@ -706,17 +735,7 @@ public class FragmentInstanceDispatcherImpl implements
IFragInstanceDispatcher {
// If the query has already timed out, do not retry. Re-dispatching the
same FragmentInstance
// may cause it to be executed twice on the remote node (see the
REPEATED_RPC_CALL handling in
// FragmentInstanceManager), so we fail fast with a timeout status
instead.
- long currentTime = System.currentTimeMillis();
- if (currentTime - queryContext.getStartTime() >=
queryContext.getTimeOut()) {
- throw new FragmentInstanceDispatchException(
- RpcUtils.getStatus(
- TSStatusCode.QUERY_TIMEOUT,
- String.format(
-
QueryTimeoutRuntimeException.QUERY_TIMEOUT_EXCEPTION_MESSAGE,
- queryContext.getStartTime(),
- queryContext.getStartTime() + queryContext.getTimeOut(),
- currentTime)));
- }
+ remainingQueryTimeMs(instance);
// we just retry once to clear stale connection for a restart node.
checkNotAborted();
try {
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/exchange/MPPDataExchangeManagerTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/exchange/MPPDataExchangeManagerTest.java
index a5573159a94..668c02adee6 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/exchange/MPPDataExchangeManagerTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/exchange/MPPDataExchangeManagerTest.java
@@ -20,9 +20,7 @@
package org.apache.iotdb.db.queryengine.execution.exchange;
import org.apache.iotdb.common.rpc.thrift.TEndPoint;
-import org.apache.iotdb.commons.client.ClientPoolFactory;
-import org.apache.iotdb.commons.client.IClientManager;
-import
org.apache.iotdb.commons.client.sync.SyncDataNodeMPPDataExchangeServiceClient;
+import org.apache.iotdb.commons.client.sync.MPPDataExchangeClientManager;
import org.apache.iotdb.commons.memory.MemoryManager;
import org.apache.iotdb.db.conf.IoTDBDescriptor;
import org.apache.iotdb.db.queryengine.common.FragmentInstanceId;
@@ -50,10 +48,43 @@ import org.junit.Test;
import org.mockito.Mockito;
import java.util.Collections;
+import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
public class MPPDataExchangeManagerTest {
+ @Test
+ public void exchangeExecutorClosesClientsAfterItsLastTask() throws Exception
{
+ MPPDataExchangeClientManager clients =
Mockito.mock(MPPDataExchangeClientManager.class);
+ ExecutorService executor =
MPPDataExchangeService.createExchangeExecutor(clients);
+ CountDownLatch started = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ try {
+ TEndPoint endpoint = new TEndPoint("localhost", 1);
+ Future<?> task =
+ executor.submit(
+ () -> {
+ started.countDown();
+ release.await();
+ return clients.borrowClient(endpoint);
+ });
+ Assert.assertTrue(started.await(5, TimeUnit.SECONDS));
+ executor.shutdown();
+ Mockito.verify(clients, Mockito.never()).close();
+ release.countDown();
+ task.get(5, TimeUnit.SECONDS);
+ Assert.assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
+ org.mockito.InOrder order = Mockito.inOrder(clients);
+ order.verify(clients).borrowClient(endpoint);
+ order.verify(clients).close();
+ } finally {
+ release.countDown();
+ executor.shutdownNow();
+ }
+ }
+
@Test
public void testNewDataBlockMemoryFailureMarksTargetFragmentFailed() throws
Exception {
final String queryId = "q_memory_reservation_failure";
@@ -92,7 +123,7 @@ public class MPPDataExchangeManagerTest {
localMemoryManager,
new TsBlockSerdeFactory(),
exchangeExecutor,
- Mockito.mock(IClientManager.class));
+ Mockito.mock(MPPDataExchangeClientManager.class));
ISourceHandle sourceHandle =
exchangeManager.createSourceHandle(
targetFragmentInstanceId,
@@ -147,9 +178,7 @@ public class MPPDataExchangeManagerTest {
mockLocalMemoryManager,
new TsBlockSerdeFactory(),
Executors.newSingleThreadExecutor(),
- new IClientManager.Factory<TEndPoint,
SyncDataNodeMPPDataExchangeServiceClient>()
- .createClientManager(
- new
ClientPoolFactory.SyncDataNodeMPPDataExchangeServiceClientPoolFactory()));
+ Mockito.mock(MPPDataExchangeClientManager.class));
ISinkHandle shuffleSinkHandle =
mppDataExchangeManager.createShuffleSinkHandle(
@@ -211,9 +240,7 @@ public class MPPDataExchangeManagerTest {
mockLocalMemoryManager,
new TsBlockSerdeFactory(),
Executors.newSingleThreadExecutor(),
- new IClientManager.Factory<TEndPoint,
SyncDataNodeMPPDataExchangeServiceClient>()
- .createClientManager(
- new
ClientPoolFactory.SyncDataNodeMPPDataExchangeServiceClientPoolFactory()));
+ Mockito.mock(MPPDataExchangeClientManager.class));
ISourceHandle localSourceHandle =
mppDataExchangeManager.createLocalSourceHandleForFragment(
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/exchange/SinkChannelDeadlineTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/exchange/SinkChannelDeadlineTest.java
new file mode 100644
index 00000000000..c356213a602
--- /dev/null
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/exchange/SinkChannelDeadlineTest.java
@@ -0,0 +1,487 @@
+/*
+ * 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.execution.exchange;
+
+import org.apache.iotdb.common.rpc.thrift.TEndPoint;
+import org.apache.iotdb.commons.client.sync.MPPDataExchangeClientManager;
+import
org.apache.iotdb.commons.client.sync.SyncDataNodeMPPDataExchangeServiceClient;
+import org.apache.iotdb.commons.exception.QueryTimeoutException;
+import org.apache.iotdb.db.queryengine.common.FragmentInstanceId;
+import org.apache.iotdb.db.queryengine.common.PlanFragmentId;
+import org.apache.iotdb.db.queryengine.common.QueryId;
+import
org.apache.iotdb.db.queryengine.execution.exchange.MPPDataExchangeManager.SinkListener;
+import
org.apache.iotdb.db.queryengine.execution.exchange.sink.DownStreamChannelIndex;
+import
org.apache.iotdb.db.queryengine.execution.exchange.sink.DownStreamChannelLocation;
+import org.apache.iotdb.db.queryengine.execution.exchange.sink.ISinkHandle;
+import
org.apache.iotdb.db.queryengine.execution.exchange.sink.ShuffleSinkHandle;
+import org.apache.iotdb.db.queryengine.execution.exchange.sink.SinkChannel;
+import
org.apache.iotdb.db.queryengine.execution.fragment.FragmentInstanceContext;
+import
org.apache.iotdb.db.queryengine.execution.fragment.FragmentInstanceStateMachine;
+import org.apache.iotdb.db.queryengine.execution.memory.LocalMemoryManager;
+import org.apache.iotdb.mpp.rpc.thrift.TFragmentInstanceId;
+
+import com.google.common.base.Throwables;
+import com.google.common.util.concurrent.Uninterruptibles;
+import org.apache.thrift.TApplicationException;
+import org.apache.thrift.TException;
+import org.junit.After;
+import org.junit.Test;
+import org.mockito.ArgumentCaptor;
+
+import java.net.InetAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.nio.channels.ClosedByInterruptException;
+import java.util.Collections;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.locks.LockSupport;
+
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.isA;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class SinkChannelDeadlineTest {
+ private final ExecutorService executor = Executors.newSingleThreadExecutor();
+ private final SinkListener listener = mock(SinkListener.class);
+ private final LocalMemoryManager memory = mock(LocalMemoryManager.class);
+
+ @After
+ public void tearDown() {
+ executor.shutdownNow();
+ }
+
+ private SinkChannel channel(
+ TEndPoint endpoint, long deadline, MPPDataExchangeClientManager clients)
{
+ return channel(endpoint, deadline, clients, executor);
+ }
+
+ private SinkChannel channel(
+ TEndPoint endpoint,
+ long deadline,
+ MPPDataExchangeClientManager clients,
+ ExecutorService workers) {
+
doReturn(Utils.createMockNonBlockedMemoryPool()).when(memory).getQueryPool();
+ return new SinkChannel(
+ endpoint,
+ new TFragmentInstanceId("query", 0, "0"),
+ "exchange",
+ "sink",
+ new TFragmentInstanceId("query", 1, "0"),
+ memory,
+ workers,
+ Utils.createMockTsBlockSerde(1024),
+ listener,
+ false,
+ deadline,
+ clients);
+ }
+
+ private void awaitWorker() throws Exception {
+ executor.submit(() -> {}).get(3, SECONDS);
+ }
+
+ @Test
+ public void queuedEventsExpireWithoutBorrowingAndReleaseMemory() throws
Exception {
+ MPPDataExchangeClientManager clients =
mock(MPPDataExchangeClientManager.class);
+ CountDownLatch dequeue = new CountDownLatch(1);
+ executor.submit(
+ () -> {
+ dequeue.await();
+ return null;
+ });
+ long deadline = System.currentTimeMillis() + 200;
+ SinkChannel channel = channel(new TEndPoint("unused", 1), deadline,
clients);
+ doAnswer(call -> channel.abort())
+ .when(listener)
+ .onFailure(eq(channel), isA(QueryTimeoutException.class));
+ channel.open();
+ channel.send(Utils.createMockTsBlocks(1, 1024).get(0));
+ channel.setNoMoreTsBlocks();
+ long remaining;
+ while ((remaining = deadline - System.currentTimeMillis()) > 0) {
+ MILLISECONDS.sleep(remaining);
+ }
+ dequeue.countDown();
+ awaitWorker();
+ verify(clients, never()).borrowClient(any(), anyLong());
+ verify(listener).onFailure(eq(channel), isA(QueryTimeoutException.class));
+ verify(listener, never()).onEndOfBlocks(channel);
+ assertEquals(0, channel.getBufferRetainedSizeInBytes());
+ }
+
+ @Test
+ public void cancelledFragmentSkipsQueuedEndEventBeforeChannelCleanup()
throws Exception {
+ MPPDataExchangeClientManager clients =
mock(MPPDataExchangeClientManager.class);
+ CountDownLatch dequeue = new CountDownLatch(1);
+ executor.submit(
+ () -> {
+ dequeue.await();
+ return null;
+ });
+
doReturn(Utils.createMockNonBlockedMemoryPool()).when(memory).getQueryPool();
+ FragmentInstanceId id =
+ new FragmentInstanceId(new PlanFragmentId(new QueryId("query"), 1),
"0");
+ FragmentInstanceStateMachine state = new FragmentInstanceStateMachine(id,
Runnable::run);
+ FragmentInstanceContext context =
+ FragmentInstanceContext.createFragmentInstanceContext(id, state);
+ MPPDataExchangeManager exchange =
+ new MPPDataExchangeManager(memory, new TsBlockSerdeFactory(),
executor, clients);
+ ISinkHandle sink =
+ exchange.createShuffleSinkHandle(
+ Collections.singletonList(
+ new DownStreamChannelLocation(
+ new TEndPoint("unused", 1),
+ new TFragmentInstanceId("query", 0, "0"),
+ "exchange")),
+ new DownStreamChannelIndex(0),
+ ShuffleSinkHandle.ShuffleStrategyEnum.PLAIN,
+ id.toThrift(),
+ "sink",
+ context);
+ SinkChannel channel = (SinkChannel) sink.getChannel(0);
+ channel.setNoMoreTsBlocks();
+ state.cancel();
+ dequeue.countDown();
+ awaitWorker();
+ verify(clients, never()).borrowClient(any(), anyLong());
+ assertFalse(channel.isNoMoreTsBlocks());
+ assertTrue(state.getFailureCauses().isEmpty());
+ sink.abort();
+ }
+
+ @Test
+ public void retryBackoffSharesTheDeadline() throws Exception {
+ TEndPoint endpoint = new TEndPoint("unused", 1);
+ MPPDataExchangeClientManager clients =
mock(MPPDataExchangeClientManager.class);
+ SyncDataNodeMPPDataExchangeServiceClient client =
+ mock(SyncDataNodeMPPDataExchangeServiceClient.class);
+ when(clients.borrowClient(eq(endpoint), anyLong())).thenReturn(client);
+ TException networkFailure = new TException("transient failure");
+ doThrow(networkFailure).when(client).onNewDataBlockEvent(any());
+ SinkChannel channel = channel(endpoint, System.currentTimeMillis() + 800,
clients);
+ channel.setRetryIntervalInMs(30_000);
+ channel.open();
+ channel.send(Utils.createMockTsBlocks(1, 1024).get(0));
+ awaitWorker();
+ verify(client).onNewDataBlockEvent(any());
+ ArgumentCaptor<Throwable> reported =
ArgumentCaptor.forClass(Throwable.class);
+ verify(listener).onFailure(eq(channel), reported.capture());
+ assertTrue(reported.getValue() instanceof QueryTimeoutException);
+ assertSame(networkFailure, Throwables.getRootCause(reported.getValue()));
+ channel.abort();
+ }
+
+ @Test
+ public void abortInterruptsPoolWaitWithoutDiscardingTheHeldConnection()
throws Exception {
+ MPPDataExchangeClientManager clients = new MPPDataExchangeClientManager();
+ clients.getPool().setMaxTotalPerKey(1);
+ try (ServerSocket server = new ServerSocket(0, 1,
InetAddress.getLoopbackAddress())) {
+ TEndPoint endpoint =
+ new TEndPoint(server.getInetAddress().getHostAddress(),
server.getLocalPort());
+ try (SyncDataNodeMPPDataExchangeServiceClient held =
clients.borrowClient(endpoint);
+ Socket peer = server.accept()) {
+ SinkChannel channel = channel(endpoint, System.currentTimeMillis() +
20_000, clients);
+ channel.setNoMoreTsBlocks();
+ long start = System.nanoTime();
+ while (clients.getPool().getNumWaiters() == 0
+ && System.nanoTime() - start < SECONDS.toNanos(3)) {
+ Thread.sleep(10);
+ }
+ assertEquals(1, clients.getPool().getNumWaiters());
+ channel.abort();
+ awaitWorker();
+ verify(listener, never()).onFailure(any(), any());
+ assertEquals(1, clients.getPool().getNumActive());
+ }
+ assertEquals(1, clients.getPool().getNumIdle());
+ } finally {
+ clients.close();
+ }
+ }
+
+ @Test
+ public void deadlineInterruptIsClearedBeforeListenerAndWorkerReturn() throws
Exception {
+ verifyWorkerInterrupt(false);
+ }
+
+ @Test
+ public void executorShutdownInterruptSurvivesNotificationCleanup() throws
Exception {
+ verifyWorkerInterrupt(true);
+ }
+
+ private void verifyWorkerInterrupt(boolean shutdownNow) throws Exception {
+ CompletableFuture<Boolean> afterTask = new CompletableFuture<>();
+ CompletableFuture<Boolean> inListener = new CompletableFuture<>();
+ ThreadPoolExecutor workers =
+ new ThreadPoolExecutor(1, 1, 0, SECONDS, new LinkedBlockingQueue<>()) {
+ @Override
+ protected void afterExecute(Runnable task, Throwable error) {
+ afterTask.complete(Thread.currentThread().isInterrupted());
+ }
+ };
+ CountDownLatch sending = new CountDownLatch(1);
+ ClosedByInterruptException socketFailure = new
ClosedByInterruptException();
+ try {
+ TEndPoint endpoint = new TEndPoint("unused", 1);
+ MPPDataExchangeClientManager clients =
mock(MPPDataExchangeClientManager.class);
+ SyncDataNodeMPPDataExchangeServiceClient client =
+ mock(SyncDataNodeMPPDataExchangeServiceClient.class);
+ when(clients.borrowClient(eq(endpoint), anyLong())).thenReturn(client);
+ doAnswer(
+ call -> {
+ sending.countDown();
+ while (!Thread.currentThread().isInterrupted()) {
+ LockSupport.park();
+ }
+ throw new TException(socketFailure);
+ })
+ .when(client)
+ .onEndOfDataBlockEvent(any());
+ doAnswer(call ->
inListener.complete(Thread.currentThread().isInterrupted()))
+ .when(listener)
+ .onFailure(any(), any());
+ long deadline = shutdownNow ? Long.MAX_VALUE :
System.currentTimeMillis() + 1_000;
+ SinkChannel channel = channel(endpoint, deadline, clients, workers);
+ channel.setNoMoreTsBlocks();
+ assertTrue(sending.await(5, SECONDS));
+ if (shutdownNow) {
+ workers.shutdownNow();
+ } else {
+ // Graceful shutdown lets the running task reach its own deadline.
+ workers.shutdown();
+ }
+ assertEquals(shutdownNow, inListener.get(5, SECONDS));
+ assertEquals(shutdownNow, afterTask.get(5, SECONDS));
+ if (!shutdownNow) {
+ ArgumentCaptor<Throwable> reported =
ArgumentCaptor.forClass(Throwable.class);
+ verify(listener).onFailure(eq(channel), reported.capture());
+ assertTrue(reported.getValue() instanceof QueryTimeoutException);
+ assertSame(socketFailure,
Throwables.getRootCause(reported.getValue()));
+ }
+ verify(listener, never()).onEndOfBlocks(channel);
+ } finally {
+ workers.shutdownNow();
+ }
+ }
+
+ @Test
+ public void failureWinsAgainstLateEndAndNormalClose() throws Exception {
+ verifyTerminalCallbacks(false);
+ }
+
+ @Test
+ public void acknowledgedEndWinsAgainstLateNotificationFailure() throws
Exception {
+ verifyTerminalCallbacks(true);
+ }
+
+ private void verifyTerminalCallbacks(boolean finishFirst) throws Exception {
+ ExecutorService workers = Executors.newFixedThreadPool(2);
+ CountDownLatch bothSending = new CountDownLatch(2);
+ CountDownLatch releaseData = new CountDownLatch(1);
+ CountDownLatch releaseEnd = new CountDownLatch(1);
+ CountDownLatch normalEnd = new CountDownLatch(1);
+ CompletableFuture<Boolean> dataInterrupted = new CompletableFuture<>();
+ CountDownLatch failure = new CountDownLatch(1);
+ try {
+ TEndPoint endpoint = new TEndPoint("unused", 1);
+ MPPDataExchangeClientManager clients =
mock(MPPDataExchangeClientManager.class);
+ SyncDataNodeMPPDataExchangeServiceClient client =
+ mock(SyncDataNodeMPPDataExchangeServiceClient.class);
+ when(clients.borrowClient(eq(endpoint), anyLong())).thenReturn(client);
+ doAnswer(
+ call -> {
+ bothSending.countDown();
+ Uninterruptibles.awaitUninterruptibly(releaseData);
+
dataInterrupted.complete(Thread.currentThread().isInterrupted());
+ throw new TApplicationException("injected data notification
failure");
+ })
+ .when(client)
+ .onNewDataBlockEvent(any());
+ doAnswer(
+ call -> {
+ bothSending.countDown();
+ Uninterruptibles.awaitUninterruptibly(releaseEnd);
+ return null;
+ })
+ .when(client)
+ .onEndOfDataBlockEvent(any());
+ doAnswer(
+ call -> {
+ normalEnd.countDown();
+ return null;
+ })
+ .when(listener)
+ .onEndOfBlocks(any());
+ doAnswer(
+ call -> {
+ failure.countDown();
+ return null;
+ })
+ .when(listener)
+ .onFailure(any(), any());
+ SinkChannel channel = channel(endpoint, Long.MAX_VALUE, clients,
workers);
+ channel.open();
+ channel.send(Utils.createMockTsBlocks(1, 1024).get(0));
+ channel.setNoMoreTsBlocks();
+ assertTrue(bothSending.await(5, SECONDS));
+ channel.acknowledgeTsBlock(0, 1);
+ if (finishFirst) {
+ releaseEnd.countDown();
+ assertTrue(normalEnd.await(5, SECONDS));
+ // The owning shuffle handle closes normally finished channels.
+ channel.close();
+ releaseData.countDown();
+ assertFalse(dataInterrupted.get(5, SECONDS));
+ } else {
+ releaseData.countDown();
+ assertTrue(failure.await(5, SECONDS));
+ channel.close();
+ releaseEnd.countDown();
+ }
+ workers.shutdown();
+ assertTrue(workers.awaitTermination(5, SECONDS));
+ if (finishFirst) {
+ verify(listener).onFinish(channel);
+ verify(listener, never()).onFailure(any(), any());
+ } else {
+ verify(listener, never()).onFinish(channel);
+ verify(listener, never()).onEndOfBlocks(channel);
+ }
+ } finally {
+ releaseData.countDown();
+ releaseEnd.countDown();
+ workers.shutdownNow();
+ }
+ }
+
+ @Test
+ public void acknowledgedChannelStillBoundsAnOutstandingReadAtItsDeadline()
throws Exception {
+ ExecutorService workers = Executors.newFixedThreadPool(2);
+ CountDownLatch dataSending = new CountDownLatch(1);
+ CountDownLatch endDelivered = new CountDownLatch(1);
+ CompletableFuture<Long> interruptedAt = new CompletableFuture<>();
+ try {
+ TEndPoint endpoint = new TEndPoint("unused", 1);
+ MPPDataExchangeClientManager clients =
mock(MPPDataExchangeClientManager.class);
+ SyncDataNodeMPPDataExchangeServiceClient client =
+ mock(SyncDataNodeMPPDataExchangeServiceClient.class);
+ when(clients.borrowClient(eq(endpoint), anyLong())).thenReturn(client);
+ doAnswer(
+ call -> {
+ dataSending.countDown();
+ while (!Thread.currentThread().isInterrupted()) {
+ LockSupport.park();
+ }
+ interruptedAt.complete(System.currentTimeMillis());
+ throw new TException(new ClosedByInterruptException());
+ })
+ .when(client)
+ .onNewDataBlockEvent(any());
+ doAnswer(
+ call -> {
+ endDelivered.countDown();
+ return null;
+ })
+ .when(listener)
+ .onEndOfBlocks(any());
+ long deadline = System.currentTimeMillis() + 1_500;
+ SinkChannel channel = channel(endpoint, deadline, clients, workers);
+ channel.open();
+ channel.send(Utils.createMockTsBlocks(1, 1024).get(0));
+ assertTrue(dataSending.await(5, SECONDS));
+ channel.acknowledgeTsBlock(0, 1);
+ channel.setNoMoreTsBlocks();
+ assertTrue(endDelivered.await(5, SECONDS));
+ assertTrue(interruptedAt.get(5, SECONDS) >= deadline - 2);
+ workers.shutdown();
+ assertTrue(workers.awaitTermination(5, SECONDS));
+ verify(listener).onFinish(channel);
+ verify(listener, never()).onFailure(any(), any());
+ } finally {
+ workers.shutdownNow();
+ }
+ }
+
+ @Test
+ public void silentPeerReleasesWorkerAtDeadline() throws Exception {
+ verifyBlockedRead(false);
+ }
+
+ @Test
+ public void abortInterruptsReadAndLeavesOtherConnectionUsable() throws
Exception {
+ verifyBlockedRead(true);
+ }
+
+ private void verifyBlockedRead(boolean abort) throws Exception {
+ MPPDataExchangeClientManager clients = new MPPDataExchangeClientManager();
+ try (ServerSocket server = new ServerSocket(0, 2,
InetAddress.getLoopbackAddress())) {
+ server.setSoTimeout(3_000);
+ TEndPoint endpoint =
+ new TEndPoint(server.getInetAddress().getHostAddress(),
server.getLocalPort());
+ // Warm up the connection and keep another idle connection to the same
endpoint.
+ try (SyncDataNodeMPPDataExchangeServiceClient first =
clients.borrowClient(endpoint);
+ SyncDataNodeMPPDataExchangeServiceClient second =
clients.borrowClient(endpoint)) {}
+ long borrowed = clients.getPool().getBorrowedCount();
+ // The pool is LIFO, and the first client was returned last.
+ try (Socket peer = server.accept();
+ Socket other = server.accept()) {
+ peer.setSoTimeout(3_000);
+ long deadline = System.currentTimeMillis() + (abort ? 20_000 : 800);
+ SinkChannel channel = channel(endpoint, deadline, clients);
+ channel.setNoMoreTsBlocks();
+ assertTrue(peer.getInputStream().read() >= 0);
+ if (abort) {
+ channel.abort();
+ }
+ awaitWorker();
+ assertEquals(borrowed + 1, clients.getPool().getBorrowedCount());
+ assertEquals(0, clients.getPool().getNumActive());
+ assertEquals(1, clients.getPool().getNumIdle());
+ verify(listener, never()).onEndOfBlocks(channel);
+ if (abort) {
+ verify(listener, never()).onFailure(any(), any());
+ } else {
+ verify(listener).onFailure(eq(channel),
isA(QueryTimeoutException.class));
+ }
+ }
+ } finally {
+ clients.close();
+ }
+ }
+}
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/exchange/SinkChannelFailurePropagationTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/exchange/SinkChannelFailurePropagationTest.java
index 7030b5c210c..12e2cc105fe 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/exchange/SinkChannelFailurePropagationTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/exchange/SinkChannelFailurePropagationTest.java
@@ -22,6 +22,7 @@ package org.apache.iotdb.db.queryengine.execution.exchange;
import org.apache.iotdb.common.rpc.thrift.TDataNodeLocation;
import org.apache.iotdb.common.rpc.thrift.TEndPoint;
import org.apache.iotdb.commons.client.IClientManager;
+import org.apache.iotdb.commons.client.sync.MPPDataExchangeClientManager;
import org.apache.iotdb.commons.client.sync.SyncDataNodeInternalServiceClient;
import
org.apache.iotdb.commons.client.sync.SyncDataNodeMPPDataExchangeServiceClient;
import org.apache.iotdb.db.queryengine.common.FragmentInstanceId;
@@ -79,7 +80,7 @@ public class SinkChannelFailurePropagationTest {
Mockito.mock(LocalMemoryManager.class),
new TsBlockSerdeFactory(),
exchangeExecutor,
- Mockito.mock(IClientManager.class));
+ Mockito.mock(MPPDataExchangeClientManager.class));
AtomicInteger remainingChannels = new AtomicInteger(1);
AtomicBoolean hasChannelFailedOrAborted = new AtomicBoolean(false);
AtomicBoolean callbackInvoked = new AtomicBoolean(false);
@@ -131,8 +132,8 @@ public class SinkChannelFailurePropagationTest {
MemoryPool memoryPool = Utils.createMockNonBlockedMemoryPool();
Mockito.when(localMemoryManager.getQueryPool()).thenReturn(memoryPool);
- IClientManager<TEndPoint, SyncDataNodeMPPDataExchangeServiceClient>
exchangeClientManager =
- Mockito.mock(IClientManager.class);
+ MPPDataExchangeClientManager exchangeClientManager =
+ Mockito.mock(MPPDataExchangeClientManager.class);
SyncDataNodeMPPDataExchangeServiceClient exchangeClient =
Mockito.mock(SyncDataNodeMPPDataExchangeServiceClient.class);
TException expectedFailure =
@@ -143,7 +144,8 @@ public class SinkChannelFailurePropagationTest {
new TApplicationException(
TApplicationException.INTERNAL_ERROR,
"Internal error processing onNewDataBlockEvent")));
-
Mockito.when(exchangeClientManager.borrowClient(secondEndpoint)).thenReturn(exchangeClient);
+ Mockito.when(exchangeClientManager.borrowClient(secondEndpoint,
Long.MAX_VALUE))
+ .thenReturn(exchangeClient);
Mockito.doThrow(expectedFailure)
.when(exchangeClient)
.onNewDataBlockEvent(Mockito.any(TNewDataBlockEvent.class));
@@ -226,12 +228,13 @@ public class SinkChannelFailurePropagationTest {
MemoryPool memoryPool = Utils.createMockNonBlockedMemoryPool();
Mockito.when(localMemoryManager.getQueryPool()).thenReturn(memoryPool);
- IClientManager<TEndPoint, SyncDataNodeMPPDataExchangeServiceClient>
exchangeClientManager =
- Mockito.mock(IClientManager.class);
+ MPPDataExchangeClientManager exchangeClientManager =
+ Mockito.mock(MPPDataExchangeClientManager.class);
SyncDataNodeMPPDataExchangeServiceClient exchangeClient =
Mockito.mock(SyncDataNodeMPPDataExchangeServiceClient.class);
TException expectedFailure = new TException("injected
onNewDataBlockEvent failure");
-
Mockito.when(exchangeClientManager.borrowClient(exchangeEndpoint)).thenReturn(exchangeClient);
+ Mockito.when(exchangeClientManager.borrowClient(exchangeEndpoint,
Long.MAX_VALUE))
+ .thenReturn(exchangeClient);
Mockito.doThrow(expectedFailure)
.when(exchangeClient)
.onNewDataBlockEvent(Mockito.any(TNewDataBlockEvent.class));
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/exchange/SinkChannelTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/exchange/SinkChannelTest.java
index f22725c0fea..220993bbfad 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/exchange/SinkChannelTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/exchange/SinkChannelTest.java
@@ -20,8 +20,8 @@
package org.apache.iotdb.db.queryengine.execution.exchange;
import org.apache.iotdb.common.rpc.thrift.TEndPoint;
-import org.apache.iotdb.commons.client.IClientManager;
import org.apache.iotdb.commons.client.exception.ClientManagerException;
+import org.apache.iotdb.commons.client.sync.MPPDataExchangeClientManager;
import
org.apache.iotdb.commons.client.sync.SyncDataNodeMPPDataExchangeServiceClient;
import org.apache.iotdb.commons.memory.MemoryManager;
import org.apache.iotdb.db.conf.IoTDBDescriptor;
@@ -67,13 +67,14 @@ public class SinkChannelTest {
LocalMemoryManager mockLocalMemoryManager =
Mockito.mock(LocalMemoryManager.class);
MemoryPool mockMemoryPool = Utils.createMockNonBlockedMemoryPool();
Mockito.when(mockLocalMemoryManager.getQueryPool()).thenReturn(mockMemoryPool);
- IClientManager<TEndPoint, SyncDataNodeMPPDataExchangeServiceClient>
mockClientManager =
- Mockito.mock(IClientManager.class);
+ MPPDataExchangeClientManager mockClientManager =
+ Mockito.mock(MPPDataExchangeClientManager.class);
// Construct a mock client.
SyncDataNodeMPPDataExchangeServiceClient mockClient =
Mockito.mock(SyncDataNodeMPPDataExchangeServiceClient.class);
try {
-
Mockito.when(mockClientManager.borrowClient(remoteEndpoint)).thenReturn(mockClient);
+ Mockito.when(mockClientManager.borrowClient(remoteEndpoint,
Long.MAX_VALUE))
+ .thenReturn(mockClient);
Mockito.doNothing()
.when(mockClient)
.onEndOfDataBlockEvent(Mockito.any(TEndOfDataBlockEvent.class));
@@ -232,13 +233,14 @@ public class SinkChannelTest {
SinkListener mockSinkListener = Mockito.mock(SinkListener.class);
// Construct several mock TsBlock(s).
List<TsBlock> mockTsBlocks = Utils.createMockTsBlocks(numOfMockTsBlock,
mockTsBlockSize);
- IClientManager<TEndPoint, SyncDataNodeMPPDataExchangeServiceClient>
mockClientManager =
- Mockito.mock(IClientManager.class);
+ MPPDataExchangeClientManager mockClientManager =
+ Mockito.mock(MPPDataExchangeClientManager.class);
// Construct a mock client.
SyncDataNodeMPPDataExchangeServiceClient mockClient =
Mockito.mock(SyncDataNodeMPPDataExchangeServiceClient.class);
try {
-
Mockito.when(mockClientManager.borrowClient(remoteEndpoint)).thenReturn(mockClient);
+ Mockito.when(mockClientManager.borrowClient(remoteEndpoint,
Long.MAX_VALUE))
+ .thenReturn(mockClient);
Mockito.doNothing()
.when(mockClient)
.onEndOfDataBlockEvent(Mockito.any(TEndOfDataBlockEvent.class));
@@ -436,14 +438,15 @@ public class SinkChannelTest {
SinkListener mockSinkListener = Mockito.mock(SinkListener.class);
// Construct several mock TsBlock(s).
List<TsBlock> mockTsBlocks = Utils.createMockTsBlocks(numOfMockTsBlock,
mockTsBlockSize);
- IClientManager<TEndPoint, SyncDataNodeMPPDataExchangeServiceClient>
mockClientManager =
- Mockito.mock(IClientManager.class);
+ MPPDataExchangeClientManager mockClientManager =
+ Mockito.mock(MPPDataExchangeClientManager.class);
// Construct a mock client.
SyncDataNodeMPPDataExchangeServiceClient mockClient =
Mockito.mock(SyncDataNodeMPPDataExchangeServiceClient.class);
TException mockException = new TException("Mock exception");
try {
-
Mockito.when(mockClientManager.borrowClient(remoteEndpoint)).thenReturn(mockClient);
+ Mockito.when(mockClientManager.borrowClient(remoteEndpoint,
Long.MAX_VALUE))
+ .thenReturn(mockClient);
Mockito.doThrow(mockException)
.when(mockClient)
.onEndOfDataBlockEvent(Mockito.any(TEndOfDataBlockEvent.class));
@@ -547,13 +550,14 @@ public class SinkChannelTest {
SinkListener mockSinkListener = Mockito.mock(SinkListener.class);
// Construct several mock TsBlock(s).
List<TsBlock> mockTsBlocks = Utils.createMockTsBlocks(numOfMockTsBlock,
mockTsBlockSize);
- IClientManager<TEndPoint, SyncDataNodeMPPDataExchangeServiceClient>
mockClientManager =
- Mockito.mock(IClientManager.class);
+ MPPDataExchangeClientManager mockClientManager =
+ Mockito.mock(MPPDataExchangeClientManager.class);
// Construct a mock client.
SyncDataNodeMPPDataExchangeServiceClient mockClient =
Mockito.mock(SyncDataNodeMPPDataExchangeServiceClient.class);
try {
-
Mockito.when(mockClientManager.borrowClient(remoteEndpoint)).thenReturn(mockClient);
+ Mockito.when(mockClientManager.borrowClient(remoteEndpoint,
Long.MAX_VALUE))
+ .thenReturn(mockClient);
Mockito.doNothing()
.when(mockClient)
.onEndOfDataBlockEvent(Mockito.any(TEndOfDataBlockEvent.class));
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/fragment/FragmentInstanceContextTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/fragment/FragmentInstanceContextTest.java
index 4c103afff0d..002eb5fb02d 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/fragment/FragmentInstanceContextTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/fragment/FragmentInstanceContextTest.java
@@ -34,6 +34,7 @@ import org.apache.iotdb.commons.service.metric.enums.Metric;
import org.apache.iotdb.commons.service.metric.enums.Tag;
import org.apache.iotdb.db.queryengine.common.FragmentInstanceId;
import org.apache.iotdb.db.queryengine.common.PlanFragmentId;
+import org.apache.iotdb.db.queryengine.common.QueryId;
import org.apache.iotdb.db.queryengine.execution.aggregation.TreeAggregator;
import
org.apache.iotdb.db.queryengine.execution.aggregation.timerangeiterator.ITimeRangeIterator;
import org.apache.iotdb.db.queryengine.execution.driver.DriverContext;
@@ -75,6 +76,29 @@ import static org.junit.Assert.assertTrue;
public class FragmentInstanceContextTest {
+ @Test
+ public void exchangeDeadlineHonorsBothCoordinatorAndLegacyFragmentLimits() {
+ FragmentInstanceId id =
+ new FragmentInstanceId(new PlanFragmentId(new QueryId("deadline"), 0),
"0");
+ FragmentInstanceStateMachine state = new FragmentInstanceStateMachine(id,
Runnable::run);
+ long localDeadline = System.currentTimeMillis() + 30_000;
+ FragmentInstanceContext context =
+ FragmentInstanceContext.createFragmentInstanceContext(
+ id, state, null, localDeadline, false, false);
+ assertEquals(localDeadline, context.getExchangeDeadlineMs());
+ context.setExchangeDeadlineMs(localDeadline - 1000);
+ assertEquals(localDeadline - 1000, context.getExchangeDeadlineMs());
+ assertEquals(localDeadline, context.getOuterQueryDeadlineMs());
+ context.setExchangeDeadlineMs(Long.MAX_VALUE);
+ assertEquals(localDeadline, context.getExchangeDeadlineMs());
+
+ FragmentInstanceContext withoutLocalDeadline =
+ FragmentInstanceContext.createFragmentInstanceContext(id, state);
+ assertEquals(-1L, withoutLocalDeadline.getExchangeDeadlineMs());
+ withoutLocalDeadline.setExchangeDeadlineMs(localDeadline);
+ assertEquals(localDeadline, withoutLocalDeadline.getExchangeDeadlineMs());
+ }
+
@Test
public void testConcurrentQueryDataSourceStatistics() throws
InterruptedException {
ExecutorService instanceNotificationExecutor =
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/spill/DeviceEntryRpcSegmentFetcherTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/spill/DeviceEntryRpcSegmentFetcherTest.java
index 62c0784567c..c752d12b5b4 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/spill/DeviceEntryRpcSegmentFetcherTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/spill/DeviceEntryRpcSegmentFetcherTest.java
@@ -33,9 +33,11 @@ import org.junit.Test;
import org.mockito.Mockito;
import java.io.IOException;
+import java.nio.channels.ClosedByInterruptException;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -75,6 +77,27 @@ public class DeviceEntryRpcSegmentFetcherTest {
verify(client, times(3)).fetchDeviceEntrySegment(any());
}
+ @Test
+ public void driverInterruptStopsRetriesForFetchAndFinish() throws Exception {
+ when(client.fetchDeviceEntrySegment(any()))
+ .thenAnswer(
+ call -> {
+ Thread.currentThread().interrupt();
+ throw new TException(new ClosedByInterruptException());
+ });
+ when(client.finishDeviceEntrySegment(any(), any()))
+ .thenThrow(new TException(new ClosedByInterruptException()));
+ try {
+ assertThrows(IOException.class, () -> fetcher.fetch(handle, 0));
+ assertTrue(Thread.currentThread().isInterrupted());
+ verify(client).fetchDeviceEntrySegment(any());
+ fetcher.finish(handle);
+ verify(client).finishDeviceEntrySegment(any(), any());
+ } finally {
+ Thread.interrupted();
+ }
+ }
+
@Test
public void testFetchDoesNotRetryServerFailure() throws Exception {
when(client.fetchDeviceEntrySegment(any()))
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/scheduler/FragmentInstanceDispatcherLifecycleTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/scheduler/FragmentInstanceDispatcherLifecycleTest.java
index 5846254faad..a88240f52d0 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/scheduler/FragmentInstanceDispatcherLifecycleTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/scheduler/FragmentInstanceDispatcherLifecycleTest.java
@@ -119,6 +119,8 @@ public class FragmentInstanceDispatcherLifecycleTest {
public void transportRetryReusesTokenAndStopFreezesIssuedTokens() throws
Exception {
FragmentInstanceDispatcherImpl dispatcher = dispatcher();
context.prepareForRetry();
+ context.setTimeOut(30_000);
+ context.setStartTime(System.currentTimeMillis() - 3_200);
List<TSendFragmentInstanceReq> requests = new ArrayList<>();
when(client.sendFragmentInstance(any()))
.thenAnswer(
@@ -126,6 +128,11 @@ public class FragmentInstanceDispatcherLifecycleTest {
TSendFragmentInstanceReq request = invocation.getArgument(0);
requests.add(request.deepCopy());
if (requests.size() == 1) {
+ // Wait for the coordinator clock to advance before the retry.
+ long firstSend = System.currentTimeMillis();
+ while (System.currentTimeMillis() <= firstSend) {
+ Thread.sleep(1);
+ }
throw new TException("response lost");
}
return new TSendFragmentInstanceResp(true);
@@ -133,6 +140,17 @@ public class FragmentInstanceDispatcherLifecycleTest {
FragmentInstance instance = instance(0);
assertTrue(dispatcher.dispatch(null,
Collections.singletonList(instance)).get().isSuccessful());
assertEquals(2, requests.size());
+ long firstBudget = requests.get(0).getRemainingQueryTimeMs();
+ long retryBudget = requests.get(1).getRemainingQueryTimeMs();
+ assertTrue(firstBudget <= 30_000 - 3_200);
+ assertTrue(retryBudget > 0 && retryBudget < firstBudget);
+ // Both receivers have the same remaining budget even if their clocks
differ by a minute.
+ FragmentInstance receiver = instance(1);
+ for (long receiverNow :
+ new long[] {context.getStartTime() - 60_000, context.getStartTime() +
60_000}) {
+ receiver.setQueryDeadlineFromTimeout(receiverNow, retryBudget);
+ assertEquals(receiverNow + retryBudget, receiver.getQueryDeadlineMs());
+ }
assertEquals(0, requests.get(0).getQueryAttemptId());
assertEquals(token, requests.get(0).getAdmissionToken());
assertEquals(requests.get(0).getAdmissionToken(),
requests.get(1).getAdmissionToken());
@@ -145,6 +163,59 @@ public class FragmentInstanceDispatcherLifecycleTest {
assertEquals(issued, dispatcher.getIssuedAdmissionTokens());
}
+ @Test
+ public void expiredBudgetSkipsAdmissionAndDispatch() throws Exception {
+ FragmentInstanceDispatcherImpl dispatcher = dispatcher();
+ context.setStartTime(System.currentTimeMillis() - 10_000);
+ context.setTimeOut(4_000);
+ FragInstanceDispatchResult result =
+ dispatcher.dispatch(null,
Collections.singletonList(instance(0))).get();
+ assertEquals(TSStatusCode.QUERY_TIMEOUT.getStatusCode(),
result.getFailureStatus().getCode());
+ verify(client, never()).fetchQueryAdmissionToken(anyLong());
+ verify(client, never()).sendFragmentInstance(any());
+ }
+
+ @Test
+ public void rechecksBudgetAfterAdmission() throws Exception {
+ FragmentInstanceDispatcherImpl dispatcher = dispatcher();
+ context.setTimeOut(10_000);
+ FragmentInstance fi = instance(0);
+ when(client.fetchQueryAdmissionToken(anyLong()))
+ .thenAnswer(
+ invocation -> {
+ // Model a query that expired while the token RPC was in flight.
+ fi.setQueryDeadlineFromTimeout(System.currentTimeMillis(), 0);
+ return token;
+ });
+ FragInstanceDispatchResult result =
+ dispatcher.dispatch(null, Collections.singletonList(fi)).get();
+ assertEquals(TSStatusCode.QUERY_TIMEOUT.getStatusCode(),
result.getFailureStatus().getCode());
+ verify(client, never()).sendFragmentInstance(any());
+ }
+
+ @Test
+ public void
unspecifiedCoordinatorTimeoutRetainsTheFragmentLimitOnReconnect() throws
Exception {
+ FragmentInstanceDispatcherImpl dispatcher = dispatcher();
+ context.setTimeOut(0);
+ List<TSendFragmentInstanceReq> requests = new ArrayList<>();
+ when(client.sendFragmentInstance(any()))
+ .thenAnswer(
+ invocation -> {
+ TSendFragmentInstanceReq request = invocation.getArgument(0);
+ requests.add(request.deepCopy());
+ if (requests.size() == 1) {
+ throw new TException("connection closed");
+ }
+ return new TSendFragmentInstanceResp(true);
+ });
+ assertTrue(
+ dispatcher.dispatch(null,
Collections.singletonList(instance(0))).get().isSuccessful());
+ assertEquals(2, requests.size());
+ for (TSendFragmentInstanceReq request : requests) {
+ assertFalse(request.isSetRemainingQueryTimeMs());
+ }
+ }
+
@Test
public void fragmentsOnTheSameNodeReuseOneTokenRpc() throws Exception {
FragmentInstanceDispatcherImpl dispatcher = dispatcher();
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/scheduler/QueryAttemptProtocolTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/scheduler/QueryAttemptProtocolTest.java
index d77cdc8e1a7..b950f0dcba9 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/scheduler/QueryAttemptProtocolTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/scheduler/QueryAttemptProtocolTest.java
@@ -49,6 +49,7 @@ public class QueryAttemptProtocolTest {
assertEquals(original, received);
assertFalse(received.isSetQueryAttemptId());
assertFalse(received.isSetAdmissionToken());
+ assertFalse(received.isSetRemainingQueryTimeMs());
TCancelQueryReq cancel = new TCancelQueryReq("query",
Collections.emptyList(), true);
TCancelQueryReq receivedCancel = new TCancelQueryReq();
new TDeserializer().deserialize(receivedCancel, new
TSerializer().serialize(cancel));
@@ -62,6 +63,7 @@ public class QueryAttemptProtocolTest {
TFragmentInstance body = new TFragmentInstance(ByteBuffer.wrap(new byte[]
{1, 2, 3}));
TSendFragmentInstanceReq request =
new TSendFragmentInstanceReq(body)
+ .setRemainingQueryTimeMs(800L)
.setQueryAttemptId(2)
.setAdmissionToken(new TQueryAdmissionToken("receiver", 123450L,
1000L));
byte[] serialized = new TSerializer().serialize(request);
diff --git
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/client/ClientManager.java
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/client/ClientManager.java
index 336658fd5dd..05e698f67ac 100644
---
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/client/ClientManager.java
+++
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/client/ClientManager.java
@@ -38,7 +38,7 @@ public class ClientManager<K, V> implements IClientManager<K,
V> {
private final GenericKeyedObjectPool<K, V> pool;
- ClientManager(IClientPoolFactory<K, V> factory) {
+ protected ClientManager(IClientPoolFactory<K, V> factory) {
pool = factory.createClientPool(this);
}
@@ -49,11 +49,23 @@ public class ClientManager<K, V> implements
IClientManager<K, V> {
@Override
public V borrowClient(K node) throws ClientManagerException {
+ return borrowClientWithTimeout(node, Long.MAX_VALUE);
+ }
+
+ protected V borrowClientWithTimeout(K node, long maxWaitMs) throws
ClientManagerException {
if (node == null) {
throw new BorrowNullClientManagerException();
}
try {
- return pool.borrowObject(node);
+ if (maxWaitMs == Long.MAX_VALUE) {
+ return pool.borrowObject(node);
+ }
+ maxWaitMs = Math.max(0L, maxWaitMs);
+ long poolWaitMs = pool.getMaxWaitDuration().toMillis();
+ return pool.borrowObject(node, poolWaitMs < 0 ? maxWaitMs :
Math.min(poolWaitMs, maxWaitMs));
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new ClientManagerException(e);
} catch (Exception e) {
throw new ClientManagerException(e);
}
diff --git
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/client/ThriftClient.java
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/client/ThriftClient.java
index 64c48fb2c49..e79c223fbaf 100644
---
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/client/ThriftClient.java
+++
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/client/ThriftClient.java
@@ -30,7 +30,7 @@ import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.ConnectException;
-import java.net.SocketException;
+import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.ClosedChannelException;
import java.util.Optional;
@@ -106,15 +106,15 @@ public interface ThriftClient {
* @return true/false
*/
static boolean isConnectionBroken(Throwable cause) {
- return (cause instanceof SocketException &&
cause.getMessage().contains("Broken pipe"))
- || (cause instanceof TTransportException
+ return (cause instanceof TTransportException
&& (hasExpectedMessage(cause, "Socket is closed by peer")
|| hasExpectedMessage(cause, "Read call frame size failed")))
|| (cause instanceof IOException
&& (hasExpectedMessage(cause, "Connection reset by peer")
|| hasExpectedMessage(cause, "Broken pipe")))
- || (cause instanceof ConnectException && hasExpectedMessage(cause,
"Connection refused")
- || (cause instanceof ClosedChannelException))
+ || (cause instanceof ConnectException && hasExpectedMessage(cause,
"Connection refused"))
+ || (cause instanceof ClosedChannelException
+ && !(cause instanceof ClosedByInterruptException))
|| (cause instanceof java.util.concurrent.TimeoutException);
}
diff --git
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/client/sync/MPPDataExchangeClientManager.java
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/client/sync/MPPDataExchangeClientManager.java
new file mode 100644
index 00000000000..77ff9b19a53
--- /dev/null
+++
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/client/sync/MPPDataExchangeClientManager.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.commons.client.sync;
+
+import org.apache.iotdb.common.rpc.thrift.TEndPoint;
+import org.apache.iotdb.commons.client.ClientManager;
+import org.apache.iotdb.commons.client.ClientPoolFactory;
+import org.apache.iotdb.commons.client.exception.ClientManagerException;
+import org.apache.iotdb.commons.exception.QueryTimeoutException;
+
+import org.apache.thrift.transport.TTransportException;
+
+import java.io.IOException;
+
+public class MPPDataExchangeClientManager
+ extends ClientManager<TEndPoint, SyncDataNodeMPPDataExchangeServiceClient>
{
+
+ public MPPDataExchangeClientManager() {
+ super(new
ClientPoolFactory.SyncDataNodeMPPDataExchangeServiceClientPoolFactory());
+ }
+
+ @Override
+ public SyncDataNodeMPPDataExchangeServiceClient borrowClient(TEndPoint
endpoint)
+ throws ClientManagerException {
+ return borrowClient(endpoint, Long.MAX_VALUE);
+ }
+
+ public SyncDataNodeMPPDataExchangeServiceClient borrowClient(TEndPoint
endpoint, long deadlineMs)
+ throws ClientManagerException {
+ SyncDataNodeMPPDataExchangeServiceClient client = null;
+ boolean ready = false;
+ try {
+ client = borrowClientWithTimeout(endpoint, remainingMillis(deadlineMs));
+ client.prepare(deadlineMs);
+ ready = true;
+ return client;
+ } catch (IOException | TTransportException | RuntimeException e) {
+ throw new ClientManagerException(e);
+ } finally {
+ if (client != null && !ready) {
+ try {
+ client.invalidate();
+ } finally {
+ client.close();
+ }
+ }
+ }
+ }
+
+ public static long remainingMillis(long deadlineMs) {
+ if (deadlineMs == Long.MAX_VALUE) {
+ return Long.MAX_VALUE;
+ }
+ long remaining = deadlineMs - System.currentTimeMillis();
+ if (remaining <= 0) {
+ throw new QueryTimeoutException();
+ }
+ return remaining;
+ }
+}
diff --git
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/client/sync/SyncDataNodeMPPDataExchangeServiceClient.java
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/client/sync/SyncDataNodeMPPDataExchangeServiceClient.java
index b4393bfd4ee..da6d1e938be 100644
---
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/client/sync/SyncDataNodeMPPDataExchangeServiceClient.java
+++
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/client/sync/SyncDataNodeMPPDataExchangeServiceClient.java
@@ -26,57 +26,219 @@ import
org.apache.iotdb.commons.client.factory.ThriftClientFactory;
import org.apache.iotdb.commons.client.property.ThriftClientProperty;
import org.apache.iotdb.commons.conf.CommonConfig;
import org.apache.iotdb.commons.conf.CommonDescriptor;
+import org.apache.iotdb.commons.i18n.ServiceMessages;
import org.apache.iotdb.mpp.rpc.thrift.MPPDataExchangeService;
import org.apache.iotdb.rpc.DeepCopyRpcTransportFactory;
-import org.apache.iotdb.rpc.TConfigurationConst;
+import org.apache.iotdb.rpc.RpcSslUtils;
import org.apache.iotdb.rpc.TimeoutChangeableTransport;
+import com.google.common.io.Closer;
+import com.google.common.net.InetAddresses;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.thrift.transport.TSocket;
+import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
+import org.apache.tsfile.external.commons.lang3.StringUtils;
+import javax.net.ssl.SSLParameters;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.SSLSocketFactory;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.Socket;
import java.net.SocketException;
+import java.nio.channels.ClosedByInterruptException;
+import java.nio.channels.SocketChannel;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileTime;
+import java.security.GeneralSecurityException;
+import java.util.concurrent.atomic.AtomicReference;
public class SyncDataNodeMPPDataExchangeServiceClient extends
MPPDataExchangeService.Client
implements ThriftClient, AutoCloseable {
- private final boolean printLogWhenEncounterException;
+ private static final CommonConfig commonConfig =
CommonDescriptor.getInstance().getConfig();
+
+ private final ThriftClientProperty property;
+ private final int defaultTimeoutMs;
private final TEndPoint endpoint;
private final ClientManager<TEndPoint,
SyncDataNodeMPPDataExchangeServiceClient> clientManager;
- private static final CommonConfig commonConfig =
CommonDescriptor.getInstance().getConfig();
+ private boolean invalidated;
+ private boolean restoreTimeout;
public SyncDataNodeMPPDataExchangeServiceClient(
ThriftClientProperty property,
TEndPoint endpoint,
ClientManager<TEndPoint, SyncDataNodeMPPDataExchangeServiceClient>
clientManager)
throws TTransportException {
- super(
- property
- .getProtocolFactory()
- .getProtocol(
- commonConfig.isEnableInternalSSL()
- ? DeepCopyRpcTransportFactory.INSTANCE.getTransport(
- endpoint.getIp(),
- endpoint.getPort(),
- property.getConnectionTimeoutMs(),
- commonConfig.getTrustStorePath(),
- commonConfig.getTrustStorePwd(),
- commonConfig.getKeyStorePath(),
- commonConfig.getKeyStorePwd(),
- commonConfig.getSslProtocol())
- : DeepCopyRpcTransportFactory.INSTANCE.getTransport(
- new TSocket(
- TConfigurationConst.defaultTConfiguration,
- endpoint.getIp(),
- endpoint.getPort(),
- property.getConnectionTimeoutMs()))));
- this.printLogWhenEncounterException =
property.isPrintLogWhenEncounterException();
+ this(property, endpoint, clientManager, true);
+ }
+
+ // Deadline-aware borrowers open new connections after Commons Pool hands
out the client.
+ protected SyncDataNodeMPPDataExchangeServiceClient(
+ ThriftClientProperty property,
+ TEndPoint endpoint,
+ ClientManager<TEndPoint, SyncDataNodeMPPDataExchangeServiceClient>
clientManager,
+ boolean openImmediately)
+ throws TTransportException {
+ super(null);
+ this.property = property;
+ this.defaultTimeoutMs = Math.max(0, property.getConnectionTimeoutMs());
this.endpoint = endpoint;
this.clientManager = clientManager;
- if (!getInputProtocol().getTransport().isOpen()) {
- getInputProtocol().getTransport().open();
+ if (openImmediately) {
+ try {
+ prepare(Long.MAX_VALUE);
+ } catch (IOException e) {
+ throw new TTransportException(e);
+ }
+ }
+ }
+
+ final void prepare(long deadlineMs) throws TTransportException, IOException {
+ if (iprot_ == null) {
+ SocketChannel channel = SocketChannel.open();
+ // TSocket owns the channel once its protocol has been installed.
+ try (Closeable rollback = closeUnlessConnected(channel)) {
+ connect(channel.socket(), deadlineMs);
+ }
+ }
+ if (deadlineMs != Long.MAX_VALUE) {
+ setTimeout(rpcTimeout(deadlineMs));
+ }
+ }
+
+ private Closeable closeUnlessConnected(Closeable resources) {
+ return () -> {
+ if (iprot_ == null) {
+ resources.close();
+ }
+ };
+ }
+
+ final void connect(Socket socket, long deadlineMs) throws IOException,
TTransportException {
+ Closer resources = Closer.create();
+ try (Closeable rollback = closeUnlessConnected(resources)) {
+ resources.register(socket);
+ checkConnectionSetupActive(deadlineMs);
+ String host = endpoint.getIp();
+ int port = endpoint.getPort();
+ // JVM hostname lookup runs on the caller and can outlast the deadline.
Recheck the budget
+ // before starting TCP I/O. IP literals take this direct path with or
without TLS.
+ InetSocketAddress address =
+ InetAddresses.isInetAddress(host)
+ ? new InetSocketAddress(InetAddresses.forString(host), port)
+ : new InetSocketAddress(host, port);
+ SSLSocketFactory sslFactory = null;
+ if (commonConfig.isEnableInternalSSL()) {
+ checkConnectionSetupActive(deadlineMs);
+ sslFactory = sslSocketFactory();
+ }
+ socket.connect(address, rpcTimeout(deadlineMs));
+ if (sslFactory != null) {
+ socket.setSoTimeout(rpcTimeout(deadlineMs));
+ SSLSocket ssl =
+ resources.register((SSLSocket) sslFactory.createSocket(socket,
host, port, true));
+ // Match TSSLTransportFactory.createClient in libthrift 0.25, used by
other internal
+ // clients.
+ SSLParameters params = ssl.getSSLParameters();
+ params.setEndpointIdentificationAlgorithm("HTTPS");
+ ssl.setSSLParameters(params);
+ socket = ssl;
+ }
+ socket.setSoTimeout(rpcTimeout(deadlineMs));
+ TTransport transport =
+ resources.register(
+ DeepCopyRpcTransportFactory.INSTANCE.getTransport(new
TSocket(socket)));
+ iprot_ = oprot_ = property.getProtocolFactory().getProtocol(transport);
+ }
+ }
+
+ private static void checkConnectionSetupActive(long deadlineMs)
+ throws ClosedByInterruptException {
+ MPPDataExchangeClientManager.remainingMillis(deadlineMs);
+ if (Thread.currentThread().isInterrupted()) {
+ throw new ClosedByInterruptException();
+ }
+ }
+
+ private record StoreVersion(
+ String path, String password, FileTime modified, long size, Object
fileKey) {
+ static StoreVersion read(String path, String password) throws IOException {
+ if (StringUtils.isBlank(path)) {
+ return new StoreVersion(null, null, null, 0L, null);
+ }
+ BasicFileAttributes attributes =
+ Files.readAttributes(Path.of(path), BasicFileAttributes.class);
+ return new StoreVersion(
+ path, password, attributes.lastModifiedTime(), attributes.size(),
attributes.fileKey());
}
+
+ @Override
+ public String toString() {
+ return String.valueOf(path);
+ }
+ }
+
+ private record TlsSettings(String protocol, StoreVersion keys, StoreVersion
trust) {
+ static TlsSettings read() throws IOException, TTransportException {
+ StoreVersion keys =
+ StoreVersion.read(commonConfig.getKeyStorePath(),
commonConfig.getKeyStorePwd());
+ StoreVersion trust =
+ StoreVersion.read(commonConfig.getTrustStorePath(),
commonConfig.getTrustStorePwd());
+ if (keys.path() == null && trust.path() == null) {
+ throw new
TTransportException(ServiceMessages.KEYSTORE_OR_TRUSTSTORE_NOT_FOUND);
+ }
+ return new TlsSettings(
+ RpcSslUtils.resolveProtocol(commonConfig.getSslProtocol()), keys,
trust);
+ }
+
+ SSLSocketFactory load() throws IOException, TTransportException {
+ try {
+ return RpcSslUtils.createSSLContext(
+ keys.path(), keys.password(), trust.path(), trust.password(),
protocol)
+ .getSocketFactory();
+ } catch (GeneralSecurityException e) {
+ throw new TTransportException(e);
+ }
+ }
+ }
+
+ private record CachedSslFactory(TlsSettings settings, SSLSocketFactory
factory) {}
+
+ private static final AtomicReference<CachedSslFactory> cachedSslFactory =
new AtomicReference<>();
+
+ static SSLSocketFactory sslSocketFactory() throws IOException,
TTransportException {
+ CachedSslFactory cached = cachedSslFactory.get();
+ if (cached != null && cached.settings().equals(TlsSettings.read())) {
+ return cached.factory();
+ }
+ return reloadSslSocketFactory();
+ }
+
+ private static synchronized SSLSocketFactory reloadSslSocketFactory()
+ throws IOException, TTransportException {
+ // Re-read after acquiring the lock in case another borrower observed a
certificate rotation.
+ TlsSettings current = TlsSettings.read();
+ CachedSslFactory cached = cachedSslFactory.get();
+ if (cached == null || !cached.settings().equals(current)) {
+ cached = new CachedSslFactory(current, current.load());
+ cachedSslFactory.set(cached);
+ }
+ return cached.factory();
+ }
+
+ private int rpcTimeout(long deadlineMs) {
+ if (deadlineMs == Long.MAX_VALUE) {
+ return defaultTimeoutMs;
+ }
+ long remaining = MPPDataExchangeClientManager.remainingMillis(deadlineMs);
+ return (int) Math.min(remaining, defaultTimeoutMs > 0 ? defaultTimeoutMs :
Integer.MAX_VALUE);
}
public int getTimeout() throws SocketException {
@@ -84,6 +246,7 @@ public class SyncDataNodeMPPDataExchangeServiceClient
extends MPPDataExchangeSer
}
public void setTimeout(int timeout) {
+ restoreTimeout = timeout != defaultTimeoutMs;
// the same transport is used in both input and output
((TimeoutChangeableTransport)
(getInputProtocol().getTransport())).setTimeout(timeout);
}
@@ -95,7 +258,12 @@ public class SyncDataNodeMPPDataExchangeServiceClient
extends MPPDataExchangeSer
@Override
public void invalidate() {
- getInputProtocol().getTransport().close();
+ if (!invalidated) {
+ invalidated = true;
+ if (iprot_ != null) {
+ iprot_.getTransport().close();
+ }
+ }
}
@Override
@@ -105,7 +273,7 @@ public class SyncDataNodeMPPDataExchangeServiceClient
extends MPPDataExchangeSer
@Override
public boolean printLogWhenEncounterException() {
- return printLogWhenEncounterException;
+ return property.isPrintLogWhenEncounterException();
}
@Override
@@ -134,17 +302,29 @@ public class SyncDataNodeMPPDataExchangeServiceClient
extends MPPDataExchangeSer
return new DefaultPooledObject<>(
SyncThriftClientWithErrorHandler.newErrorHandler(
SyncDataNodeMPPDataExchangeServiceClient.class,
- SyncDataNodeMPPDataExchangeServiceClient.class.getConstructor(
- thriftClientProperty.getClass(), endpoint.getClass(),
clientManager.getClass()),
+
SyncDataNodeMPPDataExchangeServiceClient.class.getDeclaredConstructor(
+ ThriftClientProperty.class, TEndPoint.class,
ClientManager.class, boolean.class),
thriftClientProperty,
endpoint,
- clientManager));
+ clientManager,
+ !(clientManager instanceof MPPDataExchangeClientManager)));
+ }
+
+ @Override
+ public void passivateObject(
+ TEndPoint endpoint,
PooledObject<SyncDataNodeMPPDataExchangeServiceClient> pooledObject) {
+ SyncDataNodeMPPDataExchangeServiceClient client =
pooledObject.getObject();
+ if (client.restoreTimeout) {
+ client.setTimeout(client.defaultTimeoutMs);
+ }
}
@Override
public boolean validateObject(
TEndPoint endpoint,
PooledObject<SyncDataNodeMPPDataExchangeServiceClient> pooledObject) {
- return
pooledObject.getObject().getInputProtocol().getTransport().isOpen();
+ SyncDataNodeMPPDataExchangeServiceClient client =
pooledObject.getObject();
+ return !client.invalidated
+ && (client.iprot_ == null || client.iprot_.getTransport().isOpen());
}
}
}
diff --git
a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/client/ClientManagerTest.java
b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/client/ClientManagerTest.java
index be7cf49239a..11dc40835d0 100644
---
a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/client/ClientManagerTest.java
+++
b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/client/ClientManagerTest.java
@@ -42,11 +42,15 @@ import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
+import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -399,6 +403,22 @@ public class ClientManagerTest {
Assert.assertTrue(e.getMessage().contains("Timeout waiting for idle
object"));
}
+ // A negative caller budget must return immediately even with unbounded
pool waits configured.
+ syncClusterManager.getPool().setMaxWait(Duration.ofMillis(-1));
+ ExecutorService borrower = Executors.newSingleThreadExecutor();
+ try {
+ Future<ClientManagerException> failed =
+ borrower.submit(
+ () ->
+ Assert.assertThrows(
+ ClientManagerException.class,
+ () ->
syncClusterManager.borrowClientWithTimeout(endPoint, -1)));
+ Assert.assertTrue(
+ failed.get(5, TimeUnit.SECONDS).getCause() instanceof
NoSuchElementException);
+ } finally {
+ borrower.shutdownNow();
+ }
+
// return one sync client
syncClient1.close();
Assert.assertEquals(0,
syncClusterManager.getPool().getNumActive(endPoint));
diff --git
a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/client/sync/MPPDataExchangeClientManagerTest.java
b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/client/sync/MPPDataExchangeClientManagerTest.java
new file mode 100644
index 00000000000..f53e583d5b8
--- /dev/null
+++
b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/client/sync/MPPDataExchangeClientManagerTest.java
@@ -0,0 +1,221 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.iotdb.commons.client.sync;
+
+import org.apache.iotdb.common.rpc.thrift.TEndPoint;
+import org.apache.iotdb.commons.client.ClientManager;
+import org.apache.iotdb.commons.client.ClientPoolFactory;
+import org.apache.iotdb.commons.client.IClientManager;
+import org.apache.iotdb.commons.client.ThriftClient;
+import org.apache.iotdb.commons.client.exception.ClientManagerException;
+import org.apache.iotdb.commons.client.property.ThriftClientProperty;
+import org.apache.iotdb.commons.conf.CommonDescriptor;
+import org.apache.iotdb.commons.exception.QueryTimeoutException;
+
+import org.apache.thrift.TException;
+import org.junit.Test;
+import org.mockito.ArgumentCaptor;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.SocketAddress;
+import java.net.SocketException;
+import java.net.SocketTimeoutException;
+import java.nio.channels.ClosedByInterruptException;
+import java.time.Duration;
+
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+
+public class MPPDataExchangeClientManagerTest {
+ @Test
+ public void reusedConnectionUsesEachBorrowersTimeout() throws Exception {
+ MPPDataExchangeClientManager manager = new MPPDataExchangeClientManager();
+ int configured =
CommonDescriptor.getInstance().getConfig().getDnConnectionTimeoutInMS();
+ try (ServerSocket server = new ServerSocket(0, 1,
InetAddress.getLoopbackAddress())) {
+ TEndPoint endpoint =
+ new TEndPoint(server.getInetAddress().getHostAddress(),
server.getLocalPort());
+ SyncDataNodeMPPDataExchangeServiceClient first;
+ try (SyncDataNodeMPPDataExchangeServiceClient client =
manager.borrowClient(endpoint)) {
+ first = client;
+ assertEquals(configured, client.getTimeout());
+ }
+ try (Socket peer = server.accept()) {
+ try (SyncDataNodeMPPDataExchangeServiceClient shortQuery =
+ manager.borrowClient(endpoint, System.currentTimeMillis() +
5_000)) {
+ assertSame(first, shortQuery);
+ assertTrue(shortQuery.getTimeout() > 0 && shortQuery.getTimeout() <=
5_000);
+ }
+ try (SyncDataNodeMPPDataExchangeServiceClient legacy =
manager.borrowClient(endpoint)) {
+ assertSame(first, legacy);
+ assertEquals(configured, legacy.getTimeout());
+ }
+ try (SyncDataNodeMPPDataExchangeServiceClient longQuery =
+ manager.borrowClient(endpoint, System.currentTimeMillis() +
20_000)) {
+ assertSame(first, longQuery);
+ assertTrue(longQuery.getTimeout() > 5_000 && longQuery.getTimeout()
<= 20_000);
+ }
+ try (SyncDataNodeMPPDataExchangeServiceClient capped =
+ manager.borrowClient(endpoint, System.currentTimeMillis() + 2L *
configured)) {
+ assertEquals(configured, capped.getTimeout());
+ }
+ }
+ } finally {
+ manager.close();
+ }
+ }
+
+ @Test(timeout = 10_000)
+ public void exhaustedPoolHonorsBothQueryAndPoolWaitLimits() throws Exception
{
+ MPPDataExchangeClientManager manager = new MPPDataExchangeClientManager();
+ manager.getPool().setMaxTotalPerKey(1);
+ try (ServerSocket server = new ServerSocket(0, 1,
InetAddress.getLoopbackAddress())) {
+ TEndPoint endpoint =
+ new TEndPoint(server.getInetAddress().getHostAddress(),
server.getLocalPort());
+ try (SyncDataNodeMPPDataExchangeServiceClient held =
manager.borrowClient(endpoint);
+ Socket peer = server.accept()) {
+ long start = System.nanoTime();
+ long deadline = System.currentTimeMillis() + 150;
+ assertThrows(ClientManagerException.class, () ->
manager.borrowClient(endpoint, deadline));
+ assertTrue(System.nanoTime() - start >= MILLISECONDS.toNanos(140));
+ ClientManagerException expired =
+ assertThrows(
+ ClientManagerException.class,
+ () -> manager.borrowClient(endpoint,
System.currentTimeMillis() - 1));
+ assertTrue(expired.getCause() instanceof QueryTimeoutException);
+ manager.getPool().setMaxWait(Duration.ofMillis(30));
+ assertThrows(
+ ClientManagerException.class,
+ () -> manager.borrowClient(endpoint, System.currentTimeMillis() +
20_000));
+ assertEquals(1, manager.getPool().getNumActive());
+ }
+ assertEquals(1, manager.getPool().getNumIdle());
+ } finally {
+ manager.close();
+ }
+ }
+
+ @Test
+ public void legacyFactoryAndConstructorReturnConnectedClients() throws
Exception {
+ ThriftClientProperty property =
+ new
ThriftClientProperty.Builder().setConnectionTimeoutMs(5_000).build();
+ ClientManager<TEndPoint, SyncDataNodeMPPDataExchangeServiceClient> manager
=
+ (ClientManager<TEndPoint, SyncDataNodeMPPDataExchangeServiceClient>)
+ new IClientManager.Factory<TEndPoint,
SyncDataNodeMPPDataExchangeServiceClient>()
+ .createClientManager(
+ new
ClientPoolFactory.SyncDataNodeMPPDataExchangeServiceClientPoolFactory());
+ try (ServerSocket server = new ServerSocket(0, 3,
InetAddress.getLoopbackAddress())) {
+ TEndPoint endpoint =
+ new TEndPoint(server.getInetAddress().getHostAddress(),
server.getLocalPort());
+ try (SyncDataNodeMPPDataExchangeServiceClient borrowed =
manager.borrowClient(endpoint);
+ Socket peer = server.accept()) {
+ assertTrue(borrowed.getInputProtocol().getTransport().isOpen());
+ }
+ SyncDataNodeMPPDataExchangeServiceClient direct =
+ new SyncDataNodeMPPDataExchangeServiceClient(property, endpoint,
manager);
+ try (Socket peer = server.accept()) {
+ assertTrue(direct.getInputProtocol().getTransport().isOpen());
+ assertEquals(5_000, direct.getTimeout());
+ } finally {
+ direct.invalidate();
+ }
+ } finally {
+ manager.close();
+ }
+ }
+
+ @Test
+ public void onlyPeerFailuresClearOtherConnectionsEvenOnInterruptedWorker()
throws Exception {
+ TEndPoint endpoint = new TEndPoint("127.0.0.1", 10740);
+ MPPDataExchangeClientManager manager =
mock(MPPDataExchangeClientManager.class);
+ SyncDataNodeMPPDataExchangeServiceClient client =
+ new SyncDataNodeMPPDataExchangeServiceClient(
+ new
ThriftClientProperty.Builder().setPrintLogWhenEncounterException(false).build(),
+ endpoint,
+ manager,
+ false);
+ ThriftClient.resolveException(new TException(new
ClosedByInterruptException()), client);
+ verify(manager, never()).clear(endpoint);
+ Thread.currentThread().interrupt();
+ try {
+ ThriftClient.resolveException(new TException(new SocketException("Broken
pipe")), client);
+ verify(manager).clear(endpoint);
+ } finally {
+ Thread.interrupted();
+ }
+ }
+
+ @Test
+ public void connectUsesRemainingBudgetAndClosesFailedSocket() throws
Exception {
+ SyncDataNodeMPPDataExchangeServiceClient client =
+ new SyncDataNodeMPPDataExchangeServiceClient(
+ new
ThriftClientProperty.Builder().setConnectionTimeoutMs(60_000).build(),
+ new TEndPoint("127.0.0.1", 10740),
+ null,
+ false);
+ Socket socket = mock(Socket.class);
+ doThrow(new
SocketTimeoutException()).when(socket).connect(any(SocketAddress.class),
anyInt());
+ long deadline = System.currentTimeMillis() - 3_200 + 4_000;
+ assertThrows(SocketTimeoutException.class, () -> client.connect(socket,
deadline));
+ ArgumentCaptor<Integer> timeout = ArgumentCaptor.forClass(Integer.class);
+ verify(socket).connect(any(SocketAddress.class), timeout.capture());
+ assertTrue(timeout.getValue() > 0 && timeout.getValue() <= 800);
+ verify(socket).close();
+
+ Socket expired = mock(Socket.class);
+ IOException closeFailure = new IOException("failed to close");
+ doThrow(closeFailure).when(expired).close();
+ QueryTimeoutException timeoutFailure =
+ assertThrows(
+ QueryTimeoutException.class,
+ () -> client.connect(expired, System.currentTimeMillis() - 1));
+ assertArrayEquals(new Throwable[] {closeFailure},
timeoutFailure.getSuppressed());
+ verify(expired, never()).connect(any(SocketAddress.class), anyInt());
+ verify(expired).close();
+
+ SyncDataNodeMPPDataExchangeServiceClient unlimited =
+ new SyncDataNodeMPPDataExchangeServiceClient(
+ new
ThriftClientProperty.Builder().setConnectionTimeoutMs(-1).build(),
+ new TEndPoint("127.0.0.1", 10740),
+ null,
+ false);
+ Socket failed = mock(Socket.class);
+ AssertionError connectFailure = new AssertionError("connect failed");
+ doThrow(connectFailure).when(failed).connect(any(SocketAddress.class),
eq(0));
+ doThrow(closeFailure).when(failed).close();
+ assertSame(
+ connectFailure,
+ assertThrows(AssertionError.class, () -> unlimited.connect(failed,
Long.MAX_VALUE)));
+ assertArrayEquals(new Throwable[] {closeFailure},
connectFailure.getSuppressed());
+ }
+}
diff --git
a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/client/sync/MPPDataExchangeClientTlsTest.java
b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/client/sync/MPPDataExchangeClientTlsTest.java
new file mode 100644
index 00000000000..170ea4513b6
--- /dev/null
+++
b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/client/sync/MPPDataExchangeClientTlsTest.java
@@ -0,0 +1,330 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.iotdb.commons.client.sync;
+
+import org.apache.iotdb.common.rpc.thrift.TEndPoint;
+import org.apache.iotdb.commons.client.property.ThriftClientProperty;
+import org.apache.iotdb.commons.conf.CommonConfig;
+import org.apache.iotdb.commons.conf.CommonDescriptor;
+import org.apache.iotdb.commons.exception.QueryTimeoutException;
+import org.apache.iotdb.mpp.rpc.thrift.TFetchDeviceEntrySegmentReq;
+import org.apache.iotdb.rpc.DeepCopyRpcTransportFactory;
+import org.apache.iotdb.rpc.RpcSslUtils;
+import org.apache.iotdb.rpc.TElasticFramedTransport;
+
+import org.apache.thrift.TException;
+import org.apache.thrift.transport.TSocket;
+import org.apache.thrift.transport.TTransport;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLHandshakeException;
+import javax.net.ssl.SSLServerSocket;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.SSLSocketFactory;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.InetAddress;
+import java.net.Socket;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.FileTime;
+import java.security.KeyStore;
+import java.security.cert.CertificateException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
+
+public class MPPDataExchangeClientTlsTest {
+ @ClassRule public static final TemporaryFolder folder = new
TemporaryFolder();
+ private static final String PASSWORD = "test-only";
+ private static Path store;
+ private static SSLContext serverContext;
+ private final MPPDataExchangeClientManager clients = new
MPPDataExchangeClientManager();
+ private final ExecutorService peerThread =
Executors.newSingleThreadExecutor();
+ private final CommonConfig config =
CommonDescriptor.getInstance().getConfig();
+ private boolean previousSsl;
+ private String previousTrustPath;
+ private String previousTrustPassword;
+
+ @BeforeClass
+ public static void createStores() throws Exception {
+ store = folder.getRoot().toPath().resolve("loopback.p12");
+ Path output = folder.newFile("keytool.log").toPath();
+ Path keytool =
+ Path.of(
+ System.getProperty("java.home"),
+ "bin",
+ File.separatorChar == '\\' ? "keytool.exe" : "keytool");
+ Process keys =
+ new ProcessBuilder(
+ keytool.toString(),
+ "-genkeypair",
+ "-alias",
+ "loopback",
+ "-keyalg",
+ "EC",
+ "-dname",
+ "CN=mpp-test",
+ "-ext",
+ "SAN=dns:localhost",
+ "-validity",
+ "2",
+ "-storetype",
+ "PKCS12",
+ "-keystore",
+ store.toString(),
+ "-storepass",
+ PASSWORD)
+ .redirectErrorStream(true)
+ .redirectOutput(output.toFile())
+ .start();
+ try {
+ assertTrue(keys.waitFor(30, SECONDS));
+ assertEquals(Files.readString(output), 0, keys.exitValue());
+ } finally {
+ keys.destroyForcibly();
+ }
+ serverContext =
+ RpcSslUtils.createSSLContext(store.toString(), PASSWORD,
store.toString(), PASSWORD);
+ }
+
+ @Before
+ public void enableTls() {
+ previousSsl = config.isEnableInternalSSL();
+ previousTrustPath = config.getTrustStorePath();
+ previousTrustPassword = config.getTrustStorePwd();
+ config.setEnableInternalSSL(true);
+ config.setTrustStorePath(store.toString());
+ config.setTrustStorePwd(PASSWORD);
+ }
+
+ @After
+ public void cleanUp() {
+ config.setEnableInternalSSL(previousSsl);
+ config.setTrustStorePath(previousTrustPath);
+ config.setTrustStorePwd(previousTrustPassword);
+ clients.close();
+ peerThread.shutdownNow();
+ }
+
+ private SSLServerSocket server() throws IOException {
+ SSLServerSocket server =
+ (SSLServerSocket)
+ serverContext
+ .getServerSocketFactory()
+ .createServerSocket(0, 4, InetAddress.getByName("localhost"));
+ server.setSoTimeout(10_000);
+ return server;
+ }
+
+ @Test
+ public void bothTransportsAcceptMatchingHostname() throws Exception {
+ checkPeerIdentity(true, true);
+ checkPeerIdentity(false, true);
+ }
+
+ @Test
+ public void bothTransportsRejectTrustedCertificateWithoutIpSan() throws
Exception {
+ checkPeerIdentity(true, false);
+ checkPeerIdentity(false, false);
+ }
+
+ private void checkPeerIdentity(boolean thrift, boolean matches) throws
Exception {
+ try (SSLServerSocket listener = server()) {
+ String host = matches ? "localhost" :
listener.getInetAddress().getHostAddress();
+ int port = listener.getLocalPort();
+ Future<?> handshake =
+ peerThread.submit(
+ () -> {
+ try (SSLSocket peer = (SSLSocket) listener.accept()) {
+ peer.setSoTimeout(10_000);
+ peer.startHandshake();
+ } catch (IOException e) {
+ if (matches) {
+ throw e;
+ }
+ }
+ return null;
+ });
+ if (thrift) {
+ // Original MPP transport, also used by the other internal TLS clients.
+ try (TTransport transport =
+ DeepCopyRpcTransportFactory.INSTANCE.getTransport(
+ host, port, 10_000, store.toString(), PASSWORD, "", "",
config.getSslProtocol())) {
+ checkHandshake(transport, matches);
+ }
+ } else {
+ try (SyncDataNodeMPPDataExchangeServiceClient client =
+ clients.borrowClient(new TEndPoint(host, port),
System.currentTimeMillis() + 10_000)) {
+ try {
+ checkHandshake(client.getInputProtocol().getTransport(), matches);
+ } finally {
+ client.invalidate();
+ }
+ }
+ }
+ handshake.get(10, SECONDS);
+ }
+ }
+
+ private static void checkHandshake(TTransport transport, boolean matches)
throws IOException {
+ TSocket thriftSocket = (TSocket) ((TElasticFramedTransport)
transport).getSocket();
+ SSLSocket socket = (SSLSocket) thriftSocket.getSocket();
+ assertEquals("HTTPS",
socket.getSSLParameters().getEndpointIdentificationAlgorithm());
+ if (matches) {
+ socket.startHandshake();
+ assertTrue(socket.getSession().getPeerCertificates().length > 0);
+ } else {
+ SSLHandshakeException failure =
+ assertThrows(SSLHandshakeException.class, socket::startHandshake);
+ assertTrue(failure.getCause() instanceof CertificateException);
+ }
+ }
+
+ @Test
+ public void interruptedTlsReadLeavesOtherPooledClientsUsable() throws
Exception {
+ try (SSLServerSocket listener = server()) {
+ TEndPoint endpoint = new TEndPoint("localhost", listener.getLocalPort());
+ AtomicReference<Thread> owner = new AtomicReference<>();
+ Future<Boolean> interrupted =
+ peerThread.submit(
+ () -> {
+ owner.set(Thread.currentThread());
+ try (SyncDataNodeMPPDataExchangeServiceClient client =
+ clients.borrowClient(endpoint)) {
+ assertThrows(
+ TException.class,
+ () ->
+ client.fetchDeviceEntrySegment(
+ new TFetchDeviceEntrySegmentReq("q", "p", 0)));
+ return Thread.currentThread().isInterrupted();
+ }
+ });
+ try (SSLSocket peer = (SSLSocket) listener.accept()) {
+ peer.setSoTimeout(10_000);
+ assertTrue(peer.getInputStream().read() >= 0);
+ SyncDataNodeMPPDataExchangeServiceClient other;
+ try (SyncDataNodeMPPDataExchangeServiceClient borrowed =
clients.borrowClient(endpoint)) {
+ other = borrowed;
+ }
+ try (Socket otherPeer = listener.accept()) {
+ owner.get().interrupt();
+ assertTrue(interrupted.get(10, SECONDS));
+ assertEquals(0, clients.getPool().getNumActive());
+ assertEquals(1, clients.getPool().getNumIdle());
+ try (SyncDataNodeMPPDataExchangeServiceClient reused =
clients.borrowClient(endpoint)) {
+ assertSame(other, reused);
+ }
+ }
+ }
+ }
+ }
+
+ @Test
+ public void expiredBudgetSkipsLocalStoreAccess() throws Exception {
+
config.setTrustStorePath(folder.getRoot().toPath().resolve("missing.p12").toString());
+ SyncDataNodeMPPDataExchangeServiceClient client =
+ new SyncDataNodeMPPDataExchangeServiceClient(
+ new ThriftClientProperty.Builder().build(),
+ new TEndPoint("localhost", 1),
+ clients,
+ false);
+ assertThrows(QueryTimeoutException.class, () ->
client.prepare(System.currentTimeMillis() - 1));
+ }
+
+ @Test
+ public void concurrentColdConnectionsShareTheFactory() throws Exception {
+ Path copy = folder.getRoot().toPath().resolve("reconnect.p12");
+ Files.copy(store, copy);
+ config.setTrustStorePath(copy.toString());
+ ExecutorService borrowers = Executors.newFixedThreadPool(8);
+ CountDownLatch start = new CountDownLatch(1);
+ try {
+ List<Future<SSLSocketFactory>> factories = new ArrayList<>();
+ for (int i = 0; i < 8; i++) {
+ factories.add(
+ borrowers.submit(
+ () -> {
+ start.await();
+ return
SyncDataNodeMPPDataExchangeServiceClient.sslSocketFactory();
+ }));
+ }
+ start.countDown();
+ SSLSocketFactory first = factories.get(0).get(5, SECONDS);
+ for (Future<SSLSocketFactory> factory : factories) {
+ assertSame(first, factory.get(5, SECONDS));
+ }
+ } finally {
+ start.countDown();
+ borrowers.shutdownNow();
+ }
+ }
+
+ @Test
+ public void sslFactoryReloadsRotatedStoresAndRetriesFailedLoads() throws
Exception {
+ String password = PASSWORD;
+ Path store = folder.getRoot().toPath().resolve("rotating-trust.p12");
+ KeyStore trust = KeyStore.getInstance("PKCS12");
+ trust.load(null, null);
+ try (OutputStream output = Files.newOutputStream(store)) {
+ trust.store(output, password.toCharArray());
+ }
+ byte[] validStore = Files.readAllBytes(store);
+ config.setTrustStorePath(store.toString());
+ config.setTrustStorePwd(password);
+ SSLSocketFactory first =
SyncDataNodeMPPDataExchangeServiceClient.sslSocketFactory();
+ assertSame(first,
SyncDataNodeMPPDataExchangeServiceClient.sslSocketFactory());
+ FileTime nextVersion =
+ FileTime.fromMillis(Files.getLastModifiedTime(store).toMillis() +
10_000);
+ Files.setLastModifiedTime(store, nextVersion);
+ SSLSocketFactory rotated =
SyncDataNodeMPPDataExchangeServiceClient.sslSocketFactory();
+ assertNotSame(first, rotated);
+ assertSame(rotated,
SyncDataNodeMPPDataExchangeServiceClient.sslSocketFactory());
+
+ Files.write(store, new byte[validStore.length]);
+ FileTime damagedVersion = FileTime.fromMillis(nextVersion.toMillis() +
10_000);
+ Files.setLastModifiedTime(store, damagedVersion);
+ assertThrows(IOException.class,
SyncDataNodeMPPDataExchangeServiceClient::sslSocketFactory);
+ Files.write(store, validStore);
+ Files.setLastModifiedTime(store, damagedVersion);
+ SSLSocketFactory repaired =
SyncDataNodeMPPDataExchangeServiceClient.sslSocketFactory();
+ assertNotSame(rotated, repaired);
+ assertSame(repaired,
SyncDataNodeMPPDataExchangeServiceClient.sslSocketFactory());
+ }
+}
diff --git a/iotdb-protocol/thrift-datanode/src/main/thrift/datanode.thrift
b/iotdb-protocol/thrift-datanode/src/main/thrift/datanode.thrift
index 8e2335fab0c..1a01360cc98 100644
--- a/iotdb-protocol/thrift-datanode/src/main/thrift/datanode.thrift
+++ b/iotdb-protocol/thrift-datanode/src/main/thrift/datanode.thrift
@@ -152,6 +152,8 @@ struct TSendFragmentInstanceReq {
// Attempt metadata is absent for a legacy coordinator. Do not change the
binary FI body.
3: optional i32 queryAttemptId
4: optional TQueryAdmissionToken admissionToken
+ // The receiver anchors the remaining duration to its own clock at RPC
receipt.
+ 5: optional i64 remainingQueryTimeMs
}
struct TSendFragmentInstanceResp {