Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
147 changes: 105 additions & 42 deletions iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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<SessionConnection> 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) {
Expand All @@ -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<SessionConnection> connectionsToClose;
synchronized (connectionStateLock) {
closing = true;
if (isClosed) {
return;
}
connectionsToClose = getSessionConnections();
}
try {
for (SessionConnection sessionConnection : getSessionConnections()) {
for (SessionConnection sessionConnection : connectionsToClose) {
sessionConnection.forceCloseTransport();
}
} finally {
Expand All @@ -784,14 +793,16 @@ private List<SessionConnection> 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) {
Expand Down Expand Up @@ -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<Entry<TEndPoint, SessionConnection>> it =
endPointToSessionConnection.entrySet().iterator();
it.hasNext(); ) {
Entry<TEndPoint, SessionConnection> entry = it.next();
if (entry.getValue().equals(sessionConnection)) {
endPoint = entry.getKey();
it.remove();
break;
}
if (endPointToSessionConnection == null) {
return;
}
Set<TEndPoint> removedEndPoints = new HashSet<>();
for (Iterator<Entry<TEndPoint, SessionConnection>> it =
endPointToSessionConnection.entrySet().iterator();
it.hasNext(); ) {
Entry<TEndPoint, SessionConnection> entry = it.next();
if (entry.getValue().equals(sessionConnection)) {
removedEndPoints.add(entry.getKey());
it.remove();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep a reconnecting query connection visible to forceClose().

With only query redirection enabled, a query on non-default connection B can reopen its transport and remove B here before reconnect() makes B the default. A concurrent forceClose() then sees only A. I paused the reconnect in this window. B received the retried query after forceClose() returned and still had one open socket. On the base revision the retry stopped and both nodes had zero open sockets.

Please coordinate registration of the reopened connection with the session's close state so that a close in this window releases the new transport and stops the retry.

}
}
if (!enableRedirection || removedEndPoints.isEmpty()) {
return;
}
if (deviceIdToEndpoint != null && !deviceIdToEndpoint.isEmpty()) {
for (Iterator<Entry<String, TEndPoint>> it = deviceIdToEndpoint.entrySet().iterator();
it.hasNext(); ) {
Entry<String, TEndPoint> entry = it.next();
if (removedEndPoints.contains(entry.getValue())) {
it.remove();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Guard device-route cleanup with enableRedirection.

Session.open(..., deviceIdToEndpoint, nodesSupplier) accepts a caller-supplied map. With write redirection disabled and query redirection enabled, I passed a read-only view containing a route to A and made a query fail over to B. B accepted the connection, then it.remove() threw UnsupportedOperationException before B received the query. The same query also deletes a route from a mutable map shared with writers.

Please keep the endpoint-to-connection cleanup independent of the write flag and only invalidate the tree and table device-route caches when write redirection is enabled.

}
}
if (deviceIdToEndpoint != null && !deviceIdToEndpoint.isEmpty()) {
for (Iterator<Entry<String, TEndPoint>> it = deviceIdToEndpoint.entrySet().iterator();
}
if (tableModelDeviceIdToEndpoint != null && !tableModelDeviceIdToEndpoint.isEmpty()) {
for (Map<IDeviceID, TEndPoint> databaseToEndpoint : tableModelDeviceIdToEndpoint.values()) {
for (Iterator<Entry<IDeviceID, TEndPoint>> it = databaseToEndpoint.entrySet().iterator();
it.hasNext(); ) {
Entry<String, TEndPoint> entry = it.next();
if (entry.getValue().equals(endPoint)) {
Entry<IDeviceID, TEndPoint> entry = it.next();
if (removedEndPoints.contains(entry.getValue())) {
it.remove();
}
}
}
if (tableModelDeviceIdToEndpoint != null && !tableModelDeviceIdToEndpoint.isEmpty()) {
for (Map<IDeviceID, TEndPoint> databaseToEndpoint : tableModelDeviceIdToEndpoint.values()) {
for (Iterator<Entry<IDeviceID, TEndPoint>> it = databaseToEndpoint.entrySet().iterator();
it.hasNext(); ) {
Entry<IDeviceID, TEndPoint> entry = it.next();
if (Objects.equals(entry.getValue(), endPoint)) {
it.remove();
}
}
}
}
}
}

Expand Down Expand Up @@ -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<TEndPoint, SessionConnection> 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -367,6 +366,10 @@ protected boolean setTransportTimeout(final int timeoutInMs) {
}
}

boolean isForceClosed() {
return forceClosed;
}

protected void forceCloseTransport() {
forceClosed = true;
if (transport == null) {
Expand Down Expand Up @@ -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) {
Expand All @@ -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;
Expand All @@ -1275,7 +1278,7 @@ private boolean reconnect() {
session.keyStore,
session.keyStorePwd,
session.sslProtocol);
if (forceClosed) {
if (forceClosed || session.isClosing()) {
forceCloseTransport();
return false;
}
Expand All @@ -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;
}
}
Expand Down
Loading
Loading