This is an automated email from the ASF dual-hosted git repository. JackieTien97 pushed a commit to branch ty/fix-session-reconnect-self-close in repository https://gitbox.apache.org/repos/asf/iotdb.git
commit 35c48c7c5c4bf809f56c7452f834d68e307cef57 Author: JackieTien97 <[email protected]> AuthorDate: Fri Dec 4 19:03:58 2026 +0800 Fix SessionConnection.reconnect() self-closing transport when enableRedirection is false --- .../java/org/apache/iotdb/session/Session.java | 55 ++--- .../apache/iotdb/session/SessionConnection.java | 32 +-- .../iotdb/session/SessionConnectionTest.java | 229 +++++++++++++++++++++ .../java/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 31cdd2bc3d8..e8a433303e1 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 class Session implements ISession { // 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<Entry<TEndPoint, SessionConnection>> it = - endPointToSessionConnection.entrySet().iterator(); - it.hasNext(); ) { - Entry<TEndPoint, SessionConnection> entry = it.next(); - if (entry.getValue().equals(sessionConnection)) { - endPoint = entry.getKey(); - it.remove(); - break; - } + if (endPointToSessionConnection == null) { + return; + } + Set<TEndPoint> removedEndPoints = new HashSet<>(); + for (Iterator<Entry<TEndPoint, SessionConnection>> it = + endPointToSessionConnection.entrySet().iterator(); + it.hasNext(); ) { + Entry<TEndPoint, SessionConnection> 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<Entry<String, TEndPoint>> it = deviceIdToEndpoint.entrySet().iterator(); + it.hasNext(); ) { + Entry<String, TEndPoint> entry = it.next(); + if (removedEndPoints.contains(entry.getValue())) { + it.remove(); } } - if (deviceIdToEndpoint != null && !deviceIdToEndpoint.isEmpty()) { - for (Iterator<Entry<String, TEndPoint>> it = deviceIdToEndpoint.entrySet().iterator(); + } + if (tableModelDeviceIdToEndpoint != null && !tableModelDeviceIdToEndpoint.isEmpty()) { + for (Map<IDeviceID, TEndPoint> databaseToEndpoint : tableModelDeviceIdToEndpoint.values()) { + for (Iterator<Entry<IDeviceID, TEndPoint>> it = databaseToEndpoint.entrySet().iterator(); it.hasNext(); ) { - Entry<String, TEndPoint> entry = it.next(); - if (entry.getValue().equals(endPoint)) { + Entry<IDeviceID, TEndPoint> entry = it.next(); + if (removedEndPoints.contains(entry.getValue())) { it.remove(); } } } - if (tableModelDeviceIdToEndpoint != null && !tableModelDeviceIdToEndpoint.isEmpty()) { - for (Map<IDeviceID, TEndPoint> databaseToEndpoint : tableModelDeviceIdToEndpoint.values()) { - for (Iterator<Entry<IDeviceID, TEndPoint>> it = databaseToEndpoint.entrySet().iterator(); - it.hasNext(); ) { - Entry<IDeviceID, TEndPoint> 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 a0d7657e0a8..0f7ad60736d 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 @@ public class SessionConnection { 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 0a12a841f86..25ec4958b98 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.TServerEventHandler; 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 class SessionConnectionTest { 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 eaf24080c43..ce2f631bb42 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.iotdb.session.i18n.SessionMessages; import org.apache.tsfile.common.conf.TSFileConfig; import org.apache.tsfile.enums.ColumnCategory; import org.apache.tsfile.enums.TSDataType; +import org.apache.tsfile.file.metadata.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.LinkedHashMap; 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 class SessionTest { } } } + + @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<TEndPoint, SessionConnection> endPointMap = new ConcurrentHashMap<>(); + endPointMap.put(ep1, brokenConnection); + endPointMap.put(ep2, brokenConnection); + endPointMap.put(ep3, healthyConnection); + testSession.endPointToSessionConnection = endPointMap; + + Map<String, TEndPoint> 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<IDeviceID, TEndPoint> 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<String, Map<IDeviceID, TEndPoint>> 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)); + } }
