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 31cdd2bc3d8f..35ec696768f6 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,43 +1530,79 @@ 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 - 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 (!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 (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(); - } - } - } - } } } @@ -4811,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 a0d7657e0a8a..f857f0dcdc01 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,29 +1296,14 @@ 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.endPointToSessionConnection = new ConcurrentHashMap<>(); + if (forceClosed || session.isClosing()) { + forceCloseTransport(); + return false; } - 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()); - } - } - 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 0a12a841f868..9681f685b77d 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; @@ -71,6 +72,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; @@ -84,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; @@ -696,6 +703,425 @@ 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(); + } + } + } + + @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( + "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 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); + 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.requestStatementId(anyLong())).thenReturn(1L); + Mockito.when(handler.closeOperation(any())) + .thenReturn(new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode())); + 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()); + }); + 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( + 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) { + activeConnections.incrementAndGet(); + 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) { + activeConnections.decrementAndGet(); + } + }); + 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(); + } + + 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(); + 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 eaf24080c434..84043c794abb 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,116 @@ 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 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); + 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)); + } }