Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,11 @@ public class SessionConfig {

public static final int DEFAULT_SESSION_POOL_MAX_SIZE = 5;

public static final int DEFAULT_SESSION_POOL_CORE_SIZE = 0;

/** 0 means idle sessions are never evicted. */
public static final long DEFAULT_SESSION_POOL_MAX_IDLE_TIME_IN_MS = 0;

public static final Version DEFAULT_VERSION = Version.V_1_0;

public static final boolean DEFAULT_ENABLE_AUTO_FETCH = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,14 @@ public final class SessionMessages {
public static final String INTERRUPTED = "Interrupted!";
public static final String CLOSING_SESSION_POOL = "closing the session pool, cleaning queues...";

// SessionPool - configuration
public static final String SESSION_POOL_CORE_SIZE_ARG_ILLEGAL =
"the coreSize %d must be in [0, maxSize(%d)]";
public static final String SESSION_POOL_MAX_IDLE_TIME_ARG_ILLEGAL =
"the maxIdleTimeInMs %d must not be negative";
public static final String EVICT_IDLE_SESSIONS =
"evicted {} idle sessions, remaining session count: {}, coreSize: {}";

// SessionPool - operation failed (warn)
public static final String INSERT_TABLET_FAILED = "insertTablet failed";
public static final String INSERT_ALIGNED_TABLET_FAILED = "insertAlignedTablet failed";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,14 @@ public final class SessionMessages {
public static final String INTERRUPTED = "被中断!";
public static final String CLOSING_SESSION_POOL = "正在关闭 Session 连接池,清理队列...";

// SessionPool - configuration
public static final String SESSION_POOL_CORE_SIZE_ARG_ILLEGAL =
"coreSize %d 必须位于 [0, maxSize(%d)] 范围内";
public static final String SESSION_POOL_MAX_IDLE_TIME_ARG_ILLEGAL =
"maxIdleTimeInMs %d 不能为负数";
public static final String EVICT_IDLE_SESSIONS =
"回收了 {} 个空闲 Session,剩余 Session 数:{},coreSize:{}";

// SessionPool - operation failed (warn)
public static final String INSERT_TABLET_FAILED = "insertTablet 失败";
public static final String INSERT_ALIGNED_TABLET_FAILED = "insertAlignedTablet 失败";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@

public class AbstractSessionPoolBuilder extends AbstractSessionBuilder {
int maxSize = SessionConfig.DEFAULT_SESSION_POOL_MAX_SIZE;
int coreSize = SessionConfig.DEFAULT_SESSION_POOL_CORE_SIZE;
long maxIdleTimeInMs = SessionConfig.DEFAULT_SESSION_POOL_MAX_IDLE_TIME_IN_MS;
long waitToGetSessionTimeoutInMs = 60_000;
int connectionTimeoutInMs = SessionConfig.DEFAULT_CONNECTION_TIMEOUT_MS;
protected INodeSupplier nodeSupplier;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static org.apache.iotdb.rpc.RpcUtils.isSetSqlDialect;
import static org.apache.iotdb.rpc.RpcUtils.isUseDatabase;
Expand Down Expand Up @@ -99,11 +100,13 @@ public class SessionPool implements ISessionPool {
private static final int RETRY = 3;
private static final int FINAL_RETRY = RETRY - 1;

private final ConcurrentLinkedDeque<ISession> queue = new ConcurrentLinkedDeque<>();
private final ConcurrentLinkedDeque<IdleSession> queue = new ConcurrentLinkedDeque<>();
// sessions currently borrowed for a result set or a table-session wrapper.
private final ConcurrentMap<ISession, ISession> occupied = new ConcurrentHashMap<>();
private int size = 0;
private int maxSize = 0;
private int coreSize = SessionConfig.DEFAULT_SESSION_POOL_CORE_SIZE;
private long maxIdleTimeInMs = SessionConfig.DEFAULT_SESSION_POOL_MAX_IDLE_TIME_IN_MS;
Comment on lines +108 to +109

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

SessionPool / ISessionPool provide getters for the other pool settings (getMaxSize(), getWaitToGetSessionTimeoutInMs(), getConnectionTimeoutInMs(), etc.). Consider adding getCoreSize() and getMaxIdleTimeInMs() (as default methods on ISessionPool if exposed on the interface to keep backward compatibility), which would also eliminate the Whitebox.getInternalState reflection in SessionPoolTest. Both fields can also be final if assigned defaults in the non-builder constructors.

private final long waitToGetSessionTimeoutInMs;

// parameters for Session constructor
Expand Down Expand Up @@ -526,8 +529,12 @@ public SessionPool(
initAvailableNodes(SessionUtils.parseSeedNodeUrls(this.nodeUrls));
}

@SuppressWarnings("unsafeThreadSchedule")
public SessionPool(AbstractSessionPoolBuilder builder) {
this.maxSize = builder.maxSize;
this.coreSize = builder.coreSize;
this.maxIdleTimeInMs = builder.maxIdleTimeInMs;
validateIdleConfig(coreSize, maxSize, maxIdleTimeInMs);
this.user = builder.username;
this.password = builder.pw;
this.fetchSize = builder.fetchSize;
Expand Down Expand Up @@ -589,6 +596,15 @@ public SessionPool(AbstractSessionPoolBuilder builder) {
} else {
this.availableNodes = new DummyNodesSupplier(endPointList);
}

if (maxIdleTimeInMs > 0) {
if (executorService == null) {
initThreadPool();
}
long checkIntervalInMs = Math.max(1_000L, Math.min(maxIdleTimeInMs, 60_000L));
executorService.scheduleWithFixedDelay(
this::evictIdleSessions, checkIntervalInMs, checkIntervalInMs, TimeUnit.MILLISECONDS);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Several issues with scheduling idle eviction here:

  1. Head-of-line blocking on the single-threaded executorService: initThreadPool() creates a single-thread executor named PeriodicalUpdateDNList shared with NodesSupplier. evictIdleSessions() calls closeSession(), which sends a synchronous client.closeSession Thrift RPC (with default connectionTimeoutInMs = 0, i.e., no socket timeout). A stalled/blackholed DataNode during eviction will block that single thread and freeze NodesSupplier's periodic refresh and requestRefresh() failover; conversely, NodesSupplier.run() (60s RPC timeout per candidate) can starve eviction. Using a dedicated single-thread scheduled executor (e.g. SessionPoolIdleEvictor, shut down in close()) isolates the two and also avoids a misleading thread name when enableAutoFetch == false.
  2. Uncaught Throwable permanently cancels the periodic task: @SuppressWarnings("unsafeThreadSchedule") is placed on the whole constructor to bypass checkstyle, while evictIdleSessions() has no outer try { ... } catch (Throwable t) guard (closeSession only catches Exception). Any uncaught RuntimeException/Error will silently kill all future eviction runs. Please wrap the scheduled runnable with a Throwable catch + log, and narrow @SuppressWarnings("unsafeThreadSchedule") to a small helper method (also note that scheduling this::evictIdleSessions inside a non-final class constructor publishes this before subclass constructors complete—cf. NodesSupplier.createNodeSupplier).
  3. Skip scheduling when coreSize == maxSize: Guard with if (maxIdleTimeInMs > 0 && coreSize < maxSize) so we don't spawn a background thread and run no-op ticks when size can never exceed coreSize.
  4. Eviction delay up to ~2 * maxIdleTimeInMs: With checkIntervalInMs = Math.max(1_000L, Math.min(maxIdleTimeInMs, 60_000L)), for maxIdleTimeInMs in (1s, 60s] a session returned just after a tick can stay idle for nearly 2 * maxIdleTimeInMs before eviction. Using e.g. Math.max(1_000L, Math.min(maxIdleTimeInMs / 2, 60_000L)) (or documenting the periodic check cadence) would tighten this.

}

private Session constructNewSession() {
Expand Down Expand Up @@ -712,7 +728,8 @@ private ISession getSession() throws IoTDBConnectionException {
if (closed) {
throw new IoTDBConnectionException(SESSION_POOL_IS_CLOSED);
}
session = queue.poll();
IdleSession idleSession = queue.poll();
session = idleSession == null ? null : idleSession.session;
}
if (session != null) {
return session;
Expand Down Expand Up @@ -763,14 +780,11 @@ private ISession getSession() throws IoTDBConnectionException {
// wake up from this.wait(1000) by this.notify()
}

session = queue.poll();
IdleSession idleSession = queue.poll();
session = idleSession == null ? null : idleSession.session;

// for putBack or size--
this.notify();

if (closed) {
throw new IoTDBConnectionException(SESSION_POOL_IS_CLOSED);
}
Comment on lines -771 to -773

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This if (closed) check looks like it was accidentally dropped while resolving the merge conflict in be6a34a462. Without it, a waiter woken up by close() performs an unnecessary queue.poll() and this.notify() before re-entering the loop to observe closed—and if queue.poll() ever yields a session as closed becomes true (e.g., via a monitor-releasing test hook like BlockingAfterPollDeque), the loop exits and returns a session from a closed pool. Please restore it (and consider checking if (closed) right after this.wait(1000) before polling as well).

}
}

Expand Down Expand Up @@ -835,7 +849,7 @@ public int currentOccupiedSize() {
protected void putBack(ISession session) {
synchronized (this) {
if (!closed) {
queue.push(session);
queue.push(new IdleSession(session, System.currentTimeMillis()));
// we do not need to notifyAll as any waited thread can continue to work after waked up.
this.notify();
// comment the following codes as putBack is too frequently called.
Expand Down Expand Up @@ -903,7 +917,10 @@ public void close() {
return;
}
closed = true;
idleSessions = new ArrayList<>(queue);
idleSessions = new ArrayList<>(queue.size());
for (IdleSession idleSession : queue) {
idleSessions.add(idleSession.session);
}
borrowedSessions = new ArrayList<>(occupied.keySet());
queue.clear();
occupied.clear();
Expand Down Expand Up @@ -974,7 +991,7 @@ private void tryConstructNewSession() {
session.close();
throw new IoTDBConnectionException(SESSION_POOL_IS_CLOSED);
}
queue.push(session);
queue.push(new IdleSession(session, System.currentTimeMillis()));
this.notify();
}
} catch (IoTDBConnectionException e) {
Expand All @@ -986,6 +1003,54 @@ private void tryConstructNewSession() {
}
}

private static void validateIdleConfig(int coreSize, int maxSize, long maxIdleTimeInMs) {
if (coreSize < 0 || coreSize > maxSize) {
throw new IllegalArgumentException(
String.format(SessionMessages.SESSION_POOL_CORE_SIZE_ARG_ILLEGAL, coreSize, maxSize));
}
if (maxIdleTimeInMs < 0) {
throw new IllegalArgumentException(
String.format(SessionMessages.SESSION_POOL_MAX_IDLE_TIME_ARG_ILLEGAL, maxIdleTimeInMs));
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Minor validation edge case: if a caller passes maxSize <= 0 with the default coreSize = 0, maxSize(-1) throws a confusing message blaming coreSize (the coreSize 0 must be in [0, maxSize(-1)]), and maxSize(0) passes silently and times out on every getSession(). Consider validating maxSize <= 0 explicitly before checking coreSize.


/**
* Closes idle sessions which have been idle for more than {@link #maxIdleTimeInMs}, until the
* total number of sessions drops to {@link #coreSize}. Evicted sessions are closed outside the
* lock to avoid holding it during I/O.
*/
private void evictIdleSessions() {
List<ISession> evicted = new ArrayList<>();
int sizeAfterEviction;
synchronized (this) {
if (closed) {
return;
}
long now = System.currentTimeMillis();
while (size > coreSize) {
IdleSession idleSession = queue.peekLast();
if (idleSession == null || now - idleSession.idleSince <= maxIdleTimeInMs) {
break;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Please use monotonic System.nanoTime() instead of wall-clock System.currentTimeMillis() (here and in putBack / tryConstructNewSession). Because this loop assumes tail-to-head timestamp monotonicity and breaks on the first non-expired tail entry, a backward clock jump (NTP/manual adjustment) leaves a future-stamped entry at the tail that blocks eviction of all newer idle sessions behind it until wall time catches up, while a forward jump prematurely evicts active-recently sessions. Storing idleSinceNanos = System.nanoTime() and comparing (nowNanos - idleSession.idleSinceNanos) > TimeUnit.MILLISECONDS.toNanos(maxIdleTimeInMs) avoids both issues safely (including for Long.MAX_VALUE).

queue.pollLast();
size--;
evicted.add(idleSession.session);
}
sizeAfterEviction = size;
if (!evicted.isEmpty()) {
// wake up all waiters so that they can create new sessions if size < maxSize.
this.notifyAll();
}
}
if (!evicted.isEmpty()) {
LOGGER.debug(
SessionMessages.EVICT_IDLE_SESSIONS, evicted.size(), sizeAfterEviction, coreSize);
}
for (ISession session : evicted) {
closeSession(session);
}
}

private void closeSession(ISession session) {
if (session != null) {
try {
Expand Down Expand Up @@ -3583,8 +3648,8 @@ public String getPassword() {
@Override
public void setFetchSize(int fetchSize) {
this.fetchSize = fetchSize;
for (ISession session : queue) {
session.setFetchSize(fetchSize);
for (IdleSession idleSession : queue) {
idleSession.session.setFetchSize(fetchSize);
}
for (ISession session : occupied.keySet()) {
session.setFetchSize(fetchSize);
Expand Down Expand Up @@ -3614,8 +3679,8 @@ public void setTimeZone(String zoneId)
}
}
this.zoneId = ZoneId.of(zoneId);
for (ISession session : queue) {
session.setTimeZoneOfSession(zoneId);
for (IdleSession idleSession : queue) {
idleSession.session.setTimeZoneOfSession(zoneId);
}
for (ISession session : occupied.keySet()) {
session.setTimeZoneOfSession(zoneId);
Expand Down Expand Up @@ -3644,8 +3709,8 @@ public void setEnableRedirection(boolean enableRedirection) {
deviceIdToEndpoint = new ConcurrentHashMap<>();
tableModelDeviceIdToEndpoint = new ConcurrentHashMap<>();
}
for (ISession session : queue) {
session.setEnableRedirection(enableRedirection);
for (IdleSession idleSession : queue) {
idleSession.session.setEnableRedirection(enableRedirection);
}
for (ISession session : occupied.keySet()) {
session.setEnableRedirection(enableRedirection);
Expand All @@ -3660,8 +3725,8 @@ public boolean isEnableRedirection() {
@Override
public void setEnableQueryRedirection(boolean enableQueryRedirection) {
this.enableQueryRedirection = enableQueryRedirection;
for (ISession session : queue) {
session.setEnableQueryRedirection(enableQueryRedirection);
for (IdleSession idleSession : queue) {
idleSession.session.setEnableQueryRedirection(enableQueryRedirection);
}
for (ISession session : occupied.keySet()) {
session.setEnableQueryRedirection(enableQueryRedirection);
Expand Down Expand Up @@ -3722,8 +3787,8 @@ public TSConnectionInfoResp fetchAllConnections() throws IoTDBConnectionExceptio
@Override
public void setVersion(Version version) {
this.version = version;
for (ISession session : queue) {
session.setVersion(version);
for (IdleSession idleSession : queue) {
idleSession.session.setVersion(version);
}
for (ISession session : occupied.keySet()) {
session.setVersion(version);
Expand All @@ -3738,8 +3803,8 @@ public Version getVersion() {
@Override
public void setQueryTimeout(long timeoutInMs) {
this.queryTimeoutInMs = timeoutInMs;
for (ISession session : queue) {
session.setQueryTimeout(timeoutInMs);
for (IdleSession idleSession : queue) {
idleSession.session.setQueryTimeout(timeoutInMs);
}
for (ISession session : occupied.keySet()) {
session.setQueryTimeout(timeoutInMs);
Expand All @@ -3751,6 +3816,16 @@ public long getQueryTimeout() {
return queryTimeoutInMs;
}

private static final class IdleSession {
private final ISession session;
private final long idleSince;

private IdleSession(ISession session, long idleSince) {
this.session = session;
this.idleSince = idleSince;
}
}

public static class Builder extends AbstractSessionPoolBuilder {

public Builder useSSL(boolean useSSL) {
Expand Down Expand Up @@ -3807,6 +3882,31 @@ public Builder maxSize(int maxSize) {
return this;
}

/**
* Sets the minimum number of sessions kept in the pool. Idle sessions will not be evicted when
* the total number of sessions reaches this value.
*
* @param coreSize the minimum number of sessions, must be in [0, maxSize]
* @return this builder
*/
public Builder coreSize(int coreSize) {
this.coreSize = coreSize;
return this;
}
Comment on lines +3949 to +3964

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggest clarifying in both SessionPool.Builder#coreSize and TableSessionPoolBuilder#coreSize Javadocs that:

  1. Sessions are still created lazily on demand (not pre-warmed to coreSize at construction time).
  2. coreSize only takes effect when maxIdleTimeInMs > 0.
  3. coreSize bounds the total number of sessions (size, including borrowed and idle sessions), not idle sessions alone.


/**
* Sets the maximum time in milliseconds that an idle session can stay in the pool. Idle
* sessions are evicted until the total number of sessions drops to the core size. 0 means idle
* sessions are never evicted.
*
* @param maxIdleTimeInMs the maximum idle time in milliseconds, must not be negative
* @return this builder
*/
public Builder maxIdleTimeInMs(long maxIdleTimeInMs) {
this.maxIdleTimeInMs = maxIdleTimeInMs;
return this;
}

public Builder user(String user) {
this.username = user;
return this;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,33 @@ public TableSessionPoolBuilder maxSize(int maxSize) {
return this;
}

/**
* Sets the minimum number of sessions kept in the pool. Idle sessions will not be evicted when
* the total number of sessions reaches this value.
*
* @param coreSize the minimum number of sessions, must be in [0, maxSize].
* @return the current {@link TableSessionPoolBuilder} instance.
* @defaultValue 0
*/
public TableSessionPoolBuilder coreSize(int coreSize) {
this.coreSize = coreSize;
return this;
}

/**
* Sets the maximum time in milliseconds that an idle session can stay in the pool. Idle sessions
* are evicted until the total number of sessions drops to the core size. 0 means idle sessions
* are never evicted.
*
* @param maxIdleTimeInMs the maximum idle time in milliseconds, must not be negative.
* @return the current {@link TableSessionPoolBuilder} instance.
* @defaultValue 0
*/
public TableSessionPoolBuilder maxIdleTimeInMs(long maxIdleTimeInMs) {
this.maxIdleTimeInMs = maxIdleTimeInMs;
return this;
}

/**
* Sets the username for the connection.
*
Expand Down
Loading
Loading