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..67de509a173a 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,13 +105,13 @@ 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; 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; @@ -162,9 +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 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. @@ -174,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; @@ -197,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; @@ -573,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()); } } @@ -656,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()); } } @@ -705,31 +712,64 @@ 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 { - closing = true; Throwable closeException = null; try { - if (isClosed) { - return; + List connectionsToClose; + List inProgressCloses; + synchronized (connectionStateLock) { + if (isClosed) { + return; + } + connectionState.closeMode = CloseMode.GRACEFUL; + connectionsToClose = getSessionConnections(false); + inProgressCloses = new ArrayList<>(connectionState.closingConnections.values()); } - for (SessionConnection sessionConnection : getSessionConnections()) { + for (SessionConnection sessionConnection : connectionsToClose) { try { sessionConnection.close(); } catch (IoTDBConnectionException | RuntimeException e) { @@ -740,6 +780,14 @@ public synchronized void close() throws IoTDBConnectionException { } } } + for (CountDownLatch latch : inProgressCloses) { + try { + latch.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + break; + } + } } finally { finishClose(); } @@ -754,12 +802,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) { + if (isClosed) { + return; + } + connectionState.closeMode = CloseMode.FORCE; + connectionsToClose = getSessionConnections(true); } try { - for (SessionConnection sessionConnection : getSessionConnections()) { + for (SessionConnection sessionConnection : connectionsToClose) { sessionConnection.forceCloseTransport(); } } finally { @@ -767,9 +819,10 @@ public synchronized void forceClose() { } } - private List getSessionConnections() { + 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)) { @@ -780,18 +833,23 @@ private List getSessionConnections() { if (defaultSessionConnection != null && seen.add(defaultSessionConnection)) { connections.add(defaultSessionConnection); } + if (includeClosingConnections) { + connections.addAll(connectionState.closingConnections.keySet()); + } return connections; } 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) { @@ -1110,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; } /** @@ -1519,41 +1613,130 @@ public String getTimestampPrecision() throws TException, IoTDBConnectionExceptio return getDefaultSessionConnection().getClient().getProperties().getTimestampPrecision(); } + ConnectionState getConnectionState() { + return connectionState; + } + + boolean isClosing() { + 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) { + ConnectionState owner = connection.ownerState == null ? connectionState : connection.ownerState; + SessionConnection displaced; + CloseMode mode; + CountDownLatch closed; + synchronized (connectionStateLock) { + if (connection.isClosed() + || owner.closingConnections.containsKey(connection) + || !newEndPoint.equals(connection.getEndPoint())) { + return false; + } + mode = owner.closeMode; + if (mode == null) { + displaced = replaceDefaultConnection(connection, newEndPoint); + if (displaced == null + || displaced == connection + || owner.closingConnections.containsKey(displaced)) { + return true; + } + } 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); + } + + try { + closeDiscardedConnection(displaced, mode); + } finally { + synchronized (connectionStateLock) { + owner.closingConnections.remove(displaced, closed); + if (owner.closingConnections.isEmpty()) { + owner.closingConnections = Collections.emptyMap(); + } + closed.countDown(); + } + } + 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 (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; - } + Map connections = endPointToSessionConnection; + if (connections == null) { + return; + } + 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() == sessionConnection) { + if (removed == null) { + removed = new HashSet<>(); } + removed.add(entry.getKey()); + it.remove(); } - if (deviceIdToEndpoint != null && !deviceIdToEndpoint.isEmpty()) { - for (Iterator> it = deviceIdToEndpoint.entrySet().iterator(); - it.hasNext(); ) { - Entry entry = it.next(); - if (entry.getValue().equals(endPoint)) { - 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 (Objects.equals(entry.getValue(), endPoint)) { - 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(); } } } @@ -1561,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 @@ -1572,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); } } @@ -1606,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 @@ -1619,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); } } @@ -1678,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); } } @@ -4811,7 +4924,20 @@ public boolean isEnableQueryRedirection() { @Override public void setEnableQueryRedirection(boolean enableQueryRedirection) { - this.enableQueryRedirection = enableQueryRedirection; + synchronized (connectionStateLock) { + if (!isClosed && !isClosing()) { + if (enableQueryRedirection && endPointToSessionConnection == null) { + initializeConnectionCache(defaultSessionConnection); + } + defaultSessionConnection.setEnableRedirect(enableQueryRedirection); + if (endPointToSessionConnection != null) { + endPointToSessionConnection + .values() + .forEach(c -> c.setEnableRedirect(enableQueryRedirection)); + } + } + this.enableQueryRedirection = enableQueryRedirection; + } } @Override @@ -4854,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 a0d7657e0a8a..dc0255a835c4 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,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; - private 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; @@ -134,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); @@ -156,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; @@ -190,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; @@ -215,9 +219,7 @@ private void init( session.thriftMaxFrameSize, session.thriftMaxReusableBufferSize); try { - if (transport != null && transport.isOpen()) { - close(); - } + closeSession(); if (useSSL) { transport = transportFactory.getTransport( @@ -238,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); } @@ -312,6 +319,7 @@ private void init( private void initClusterConn() throws IoTDBConnectionException { for (TEndPoint tEndPoint : endPointList) { try { + endPoint = tEndPoint; session.defaultEndPoint = tEndPoint; init( tEndPoint, @@ -333,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; } @@ -344,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(); } } @@ -367,14 +380,24 @@ protected boolean setTransportTimeout(final int timeoutInMs) { } } + 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. } @@ -478,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); @@ -551,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); @@ -595,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); @@ -639,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; @@ -647,6 +669,7 @@ protected Pair executeLastDataQueryForOneDevice( RetryResult result = callWithRetryAndReconnect( () -> { + req.setEnableRedirectQuery(isEnableRedirect()); req.setSessionId(sessionId); req.setStatementId(statementId); return client.executeFastLastDataQueryForOneDeviceV2(req); @@ -692,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); @@ -984,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; @@ -1021,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; @@ -1066,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 @@ -1078,7 +1101,7 @@ private RetryResult callWithRetryAndReconnect( lastTException = e; } - if (forceClosed) { + if (isClosing()) { throw new IoTDBConnectionException(SessionMessages.SESSION_NOT_OPEN); } @@ -1100,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); @@ -1232,94 +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) { + 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) { - 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) { - return false; - } - this.endPoint = candidate; - try { - init( - endPoint, - session.useSSL, - session.trustStore, - session.trustStorePwd, - session.keyStore, - session.keyStorePwd, - session.sslProtocol); - if (forceClosed) { - 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) { - 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<>(); - } - 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; + } + 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) @@ -1433,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(); @@ -1458,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 0a12a841f868..569838faab45 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; @@ -34,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; @@ -41,6 +43,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; @@ -71,6 +74,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 +91,10 @@ 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.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; @@ -696,6 +706,918 @@ 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); + Mockito.doThrow(new IllegalStateException("Transport closed while reading closeSession")) + .when(staleConnection) + .close(); + 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 { + 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)) { + 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( + Collections.singletonList( + serverA.getEndpoint().getIp() + ":" + serverA.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(serverA.getEndpoint(), testSession.defaultEndPoint); + + Future queryFuture = + executor.submit( + () -> { + testSession.executeQueryStatement("select s1 from root.sg.d1"); + return null; + }); + if (!beforeRegister.await(5, TimeUnit.SECONDS)) { + if (queryFuture.isDone()) { + queryFuture.get(1, TimeUnit.SECONDS); + } + Assert.fail("Reconnect did not reach registration"); + } + + 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 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)); + Assert.assertTrue( + "Server B still has active connections", + serverB.awaitNoActiveConnections(5, TimeUnit.SECONDS)); + } finally { + resumeRegister.countDown(); + executor.shutdownNow(); + testSession.forceClose(); + } + } + } + + @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 { + 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()); + 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(); + } + } + } + + @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 { + // 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( + () -> { + 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(); + Assert.assertFalse( + "Displaced transport should be closed immediately when forceClose() returns", + displacedTransport.isOpen()); + + 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 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; + }); + awaitSessionClosing(testSession); + + 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 { + 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()); + + 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( + "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 IClientRPCService.Iface handler = Mockito.mock(IClientRPCService.Iface.class); + 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 final List observedEnableRedirectQuery = new CopyOnWriteArrayList<>(); + + private ReconnectTestServer(int failInsertCount) throws Exception { + 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); + 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 -> { + int count = closeSessionCount.incrementAndGet(); + if (closeSessionStarted != null && count == 1) { + closeSessionStarted.countDown(); + continueCloseSession.await(30, TimeUnit.SECONDS); + } + 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( + 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"); + } + 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 List getObservedEnableRedirectQuery() { + return observedEnableRedirectQuery; + } + + 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)); + } }