From 35c48c7c5c4bf809f56c7452f834d68e307cef57 Mon Sep 17 00:00:00 2001 From: JackieTien97 Date: Fri, 4 Dec 2026 19:03:58 +0800 Subject: [PATCH 1/5] Fix SessionConnection.reconnect() self-closing transport when enableRedirection is false --- .../org/apache/iotdb/session/Session.java | 55 ++--- .../iotdb/session/SessionConnection.java | 32 +-- .../iotdb/session/SessionConnectionTest.java | 229 ++++++++++++++++++ .../org/apache/iotdb/session/SessionTest.java | 59 +++++ 4 files changed, 334 insertions(+), 41 deletions(-) diff --git a/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java b/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java index 31cdd2bc3d8f2..e8a433303e1cc 100644 --- a/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java +++ b/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java @@ -1522,40 +1522,41 @@ public String getTimestampPrecision() throws TException, IoTDBConnectionExceptio // TODO https://issues.apache.org/jira/browse/IOTDB-1399 public void removeBrokenSessionConnection(SessionConnection sessionConnection) { // remove the cached broken leader session - if (enableRedirection) { - TEndPoint endPoint = null; - if (endPointToSessionConnection != null) { - for (Iterator> it = - endPointToSessionConnection.entrySet().iterator(); - it.hasNext(); ) { - Entry entry = it.next(); - if (entry.getValue().equals(sessionConnection)) { - endPoint = entry.getKey(); - it.remove(); - break; - } + if (endPointToSessionConnection == null) { + return; + } + Set removedEndPoints = new HashSet<>(); + for (Iterator> it = + endPointToSessionConnection.entrySet().iterator(); + it.hasNext(); ) { + Entry entry = it.next(); + if (entry.getValue().equals(sessionConnection)) { + removedEndPoints.add(entry.getKey()); + it.remove(); + } + } + if (removedEndPoints.isEmpty()) { + return; + } + if (deviceIdToEndpoint != null && !deviceIdToEndpoint.isEmpty()) { + for (Iterator> it = deviceIdToEndpoint.entrySet().iterator(); + it.hasNext(); ) { + Entry entry = it.next(); + if (removedEndPoints.contains(entry.getValue())) { + it.remove(); } } - if (deviceIdToEndpoint != null && !deviceIdToEndpoint.isEmpty()) { - for (Iterator> it = deviceIdToEndpoint.entrySet().iterator(); + } + if (tableModelDeviceIdToEndpoint != null && !tableModelDeviceIdToEndpoint.isEmpty()) { + for (Map databaseToEndpoint : tableModelDeviceIdToEndpoint.values()) { + for (Iterator> it = databaseToEndpoint.entrySet().iterator(); it.hasNext(); ) { - Entry entry = it.next(); - if (entry.getValue().equals(endPoint)) { + Entry entry = it.next(); + if (removedEndPoints.contains(entry.getValue())) { it.remove(); } } } - if (tableModelDeviceIdToEndpoint != null && !tableModelDeviceIdToEndpoint.isEmpty()) { - for (Map databaseToEndpoint : tableModelDeviceIdToEndpoint.values()) { - for (Iterator> it = databaseToEndpoint.entrySet().iterator(); - it.hasNext(); ) { - Entry entry = it.next(); - if (Objects.equals(entry.getValue(), endPoint)) { - it.remove(); - } - } - } - } } } diff --git a/iotdb-client/session/src/main/java/org/apache/iotdb/session/SessionConnection.java b/iotdb-client/session/src/main/java/org/apache/iotdb/session/SessionConnection.java index a0d7657e0a8a2..0f7ad60736d50 100644 --- a/iotdb-client/session/src/main/java/org/apache/iotdb/session/SessionConnection.java +++ b/iotdb-client/session/src/main/java/org/apache/iotdb/session/SessionConnection.java @@ -1301,21 +1301,25 @@ private boolean reconnect() { session.removeBrokenSessionConnection(this); session.defaultEndPoint = this.endPoint; session.setDefaultSessionConnection(this); - if (session.endPointToSessionConnection == null) { - session.endPointToSessionConnection = new ConcurrentHashMap<>(); - } - session.endPointToSessionConnection.compute( - session.defaultEndPoint, - (k, v) -> { - if (v != null && v.transport != null && v.transport.isOpen()) { - try { - v.close(); - } catch (IoTDBConnectionException e) { - logger.warn(SessionMessages.CLOSE_CONNECTION_FAILED, e.getMessage()); + if (session.endPointToSessionConnection != null + || session.enableRedirection + || session.enableQueryRedirection) { + if (session.endPointToSessionConnection == null) { + session.endPointToSessionConnection = new ConcurrentHashMap<>(); + } + session.endPointToSessionConnection.compute( + session.defaultEndPoint, + (k, v) -> { + if (v != null && v != this && v.transport != null && v.transport.isOpen()) { + try { + v.close(); + } catch (IoTDBConnectionException e) { + logger.warn(SessionMessages.CLOSE_CONNECTION_FAILED, e.getMessage()); + } } - } - return this; - }); + return this; + }); + } break; } } diff --git a/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionConnectionTest.java b/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionConnectionTest.java index 0a12a841f868a..25ec4958b98c5 100644 --- a/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionConnectionTest.java +++ b/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionConnectionTest.java @@ -71,6 +71,10 @@ import org.apache.thrift.server.TThreadPoolServer; import org.apache.thrift.transport.TServerSocket; import org.apache.thrift.transport.TTransport; +import org.apache.thrift.transport.TTransportException; +import org.apache.tsfile.enums.TSDataType; +import org.apache.tsfile.write.record.Tablet; +import org.apache.tsfile.write.schema.MeasurementSchema; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -696,6 +700,231 @@ public void testToString() { sessionConnection.toString(); } + @Test + public void testReconnectWithoutRedirectionDoesNotSelfClose() throws Exception { + try (ReconnectTestServer server = new ReconnectTestServer(2)) { + Session testSession = + new Session.Builder() + .host(server.getEndpoint().getIp()) + .port(server.getEndpoint().getPort()) + .username("root") + .password("root") + .enableRedirection(false) + .enableAutoFetch(false) + .maxRetryCount(5) + .retryIntervalInMs(10) + .build(); + try { + testSession.open(false, 1000); + Assert.assertFalse(testSession.enableRedirection); + Assert.assertFalse(testSession.enableQueryRedirection); + Assert.assertNull(testSession.endPointToSessionConnection); + + testSession.insertTablet(createSingleRowTablet()); + + Assert.assertEquals(3, server.getInsertTabletCount()); + Assert.assertEquals(3, server.getOpenSessionCount()); + Assert.assertEquals(0, server.getCloseSessionCount()); + Assert.assertNull(testSession.endPointToSessionConnection); + TTransport activeTransport = + Whitebox.getInternalState(testSession.getDefaultSessionConnection(), "transport"); + Assert.assertTrue(activeTransport.isOpen()); + } finally { + testSession.close(); + } + } + } + + @Test + public void testReconnectWithQueryRedirectionAndWriteRedirectionDisabledDoesNotSelfClose() + throws Exception { + try (ReconnectTestServer server = new ReconnectTestServer(1)) { + Session testSession = + new Session.Builder() + .nodeUrls( + Collections.singletonList( + server.getEndpoint().getIp() + ":" + server.getEndpoint().getPort())) + .username("root") + .password("root") + .enableRedirection(false) + .enableAutoFetch(false) + .maxRetryCount(5) + .retryIntervalInMs(10) + .build(); + try { + testSession.open(false, 1000); + Assert.assertFalse(testSession.enableRedirection); + Assert.assertTrue(testSession.enableQueryRedirection); + Assert.assertSame( + testSession.getDefaultSessionConnection(), + testSession.endPointToSessionConnection.get(testSession.defaultEndPoint)); + + testSession.insertTablet(createSingleRowTablet()); + + Assert.assertEquals(2, server.getInsertTabletCount()); + Assert.assertEquals(2, server.getOpenSessionCount()); + Assert.assertEquals(0, server.getCloseSessionCount()); + Assert.assertSame( + testSession.getDefaultSessionConnection(), + testSession.endPointToSessionConnection.get(testSession.defaultEndPoint)); + TTransport activeTransport = + Whitebox.getInternalState(testSession.getDefaultSessionConnection(), "transport"); + Assert.assertTrue(activeTransport.isOpen()); + } finally { + testSession.close(); + } + } + } + + @Test + public void testReconnectStillClosesDifferentStaleConnectionForSameEndPoint() throws Exception { + try (ReconnectTestServer server = new ReconnectTestServer(1)) { + Session testSession = + new Session.Builder() + .nodeUrls( + Collections.singletonList( + server.getEndpoint().getIp() + ":" + server.getEndpoint().getPort())) + .username("root") + .password("root") + .enableRedirection(true) + .enableAutoFetch(false) + .maxRetryCount(5) + .retryIntervalInMs(10) + .build(); + try { + testSession.open(false, 1000); + SessionConnection staleConnection = Mockito.mock(SessionConnection.class); + TTransport staleTransport = Mockito.mock(TTransport.class); + Mockito.when(staleTransport.isOpen()).thenReturn(true); + Whitebox.setInternalState(staleConnection, "transport", staleTransport); + testSession.endPointToSessionConnection.put(testSession.defaultEndPoint, staleConnection); + + testSession.insertTablet(createSingleRowTablet()); + + Assert.assertEquals(2, server.getInsertTabletCount()); + Assert.assertEquals(2, server.getOpenSessionCount()); + Mockito.verify(staleConnection, Mockito.times(1)).close(); + Assert.assertSame( + testSession.getDefaultSessionConnection(), + testSession.endPointToSessionConnection.get(testSession.defaultEndPoint)); + TTransport activeTransport = + Whitebox.getInternalState(testSession.getDefaultSessionConnection(), "transport"); + Assert.assertTrue(activeTransport.isOpen()); + } finally { + testSession.close(); + } + } + } + + private static Tablet createSingleRowTablet() { + Tablet tablet = + new Tablet( + "root.sg.d1", + Collections.singletonList(new MeasurementSchema("s1", TSDataType.INT32)), + 1); + tablet.addTimestamp(0, 1L); + tablet.addValue("s1", 0, 42); + return tablet; + } + + private static class ReconnectTestServer implements AutoCloseable { + + private final TEndPoint endpoint; + private final TServerSocket socket; + private final TThreadPoolServer server; + private final ExecutorService workers = Executors.newCachedThreadPool(); + private final Thread thread; + private final AtomicInteger openSessionCount = new AtomicInteger(); + private final AtomicInteger closeSessionCount = new AtomicInteger(); + private final AtomicInteger insertTabletCount = new AtomicInteger(); + + private ReconnectTestServer(int failInsertCount) throws Exception { + ServerSocket listener = new ServerSocket(0); + endpoint = new TEndPoint("127.0.0.1", listener.getLocalPort()); + socket = new TServerSocket(listener); + IClientRPCService.Iface handler = Mockito.mock(IClientRPCService.Iface.class); + Mockito.when(handler.openSession(any())) + .thenAnswer( + ignored -> + new TSOpenSessionResp( + new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode()), + TSProtocolVersion.IOTDB_SERVICE_PROTOCOL_V3) + .setSessionId(openSessionCount.incrementAndGet())); + Mockito.when(handler.closeSession(any())) + .thenAnswer( + ignored -> { + closeSessionCount.incrementAndGet(); + return new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode()); + }); + Mockito.when(handler.insertTablet(any())) + .thenAnswer( + ignored -> { + if (insertTabletCount.incrementAndGet() <= failInsertCount) { + throw new TTransportException( + TTransportException.END_OF_FILE, "Simulated transport failure"); + } + return new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode()); + }); + + server = + new TThreadPoolServer( + new TThreadPoolServer.Args(socket) + .processor(new IClientRPCService.Processor<>(handler)) + .protocolFactory(new TBinaryProtocol.Factory()) + .transportFactory(DeepCopyRpcTransportFactory.INSTANCE) + .executorService(workers)); + CountDownLatch serving = new CountDownLatch(1); + server.setServerEventHandler( + new TServerEventHandler() { + @Override + public void preServe() { + serving.countDown(); + } + + @Override + public ServerContext createContext(TProtocol input, TProtocol output) { + return Mockito.mock(ServerContext.class); + } + + @Override + public void processContext( + ServerContext context, TTransport input, TTransport output) {} + + @Override + public void deleteContext(ServerContext context, TProtocol input, TProtocol output) {} + }); + thread = new Thread(server::serve, "reconnect-test-server"); + thread.setDaemon(true); + thread.start(); + Assert.assertTrue("Fake server did not start", serving.await(5, TimeUnit.SECONDS)); + } + + private TEndPoint getEndpoint() { + return endpoint; + } + + private int getOpenSessionCount() { + return openSessionCount.get(); + } + + private int getCloseSessionCount() { + return closeSessionCount.get(); + } + + private int getInsertTabletCount() { + return insertTabletCount.get(); + } + + @Override + public void close() throws Exception { + server.stop(); + socket.close(); + workers.shutdownNow(); + thread.join(5000); + workers.awaitTermination(5, TimeUnit.SECONDS); + } + } + private static class ForceCloseTestServer implements AutoCloseable { private final TEndPoint endpoint; diff --git a/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionTest.java b/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionTest.java index eaf24080c4340..ce2f631bb42f6 100644 --- a/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionTest.java +++ b/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionTest.java @@ -35,6 +35,8 @@ import org.apache.tsfile.common.conf.TSFileConfig; import org.apache.tsfile.enums.ColumnCategory; import org.apache.tsfile.enums.TSDataType; +import org.apache.tsfile.file.metadata.IDeviceID; +import org.apache.tsfile.file.metadata.StringArrayDeviceID; import org.apache.tsfile.file.metadata.enums.CompressionType; import org.apache.tsfile.file.metadata.enums.TSEncoding; import org.apache.tsfile.utils.Binary; @@ -63,6 +65,7 @@ import java.util.List; import java.util.Map; import java.util.Random; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledExecutorService; import static org.junit.Assert.assertEquals; @@ -1427,4 +1430,60 @@ public void testSortTabletOrderedRunsAndStableDuplicates() { } } } + + @Test + public void testRemoveBrokenSessionConnectionWhenRedirectionDisabled() { + Session testSession = + new Session.Builder() + .nodeUrls(Collections.singletonList("127.0.0.1:6667")) + .username("root") + .password("root") + .enableRedirection(false) + .enableAutoFetch(false) + .build(); + Assert.assertFalse(testSession.enableRedirection); + + TEndPoint ep1 = new TEndPoint("127.0.0.1", 6667); + TEndPoint ep2 = new TEndPoint("127.0.0.1", 6668); + TEndPoint ep3 = new TEndPoint("127.0.0.1", 6669); + SessionConnection brokenConnection = Mockito.mock(SessionConnection.class); + SessionConnection healthyConnection = Mockito.mock(SessionConnection.class); + + Map endPointMap = new ConcurrentHashMap<>(); + endPointMap.put(ep1, brokenConnection); + endPointMap.put(ep2, brokenConnection); + endPointMap.put(ep3, healthyConnection); + testSession.endPointToSessionConnection = endPointMap; + + Map deviceMap = new ConcurrentHashMap<>(); + deviceMap.put("root.sg.d1", ep1); + deviceMap.put("root.sg.d2", ep2); + deviceMap.put("root.sg.d3", ep3); + testSession.deviceIdToEndpoint = deviceMap; + + Map tableDeviceMap = new ConcurrentHashMap<>(); + IDeviceID dev1 = new StringArrayDeviceID("t1", "d1"); + IDeviceID dev2 = new StringArrayDeviceID("t1", "d2"); + IDeviceID dev3 = new StringArrayDeviceID("t1", "d3"); + tableDeviceMap.put(dev1, ep1); + tableDeviceMap.put(dev2, ep2); + tableDeviceMap.put(dev3, ep3); + Map> tableMap = new ConcurrentHashMap<>(); + tableMap.put("db1", tableDeviceMap); + testSession.tableModelDeviceIdToEndpoint = tableMap; + + testSession.removeBrokenSessionConnection(brokenConnection); + + Assert.assertFalse(testSession.endPointToSessionConnection.containsKey(ep1)); + Assert.assertFalse(testSession.endPointToSessionConnection.containsKey(ep2)); + Assert.assertSame(healthyConnection, testSession.endPointToSessionConnection.get(ep3)); + + Assert.assertFalse(testSession.deviceIdToEndpoint.containsKey("root.sg.d1")); + Assert.assertFalse(testSession.deviceIdToEndpoint.containsKey("root.sg.d2")); + Assert.assertEquals(ep3, testSession.deviceIdToEndpoint.get("root.sg.d3")); + + Assert.assertFalse(testSession.tableModelDeviceIdToEndpoint.get("db1").containsKey(dev1)); + Assert.assertFalse(testSession.tableModelDeviceIdToEndpoint.get("db1").containsKey(dev2)); + Assert.assertEquals(ep3, testSession.tableModelDeviceIdToEndpoint.get("db1").get(dev3)); + } } From 88e8cb16eb4b69830ad66091ffd388d023efd0e8 Mon Sep 17 00:00:00 2001 From: JackieTien97 Date: Fri, 4 Dec 2026 20:54:16 +0800 Subject: [PATCH 2/5] Address PR review comments: coordinate reconnect with close, guard device route cleanup, init cache on setEnableQueryRedirection --- .../org/apache/iotdb/session/Session.java | 94 +++++++-- .../iotdb/session/SessionConnection.java | 42 ++-- .../iotdb/session/SessionConnectionTest.java | 199 +++++++++++++++++- .../org/apache/iotdb/session/SessionTest.java | 56 +++++ 4 files changed, 345 insertions(+), 46 deletions(-) diff --git a/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java b/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java index e8a433303e1cc..35ec696768f65 100644 --- a/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java +++ b/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java @@ -165,6 +165,7 @@ public class Session implements ISession { protected SessionConnection defaultSessionConnection; private boolean isClosed = true; private volatile boolean closing; + private final Object connectionStateLock = new Object(); // this field only take effect in write request, nothing to do with any other type requests, // like query, load and so on. @@ -722,14 +723,18 @@ public synchronized void openWithTableModelDatabaseCache( @Override public synchronized void close() throws IoTDBConnectionException { - closing = true; Throwable closeException = null; try { - if (isClosed) { - return; + List connectionsToClose; + synchronized (connectionStateLock) { + closing = true; + if (isClosed) { + return; + } + connectionsToClose = getSessionConnections(); } - for (SessionConnection sessionConnection : getSessionConnections()) { + for (SessionConnection sessionConnection : connectionsToClose) { try { sessionConnection.close(); } catch (IoTDBConnectionException | RuntimeException e) { @@ -754,12 +759,16 @@ public synchronized void close() throws IoTDBConnectionException { /** Closes the underlying transports without waiting for a close-session RPC. */ public synchronized void forceClose() { - closing = true; - if (isClosed) { - return; + List connectionsToClose; + synchronized (connectionStateLock) { + closing = true; + if (isClosed) { + return; + } + connectionsToClose = getSessionConnections(); } try { - for (SessionConnection sessionConnection : getSessionConnections()) { + for (SessionConnection sessionConnection : connectionsToClose) { sessionConnection.forceCloseTransport(); } } finally { @@ -784,14 +793,16 @@ private List getSessionConnections() { } private void finishClose() { - if (!isClosed) { - if (endPointToSessionConnection != null) { - // Do not wait for a concurrent computeIfAbsent that is still opening a connection. - endPointToSessionConnection = new ConcurrentHashMap<>(); + synchronized (connectionStateLock) { + if (!isClosed) { + if (endPointToSessionConnection != null) { + // Do not wait for a concurrent computeIfAbsent that is still opening a connection. + endPointToSessionConnection = new ConcurrentHashMap<>(); + } + setDefaultSessionConnection(null); } - setDefaultSessionConnection(null); + isClosed = true; } - isClosed = true; // if executorService is null, it means that availableNodes is got from SessionPool and we // shouldn't clean that if (this.executorService != null) { @@ -1519,6 +1530,41 @@ public String getTimestampPrecision() throws TException, IoTDBConnectionExceptio return getDefaultSessionConnection().getClient().getProperties().getTimestampPrecision(); } + boolean isClosing() { + return closing; + } + + boolean registerReconnectedConnection(SessionConnection connection, TEndPoint newEndPoint) { + SessionConnection staleConnection = null; + synchronized (connectionStateLock) { + if (closing || connection.isForceClosed()) { + return false; + } + removeBrokenSessionConnection(connection); + defaultEndPoint = newEndPoint; + setDefaultSessionConnection(connection); + if (endPointToSessionConnection != null || enableRedirection || enableQueryRedirection) { + if (endPointToSessionConnection == null) { + endPointToSessionConnection = new ConcurrentHashMap<>(); + } + SessionConnection previous = endPointToSessionConnection.put(newEndPoint, connection); + if (previous != null && previous != connection) { + staleConnection = previous; + } + } + } + if (staleConnection != null + && staleConnection.transport != null + && staleConnection.transport.isOpen()) { + try { + staleConnection.close(); + } catch (IoTDBConnectionException e) { + logger.warn(SessionMessages.CLOSE_CONNECTION_FAILED, e.getMessage()); + } + } + return true; + } + // TODO https://issues.apache.org/jira/browse/IOTDB-1399 public void removeBrokenSessionConnection(SessionConnection sessionConnection) { // remove the cached broken leader session @@ -1535,7 +1581,7 @@ public void removeBrokenSessionConnection(SessionConnection sessionConnection) { it.remove(); } } - if (removedEndPoints.isEmpty()) { + if (!enableRedirection || removedEndPoints.isEmpty()) { return; } if (deviceIdToEndpoint != null && !deviceIdToEndpoint.isEmpty()) { @@ -4812,7 +4858,23 @@ public boolean isEnableQueryRedirection() { @Override public void setEnableQueryRedirection(boolean enableQueryRedirection) { - this.enableQueryRedirection = enableQueryRedirection; + synchronized (connectionStateLock) { + this.enableQueryRedirection = enableQueryRedirection; + if (enableQueryRedirection && !isClosed && !closing) { + if (defaultSessionConnection != null) { + defaultSessionConnection.setEnableRedirect(true); + } + if (endPointToSessionConnection == null) { + Map connections = new ConcurrentHashMap<>(); + if (defaultEndPoint != null && defaultSessionConnection != null) { + connections.put(defaultEndPoint, defaultSessionConnection); + } + endPointToSessionConnection = connections; + } else if (defaultEndPoint != null && defaultSessionConnection != null) { + endPointToSessionConnection.putIfAbsent(defaultEndPoint, defaultSessionConnection); + } + } + } } @Override diff --git a/iotdb-client/session/src/main/java/org/apache/iotdb/session/SessionConnection.java b/iotdb-client/session/src/main/java/org/apache/iotdb/session/SessionConnection.java index 0f7ad60736d50..f857f0dcdc016 100644 --- a/iotdb-client/session/src/main/java/org/apache/iotdb/session/SessionConnection.java +++ b/iotdb-client/session/src/main/java/org/apache/iotdb/session/SessionConnection.java @@ -92,7 +92,6 @@ import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; -import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.function.Predicate; @@ -111,7 +110,7 @@ public class SessionConnection { public static final String MSG_RECONNECTION_FAIL = SessionMessages.EXCEPTION_FAIL_TO_RECONNECT_TO_SERVER_PLEASE_CHECK_SERVER_STATUS_D9A2790F; protected Session session; - private TTransport transport; + TTransport transport; protected IClientRPCService.Iface client; private long sessionId; private long statementId; @@ -367,6 +366,10 @@ protected boolean setTransportTimeout(final int timeoutInMs) { } } + boolean isForceClosed() { + return forceClosed; + } + protected void forceCloseTransport() { forceClosed = true; if (transport == null) { @@ -1236,13 +1239,13 @@ protected void testInsertTablets(TSInsertTabletsReq request) "squid:S3776" }) // ignore Cognitive Complexity of methods should not be too high private boolean reconnect() { - if (forceClosed) { + if (forceClosed || (session != null && session.isClosing())) { return false; } boolean connectedSuccess = false; SecureRandom random = new SecureRandom(); for (int i = 1; i <= SessionConfig.RETRY_NUM; i++) { - if (forceClosed) { + if (forceClosed || (session != null && session.isClosing())) { return false; } if (transport != null) { @@ -1262,7 +1265,7 @@ private boolean reconnect() { // Try every discovered endpoint before falling back to seeds, once per endpoint per round. endPointList = new ArrayList<>(new LinkedHashSet<>(endPointList)); for (TEndPoint candidate : endPointList) { - if (forceClosed) { + if (forceClosed || (session != null && session.isClosing())) { return false; } this.endPoint = candidate; @@ -1275,7 +1278,7 @@ private boolean reconnect() { session.keyStore, session.keyStorePwd, session.sslProtocol); - if (forceClosed) { + if (forceClosed || session.isClosing()) { forceCloseTransport(); return false; } @@ -1293,32 +1296,13 @@ private boolean reconnect() { } } if (connectedSuccess) { - if (forceClosed) { + if (forceClosed || !session.registerReconnectedConnection(this, this.endPoint)) { forceCloseTransport(); return false; } - // remove the broken end point - session.removeBrokenSessionConnection(this); - session.defaultEndPoint = this.endPoint; - session.setDefaultSessionConnection(this); - if (session.endPointToSessionConnection != null - || session.enableRedirection - || session.enableQueryRedirection) { - if (session.endPointToSessionConnection == null) { - session.endPointToSessionConnection = new ConcurrentHashMap<>(); - } - session.endPointToSessionConnection.compute( - session.defaultEndPoint, - (k, v) -> { - if (v != null && v != this && v.transport != null && v.transport.isOpen()) { - try { - v.close(); - } catch (IoTDBConnectionException e) { - logger.warn(SessionMessages.CLOSE_CONNECTION_FAILED, e.getMessage()); - } - } - return this; - }); + if (forceClosed || session.isClosing()) { + forceCloseTransport(); + return false; } break; } diff --git a/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionConnectionTest.java b/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionConnectionTest.java index 25ec4958b98c5..9681f685b77da 100644 --- a/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionConnectionTest.java +++ b/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionConnectionTest.java @@ -22,6 +22,7 @@ import org.apache.iotdb.common.rpc.thrift.TAggregationType; import org.apache.iotdb.common.rpc.thrift.TEndPoint; import org.apache.iotdb.common.rpc.thrift.TSStatus; +import org.apache.iotdb.isession.INodeSupplier; import org.apache.iotdb.isession.SessionConfig; import org.apache.iotdb.rpc.BatchExecutionException; import org.apache.iotdb.rpc.DeepCopyRpcTransportFactory; @@ -88,7 +89,9 @@ import java.time.ZoneId; import java.util.Arrays; import java.util.Collections; +import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; @@ -816,6 +819,157 @@ public void testReconnectStillClosesDifferentStaleConnectionForSameEndPoint() th } } + @Test + public void testForceCloseDuringNonDefaultQueryConnectionReconnectReleasesSocketAndStopsRetry() + throws Exception { + CountDownLatch beforeRegister = new CountDownLatch(1); + CountDownLatch resumeRegister = new CountDownLatch(1); + try (ReconnectTestServer serverA = new ReconnectTestServer(0, 0); + ReconnectTestServer serverB = new ReconnectTestServer(0, 1)) { + List bothNodes = Arrays.asList(serverA.getEndpoint(), serverB.getEndpoint()); + INodeSupplier nodeSupplier = + new INodeSupplier() { + @Override + public List get() { + return Collections.singletonList(serverB.getEndpoint()); + } + + @Override + public Optional getQueryEndPoint() { + return Optional.of(serverB.getEndpoint()); + } + + @Override + public void close() {} + }; + Session testSession = + new Session( + new Session.Builder() + .nodeUrls( + Arrays.asList( + serverA.getEndpoint().getIp() + ":" + serverA.getEndpoint().getPort(), + serverB.getEndpoint().getIp() + ":" + serverB.getEndpoint().getPort())) + .username("root") + .password("root") + .enableRedirection(false) + .enableAutoFetch(false) + .maxRetryCount(5) + .retryIntervalInMs(10)) { + @Override + boolean registerReconnectedConnection( + SessionConnection connection, TEndPoint newEndPoint) { + beforeRegister.countDown(); + try { + Assert.assertTrue(resumeRegister.await(5, TimeUnit.SECONDS)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return super.registerReconnectedConnection(connection, newEndPoint); + } + }; + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + testSession.open(false, 1000, Collections.emptyMap(), nodeSupplier); + Assert.assertFalse(testSession.enableRedirection); + Assert.assertTrue(testSession.enableQueryRedirection); + Assert.assertEquals(bothNodes.get(0), testSession.defaultEndPoint); + + Future queryFuture = + executor.submit( + () -> { + testSession.executeQueryStatement("select s1 from root.sg.d1"); + return null; + }); + Assert.assertTrue( + "Reconnect did not reach registration", beforeRegister.await(5, TimeUnit.SECONDS)); + + testSession.forceClose(); + resumeRegister.countDown(); + + try { + queryFuture.get(5, TimeUnit.SECONDS); + Assert.fail("Expected query to fail after forceClose()"); + } catch (ExecutionException e) { + Assert.assertTrue(e.getCause() instanceof IoTDBConnectionException); + } + Assert.assertEquals(1, serverB.getQueryCount()); + Assert.assertTrue( + "Server A still has active connections", + serverA.awaitNoActiveConnections(5, TimeUnit.SECONDS)); + Assert.assertTrue( + "Server B still has active connections", + serverB.awaitNoActiveConnections(5, TimeUnit.SECONDS)); + } finally { + resumeRegister.countDown(); + executor.shutdownNow(); + testSession.forceClose(); + } + } + } + + @Test + public void testEnableQueryRedirectionOnOpenSessionAfterFailoverRoutesAcrossNodes() + throws Exception { + try (ReconnectTestServer serverA = new ReconnectTestServer(1, 0); + ReconnectTestServer serverB = new ReconnectTestServer(0, 0)) { + AtomicInteger rrIndex = new AtomicInteger(0); + List roundRobinNodes = Arrays.asList(serverA.getEndpoint(), serverB.getEndpoint()); + INodeSupplier nodeSupplier = + new INodeSupplier() { + @Override + public List get() { + return Collections.singletonList(serverB.getEndpoint()); + } + + @Override + public Optional getQueryEndPoint() { + return Optional.of( + roundRobinNodes.get(rrIndex.getAndIncrement() % roundRobinNodes.size())); + } + + @Override + public void close() {} + }; + Session testSession = + new Session.Builder() + .host(serverA.getEndpoint().getIp()) + .port(serverA.getEndpoint().getPort()) + .username("root") + .password("root") + .enableRedirection(false) + .enableAutoFetch(false) + .maxRetryCount(5) + .retryIntervalInMs(10) + .build(); + try { + testSession.open(false, 1000, Collections.emptyMap(), nodeSupplier); + Assert.assertFalse(testSession.enableRedirection); + Assert.assertFalse(testSession.enableQueryRedirection); + Assert.assertNull(testSession.endPointToSessionConnection); + + // Fail over from A to B while both redirection flags are disabled. + testSession.insertTablet(createSingleRowTablet()); + Assert.assertEquals(serverB.getEndpoint(), testSession.defaultEndPoint); + Assert.assertNull(testSession.endPointToSessionConnection); + + // Enable query redirection on the already-open session. + testSession.setEnableQueryRedirection(true); + Assert.assertNotNull(testSession.endPointToSessionConnection); + Assert.assertSame( + testSession.getDefaultSessionConnection(), + testSession.endPointToSessionConnection.get(serverB.getEndpoint())); + + for (int i = 0; i < 4; i++) { + testSession.executeQueryStatement("select s1 from root.sg.d1").close(); + } + Assert.assertEquals(2, serverA.getQueryCount()); + Assert.assertEquals(2, serverB.getQueryCount()); + } finally { + testSession.close(); + } + } + } + private static Tablet createSingleRowTablet() { Tablet tablet = new Tablet( @@ -837,8 +991,14 @@ private static class ReconnectTestServer implements AutoCloseable { private final AtomicInteger openSessionCount = new AtomicInteger(); private final AtomicInteger closeSessionCount = new AtomicInteger(); private final AtomicInteger insertTabletCount = new AtomicInteger(); + private final AtomicInteger queryCount = new AtomicInteger(); + private final AtomicInteger activeConnections = new AtomicInteger(); private ReconnectTestServer(int failInsertCount) throws Exception { + this(failInsertCount, 0); + } + + private ReconnectTestServer(int failInsertCount, int failQueryCount) throws Exception { ServerSocket listener = new ServerSocket(0); endpoint = new TEndPoint("127.0.0.1", listener.getLocalPort()); socket = new TServerSocket(listener); @@ -850,6 +1010,9 @@ private ReconnectTestServer(int failInsertCount) throws Exception { new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode()), TSProtocolVersion.IOTDB_SERVICE_PROTOCOL_V3) .setSessionId(openSessionCount.incrementAndGet())); + Mockito.when(handler.requestStatementId(anyLong())).thenReturn(1L); + Mockito.when(handler.closeOperation(any())) + .thenReturn(new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode())); Mockito.when(handler.closeSession(any())) .thenAnswer( ignored -> { @@ -865,6 +1028,24 @@ private ReconnectTestServer(int failInsertCount) throws Exception { } return new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode()); }); + Mockito.when(handler.executeQueryStatementV2(any())) + .thenAnswer( + ignored -> { + if (queryCount.incrementAndGet() <= failQueryCount) { + throw new TTransportException( + TTransportException.END_OF_FILE, "Simulated query transport failure"); + } + TSExecuteStatementResp resp = + new TSExecuteStatementResp( + new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode())); + resp.setColumns(Collections.emptyList()); + resp.setDataTypeList(Collections.emptyList()); + resp.setQueryId(1L); + resp.setQueryResult(Collections.emptyList()); + resp.setIgnoreTimeStamp(false); + resp.setMoreData(false); + return resp; + }); server = new TThreadPoolServer( @@ -883,6 +1064,7 @@ public void preServe() { @Override public ServerContext createContext(TProtocol input, TProtocol output) { + activeConnections.incrementAndGet(); return Mockito.mock(ServerContext.class); } @@ -891,7 +1073,9 @@ public void processContext( ServerContext context, TTransport input, TTransport output) {} @Override - public void deleteContext(ServerContext context, TProtocol input, TProtocol output) {} + public void deleteContext(ServerContext context, TProtocol input, TProtocol output) { + activeConnections.decrementAndGet(); + } }); thread = new Thread(server::serve, "reconnect-test-server"); thread.setDaemon(true); @@ -915,6 +1099,19 @@ private int getInsertTabletCount() { return insertTabletCount.get(); } + private int getQueryCount() { + return queryCount.get(); + } + + private boolean awaitNoActiveConnections(long timeout, TimeUnit unit) + throws InterruptedException { + long deadline = System.nanoTime() + unit.toNanos(timeout); + while (activeConnections.get() != 0 && System.nanoTime() < deadline) { + TimeUnit.MILLISECONDS.sleep(10); + } + return activeConnections.get() == 0; + } + @Override public void close() throws Exception { server.stop(); diff --git a/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionTest.java b/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionTest.java index ce2f631bb42f6..84043c794abb4 100644 --- a/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionTest.java +++ b/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionTest.java @@ -1455,6 +1455,62 @@ public void testRemoveBrokenSessionConnectionWhenRedirectionDisabled() { endPointMap.put(ep3, healthyConnection); testSession.endPointToSessionConnection = endPointMap; + Map deviceMap = new HashMap<>(); + deviceMap.put("root.sg.d1", ep1); + deviceMap.put("root.sg.d2", ep2); + deviceMap.put("root.sg.d3", ep3); + testSession.deviceIdToEndpoint = Collections.unmodifiableMap(deviceMap); + + Map tableDeviceMap = new HashMap<>(); + IDeviceID dev1 = new StringArrayDeviceID("t1", "d1"); + IDeviceID dev2 = new StringArrayDeviceID("t1", "d2"); + IDeviceID dev3 = new StringArrayDeviceID("t1", "d3"); + tableDeviceMap.put(dev1, ep1); + tableDeviceMap.put(dev2, ep2); + tableDeviceMap.put(dev3, ep3); + Map> tableMap = new HashMap<>(); + tableMap.put("db1", Collections.unmodifiableMap(tableDeviceMap)); + testSession.tableModelDeviceIdToEndpoint = Collections.unmodifiableMap(tableMap); + + testSession.removeBrokenSessionConnection(brokenConnection); + + Assert.assertFalse(testSession.endPointToSessionConnection.containsKey(ep1)); + Assert.assertFalse(testSession.endPointToSessionConnection.containsKey(ep2)); + Assert.assertSame(healthyConnection, testSession.endPointToSessionConnection.get(ep3)); + + // Device route caches must remain untouched when write redirection is disabled. + Assert.assertEquals(ep1, testSession.deviceIdToEndpoint.get("root.sg.d1")); + Assert.assertEquals(ep2, testSession.deviceIdToEndpoint.get("root.sg.d2")); + Assert.assertEquals(ep3, testSession.deviceIdToEndpoint.get("root.sg.d3")); + Assert.assertEquals(ep1, testSession.tableModelDeviceIdToEndpoint.get("db1").get(dev1)); + Assert.assertEquals(ep2, testSession.tableModelDeviceIdToEndpoint.get("db1").get(dev2)); + Assert.assertEquals(ep3, testSession.tableModelDeviceIdToEndpoint.get("db1").get(dev3)); + } + + @Test + public void testRemoveBrokenSessionConnectionCleansDeviceRoutesWhenRedirectionEnabled() { + Session testSession = + new Session.Builder() + .nodeUrls(Collections.singletonList("127.0.0.1:6667")) + .username("root") + .password("root") + .enableRedirection(true) + .enableAutoFetch(false) + .build(); + Assert.assertTrue(testSession.enableRedirection); + + TEndPoint ep1 = new TEndPoint("127.0.0.1", 6667); + TEndPoint ep2 = new TEndPoint("127.0.0.1", 6668); + TEndPoint ep3 = new TEndPoint("127.0.0.1", 6669); + SessionConnection brokenConnection = Mockito.mock(SessionConnection.class); + SessionConnection healthyConnection = Mockito.mock(SessionConnection.class); + + Map endPointMap = new ConcurrentHashMap<>(); + endPointMap.put(ep1, brokenConnection); + endPointMap.put(ep2, brokenConnection); + endPointMap.put(ep3, healthyConnection); + testSession.endPointToSessionConnection = endPointMap; + Map deviceMap = new ConcurrentHashMap<>(); deviceMap.put("root.sg.d1", ep1); deviceMap.put("root.sg.d2", ep2); From a0bc99ecb153beb4d2df815099fad6c0af4b6b00 Mon Sep 17 00:00:00 2001 From: JackieTien97 Date: Sat, 5 Dec 2026 07:44:52 +0800 Subject: [PATCH 3/5] Address second round of PR review comments: track closing connections for forceClose, propagate query redirection flag, stabilize test seed --- .../org/apache/iotdb/session/Session.java | 53 ++++-- .../iotdb/session/SessionConnectionTest.java | 153 +++++++++++++++++- 2 files changed, 183 insertions(+), 23 deletions(-) diff --git a/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java b/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java index 35ec696768f65..f2d94bd4e25f6 100644 --- a/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java +++ b/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java @@ -166,6 +166,8 @@ public class Session implements ISession { private boolean isClosed = true; private volatile boolean closing; private final Object connectionStateLock = new Object(); + private final Set closingConnections = + Collections.newSetFromMap(new IdentityHashMap<>()); // this field only take effect in write request, nothing to do with any other type requests, // like query, load and so on. @@ -789,6 +791,11 @@ private List getSessionConnections() { if (defaultSessionConnection != null && seen.add(defaultSessionConnection)) { connections.add(defaultSessionConnection); } + for (SessionConnection sessionConnection : closingConnections) { + if (sessionConnection != null && seen.add(sessionConnection)) { + connections.add(sessionConnection); + } + } return connections; } @@ -1550,16 +1557,23 @@ boolean registerReconnectedConnection(SessionConnection connection, TEndPoint ne SessionConnection previous = endPointToSessionConnection.put(newEndPoint, connection); if (previous != null && previous != connection) { staleConnection = previous; + closingConnections.add(staleConnection); } } } - if (staleConnection != null - && staleConnection.transport != null - && staleConnection.transport.isOpen()) { + if (staleConnection != null) { try { - staleConnection.close(); - } catch (IoTDBConnectionException e) { - logger.warn(SessionMessages.CLOSE_CONNECTION_FAILED, e.getMessage()); + if (staleConnection.transport != null && staleConnection.transport.isOpen()) { + try { + staleConnection.close(); + } catch (IoTDBConnectionException e) { + logger.warn(SessionMessages.CLOSE_CONNECTION_FAILED, e.getMessage()); + } + } + } finally { + synchronized (connectionStateLock) { + closingConnections.remove(staleConnection); + } } } return true; @@ -4860,18 +4874,27 @@ public boolean isEnableQueryRedirection() { public void setEnableQueryRedirection(boolean enableQueryRedirection) { synchronized (connectionStateLock) { this.enableQueryRedirection = enableQueryRedirection; - if (enableQueryRedirection && !isClosed && !closing) { + if (!isClosed && !closing) { if (defaultSessionConnection != null) { - defaultSessionConnection.setEnableRedirect(true); + defaultSessionConnection.setEnableRedirect(enableQueryRedirection); } - if (endPointToSessionConnection == null) { - Map connections = new ConcurrentHashMap<>(); - if (defaultEndPoint != null && defaultSessionConnection != null) { - connections.put(defaultEndPoint, defaultSessionConnection); + if (endPointToSessionConnection != null) { + for (SessionConnection connection : endPointToSessionConnection.values()) { + if (connection != null) { + connection.setEnableRedirect(enableQueryRedirection); + } + } + } + if (enableQueryRedirection) { + if (endPointToSessionConnection == null) { + Map connections = new ConcurrentHashMap<>(); + if (defaultEndPoint != null && defaultSessionConnection != null) { + connections.put(defaultEndPoint, defaultSessionConnection); + } + endPointToSessionConnection = connections; + } else if (defaultEndPoint != null && defaultSessionConnection != null) { + endPointToSessionConnection.putIfAbsent(defaultEndPoint, defaultSessionConnection); } - endPointToSessionConnection = connections; - } else if (defaultEndPoint != null && defaultSessionConnection != null) { - endPointToSessionConnection.putIfAbsent(defaultEndPoint, defaultSessionConnection); } } } diff --git a/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionConnectionTest.java b/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionConnectionTest.java index 9681f685b77da..c9241c6273d00 100644 --- a/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionConnectionTest.java +++ b/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionConnectionTest.java @@ -42,6 +42,7 @@ import org.apache.iotdb.service.rpc.thrift.TSCreateTimeseriesReq; import org.apache.iotdb.service.rpc.thrift.TSDeleteDataReq; import org.apache.iotdb.service.rpc.thrift.TSDropSchemaTemplateReq; +import org.apache.iotdb.service.rpc.thrift.TSExecuteStatementReq; import org.apache.iotdb.service.rpc.thrift.TSExecuteStatementResp; import org.apache.iotdb.service.rpc.thrift.TSInsertRecordReq; import org.apache.iotdb.service.rpc.thrift.TSInsertRecordsOfOneDeviceReq; @@ -92,6 +93,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; @@ -846,9 +848,8 @@ public void close() {} new Session( new Session.Builder() .nodeUrls( - Arrays.asList( - serverA.getEndpoint().getIp() + ":" + serverA.getEndpoint().getPort(), - serverB.getEndpoint().getIp() + ":" + serverB.getEndpoint().getPort())) + Collections.singletonList( + serverA.getEndpoint().getIp() + ":" + serverA.getEndpoint().getPort())) .username("root") .password("root") .enableRedirection(false) @@ -880,8 +881,12 @@ boolean registerReconnectedConnection( testSession.executeQueryStatement("select s1 from root.sg.d1"); return null; }); - Assert.assertTrue( - "Reconnect did not reach registration", beforeRegister.await(5, TimeUnit.SECONDS)); + if (!beforeRegister.await(5, TimeUnit.SECONDS)) { + if (queryFuture.isDone()) { + queryFuture.get(1, TimeUnit.SECONDS); + } + Assert.fail("Reconnect did not reach registration"); + } testSession.forceClose(); resumeRegister.countDown(); @@ -970,6 +975,118 @@ public void close() {} } } + @Test + public void testForceCloseDuringStaleConnectionCloseUnblocksReconnectAndReleasesSocket() + throws Exception { + CountDownLatch closeSessionStarted = new CountDownLatch(1); + CountDownLatch continueCloseSession = new CountDownLatch(1); + try (ReconnectTestServer serverA = + new ReconnectTestServer(0, 0, closeSessionStarted, continueCloseSession); + ReconnectTestServer serverB = new ReconnectTestServer(0, 1)) { + INodeSupplier nodeSupplier = + new INodeSupplier() { + @Override + public List get() { + return Collections.singletonList(serverA.getEndpoint()); + } + + @Override + public Optional getQueryEndPoint() { + return Optional.of(serverB.getEndpoint()); + } + + @Override + public void close() {} + }; + Session testSession = + new Session.Builder() + .nodeUrls( + Collections.singletonList( + serverA.getEndpoint().getIp() + ":" + serverA.getEndpoint().getPort())) + .username("root") + .password("root") + .enableRedirection(false) + .enableAutoFetch(false) + .maxRetryCount(5) + .retryIntervalInMs(10) + .build(); + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + testSession.open(false, 1000, Collections.emptyMap(), nodeSupplier); + Assert.assertEquals(serverA.getEndpoint(), testSession.defaultEndPoint); + + Future queryFuture = + executor.submit( + () -> { + testSession.executeQueryStatement("select s1 from root.sg.d1"); + return null; + }); + if (!closeSessionStarted.await(5, TimeUnit.SECONDS)) { + if (queryFuture.isDone()) { + queryFuture.get(1, TimeUnit.SECONDS); + } + Assert.fail("Stale connection closeSession did not start"); + } + + // Force-close while staleConnection.close() is blocked waiting for serverA's reply. + testSession.forceClose(); + + try { + queryFuture.get(5, TimeUnit.SECONDS); + Assert.fail("Expected query to fail immediately after forceClose()"); + } catch (ExecutionException e) { + Assert.assertTrue(e.getCause() instanceof IoTDBConnectionException); + } + Assert.assertEquals(0, serverA.getQueryCount()); + Assert.assertEquals(1, serverB.getQueryCount()); + continueCloseSession.countDown(); + Assert.assertTrue( + "Server A still has active connections", + serverA.awaitNoActiveConnections(5, TimeUnit.SECONDS)); + Assert.assertTrue( + "Server B still has active connections", + serverB.awaitNoActiveConnections(5, TimeUnit.SECONDS)); + } finally { + continueCloseSession.countDown(); + executor.shutdownNow(); + testSession.forceClose(); + } + } + } + + @Test + public void testSetEnableQueryRedirectionPropagatesTrueAndFalseToOpenConnections() + throws Exception { + try (ReconnectTestServer server = new ReconnectTestServer(0, 0)) { + Session testSession = + new Session.Builder() + .host(server.getEndpoint().getIp()) + .port(server.getEndpoint().getPort()) + .username("root") + .password("root") + .enableRedirection(false) + .enableAutoFetch(false) + .build(); + try { + testSession.open(false, 1000); + Assert.assertFalse(testSession.isEnableQueryRedirection()); + + testSession.setEnableQueryRedirection(true); + Assert.assertTrue(testSession.isEnableQueryRedirection()); + testSession.executeQueryStatement("select s1 from root.sg.d1").close(); + + testSession.setEnableQueryRedirection(false); + Assert.assertFalse(testSession.isEnableQueryRedirection()); + testSession.executeQueryStatement("select s1 from root.sg.d1").close(); + + Assert.assertEquals( + Arrays.asList(Boolean.TRUE, Boolean.FALSE), server.getObservedEnableRedirectQuery()); + } finally { + testSession.close(); + } + } + } + private static Tablet createSingleRowTablet() { Tablet tablet = new Tablet( @@ -993,12 +1110,22 @@ private static class ReconnectTestServer implements AutoCloseable { private final AtomicInteger insertTabletCount = new AtomicInteger(); private final AtomicInteger queryCount = new AtomicInteger(); private final AtomicInteger activeConnections = new AtomicInteger(); + private final List observedEnableRedirectQuery = new CopyOnWriteArrayList<>(); private ReconnectTestServer(int failInsertCount) throws Exception { - this(failInsertCount, 0); + this(failInsertCount, 0, null, null); } private ReconnectTestServer(int failInsertCount, int failQueryCount) throws Exception { + this(failInsertCount, failQueryCount, null, null); + } + + private ReconnectTestServer( + int failInsertCount, + int failQueryCount, + CountDownLatch closeSessionStarted, + CountDownLatch continueCloseSession) + throws Exception { ServerSocket listener = new ServerSocket(0); endpoint = new TEndPoint("127.0.0.1", listener.getLocalPort()); socket = new TServerSocket(listener); @@ -1016,7 +1143,11 @@ private ReconnectTestServer(int failInsertCount, int failQueryCount) throws Exce Mockito.when(handler.closeSession(any())) .thenAnswer( ignored -> { - closeSessionCount.incrementAndGet(); + int count = closeSessionCount.incrementAndGet(); + if (closeSessionStarted != null && count == 1) { + closeSessionStarted.countDown(); + continueCloseSession.await(5, TimeUnit.SECONDS); + } return new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode()); }); Mockito.when(handler.insertTablet(any())) @@ -1030,7 +1161,9 @@ private ReconnectTestServer(int failInsertCount, int failQueryCount) throws Exce }); Mockito.when(handler.executeQueryStatementV2(any())) .thenAnswer( - ignored -> { + invocation -> { + TSExecuteStatementReq req = invocation.getArgument(0); + observedEnableRedirectQuery.add(req.isEnableRedirectQuery()); if (queryCount.incrementAndGet() <= failQueryCount) { throw new TTransportException( TTransportException.END_OF_FILE, "Simulated query transport failure"); @@ -1103,6 +1236,10 @@ private int getQueryCount() { return queryCount.get(); } + private List getObservedEnableRedirectQuery() { + return observedEnableRedirectQuery; + } + private boolean awaitNoActiveConnections(long timeout, TimeUnit unit) throws InterruptedException { long deadline = System.nanoTime() + unit.toNanos(timeout); From 8647809f43c3c382b92b7ee36b42736629483ca7 Mon Sep 17 00:00:00 2001 From: JackieTien97 Date: Sat, 5 Dec 2026 08:49:02 +0800 Subject: [PATCH 4/5] Avoid duplicate closeSession on closing connections during Session.close() and strengthen forceClose test --- .../org/apache/iotdb/session/Session.java | 33 ++++-- .../iotdb/session/SessionConnectionTest.java | 100 +++++++++++++++++- 2 files changed, 122 insertions(+), 11 deletions(-) diff --git a/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java b/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java index f2d94bd4e25f6..2298371ace517 100644 --- a/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java +++ b/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java @@ -105,6 +105,7 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; @@ -166,8 +167,7 @@ public class Session implements ISession { private boolean isClosed = true; private volatile boolean closing; private final Object connectionStateLock = new Object(); - private final Set closingConnections = - Collections.newSetFromMap(new IdentityHashMap<>()); + private final Map closingConnections = new IdentityHashMap<>(); // this field only take effect in write request, nothing to do with any other type requests, // like query, load and so on. @@ -728,12 +728,14 @@ public synchronized void close() throws IoTDBConnectionException { Throwable closeException = null; try { List connectionsToClose; + List inProgressCloses; synchronized (connectionStateLock) { closing = true; if (isClosed) { return; } - connectionsToClose = getSessionConnections(); + connectionsToClose = getSessionConnections(false); + inProgressCloses = new ArrayList<>(closingConnections.values()); } for (SessionConnection sessionConnection : connectionsToClose) { @@ -747,6 +749,14 @@ public synchronized void close() throws IoTDBConnectionException { } } } + for (CountDownLatch latch : inProgressCloses) { + try { + latch.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + break; + } + } } finally { finishClose(); } @@ -767,7 +777,7 @@ public synchronized void forceClose() { if (isClosed) { return; } - connectionsToClose = getSessionConnections(); + connectionsToClose = getSessionConnections(true); } try { for (SessionConnection sessionConnection : connectionsToClose) { @@ -778,7 +788,7 @@ public synchronized void forceClose() { } } - private List getSessionConnections() { + private List getSessionConnections(boolean includeClosingConnections) { List connections = new ArrayList<>(); Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); if (endPointToSessionConnection != null) { @@ -791,9 +801,11 @@ private List getSessionConnections() { if (defaultSessionConnection != null && seen.add(defaultSessionConnection)) { connections.add(defaultSessionConnection); } - for (SessionConnection sessionConnection : closingConnections) { - if (sessionConnection != null && seen.add(sessionConnection)) { - connections.add(sessionConnection); + if (includeClosingConnections) { + for (SessionConnection sessionConnection : closingConnections.keySet()) { + if (sessionConnection != null && seen.add(sessionConnection)) { + connections.add(sessionConnection); + } } } return connections; @@ -1543,6 +1555,7 @@ boolean isClosing() { boolean registerReconnectedConnection(SessionConnection connection, TEndPoint newEndPoint) { SessionConnection staleConnection = null; + CountDownLatch staleCloseLatch = null; synchronized (connectionStateLock) { if (closing || connection.isForceClosed()) { return false; @@ -1557,7 +1570,8 @@ boolean registerReconnectedConnection(SessionConnection connection, TEndPoint ne SessionConnection previous = endPointToSessionConnection.put(newEndPoint, connection); if (previous != null && previous != connection) { staleConnection = previous; - closingConnections.add(staleConnection); + staleCloseLatch = new CountDownLatch(1); + closingConnections.put(staleConnection, staleCloseLatch); } } } @@ -1574,6 +1588,7 @@ boolean registerReconnectedConnection(SessionConnection connection, TEndPoint ne synchronized (connectionStateLock) { closingConnections.remove(staleConnection); } + staleCloseLatch.countDown(); } } return true; diff --git a/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionConnectionTest.java b/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionConnectionTest.java index c9241c6273d00..16b8f4cea3059 100644 --- a/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionConnectionTest.java +++ b/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionConnectionTest.java @@ -1012,8 +1012,12 @@ public void close() {} .build(); ExecutorService executor = Executors.newSingleThreadExecutor(); try { - testSession.open(false, 1000, Collections.emptyMap(), nodeSupplier); + // Disable client read timeout so the blocked closeSession RPC cannot time out on its own. + testSession.open(false, 0, Collections.emptyMap(), nodeSupplier); Assert.assertEquals(serverA.getEndpoint(), testSession.defaultEndPoint); + TTransport displacedTransport = + Whitebox.getInternalState(testSession.getDefaultSessionConnection(), "transport"); + Assert.assertTrue(displacedTransport.isOpen()); Future queryFuture = executor.submit( @@ -1030,6 +1034,9 @@ public void close() {} // Force-close while staleConnection.close() is blocked waiting for serverA's reply. testSession.forceClose(); + Assert.assertFalse( + "Displaced transport should be closed immediately when forceClose() returns", + displacedTransport.isOpen()); try { queryFuture.get(5, TimeUnit.SECONDS); @@ -1054,6 +1061,95 @@ public void close() {} } } + @Test + public void testGracefulCloseDuringStaleConnectionCloseDoesNotThrowOrDoubleClose() + throws Exception { + CountDownLatch closeSessionStarted = new CountDownLatch(1); + CountDownLatch continueCloseSession = new CountDownLatch(1); + try (ReconnectTestServer serverA = + new ReconnectTestServer(0, 0, closeSessionStarted, continueCloseSession); + ReconnectTestServer serverB = new ReconnectTestServer(0, 1)) { + INodeSupplier nodeSupplier = + new INodeSupplier() { + @Override + public List get() { + return Collections.singletonList(serverA.getEndpoint()); + } + + @Override + public Optional getQueryEndPoint() { + return Optional.of(serverB.getEndpoint()); + } + + @Override + public void close() {} + }; + Session testSession = + new Session.Builder() + .nodeUrls( + Collections.singletonList( + serverA.getEndpoint().getIp() + ":" + serverA.getEndpoint().getPort())) + .username("root") + .password("root") + .enableRedirection(false) + .enableAutoFetch(false) + .maxRetryCount(5) + .retryIntervalInMs(10) + .build(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + testSession.open(false, 0, Collections.emptyMap(), nodeSupplier); + Assert.assertEquals(serverA.getEndpoint(), testSession.defaultEndPoint); + + Future queryFuture = + executor.submit( + () -> { + testSession.executeQueryStatement("select s1 from root.sg.d1"); + return null; + }); + if (!closeSessionStarted.await(5, TimeUnit.SECONDS)) { + if (queryFuture.isDone()) { + queryFuture.get(1, TimeUnit.SECONDS); + } + Assert.fail("Stale connection closeSession did not start"); + } + + Future closeFuture = + executor.submit( + () -> { + testSession.close(); + return null; + }); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (!testSession.isClosing() && System.nanoTime() < deadline) { + TimeUnit.MILLISECONDS.sleep(5); + } + Assert.assertTrue("Session.close() did not start", testSession.isClosing()); + + continueCloseSession.countDown(); + closeFuture.get(5, TimeUnit.SECONDS); + + try { + queryFuture.get(5, TimeUnit.SECONDS); + Assert.fail("Expected query to fail after Session.close()"); + } catch (ExecutionException e) { + Assert.assertTrue(e.getCause() instanceof IoTDBConnectionException); + } + Assert.assertEquals(2, serverA.getCloseSessionCount()); + Assert.assertTrue( + "Server A still has active connections", + serverA.awaitNoActiveConnections(5, TimeUnit.SECONDS)); + Assert.assertTrue( + "Server B still has active connections", + serverB.awaitNoActiveConnections(5, TimeUnit.SECONDS)); + } finally { + continueCloseSession.countDown(); + executor.shutdownNow(); + testSession.forceClose(); + } + } + } + @Test public void testSetEnableQueryRedirectionPropagatesTrueAndFalseToOpenConnections() throws Exception { @@ -1146,7 +1242,7 @@ private ReconnectTestServer( int count = closeSessionCount.incrementAndGet(); if (closeSessionStarted != null && count == 1) { closeSessionStarted.countDown(); - continueCloseSession.await(5, TimeUnit.SECONDS); + continueCloseSession.await(30, TimeUnit.SECONDS); } return new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode()); }); From b95e9c1e86c852dbc228520c8f7aac5a7ff54ca7 Mon Sep 17 00:00:00 2001 From: JackieTien97 Date: Sun, 6 Dec 2026 15:51:17 +0800 Subject: [PATCH 5/5] Coordinate Session reconnects with shutdown and query redirection --- .../org/apache/iotdb/session/Session.java | 466 +++++++++--------- .../iotdb/session/SessionConnection.java | 197 ++++---- .../iotdb/session/SessionConnectionTest.java | 283 ++++++++++- 3 files changed, 626 insertions(+), 320 deletions(-) diff --git a/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java b/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java index 2298371ace517..67de509a173ad 100644 --- a/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java +++ b/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java @@ -112,7 +112,6 @@ import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; import java.util.function.IntToLongFunction; import java.util.stream.Collectors; @@ -163,11 +162,26 @@ public class Session implements ISession { protected int thriftMaxFrameSize; protected int thriftMaxReusableBufferSize = Integer.MAX_VALUE; protected TEndPoint defaultEndPoint; - protected SessionConnection defaultSessionConnection; + protected volatile SessionConnection defaultSessionConnection; private boolean isClosed = true; - private volatile boolean closing; + + private enum CloseMode { + GRACEFUL, + FORCE + } + + // Each open session owns its close state. An in-flight handshake can outlive a close and reopen. + static final class ConnectionState { + private volatile CloseMode closeMode; + private Map closingConnections = Collections.emptyMap(); + + boolean isClosing() { + return closeMode != null; + } + } + private final Object connectionStateLock = new Object(); - private final Map closingConnections = new IdentityHashMap<>(); + private volatile ConnectionState connectionState = new ConnectionState(); // this field only take effect in write request, nothing to do with any other type requests, // like query, load and so on. @@ -177,7 +191,7 @@ public class Session implements ISession { // to another available DataNode) // so even if enableRedirection is set to false, we may also send write request to another // datanode while encountering retriable errors in current DataNode - protected boolean enableRedirection; + protected volatile boolean enableRedirection; protected boolean enableRecordsAutoConvertTablet = SessionConfig.DEFAULT_RECORDS_AUTO_CONVERT_TABLET; private static final double CONVERT_THRESHOLD = 0.5; @@ -200,7 +214,7 @@ public class Session implements ISession { protected INodeSupplier availableNodes; - protected boolean enableQueryRedirection = false; + protected volatile boolean enableQueryRedirection; // The version number of the client which used for compatibility in the server protected Version version; @@ -576,15 +590,10 @@ public synchronized void open(boolean enableRPCCompaction, int connectionTimeout } this.connectionTimeoutInMs = connectionTimeoutInMs; - closing = false; - setDefaultSessionConnection(constructSessionConnection(this, defaultEndPoint, zoneId)); - getDefaultSessionConnection().setEnableRedirect(enableQueryRedirection); - isClosed = false; + openDefaultSessionConnection(); if (enableRedirection || enableQueryRedirection) { deviceIdToEndpoint = new ConcurrentHashMap<>(); tableModelDeviceIdToEndpoint = new ConcurrentHashMap<>(); - endPointToSessionConnection = new ConcurrentHashMap<>(); - endPointToSessionConnection.put(defaultEndPoint, getDefaultSessionConnection()); } } @@ -659,15 +668,10 @@ public synchronized void open( this.availableNodes = nodesSupplier; this.enableThriftRpcCompaction = enableThriftRpcCompaction; this.connectionTimeoutInMs = connectionTimeoutInMs; - closing = false; - setDefaultSessionConnection(constructSessionConnection(this, defaultEndPoint, zoneId)); - getDefaultSessionConnection().setEnableRedirect(enableQueryRedirection); - isClosed = false; + openDefaultSessionConnection(); if (enableRedirection || enableQueryRedirection) { this.deviceIdToEndpoint = deviceIdToEndpoint; this.tableModelDeviceIdToEndpoint = new ConcurrentHashMap<>(); - endPointToSessionConnection = new ConcurrentHashMap<>(); - endPointToSessionConnection.put(defaultEndPoint, getDefaultSessionConnection()); } } @@ -708,21 +712,48 @@ public synchronized void openWithTableModelDatabaseCache( this.availableNodes = nodesSupplier; this.enableThriftRpcCompaction = enableThriftRpcCompaction; this.connectionTimeoutInMs = connectionTimeoutInMs; - closing = false; - setDefaultSessionConnection(constructSessionConnection(this, defaultEndPoint, zoneId)); - getDefaultSessionConnection().setEnableRedirect(enableQueryRedirection); - isClosed = false; + openDefaultSessionConnection(); if (enableRedirection || enableQueryRedirection) { this.deviceIdToEndpoint = deviceIdToEndpoint; this.tableModelDeviceIdToEndpoint = tableModelDeviceIdToEndpoint == null ? new ConcurrentHashMap<>() : tableModelDeviceIdToEndpoint; - endPointToSessionConnection = new ConcurrentHashMap<>(); - endPointToSessionConnection.put(defaultEndPoint, getDefaultSessionConnection()); } } + private void openDefaultSessionConnection() throws IoTDBConnectionException { + synchronized (connectionStateLock) { + if (connectionState.isClosing()) { + endPointToSessionConnection = null; + connectionState = new ConnectionState(); + } + } + SessionConnection connection = constructSessionConnection(this, defaultEndPoint, zoneId); + synchronized (connectionStateLock) { + setDefaultSessionConnection(connection); + connection.setEnableRedirect(enableQueryRedirection); + if (enableRedirection || enableQueryRedirection) { + initializeConnectionCache(connection); + } else { + endPointToSessionConnection = null; + } + isClosed = false; + } + } + + private void initializeConnectionCache(SessionConnection connection) { + Map connections = new ConcurrentHashMap<>(); + TEndPoint endpoint = connection.getEndPoint(); + if (endpoint == null) { + endpoint = defaultEndPoint; + } + if (endpoint != null) { + connections.put(endpoint, connection); + } + endPointToSessionConnection = connections; + } + @Override public synchronized void close() throws IoTDBConnectionException { Throwable closeException = null; @@ -730,12 +761,12 @@ public synchronized void close() throws IoTDBConnectionException { List connectionsToClose; List inProgressCloses; synchronized (connectionStateLock) { - closing = true; if (isClosed) { return; } + connectionState.closeMode = CloseMode.GRACEFUL; connectionsToClose = getSessionConnections(false); - inProgressCloses = new ArrayList<>(closingConnections.values()); + inProgressCloses = new ArrayList<>(connectionState.closingConnections.values()); } for (SessionConnection sessionConnection : connectionsToClose) { @@ -773,10 +804,10 @@ public synchronized void close() throws IoTDBConnectionException { public synchronized void forceClose() { List connectionsToClose; synchronized (connectionStateLock) { - closing = true; if (isClosed) { return; } + connectionState.closeMode = CloseMode.FORCE; connectionsToClose = getSessionConnections(true); } try { @@ -791,6 +822,7 @@ public synchronized void forceClose() { private List getSessionConnections(boolean includeClosingConnections) { List connections = new ArrayList<>(); Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); + seen.addAll(connectionState.closingConnections.keySet()); if (endPointToSessionConnection != null) { for (SessionConnection sessionConnection : endPointToSessionConnection.values()) { if (sessionConnection != null && seen.add(sessionConnection)) { @@ -802,11 +834,7 @@ private List getSessionConnections(boolean includeClosingConn connections.add(defaultSessionConnection); } if (includeClosingConnections) { - for (SessionConnection sessionConnection : closingConnections.keySet()) { - if (sessionConnection != null && seen.add(sessionConnection)) { - connections.add(sessionConnection); - } - } + connections.addAll(connectionState.closingConnections.keySet()); } return connections; } @@ -1140,40 +1168,76 @@ private SessionDataSet executeStatementMayRedirect(String sql, long timeoutInMs) } private SessionConnection getQuerySessionConnection() throws IoTDBConnectionException { - if (closing) { + if (isClosing()) { throw new IoTDBConnectionException(SessionMessages.SESSION_NOT_OPEN); } - Optional endPoint = - availableNodes == null ? Optional.empty() : availableNodes.getQueryEndPoint(); - if (!endPoint.isPresent() || endPointToSessionConnection == null) { + INodeSupplier nodes = availableNodes; + if ((!enableQueryRedirection && !enableRedirection) || nodes == null) { return getDefaultSessionConnection(); } - SessionConnection connection = - endPointToSessionConnection.computeIfAbsent( - endPoint.get(), - k -> { - if (closing) { - return null; - } - try { - SessionConnection newConnection = - constructSessionConnection(this, endPoint.get(), zoneId); - if (closing) { - newConnection.forceCloseTransport(); + Map connections = endPointToSessionConnection; + Optional endpoint = nodes.getQueryEndPoint(); + if (endpoint.isPresent() && connections != null) { + try { + return getOrCreateSessionConnection(connections, endpoint.get()); + } catch (IoTDBConnectionException e) { + synchronized (connectionStateLock) { + if (isClosing() || connections != endPointToSessionConnection) { + throw e; + } + return getDefaultSessionConnection(); + } + } + } + return getDefaultSessionConnection(); + } + + private SessionConnection getRedirectedConnectionOrNull(TEndPoint endpoint) { + try { + return getOrCreateSessionConnection(endPointToSessionConnection, endpoint); + } catch (IoTDBConnectionException e) { + return null; + } + } + + private SessionConnection getOrCreateSessionConnection( + Map connections, TEndPoint endpoint) + throws IoTDBConnectionException { + ConnectionState owner = connectionState; + if (owner.isClosing() || connections == null || connections != endPointToSessionConnection) { + throw new IoTDBConnectionException(SessionMessages.SESSION_NOT_OPEN); + } + SessionConnection connection = connections.get(endpoint); + if (connection != null) { + return connection; + } + try { + connection = + connections.computeIfAbsent( + endpoint, + key -> { + if (owner.isClosing() || connections != endPointToSessionConnection) { return null; } - return newConnection; - } catch (IoTDBConnectionException ex) { - return null; - } - }); - if (closing) { + try { + return constructSessionConnection(this, key, zoneId); + } catch (IoTDBConnectionException e) { + throw new CompletionException(e); + } + }); + } catch (CompletionException e) { + if (e.getCause() instanceof IoTDBConnectionException) { + throw (IoTDBConnectionException) e.getCause(); + } + throw e; + } + if (owner.isClosing() || connections != endPointToSessionConnection || connection == null) { if (connection != null) { - connection.forceCloseTransport(); + closeDiscardedConnection(connection, owner.closeMode); } throw new IoTDBConnectionException(SessionMessages.SESSION_NOT_OPEN); } - return connection == null ? getDefaultSessionConnection() : connection; + return connection; } /** @@ -1549,87 +1613,130 @@ public String getTimestampPrecision() throws TException, IoTDBConnectionExceptio return getDefaultSessionConnection().getClient().getProperties().getTimestampPrecision(); } + ConnectionState getConnectionState() { + return connectionState; + } + boolean isClosing() { - return closing; + return connectionState.isClosing(); + } + + private void closeDiscardedConnection(SessionConnection connection, CloseMode mode) { + if (mode == CloseMode.FORCE) { + connection.forceCloseTransport(); + } else { + try { + connection.close(); + } catch (IoTDBConnectionException | RuntimeException e) { + logger.warn(SessionMessages.CLOSE_CONNECTION_FAILED, e.getMessage()); + } + } } boolean registerReconnectedConnection(SessionConnection connection, TEndPoint newEndPoint) { - SessionConnection staleConnection = null; - CountDownLatch staleCloseLatch = null; + ConnectionState owner = connection.ownerState == null ? connectionState : connection.ownerState; + SessionConnection displaced; + CloseMode mode; + CountDownLatch closed; synchronized (connectionStateLock) { - if (closing || connection.isForceClosed()) { + if (connection.isClosed() + || owner.closingConnections.containsKey(connection) + || !newEndPoint.equals(connection.getEndPoint())) { return false; } - removeBrokenSessionConnection(connection); - defaultEndPoint = newEndPoint; - setDefaultSessionConnection(connection); - if (endPointToSessionConnection != null || enableRedirection || enableQueryRedirection) { - if (endPointToSessionConnection == null) { - endPointToSessionConnection = new ConcurrentHashMap<>(); + mode = owner.closeMode; + if (mode == null) { + displaced = replaceDefaultConnection(connection, newEndPoint); + if (displaced == null + || displaced == connection + || owner.closingConnections.containsKey(displaced)) { + return true; } - SessionConnection previous = endPointToSessionConnection.put(newEndPoint, connection); - if (previous != null && previous != connection) { - staleConnection = previous; - staleCloseLatch = new CountDownLatch(1); - closingConnections.put(staleConnection, staleCloseLatch); + } else { + // close() already owns every connection in its snapshot. An uncached connection + // that finished its handshake later must close its own server session. + if (owner == connectionState + && (connection == defaultSessionConnection + || (endPointToSessionConnection != null + && endPointToSessionConnection.containsValue(connection)))) { + return false; } + displaced = connection; } + if (owner.closingConnections.isEmpty()) { + owner.closingConnections = new IdentityHashMap<>(2); + } + closed = new CountDownLatch(1); + owner.closingConnections.put(displaced, closed); } - if (staleConnection != null) { - try { - if (staleConnection.transport != null && staleConnection.transport.isOpen()) { - try { - staleConnection.close(); - } catch (IoTDBConnectionException e) { - logger.warn(SessionMessages.CLOSE_CONNECTION_FAILED, e.getMessage()); - } - } - } finally { - synchronized (connectionStateLock) { - closingConnections.remove(staleConnection); + + try { + closeDiscardedConnection(displaced, mode); + } finally { + synchronized (connectionStateLock) { + owner.closingConnections.remove(displaced, closed); + if (owner.closingConnections.isEmpty()) { + owner.closingConnections = Collections.emptyMap(); } - staleCloseLatch.countDown(); + closed.countDown(); } } - return true; + return mode == null; + } + + // Called under connectionStateLock. The caller closes any displaced connection outside the lock. + private SessionConnection replaceDefaultConnection( + SessionConnection connection, TEndPoint endPoint) { + removeBrokenSessionConnection(connection); + defaultEndPoint = endPoint; + connection.setEnableRedirect(enableQueryRedirection); + setDefaultSessionConnection(connection); + if (endPointToSessionConnection != null) { + return endPointToSessionConnection.put(endPoint, connection); + } + if (enableRedirection || enableQueryRedirection) { + initializeConnectionCache(connection); + } + return null; } // TODO https://issues.apache.org/jira/browse/IOTDB-1399 public void removeBrokenSessionConnection(SessionConnection sessionConnection) { - // remove the cached broken leader session - if (endPointToSessionConnection == null) { + Map connections = endPointToSessionConnection; + if (connections == null) { return; } - Set removedEndPoints = new HashSet<>(); - for (Iterator> it = - endPointToSessionConnection.entrySet().iterator(); + if (!enableRedirection) { + connections.values().removeIf(connection -> connection == sessionConnection); + return; + } + Set removed = null; + for (Iterator> it = connections.entrySet().iterator(); it.hasNext(); ) { Entry entry = it.next(); - if (entry.getValue().equals(sessionConnection)) { - removedEndPoints.add(entry.getKey()); + if (entry.getValue() == sessionConnection) { + if (removed == null) { + removed = new HashSet<>(); + } + removed.add(entry.getKey()); it.remove(); } } - if (!enableRedirection || removedEndPoints.isEmpty()) { - return; - } - if (deviceIdToEndpoint != null && !deviceIdToEndpoint.isEmpty()) { - for (Iterator> it = deviceIdToEndpoint.entrySet().iterator(); - it.hasNext(); ) { - Entry entry = it.next(); - if (removedEndPoints.contains(entry.getValue())) { - it.remove(); + if (removed != null) { + removeDeviceRoutes(deviceIdToEndpoint, removed); + if (tableModelDeviceIdToEndpoint != null) { + for (Map routes : tableModelDeviceIdToEndpoint.values()) { + removeDeviceRoutes(routes, removed); } } } - if (tableModelDeviceIdToEndpoint != null && !tableModelDeviceIdToEndpoint.isEmpty()) { - for (Map databaseToEndpoint : tableModelDeviceIdToEndpoint.values()) { - for (Iterator> it = databaseToEndpoint.entrySet().iterator(); - it.hasNext(); ) { - Entry entry = it.next(); - if (removedEndPoints.contains(entry.getValue())) { - it.remove(); - } + } + + private static void removeDeviceRoutes(Map routes, Set endpoints) { + if (routes != null) { + for (Iterator it = routes.values().iterator(); it.hasNext(); ) { + if (endpoints.contains(it.next())) { + it.remove(); } } } @@ -1637,7 +1744,7 @@ public void removeBrokenSessionConnection(SessionConnection sessionConnection) { private void handleRedirection(String deviceId, TEndPoint endpoint) { if (enableRedirection) { - if (closing) { + if (isClosing()) { return; } // no need to redirection @@ -1648,33 +1755,7 @@ private void handleRedirection(String deviceId, TEndPoint endpoint) { || !deviceIdToEndpoint.get(deviceId).equals(endpoint)) { deviceIdToEndpoint.put(deviceId, endpoint); } - SessionConnection connection = - endPointToSessionConnection.computeIfAbsent( - endpoint, - k -> { - if (closing) { - return null; - } - try { - SessionConnection newConnection = - constructSessionConnection(this, endpoint, zoneId); - if (closing) { - newConnection.forceCloseTransport(); - return null; - } - return newConnection; - } catch (IoTDBConnectionException ex) { - return null; - } - }); - if (closing) { - if (connection != null) { - connection.forceCloseTransport(); - } - deviceIdToEndpoint.remove(deviceId); - return; - } - if (connection == null) { + if (getRedirectedConnectionOrNull(endpoint) == null) { deviceIdToEndpoint.remove(deviceId); } } @@ -1682,7 +1763,9 @@ private void handleRedirection(String deviceId, TEndPoint endpoint) { private void handleRedirection(String routeDatabase, IDeviceID deviceId, TEndPoint endpoint) { if (enableRedirection) { - if (closing || tableModelDeviceIdToEndpoint == null || endPointToSessionConnection == null) { + if (isClosing() + || tableModelDeviceIdToEndpoint == null + || endPointToSessionConnection == null) { return; } // no need to redirection @@ -1695,33 +1778,7 @@ private void handleRedirection(String routeDatabase, IDeviceID deviceId, TEndPoi if (!endpoint.equals(resolvedDatabaseToEndpoint.get(deviceId))) { resolvedDatabaseToEndpoint.put(deviceId, endpoint); } - SessionConnection connection = - endPointToSessionConnection.computeIfAbsent( - endpoint, - k -> { - if (closing) { - return null; - } - try { - SessionConnection newConnection = - constructSessionConnection(this, endpoint, zoneId); - if (closing) { - newConnection.forceCloseTransport(); - return null; - } - return newConnection; - } catch (IoTDBConnectionException ex) { - return null; - } - }); - if (closing) { - if (connection != null) { - connection.forceCloseTransport(); - } - resolvedDatabaseToEndpoint.remove(deviceId, endpoint); - return; - } - if (connection == null) { + if (getRedirectedConnectionOrNull(endpoint) == null) { resolvedDatabaseToEndpoint.remove(deviceId, endpoint); } } @@ -1754,42 +1811,22 @@ private static String normalizeTableModelDatabaseName(String database) } private void handleQueryRedirection(TEndPoint endPoint) throws IoTDBConnectionException { - if (enableQueryRedirection) { - if (closing) { - throw new IoTDBConnectionException(SessionMessages.SESSION_NOT_OPEN); - } - AtomicReference exceptionReference = new AtomicReference<>(); - SessionConnection connection = - endPointToSessionConnection.computeIfAbsent( - endPoint, - k -> { - if (closing) { - return null; - } - try { - SessionConnection sessionConnection = - constructSessionConnection(this, endPoint, zoneId); - if (closing) { - sessionConnection.forceCloseTransport(); - return null; - } - sessionConnection.setEnableRedirect(enableQueryRedirection); - return sessionConnection; - } catch (IoTDBConnectionException ex) { - exceptionReference.set(ex); - return null; - } - }); - if (closing) { - if (connection != null) { - connection.forceCloseTransport(); - } + if (!enableQueryRedirection) { + return; + } + Map connections = endPointToSessionConnection; + getOrCreateSessionConnection(connections, endPoint); + synchronized (connectionStateLock) { + if (isClosing() || connections != endPointToSessionConnection) { throw new IoTDBConnectionException(SessionMessages.SESSION_NOT_OPEN); } - if (connection == null) { - throw new IoTDBConnectionException(exceptionReference.get()); + // A concurrent failover can replace the connection while the redirect is opening it. + SessionConnection current = connections.get(endPoint); + if (enableQueryRedirection + && current != null + && !connectionState.closingConnections.containsKey(current)) { + setDefaultSessionConnection(current); } - setDefaultSessionConnection(connection); } } @@ -4888,30 +4925,18 @@ public boolean isEnableQueryRedirection() { @Override public void setEnableQueryRedirection(boolean enableQueryRedirection) { synchronized (connectionStateLock) { - this.enableQueryRedirection = enableQueryRedirection; - if (!isClosed && !closing) { - if (defaultSessionConnection != null) { - defaultSessionConnection.setEnableRedirect(enableQueryRedirection); + if (!isClosed && !isClosing()) { + if (enableQueryRedirection && endPointToSessionConnection == null) { + initializeConnectionCache(defaultSessionConnection); } + defaultSessionConnection.setEnableRedirect(enableQueryRedirection); if (endPointToSessionConnection != null) { - for (SessionConnection connection : endPointToSessionConnection.values()) { - if (connection != null) { - connection.setEnableRedirect(enableQueryRedirection); - } - } - } - if (enableQueryRedirection) { - if (endPointToSessionConnection == null) { - Map connections = new ConcurrentHashMap<>(); - if (defaultEndPoint != null && defaultSessionConnection != null) { - connections.put(defaultEndPoint, defaultSessionConnection); - } - endPointToSessionConnection = connections; - } else if (defaultEndPoint != null && defaultSessionConnection != null) { - endPointToSessionConnection.putIfAbsent(defaultEndPoint, defaultSessionConnection); - } + endPointToSessionConnection + .values() + .forEach(c -> c.setEnableRedirect(enableQueryRedirection)); } } + this.enableQueryRedirection = enableQueryRedirection; } } @@ -4955,10 +4980,11 @@ public String getSqlDialect() { } protected SessionConnection getDefaultSessionConnection() throws IoTDBConnectionException { - if (defaultSessionConnection == null) { + SessionConnection connection = defaultSessionConnection; + if (connection == null || isClosing()) { throw new IoTDBConnectionException(SessionMessages.SESSION_NOT_OPEN); } - return defaultSessionConnection; + return connection; } protected void setDefaultSessionConnection(SessionConnection defaultSessionConnection) { diff --git a/iotdb-client/session/src/main/java/org/apache/iotdb/session/SessionConnection.java b/iotdb-client/session/src/main/java/org/apache/iotdb/session/SessionConnection.java index f857f0dcdc016..dc0255a835c43 100644 --- a/iotdb-client/session/src/main/java/org/apache/iotdb/session/SessionConnection.java +++ b/iotdb-client/session/src/main/java/org/apache/iotdb/session/SessionConnection.java @@ -110,14 +110,16 @@ public class SessionConnection { public static final String MSG_RECONNECTION_FAIL = SessionMessages.EXCEPTION_FAIL_TO_RECONNECT_TO_SERVER_PLEASE_CHECK_SERVER_STATUS_D9A2790F; protected Session session; - TTransport transport; + final Session.ConnectionState ownerState; + private volatile TTransport transport; protected IClientRPCService.Iface client; private long sessionId; private long statementId; private ZoneId zoneId; - private TEndPoint endPoint; + private volatile TEndPoint endPoint; private List endPointList = new ArrayList<>(); - private boolean enableRedirect = false; + // A newly created connection inherits the session setting, including while it is being cached. + private volatile Boolean enableRedirect; private final Supplier> availableNodes; @@ -133,10 +135,11 @@ public class SessionConnection { private int timeFactor = 1_000; private volatile boolean supportsDatabaseScopedTablet; - private volatile boolean forceClosed; + private volatile boolean closed; // TestOnly public SessionConnection(String sqlDialect) { + ownerState = null; availableNodes = Collections::emptyList; this.maxRetryCount = Math.max(0, SessionConfig.MAX_RETRY_COUNT); this.retryIntervalInMs = Math.max(0, SessionConfig.RETRY_INTERVAL_IN_MS); @@ -155,6 +158,7 @@ public SessionConnection( String database) throws IoTDBConnectionException { this.session = session; + this.ownerState = session.getConnectionState(); this.endPoint = endPoint; endPointList.add(endPoint); this.zoneId = zoneId == null ? ZoneId.systemDefault() : zoneId; @@ -189,6 +193,7 @@ public SessionConnection( String database) throws IoTDBConnectionException { this.session = session; + this.ownerState = session.getConnectionState(); this.zoneId = zoneId == null ? ZoneId.systemDefault() : zoneId; this.endPointList = SessionUtils.parseSeedNodeUrls(session.nodeUrls); this.availableNodes = availableNodes; @@ -214,9 +219,7 @@ private void init( session.thriftMaxFrameSize, session.thriftMaxReusableBufferSize); try { - if (transport != null && transport.isOpen()) { - close(); - } + closeSession(); if (useSSL) { transport = transportFactory.getTransport( @@ -237,6 +240,11 @@ private void init( if (!transport.isOpen()) { transport.open(); } + // forceCloseTransport can run while a reconnect is opening the replacement socket. + if (closed) { + transport.close(); + throw new IoTDBConnectionException(SessionMessages.SESSION_NOT_OPEN); + } } catch (TTransportException e) { throw new IoTDBConnectionException(e); } @@ -311,6 +319,7 @@ private void init( private void initClusterConn() throws IoTDBConnectionException { for (TEndPoint tEndPoint : endPointList) { try { + endPoint = tEndPoint; session.defaultEndPoint = tEndPoint; init( tEndPoint, @@ -332,8 +341,15 @@ private void initClusterConn() throws IoTDBConnectionException { } } - public void close() throws IoTDBConnectionException { - if (!transport.isOpen()) { + public synchronized void close() throws IoTDBConnectionException { + if (!closed) { + closed = true; + closeSession(); + } + } + + private void closeSession() throws IoTDBConnectionException { + if (transport == null || !transport.isOpen()) { return; } @@ -343,9 +359,7 @@ public void close() throws IoTDBConnectionException { } catch (TException e) { throw new IoTDBConnectionException(SessionMessages.CLOSE_SESSION_ERROR, e); } finally { - if (transport != null) { - transport.close(); - } + transport.close(); } } @@ -366,18 +380,24 @@ protected boolean setTransportTimeout(final int timeoutInMs) { } } - boolean isForceClosed() { - return forceClosed; + boolean isClosed() { + return closed; + } + + private boolean isClosing() { + return closed + || (ownerState != null ? ownerState.isClosing() : session != null && session.isClosing()); } protected void forceCloseTransport() { - forceClosed = true; - if (transport == null) { + closed = true; + TTransport current = transport; + if (current == null) { return; } try { - transport.close(); + current.close(); } catch (final RuntimeException ignored) { // Best effort. The caller must still finish updating its lifecycle state. } @@ -481,11 +501,11 @@ protected SessionDataSet executeQueryStatement(String sql, long timeout) TSExecuteStatementReq execReq = new TSExecuteStatementReq(sessionId, sql, statementId); execReq.setFetchSize(session.fetchSize); execReq.setTimeout(timeout); - execReq.setEnableRedirectQuery(enableRedirect); RetryResult result = callWithRetryAndReconnect( () -> { + execReq.setEnableRedirectQuery(isEnableRedirect()); execReq.setSessionId(sessionId); execReq.setStatementId(statementId); return client.executeQueryStatementV2(execReq); @@ -554,11 +574,11 @@ protected SessionDataSet executeRawDataQuery( new TSRawDataQueryReq(sessionId, paths, startTime, endTime, statementId); execReq.setFetchSize(session.fetchSize); execReq.setTimeout(timeOut); - execReq.setEnableRedirectQuery(enableRedirect); RetryResult result = callWithRetryAndReconnect( () -> { + execReq.setEnableRedirectQuery(isEnableRedirect()); execReq.setSessionId(sessionId); execReq.setStatementId(statementId); return client.executeRawDataQueryV2(execReq); @@ -598,11 +618,11 @@ protected SessionDataSet executeLastDataQueryForOnePrefixPath(final List TSFastLastDataQueryForOnePrefixPathReq req = new TSFastLastDataQueryForOnePrefixPathReq(sessionId, prefixes, statementId); req.setFetchSize(session.fetchSize); - req.setEnableRedirectQuery(enableRedirect); RetryResult result = callWithReconnect( () -> { + req.setEnableRedirectQuery(isEnableRedirect()); req.setSessionId(sessionId); req.setStatementId(statementId); return client.executeFastLastDataQueryForOnePrefixPath(req); @@ -642,7 +662,6 @@ protected Pair executeLastDataQueryForOneDevice( TSFastLastDataQueryForOneDeviceReq req = new TSFastLastDataQueryForOneDeviceReq(sessionId, db, device, sensors, statementId); req.setFetchSize(session.fetchSize); - req.setEnableRedirectQuery(enableRedirect); req.setLegalPathNodes(isLegalPathNodes); req.setTimeout(timeOut); TEndPoint redirectedEndPoint = null; @@ -650,6 +669,7 @@ protected Pair executeLastDataQueryForOneDevice( RetryResult result = callWithRetryAndReconnect( () -> { + req.setEnableRedirectQuery(isEnableRedirect()); req.setSessionId(sessionId); req.setStatementId(statementId); return client.executeFastLastDataQueryForOneDeviceV2(req); @@ -695,12 +715,12 @@ protected SessionDataSet executeLastDataQuery(List paths, long time, lon TSLastDataQueryReq tsLastDataQueryReq = new TSLastDataQueryReq(sessionId, paths, time, statementId); tsLastDataQueryReq.setFetchSize(session.fetchSize); - tsLastDataQueryReq.setEnableRedirectQuery(enableRedirect); tsLastDataQueryReq.setTimeout(timeOut); RetryResult result = callWithRetryAndReconnect( () -> { + tsLastDataQueryReq.setEnableRedirectQuery(isEnableRedirect()); tsLastDataQueryReq.setSessionId(sessionId); tsLastDataQueryReq.setStatementId(statementId); return client.executeLastDataQueryV2(tsLastDataQueryReq); @@ -987,7 +1007,7 @@ private RetryResult callWithRetry(TFunction rpc) { TSStatus status = null; int i; for (i = 0; i <= maxRetryCount; i++) { - if (forceClosed) { + if (isClosing()) { status = null; lastTException = new TException(SessionMessages.SESSION_NOT_OPEN); break; @@ -1024,7 +1044,7 @@ private RetryResult callWithRetry(TFunction rpc) { // all network exception need retry until reaching maxRetryCount lastTException = e; } - if (forceClosed) { + if (isClosing()) { status = null; lastTException = new TException(SessionMessages.SESSION_NOT_OPEN); break; @@ -1069,7 +1089,7 @@ private RetryResult callWithRetryAndReconnect( int retryAttempt; int maxRetryCountRead = 10; for (retryAttempt = 0; retryAttempt <= maxRetryCountRead; retryAttempt++) { - if (forceClosed) { + if (isClosing()) { throw new IoTDBConnectionException(SessionMessages.SESSION_NOT_OPEN); } // 1. try to execute the rpc @@ -1081,7 +1101,7 @@ private RetryResult callWithRetryAndReconnect( lastTException = e; } - if (forceClosed) { + if (isClosing()) { throw new IoTDBConnectionException(SessionMessages.SESSION_NOT_OPEN); } @@ -1103,7 +1123,9 @@ private RetryResult callWithRetryAndReconnect( // 2. the current datanode is partitioned with other nodes (not in availableNodes) // 3. asymmetric network partition logger.debug(SessionMessages.RETRY_RECONNECTING, retryAttempt); - reconnect(); + if (!reconnect() && isClosing()) { + throw new IoTDBConnectionException(SessionMessages.SESSION_NOT_OPEN); + } } try { TimeUnit.MILLISECONDS.sleep(retryIntervalInMs); @@ -1235,79 +1257,70 @@ protected void testInsertTablets(TSInsertTabletsReq request) RpcUtils.verifySuccess(status); } - @SuppressWarnings({ - "squid:S3776" - }) // ignore Cognitive Complexity of methods should not be too high private boolean reconnect() { - if (forceClosed || (session != null && session.isClosing())) { + TEndPoint target = reopenTransport(); + if (target == null) { return false; } - boolean connectedSuccess = false; + // Once registered, the transport belongs to the session's close snapshot. + return session.registerReconnectedConnection(this, target) && !isClosing(); + } + + // Graceful close must see a complete handshake (client, sessionId and transport). Force-close + // deliberately bypasses this monitor so it can interrupt a blocked network operation. + private synchronized TEndPoint reopenTransport() { + if (transport == null || isClosing()) { + return null; + } SecureRandom random = new SecureRandom(); - for (int i = 1; i <= SessionConfig.RETRY_NUM; i++) { - if (forceClosed || (session != null && session.isClosing())) { - return false; - } - if (transport != null) { - transport.close(); - List discoveredNodes = availableNodes.get(); - endPointList = new ArrayList<>(discoveredNodes); - if (!endPointList.isEmpty()) { - Collections.rotate(endPointList, -random.nextInt(endPointList.size())); - } - if (availableNodes instanceof INodeSupplier) { - List seeds = new ArrayList<>(((INodeSupplier) availableNodes).getSeedNodes()); - if (!seeds.isEmpty()) { - Collections.rotate(seeds, -random.nextInt(seeds.size())); - } - endPointList.addAll(seeds); + for (int i = 0; i < SessionConfig.RETRY_NUM && !isClosing(); i++) { + transport.close(); + List discoveredNodes = availableNodes.get(); + endPointList = reconnectCandidates(discoveredNodes, random); + for (TEndPoint candidate : endPointList) { + if (isClosing()) { + return null; } - // Try every discovered endpoint before falling back to seeds, once per endpoint per round. - endPointList = new ArrayList<>(new LinkedHashSet<>(endPointList)); - for (TEndPoint candidate : endPointList) { - if (forceClosed || (session != null && session.isClosing())) { - return false; - } - this.endPoint = candidate; - try { - init( - endPoint, - session.useSSL, - session.trustStore, - session.trustStorePwd, - session.keyStore, - session.keyStorePwd, - session.sslProtocol); - if (forceClosed || session.isClosing()) { - forceCloseTransport(); - return false; - } - connectedSuccess = true; - if (!discoveredNodes.contains(endPoint) && availableNodes instanceof INodeSupplier) { - ((INodeSupplier) availableNodes).requestRefresh(); - } - } catch (IoTDBConnectionException e) { - logger.warn(SessionMessages.NODE_DOWN_TRY_NEXT, endPoint); - continue; - } catch (StatementExecutionException e) { - logger.warn(SessionMessages.LOGIN_FAILED, e.getMessage()); + try { + init( + candidate, + session.useSSL, + session.trustStore, + session.trustStorePwd, + session.keyStore, + session.keyStorePwd, + session.sslProtocol); + endPoint = candidate; + if (!discoveredNodes.contains(candidate) && availableNodes instanceof INodeSupplier) { + ((INodeSupplier) availableNodes).requestRefresh(); } + return candidate; + } catch (IoTDBConnectionException e) { + logger.warn(SessionMessages.NODE_DOWN_TRY_NEXT, candidate); + } catch (StatementExecutionException e) { + logger.warn(SessionMessages.LOGIN_FAILED, e.getMessage()); break; } } - if (connectedSuccess) { - if (forceClosed || !session.registerReconnectedConnection(this, this.endPoint)) { - forceCloseTransport(); - return false; - } - if (forceClosed || session.isClosing()) { - forceCloseTransport(); - return false; - } - break; + } + return null; + } + + private List reconnectCandidates( + List discoveredNodes, SecureRandom random) { + List candidates = new ArrayList<>(discoveredNodes); + if (!candidates.isEmpty()) { + Collections.rotate(candidates, -random.nextInt(candidates.size())); + } + if (availableNodes instanceof INodeSupplier) { + List seeds = new ArrayList<>(((INodeSupplier) availableNodes).getSeedNodes()); + if (!seeds.isEmpty()) { + Collections.rotate(seeds, -random.nextInt(seeds.size())); } + candidates.addAll(seeds); } - return connectedSuccess; + // Try every discovered endpoint before falling back to seeds, once per endpoint per round. + return new ArrayList<>(new LinkedHashSet<>(candidates)); } protected void createSchemaTemplate(TSCreateSchemaTemplateReq request) @@ -1421,6 +1434,9 @@ protected TSBackupConfigurationResp getBackupConfiguration() private RetryResult callWithReconnect(TFunction supplier) throws IoTDBConnectionException { + if (isClosing()) { + throw new IoTDBConnectionException(SessionMessages.SESSION_NOT_OPEN); + } T ret; try { ret = supplier.run(); @@ -1446,7 +1462,8 @@ public TSConnectionInfoResp fetchAllConnections() throws IoTDBConnectionExceptio } public boolean isEnableRedirect() { - return enableRedirect; + Boolean enabled = enableRedirect; + return enabled != null ? enabled : session != null && session.isEnableQueryRedirection(); } public void setEnableRedirect(boolean enableRedirect) { diff --git a/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionConnectionTest.java b/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionConnectionTest.java index 16b8f4cea3059..569838faab454 100644 --- a/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionConnectionTest.java +++ b/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionConnectionTest.java @@ -35,6 +35,7 @@ import org.apache.iotdb.service.rpc.thrift.TCreateTimeseriesUsingSchemaTemplateReq; import org.apache.iotdb.service.rpc.thrift.TSAppendSchemaTemplateReq; import org.apache.iotdb.service.rpc.thrift.TSBackupConfigurationResp; +import org.apache.iotdb.service.rpc.thrift.TSCloseSessionReq; import org.apache.iotdb.service.rpc.thrift.TSConnectionInfoResp; import org.apache.iotdb.service.rpc.thrift.TSCreateAlignedTimeseriesReq; import org.apache.iotdb.service.rpc.thrift.TSCreateMultiTimeseriesReq; @@ -801,6 +802,9 @@ public void testReconnectStillClosesDifferentStaleConnectionForSameEndPoint() th SessionConnection staleConnection = Mockito.mock(SessionConnection.class); TTransport staleTransport = Mockito.mock(TTransport.class); Mockito.when(staleTransport.isOpen()).thenReturn(true); + Mockito.doThrow(new IllegalStateException("Transport closed while reading closeSession")) + .when(staleConnection) + .close(); Whitebox.setInternalState(staleConnection, "transport", staleTransport); testSession.endPointToSessionConnection.put(testSession.defaultEndPoint, staleConnection); @@ -824,11 +828,25 @@ public void testReconnectStillClosesDifferentStaleConnectionForSameEndPoint() th @Test public void testForceCloseDuringNonDefaultQueryConnectionReconnectReleasesSocketAndStopsRetry() throws Exception { + assertCloseDuringNonDefaultReconnect(true, false); + } + + @Test + public void testGracefulCloseReleasesReconnectMissingFromCloseSnapshot() throws Exception { + assertCloseDuringNonDefaultReconnect(false, false); + } + + @Test + public void testReopenDoesNotAdoptPreviousQueryReconnect() throws Exception { + assertCloseDuringNonDefaultReconnect(false, true); + } + + private void assertCloseDuringNonDefaultReconnect(boolean forceClose, boolean reopen) + throws Exception { CountDownLatch beforeRegister = new CountDownLatch(1); CountDownLatch resumeRegister = new CountDownLatch(1); try (ReconnectTestServer serverA = new ReconnectTestServer(0, 0); ReconnectTestServer serverB = new ReconnectTestServer(0, 1)) { - List bothNodes = Arrays.asList(serverA.getEndpoint(), serverB.getEndpoint()); INodeSupplier nodeSupplier = new INodeSupplier() { @Override @@ -873,7 +891,7 @@ boolean registerReconnectedConnection( testSession.open(false, 1000, Collections.emptyMap(), nodeSupplier); Assert.assertFalse(testSession.enableRedirection); Assert.assertTrue(testSession.enableQueryRedirection); - Assert.assertEquals(bothNodes.get(0), testSession.defaultEndPoint); + Assert.assertEquals(serverA.getEndpoint(), testSession.defaultEndPoint); Future queryFuture = executor.submit( @@ -888,16 +906,32 @@ boolean registerReconnectedConnection( Assert.fail("Reconnect did not reach registration"); } - testSession.forceClose(); + if (forceClose) { + testSession.forceClose(); + } else { + // Evict B after its handshake. The close snapshot now contains only A. + testSession.removeBrokenSessionConnection( + testSession.endPointToSessionConnection.get(serverB.getEndpoint())); + testSession.close(); + } + if (reopen) { + testSession.open(false, 1000, Collections.emptyMap(), nodeSupplier); + } resumeRegister.countDown(); try { queryFuture.get(5, TimeUnit.SECONDS); - Assert.fail("Expected query to fail after forceClose()"); + Assert.fail("Expected query to fail after session shutdown"); } catch (ExecutionException e) { Assert.assertTrue(e.getCause() instanceof IoTDBConnectionException); } Assert.assertEquals(1, serverB.getQueryCount()); + Assert.assertEquals(forceClose ? 0 : 1, serverB.getCloseSessionCount()); + if (reopen) { + Assert.assertEquals( + serverA.getEndpoint(), testSession.getDefaultSessionConnection().getEndPoint()); + testSession.close(); + } Assert.assertTrue( "Server A still has active connections", serverA.awaitNoActiveConnections(5, TimeUnit.SECONDS)); @@ -912,6 +946,140 @@ boolean registerReconnectedConnection( } } + @Test + public void testGracefulCloseDuringReconnectHandshakeClosesNewSessionId() throws Exception { + CountDownLatch secondOpen = new CountDownLatch(1); + CountDownLatch completeOpen = new CountDownLatch(1); + try (ReconnectTestServer server = new ReconnectTestServer(1)) { + TSOpenSessionResp response = + new TSOpenSessionResp( + new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode()), + TSProtocolVersion.IOTDB_SERVICE_PROTOCOL_V3); + Mockito.when(server.handler.openSession(any())) + .thenReturn(response.deepCopy().setSessionId(1L)) + .thenAnswer( + invocation -> { + secondOpen.countDown(); + Assert.assertTrue(completeOpen.await(10, TimeUnit.SECONDS)); + return response.deepCopy().setSessionId(2L); + }); + Session testSession = + new Session.Builder() + .host(server.getEndpoint().getIp()) + .port(server.getEndpoint().getPort()) + .enableRedirection(false) + .enableAutoFetch(false) + .retryIntervalInMs(1) + .build(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + testSession.open(false, 0); + Future write = + executor.submit( + () -> { + testSession.insertTablet(createSingleRowTablet()); + return null; + }); + Assert.assertTrue(secondOpen.await(5, TimeUnit.SECONDS)); + Future close = + executor.submit( + () -> { + testSession.close(); + return null; + }); + awaitSessionClosing(testSession); + completeOpen.countDown(); + close.get(5, TimeUnit.SECONDS); + ExecutionException failure = + Assert.assertThrows(ExecutionException.class, () -> write.get(5, TimeUnit.SECONDS)); + Assert.assertTrue(failure.getCause() instanceof IoTDBConnectionException); + Mockito.verify(server.handler).closeSession(new TSCloseSessionReq(2L)); + Assert.assertEquals(1, server.getCloseSessionCount()); + Assert.assertEquals(1, server.getInsertTabletCount()); + Assert.assertTrue(server.awaitNoActiveConnections(5, TimeUnit.SECONDS)); + } finally { + completeOpen.countDown(); + executor.shutdownNow(); + testSession.forceClose(); + } + } + } + + @Test + public void testGracefulCloseBeforeReconnectRegistration() throws Exception { + assertGracefulCloseDuringReconnect(false); + } + + @Test + public void testGracefulCloseAfterReconnectRegistration() throws Exception { + assertGracefulCloseDuringReconnect(true); + } + + private void assertGracefulCloseDuringReconnect(boolean pauseAfterRegistration) throws Exception { + CountDownLatch registration = new CountDownLatch(1); + CountDownLatch resumeReconnect = new CountDownLatch(1); + CountDownLatch closeStarted = new CountDownLatch(1); + CountDownLatch replyToClose = new CountDownLatch(1); + try (ReconnectTestServer server = new ReconnectTestServer(0, 1, closeStarted, replyToClose)) { + Session testSession = + new Session( + new Session.Builder() + .host(server.getEndpoint().getIp()) + .port(server.getEndpoint().getPort()) + .enableRedirection(false) + .enableAutoFetch(false) + .retryIntervalInMs(1)) { + @Override + boolean registerReconnectedConnection( + SessionConnection connection, TEndPoint endPoint) { + boolean registered = + pauseAfterRegistration + && super.registerReconnectedConnection(connection, endPoint); + registration.countDown(); + try { + Assert.assertTrue(resumeReconnect.await(10, TimeUnit.SECONDS)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AssertionError(e); + } + return pauseAfterRegistration + ? registered + : super.registerReconnectedConnection(connection, endPoint); + } + }; + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + testSession.open(false, 0); + Future query = executor.submit(() -> testSession.executeQueryStatement("show devices")); + Assert.assertTrue(registration.await(5, TimeUnit.SECONDS)); + TTransport reopened = + Whitebox.getInternalState(testSession.getDefaultSessionConnection(), "transport"); + Future close = + executor.submit( + () -> { + testSession.close(); + return null; + }); + Assert.assertTrue(closeStarted.await(5, TimeUnit.SECONDS)); + resumeReconnect.countDown(); + ExecutionException failure = + Assert.assertThrows(ExecutionException.class, () -> query.get(5, TimeUnit.SECONDS)); + Assert.assertTrue(failure.getCause() instanceof IoTDBConnectionException); + Assert.assertEquals(1, server.getQueryCount()); + Assert.assertTrue("Reconnect interrupted the closeSession RPC", reopened.isOpen()); + replyToClose.countDown(); + close.get(5, TimeUnit.SECONDS); + Assert.assertEquals(1, server.getCloseSessionCount()); + Assert.assertTrue(server.awaitNoActiveConnections(5, TimeUnit.SECONDS)); + } finally { + resumeReconnect.countDown(); + replyToClose.countDown(); + executor.shutdownNow(); + testSession.forceClose(); + } + } + } + @Test public void testEnableQueryRedirectionOnOpenSessionAfterFailoverRoutesAcrossNodes() throws Exception { @@ -969,6 +1137,89 @@ public void close() {} } Assert.assertEquals(2, serverA.getQueryCount()); Assert.assertEquals(2, serverB.getQueryCount()); + Assert.assertEquals(Arrays.asList(true, true), serverA.getObservedEnableRedirectQuery()); + Assert.assertEquals(Arrays.asList(true, true), serverB.getObservedEnableRedirectQuery()); + + testSession.setEnableQueryRedirection(false); + for (int i = 0; i < 2; i++) { + testSession.executeQueryStatement("show devices").close(); + } + Assert.assertEquals(2, serverA.getQueryCount()); + Assert.assertEquals( + Arrays.asList(true, true, false, false), serverB.getObservedEnableRedirectQuery()); + + testSession.close(); + testSession.open(false, 1000, Collections.emptyMap(), nodeSupplier); + int opens = serverB.getOpenSessionCount(); + testSession.executeQueryStatement("show devices").close(); + Assert.assertEquals(2, serverA.getQueryCount()); + Assert.assertEquals(opens, serverB.getOpenSessionCount()); + Assert.assertEquals(5, serverB.getQueryCount()); + } finally { + testSession.close(); + } + } + } + + @Test + public void testNonDefaultQueryConnectionKeepsRedirectFlagAfterFailover() throws Exception { + try (ReconnectTestServer seed = new ReconnectTestServer(0); + ReconnectTestServer other = new ReconnectTestServer(0, 1)) { + INodeSupplier nodes = Mockito.mock(INodeSupplier.class); + Mockito.when(nodes.getQueryEndPoint()).thenReturn(Optional.of(other.getEndpoint())); + Mockito.when(nodes.get()).thenReturn(Collections.singletonList(seed.getEndpoint())); + Session testSession = + new Session.Builder() + .host(seed.getEndpoint().getIp()) + .port(seed.getEndpoint().getPort()) + .enableRedirection(false) + .enableAutoFetch(false) + .retryIntervalInMs(1) + .build(); + testSession.setEnableQueryRedirection(true); + try { + testSession.open(false, 1000, Collections.emptyMap(), nodes); + testSession.executeQueryStatement("show devices").close(); + Assert.assertEquals( + Collections.singletonList(true), other.getObservedEnableRedirectQuery()); + Assert.assertEquals(Collections.singletonList(true), seed.getObservedEnableRedirectQuery()); + Assert.assertEquals( + seed.getEndpoint(), testSession.getDefaultSessionConnection().getEndPoint()); + Assert.assertTrue(testSession.getDefaultSessionConnection().isEnableRedirect()); + Assert.assertEquals(1, seed.getCloseSessionCount()); + } finally { + testSession.close(); + } + } + } + + @Test + public void testEnablingQueryRedirectionAfterServerRedirectKeepsEndpointMapping() + throws Exception { + try (ReconnectTestServer target = new ReconnectTestServer(0); + ForceCloseTestServer seed = + new ForceCloseTestServer(null, null, target.getEndpoint(), null, null)) { + Session testSession = + new Session.Builder() + .host(seed.getEndpoint().getIp()) + .port(seed.getEndpoint().getPort()) + .enableRedirection(false) + .enableAutoFetch(false) + .build(); + testSession.setEnableQueryRedirection(true); + try { + testSession.open(false, 1000); + SessionConnection original = testSession.getDefaultSessionConnection(); + testSession.executeQueryStatement("show devices").close(); + SessionConnection redirected = testSession.getDefaultSessionConnection(); + Assert.assertEquals(target.getEndpoint(), redirected.getEndPoint()); + testSession.removeBrokenSessionConnection(original); + original.close(); + + testSession.setEnableQueryRedirection(true); + Assert.assertFalse(testSession.endPointToSessionConnection.containsKey(seed.getEndpoint())); + Assert.assertSame( + redirected, testSession.endPointToSessionConnection.get(target.getEndpoint())); } finally { testSession.close(); } @@ -1120,11 +1371,7 @@ public void close() {} testSession.close(); return null; }); - long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); - while (!testSession.isClosing() && System.nanoTime() < deadline) { - TimeUnit.MILLISECONDS.sleep(5); - } - Assert.assertTrue("Session.close() did not start", testSession.isClosing()); + awaitSessionClosing(testSession); continueCloseSession.countDown(); closeFuture.get(5, TimeUnit.SECONDS); @@ -1177,12 +1424,28 @@ public void testSetEnableQueryRedirectionPropagatesTrueAndFalseToOpenConnections Assert.assertEquals( Arrays.asList(Boolean.TRUE, Boolean.FALSE), server.getObservedEnableRedirectQuery()); + + testSession.close(); + testSession.open(false, 1000); + testSession.executeQueryStatement("show devices").close(); + Assert.assertEquals(2, server.getOpenSessionCount()); + Assert.assertNull(testSession.endPointToSessionConnection); + Assert.assertEquals( + Arrays.asList(true, false, false), server.getObservedEnableRedirectQuery()); } finally { testSession.close(); } } } + private static void awaitSessionClosing(Session session) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (!session.isClosing() && System.nanoTime() < deadline) { + TimeUnit.MILLISECONDS.sleep(5); + } + Assert.assertTrue("Session.close() did not start", session.isClosing()); + } + private static Tablet createSingleRowTablet() { Tablet tablet = new Tablet( @@ -1196,6 +1459,7 @@ private static Tablet createSingleRowTablet() { private static class ReconnectTestServer implements AutoCloseable { + private final IClientRPCService.Iface handler = Mockito.mock(IClientRPCService.Iface.class); private final TEndPoint endpoint; private final TServerSocket socket; private final TThreadPoolServer server; @@ -1225,7 +1489,6 @@ private ReconnectTestServer( ServerSocket listener = new ServerSocket(0); endpoint = new TEndPoint("127.0.0.1", listener.getLocalPort()); socket = new TServerSocket(listener); - IClientRPCService.Iface handler = Mockito.mock(IClientRPCService.Iface.class); Mockito.when(handler.openSession(any())) .thenAnswer( ignored ->