Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#14761] fix(core): Interrupt abandoned JDBC connect workers off the request thread (#14763)

Qi Yu92d1c9561266
diff --git a/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/JdbcCatalogOperations.java b/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/JdbcCatalogOperations.java
index ebe9679478..308e73ec1c 100644
--- a/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/JdbcCatalogOperations.java
+++ b/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/JdbcCatalogOperations.java
@@ -170,6 +170,12 @@ public class JdbcCatalogOperations
this.jdbcConfig = new JdbcConfig(resultConf);
this.jdbcUrl = jdbcConfig.getJdbcUrl();
this.dataSource = DataSourceUtils.createDataSource(jdbcConfig);
+ try {
+ configureDataSource(dataSource, jdbcConfig);
+ } catch (RuntimeException e) {
+ DataSourceUtils.closeDataSource(dataSource);
+ throw e;
+ }
checkJDBCDriverVersion();
this.databaseOperation.initialize(dataSource, exceptionConverter, resultConf);
@@ -189,12 +195,36 @@ public class JdbcCatalogOperations
}
}
+ /**
+ * Configures the validated, lazy DBCP data source before any connection is borrowed.
+ *
+ * <p>The default makes no changes. A connector whose driver does not enforce a login timeout can
+ * bound physical connection creation with {@link
+ * org.apache.gravitino.utils.BoundedConnectionDriver}:
+ *
+ * <pre>{@code
+ * ((BasicDataSource) dataSource)
+ * .setDriver(
+ * new BoundedConnectionDriver(
+ * DataSourceUtils.configuredDriver(config), config.getConnectTimeoutMs()));
+ * }</pre>
+ *
+ * <p>Implementations must keep the URL, credentials and pool settings that the common JDBC
+ * factory applied. They must not borrow connections or start the pool in this hook, and must not
+ * retain or close the data source; these operations own its lifecycle. A runtime exception closes
+ * the data source and fails initialization.
+ *
+ * @param dataSource the DBCP data source created by the common JDBC factory
+ * @param config validated JDBC configuration
+ */
+ protected void configureDataSource(DataSource dataSource, JdbcConfig config) {}
+
/** Closes the Jdbc catalog and releases the associated client pool. */
@Override
public void close() {
// Metrics System could be null in UT.
MetricsSystem metricsSystem = GravitinoEnv.getInstance().metricsSystem();
- if (metricsSystem != null) {
+ if (metricsSystem != null && catalogMetricsSource != null) {
metricsSystem.unregister(catalogMetricsSource);
}
DataSourceUtils.closeDataSource(dataSource);
diff --git a/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/TestJdbcCatalogOperationsDataSourceHook.java b/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/TestJdbcCatalogOperationsDataSourceHook.java
new file mode 100644
index 0000000000..b6bb44b626
--- /dev/null
+++ b/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/TestJdbcCatalogOperationsDataSourceHook.java
@@ -0,0 +1,258 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.catalog.jdbc;
+
+import java.sql.Connection;
+import java.sql.Driver;
+import java.sql.DriverPropertyInfo;
+import java.sql.SQLException;
+import java.sql.SQLFeatureNotSupportedException;
+import java.time.Instant;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+import javax.sql.DataSource;
+import org.apache.commons.dbcp2.BasicDataSource;
+import org.apache.commons.lang3.reflect.FieldUtils;
+import org.apache.gravitino.Catalog;
+import org.apache.gravitino.GravitinoEnv;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.catalog.jdbc.config.JdbcConfig;
+import org.apache.gravitino.catalog.jdbc.converter.JdbcColumnDefaultValueConverter;
+import org.apache.gravitino.catalog.jdbc.converter.JdbcTypeConverter;
+import org.apache.gravitino.catalog.jdbc.converter.SqliteColumnDefaultValueConverter;
+import org.apache.gravitino.catalog.jdbc.converter.SqliteExceptionConverter;
+import org.apache.gravitino.catalog.jdbc.converter.SqliteTypeConverter;
+import org.apache.gravitino.catalog.jdbc.operation.JdbcDatabaseOperations;
+import org.apache.gravitino.catalog.jdbc.operation.JdbcTableOperations;
+import org.apache.gravitino.catalog.jdbc.operation.SqliteDatabaseOperations;
+import org.apache.gravitino.catalog.jdbc.operation.SqliteTableOperations;
+import org.apache.gravitino.catalog.jdbc.utils.DataSourceUtils;
+import org.apache.gravitino.connector.CatalogInfo;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.metrics.MetricsSystem;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/** Tests {@link JdbcCatalogOperations#configureDataSource(DataSource, JdbcConfig)}. */
+public class TestJdbcCatalogOperationsDataSourceHook {
+
+ @Test
+ void testHookRunsBeforeFirstBorrowAndItsDriverIsUsed() throws Exception {
+ AtomicInteger connects = new AtomicInteger();
+ AtomicReference<BasicDataSource> configured = new AtomicReference<>();
+ try (JdbcCatalogOperations operations =
+ new HookedOperations(
+ (dataSource, config) -> {
+ BasicDataSource pool = (BasicDataSource) dataSource;
+ // Nothing has been borrowed yet, so the driver can still be replaced.
+ Assertions.assertEquals(0, pool.getNumActive() + pool.getNumIdle());
+ pool.setDriver(
+ new CountingDriver(DataSourceUtils.configuredDriver(config), connects));
+ configured.set(pool);
+ })) {
+ operations.initialize(properties(), catalogInfo(), new TestJdbcCatalog());
+ Assertions.assertNotNull(configured.get());
+ try (Connection connection = configured.get().getConnection()) {
+ Assertions.assertTrue(connection.isValid(1));
+ }
+ Assertions.assertTrue(connects.get() > 0, "The installed driver must open connections");
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void testHookFailureClosesDataSourceAndPropagates(boolean metricsEnabled) throws Exception {
+ IllegalStateException failure = new IllegalStateException("cannot configure");
+ AtomicReference<BasicDataSource> configured = new AtomicReference<>();
+ GravitinoEnv environment = GravitinoEnv.getInstance();
+ MetricsSystem previousMetrics =
+ (MetricsSystem) FieldUtils.readField(environment, "metricsSystem", true);
+ try (MetricsSystem metricsSystem = metricsEnabled ? new MetricsSystem() : null;
+ JdbcCatalogOperations operations =
+ new HookedOperations(
+ (dataSource, config) -> {
+ configured.set((BasicDataSource) dataSource);
+ throw failure;
+ })) {
+ FieldUtils.writeField(environment, "metricsSystem", metricsSystem, true);
+ IllegalStateException thrown =
+ Assertions.assertThrows(
+ IllegalStateException.class,
+ () -> operations.initialize(properties(), catalogInfo(), new TestJdbcCatalog()));
+ Assertions.assertSame(failure, thrown);
+ Assertions.assertTrue(configured.get().isClosed());
+ } finally {
+ FieldUtils.writeField(environment, "metricsSystem", previousMetrics, true);
+ }
+ }
+
+ @Test
+ void testDefaultHookKeepsTheConfiguredDriver() throws Exception {
+ AtomicReference<BasicDataSource> created = new AtomicReference<>();
+ try (JdbcCatalogOperations operations =
+ new JdbcCatalogOperations(
+ new SqliteExceptionConverter(),
+ new SqliteTypeConverter(),
+ new SqliteDatabaseOperations(":memory:"),
+ new SqliteTableOperations(),
+ new SqliteColumnDefaultValueConverter()) {
+ @Override
+ protected void configureDataSource(DataSource dataSource, JdbcConfig config) {
+ created.set((BasicDataSource) dataSource);
+ super.configureDataSource(dataSource, config);
+ }
+ }) {
+ operations.initialize(properties(), catalogInfo(), new TestJdbcCatalog());
+ Assertions.assertNull(created.get().getDriver());
+ }
+ }
+
+ private interface Hook {
+ void configure(DataSource dataSource, JdbcConfig config);
+ }
+
+ private static final class HookedOperations extends JdbcCatalogOperations {
+ private final Hook hook;
+
+ private HookedOperations(Hook hook) {
+ super(
+ new SqliteExceptionConverter(),
+ new SqliteTypeConverter(),
+ new SqliteDatabaseOperations(":memory:"),
+ new SqliteTableOperations(),
+ new SqliteColumnDefaultValueConverter());
+ this.hook = hook;
+ }
+
+ @Override
+ protected void configureDataSource(DataSource dataSource, JdbcConfig config) {
+ hook.configure(dataSource, config);
+ }
+
+ /** Borrows a connection like connectors that read the driver version do. */
+ @Override
+ public void checkJDBCDriverVersion() {
+ try (Connection connection =
+ ((DataSource) FieldUtils.readField(this, "dataSource", true)).getConnection()) {
+ Assertions.assertTrue(connection.isValid(1));
+ } catch (Exception e) {
+ throw new IllegalStateException(e);
+ }
+ }
+ }
+
+ private static final class CountingDriver implements Driver {
+ private final Driver delegate;
+ private final AtomicInteger connects;
+
+ private CountingDriver(Driver delegate, AtomicInteger connects) {
+ this.delegate = delegate;
+ this.connects = connects;
+ }
+
+ @Override
+ public Connection connect(String url, Properties info) throws SQLException {
+ connects.incrementAndGet();
+ return delegate.connect(url, info);
+ }
+
+ @Override
+ public boolean acceptsURL(String url) throws SQLException {
+ return delegate.acceptsURL(url);
+ }
+
+ @Override
+ public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException {
+ return delegate.getPropertyInfo(url, info);
+ }
+
+ @Override
+ public int getMajorVersion() {
+ return delegate.getMajorVersion();
+ }
+
+ @Override
+ public int getMinorVersion() {
+ return delegate.getMinorVersion();
+ }
+
+ @Override
+ public boolean jdbcCompliant() {
+ return delegate.jdbcCompliant();
+ }
+
+ @Override
+ public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException {
+ return delegate.getParentLogger();
+ }
+ }
+
+ private static Map<String, String> properties() {
+ Map<String, String> properties = new HashMap<>();
+ properties.put(JdbcConfig.JDBC_URL.getKey(), "jdbc:sqlite::memory:");
+ properties.put(JdbcConfig.JDBC_DRIVER.getKey(), "org.sqlite.JDBC");
+ properties.put(JdbcConfig.USERNAME.getKey(), "user");
+ properties.put(JdbcConfig.PASSWORD.getKey(), "password");
+ return properties;
+ }
+
+ private static CatalogInfo catalogInfo() {
+ return new CatalogInfo(
+ 1L,
+ "jdbc_catalog",
+ Catalog.Type.RELATIONAL,
+ "jdbc-test",
+ "test",
+ properties(),
+ AuditInfo.builder().withCreator("test").withCreateTime(Instant.EPOCH).build(),
+ Namespace.of("metalake"));
+ }
+
+ private static class TestJdbcCatalog extends JdbcCatalog {
+ @Override
+ public String shortName() {
+ return "jdbc-test";
+ }
+
+ @Override
+ protected JdbcTypeConverter createJdbcTypeConverter() {
+ return new SqliteTypeConverter();
+ }
+
+ @Override
+ protected JdbcDatabaseOperations createJdbcDatabaseOperations() {
+ return new SqliteDatabaseOperations(":memory:");
+ }
+
+ @Override
+ protected JdbcTableOperations createJdbcTableOperations() {
+ return new SqliteTableOperations();
+ }
+
+ @Override
+ protected JdbcColumnDefaultValueConverter createJdbcColumnDefaultValueConverter() {
+ return new SqliteColumnDefaultValueConverter();
+ }
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/utils/BoundedConnectionDriver.java b/core/src/main/java/org/apache/gravitino/utils/BoundedConnectionDriver.java
index 6bc370a9a3..80600f36e2 100644
--- a/core/src/main/java/org/apache/gravitino/utils/BoundedConnectionDriver.java
+++ b/core/src/main/java/org/apache/gravitino/utils/BoundedConnectionDriver.java
@@ -34,12 +34,17 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.Semaphore;
import java.util.concurrent.SynchronousQueue;
+import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -49,15 +54,21 @@ import org.slf4j.LoggerFactory;
*
* <p>Only {@link Driver#connect} runs on a worker. Validation, metadata queries and DDL stay on the
* caller. A connection that arrives after timeout or interruption is closed by its worker and is
- * never handed to a pool. Cancellation is best effort: a driver ignoring interruption retains a
- * worker until it returns. A JVM-wide limit of 64 workers, with no queue, bounds that retention;
- * excess attempts fail with {@link SQLTransientConnectionException}. Workers are daemon threads and
- * release their catalog context class loader after each attempt. Each attempt, including late
- * connection cleanup, runs with the submitting caller's access-control context and JAAS subject;
- * shared workers do not inherit the creating request's JAAS subject. This does not isolate
- * arbitrary {@link ThreadLocal} or {@link InheritableThreadLocal} state. Delegates must clean up
- * such state and must not rely on it to carry a caller's identity. Drivers that cannot meet this
- * requirement must not use this adapter's shared workers.
+ * never handed to a pool. An abandoned attempt's worker is interrupted from a separate cancellation
+ * thread, never from the request thread, because an interrupt can synchronously run a driver's
+ * blocking channel-close callback. The interrupt is delivered only while the worker is still inside
+ * {@link Driver#connect}, so it cannot reach a later attempt on the same worker. A driver that
+ * ignores interruption retains its worker until it returns. A JVM-wide limit of 64 workers, with no
+ * queue, bounds that retention; excess attempts fail with {@link SQLTransientConnectionException}.
+ * Abandoned attempts, their completion and rejected attempts are logged. Workers are daemon threads
+ * and release their catalog context class loader after each attempt. Each attempt, including late
+ * connection cleanup, runs with the submitting caller's access-control context and JAAS subject.
+ * Driver interrupt callbacks use that same context and context class loader, restoring the
+ * cancellation thread's context afterward; shared workers do not inherit the creating request's
+ * JAAS subject. This does not isolate arbitrary {@link ThreadLocal} or {@link
+ * InheritableThreadLocal} state. Delegates must clean up such state and must not rely on it to
+ * carry a caller's identity. Drivers that cannot meet this requirement must not use this adapter's
+ * shared workers.
*
* <p>After a timeout, further attempts through this instance fail immediately until the abandoned
* attempt finishes cleanup. This prevents a lazy pool's initialization lock from serializing a
@@ -71,28 +82,29 @@ public final class BoundedConnectionDriver implements Driver {
private static final AccessControlContext WORKER_CONTEXT =
new AccessControlContext(new ProtectionDomain[0]);
- private static final ExecutorService WORKERS =
- new ThreadPoolExecutor(
- 0,
- 64,
- 60,
- TimeUnit.SECONDS,
- new SynchronousQueue<>(),
- task ->
- AccessController.doPrivileged(
- (PrivilegedAction<Thread>)
- () -> {
- Thread thread = new Thread(task, "jdbc-connect-timeout");
- thread.setDaemon(true);
- thread.setContextClassLoader(
- BoundedConnectionDriver.class.getClassLoader());
- return thread;
- },
- WORKER_CONTEXT));
+ private static final ExecutorService WORKERS = daemonPool(64, "jdbc-connect-timeout");
+
+ // Blocking interrupt callbacks must never occupy the request or retry-dispatch threads.
+ private static final ExecutorService CANCELLERS = daemonPool(64, "jdbc-connect-cancel");
+
+ private static final ScheduledExecutorService CANCELLATION_RETRIES =
+ Executors.newSingleThreadScheduledExecutor(daemonThreads("jdbc-connect-cancel-retry"));
+ // Bound retained caller contexts even if cancellation capacity never becomes available.
+ private static final Semaphore RETRY_SLOTS = new Semaphore(64);
+ private static final int MAX_CANCELLATION_RETRIES = 3;
+ private static final long FIRST_RETRY_DELAY_MS = 10;
+
+ private static final long REJECTION_LOG_INTERVAL_NANOS = TimeUnit.MINUTES.toNanos(1);
+ private static final AtomicLong LAST_REJECTION_LOG =
+ new AtomicLong(System.nanoTime() - REJECTION_LOG_INTERVAL_NANOS);
+ private static final AtomicLong REJECTIONS = new AtomicLong();
private final Driver delegate;
private final long timeoutMs;
private final ExecutorService workers;
+ private final ExecutorService cancellers;
+ private final ScheduledExecutorService cancellationRetries;
+ private final Semaphore retrySlots;
private final AtomicInteger abandonedAttempts = new AtomicInteger();
/**
@@ -107,12 +119,30 @@ public final class BoundedConnectionDriver implements Driver {
}
BoundedConnectionDriver(Driver delegate, long timeoutMs, ExecutorService workers) {
+ this(delegate, timeoutMs, workers, CANCELLERS);
+ }
+
+ BoundedConnectionDriver(
+ Driver delegate, long timeoutMs, ExecutorService workers, ExecutorService cancellers) {
+ this(delegate, timeoutMs, workers, cancellers, CANCELLATION_RETRIES, RETRY_SLOTS);
+ }
+
+ BoundedConnectionDriver(
+ Driver delegate,
+ long timeoutMs,
+ ExecutorService workers,
+ ExecutorService cancellers,
+ ScheduledExecutorService cancellationRetries,
+ Semaphore retrySlots) {
if (timeoutMs <= 0) {
throw new IllegalArgumentException("JDBC connect timeout must be positive");
}
this.delegate = delegate;
this.timeoutMs = timeoutMs;
this.workers = workers;
+ this.cancellers = cancellers;
+ this.cancellationRetries = cancellationRetries;
+ this.retrySlots = retrySlots;
}
/**
@@ -144,6 +174,7 @@ public final class BoundedConnectionDriver implements Driver {
},
callerContext));
} catch (RejectedExecutionException e) {
+ logRejection();
throw new SQLTransientConnectionException(
"The JDBC connection attempt limit has been reached. Try again after an attempt finishes.",
"08001",
@@ -154,7 +185,7 @@ public final class BoundedConnectionDriver implements Driver {
attempt.accept();
return connection;
} catch (TimeoutException e) {
- attempt.abandon();
+ attempt.abandon(context, callerContext);
throw new SQLTimeoutException(
"JDBC connection attempt exceeded "
+ timeoutMs
@@ -162,7 +193,7 @@ public final class BoundedConnectionDriver implements Driver {
"08001",
e);
} catch (InterruptedException e) {
- attempt.abandon();
+ attempt.abandon(context, callerContext);
Thread.currentThread().interrupt();
throw new SQLTimeoutException("Interrupted while opening a JDBC connection", "08001", e);
} catch (ExecutionException e) {
@@ -218,28 +249,207 @@ public final class BoundedConnectionDriver implements Driver {
return delegate.getParentLogger();
}
+ /** Names the delegate driver in logs; the URL is omitted because it may carry credentials. */
+ private String driverName() {
+ return delegate.getClass().getName();
+ }
+
+ /** Logs rejected attempts at most once a minute, with the count since the last log. */
+ private void logRejection() {
+ REJECTIONS.incrementAndGet();
+ long now = System.nanoTime();
+ long last = LAST_REJECTION_LOG.get();
+ if (now - last >= REJECTION_LOG_INTERVAL_NANOS && LAST_REJECTION_LOG.compareAndSet(last, now)) {
+ LOG.warn(
+ "Rejected {} JDBC connection attempt(s) since the last report, including one for {}: all "
+ + "connection workers are busy, likely with abandoned attempts against an "
+ + "unreachable backend",
+ REJECTIONS.getAndSet(0),
+ driverName());
+ }
+ }
+
+ private static ExecutorService daemonPool(int maxThreads, String name) {
+ return new ThreadPoolExecutor(
+ 0, maxThreads, 60, TimeUnit.SECONDS, new SynchronousQueue<>(), daemonThreads(name));
+ }
+
+ private static ThreadFactory daemonThreads(String name) {
+ return task ->
+ AccessController.doPrivileged(
+ (PrivilegedAction<Thread>)
+ () -> {
+ Thread thread = new Thread(task, name);
+ thread.setDaemon(true);
+ thread.setContextClassLoader(BoundedConnectionDriver.class.getClassLoader());
+ return thread;
+ },
+ WORKER_CONTEXT);
+ }
+
private final class Attempt {
private final CompletableFuture<Connection> result = new CompletableFuture<>();
private final CountDownLatch decision = new CountDownLatch(1);
+ private final long startNanos = System.nanoTime();
private boolean accepted;
private boolean abandoned;
private boolean finished;
- @Nullable private Thread runner;
+ @Nullable private Thread worker;
+ private volatile boolean connecting;
+ private boolean cancelling;
synchronized void accept() {
accepted = true;
}
- synchronized void abandon() {
- if (!finished) {
+ void abandon(@Nullable ClassLoader context, AccessControlContext callerContext) {
+ synchronized (this) {
+ if (finished) {
+ return;
+ }
abandoned = true;
abandonedAttempts.incrementAndGet();
- if (runner != null) {
- runner.interrupt();
+ }
+ LOG.info(
+ "Abandoned a {} connection attempt (deadline {} ms); interrupting its worker if it is "
+ + "still connecting",
+ driverName(),
+ timeoutMs);
+ // Thread.interrupt may synchronously run a driver's blocking channel-close callback, so
+ // it must not run on this request thread, which would defeat the connection deadline.
+ Runnable cancellation =
+ () ->
+ AccessController.doPrivileged(
+ (PrivilegedAction<Void>)
+ () -> {
+ Thread current = Thread.currentThread();
+ ClassLoader previous = current.getContextClassLoader();
+ try {
+ // An interrupt can execute driver code, so it needs the same caller
+ // context as connect and late connection cleanup, including on retry.
+ current.setContextClassLoader(context);
+ cancel();
+ } finally {
+ current.setContextClassLoader(previous);
+ }
+ return null;
+ },
+ callerContext);
+ try {
+ cancellers.execute(cancellation);
+ } catch (RejectedExecutionException e) {
+ if (!connecting) {
+ return;
+ }
+ if (!retrySlots.tryAcquire()) {
+ logCancellationRejection(e);
+ return;
+ }
+ boolean scheduled = false;
+ try {
+ cancellationRetries.schedule(
+ new CancellationRetry(cancellation), FIRST_RETRY_DELAY_MS, TimeUnit.MILLISECONDS);
+ scheduled = true;
+ } catch (RejectedExecutionException rejected) {
+ logCancellationRejection(rejected);
+ } finally {
+ if (!scheduled) {
+ retrySlots.release();
+ }
+ }
+ }
+ }
+
+ private void logCancellationRejection(RejectedExecutionException failure) {
+ LOG.warn(
+ "Could not schedule interruption of an abandoned {} connection attempt after bounded "
+ + "retry admission or execution failed; it remains quarantined until the driver "
+ + "and cleanup return. If they never return, restart the server",
+ driverName(),
+ failure);
+ }
+
+ /** Retries admission only: driver callbacks always run on the cancellation pool. */
+ private final class CancellationRetry implements Runnable {
+ private final Runnable cancellation;
+ private int retries;
+
+ private CancellationRetry(Runnable cancellation) {
+ this.cancellation = cancellation;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public void run() {
+ boolean rescheduled = false;
+ try {
+ // The volatile check avoids retaining obsolete attempts. cancel() still fences the
+ // actual interrupt under the attempt lock, including after an accepted retry is delayed.
+ if (!connecting) {
+ return;
+ }
+ retries++;
+ try {
+ cancellers.execute(cancellation);
+ } catch (RejectedExecutionException e) {
+ if (retries == MAX_CANCELLATION_RETRIES) {
+ logCancellationRejection(e);
+ } else {
+ cancellationRetries.schedule(
+ this, FIRST_RETRY_DELAY_MS << retries, TimeUnit.MILLISECONDS);
+ rescheduled = true;
+ }
+ }
+ } catch (RejectedExecutionException e) {
+ logCancellationRejection(e);
+ } finally {
+ if (!rescheduled) {
+ retrySlots.release();
+ }
+ }
+ }
+ }
+
+ /** Interrupts the worker only while it is still inside {@link Driver#connect}. */
+ private void cancel() {
+ Thread target;
+ synchronized (this) {
+ if (!connecting) {
+ return;
+ }
+ target = worker;
+ cancelling = true;
+ }
+ try {
+ target.interrupt();
+ } finally {
+ synchronized (this) {
+ cancelling = false;
+ notifyAll();
}
}
}
+ /**
+ * Ends the interruptible phase and waits for an in-flight interrupt to be delivered.
+ *
+ * @return whether the barrier consumed an interrupt, to restore after connection cleanup
+ */
+ private synchronized boolean endConnect() {
+ boolean interrupted = false;
+ connecting = false;
+ while (cancelling) {
+ try {
+ wait();
+ } catch (InterruptedException e) {
+ // An external interrupt can arrive during cancellation too. Preserve the signal, but
+ // restore it only after cleanup so an interrupt-sensitive close still succeeds.
+ interrupted = true;
+ }
+ }
+ return interrupted;
+ }
+
void run(String url, Properties properties, @Nullable ClassLoader context) {
Thread current = Thread.currentThread();
ClassLoader previous = current.getContextClassLoader();
@@ -248,12 +458,17 @@ public final class BoundedConnectionDriver implements Driver {
boolean interrupted = false;
try {
synchronized (this) {
- runner = current;
if (abandoned) {
return;
}
+ worker = current;
+ connecting = true;
+ }
+ try {
+ connection = delegate.connect(url, properties);
+ } finally {
+ interrupted |= endConnect();
}
- connection = delegate.connect(url, properties);
result.complete(connection);
while (true) {
try {
@@ -285,9 +500,13 @@ public final class BoundedConnectionDriver implements Driver {
} finally {
synchronized (this) {
finished = true;
- runner = null;
+ worker = null;
if (abandoned) {
abandonedAttempts.decrementAndGet();
+ LOG.info(
+ "An abandoned {} connection attempt finished after {} ms",
+ driverName(),
+ TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos));
}
}
current.setContextClassLoader(previous);
diff --git a/core/src/test/java/org/apache/gravitino/utils/TestBoundedConnectionDriver.java b/core/src/test/java/org/apache/gravitino/utils/TestBoundedConnectionDriver.java
index 39846d168e..30c0b33229 100644
--- a/core/src/test/java/org/apache/gravitino/utils/TestBoundedConnectionDriver.java
+++ b/core/src/test/java/org/apache/gravitino/utils/TestBoundedConnectionDriver.java
@@ -18,6 +18,7 @@
*/
package org.apache.gravitino.utils;
+import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
@@ -29,9 +30,11 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTimeout;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -40,6 +43,8 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
+import java.io.IOException;
+import java.nio.channels.spi.AbstractInterruptibleChannel;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.sql.Connection;
@@ -48,20 +53,31 @@ import java.sql.SQLException;
import java.sql.SQLTimeoutException;
import java.sql.SQLTransientConnectionException;
import java.time.Duration;
+import java.util.ArrayList;
+import java.util.List;
import java.util.Properties;
+import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
+import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.Semaphore;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import javax.security.auth.Subject;
import org.apache.commons.lang3.reflect.FieldUtils;
+import org.awaitility.Awaitility;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
class TestBoundedConnectionDriver {
private final ExecutorService workers = Executors.newSingleThreadExecutor();
@@ -72,6 +88,532 @@ class TestBoundedConnectionDriver {
assertTrue(workers.awaitTermination(10, TimeUnit.SECONDS));
}
+ @Test
+ void testDeadlineDoesNotRunBlockingInterruptCallbackOnCaller() throws Exception {
+ CountDownLatch entered = new CountDownLatch(1);
+ CountDownLatch releaseDriver = new CountDownLatch(1);
+ CountDownLatch callbackEntered = new CountDownLatch(1);
+ CountDownLatch releaseCallback = new CountDownLatch(1);
+ AtomicReference<Thread> callbackThread = new AtomicReference<>();
+ class BlockingInterruptChannel extends AbstractInterruptibleChannel {
+ void register() {
+ begin();
+ }
+
+ void finish() throws IOException {
+ end(false);
+ }
+ /** {@inheritDoc} */
+ @Override
+ protected void implCloseChannel() {
+ callbackThread.set(Thread.currentThread());
+ callbackEntered.countDown();
+ awaitIgnoringInterrupts(releaseCallback);
+ }
+ }
+ BlockingInterruptChannel channel = new BlockingInterruptChannel();
+ Driver driver = mock(Driver.class);
+ Connection late = mock(Connection.class);
+ when(driver.connect(anyString(), any()))
+ .thenAnswer(
+ call -> {
+ channel.register();
+ entered.countDown();
+ try {
+ awaitIgnoringInterrupts(releaseDriver);
+ } finally {
+ channel.finish();
+ }
+ return late;
+ });
+ BoundedConnectionDriver bounded = new BoundedConnectionDriver(driver, 500, workers);
+ ExecutorService callers = Executors.newSingleThreadExecutor();
+ AtomicReference<Thread> callerThread = new AtomicReference<>();
+ try {
+ Future<SQLTimeoutException> result =
+ callers.submit(
+ () -> {
+ callerThread.set(Thread.currentThread());
+ return assertThrows(
+ SQLTimeoutException.class,
+ () -> bounded.connect("jdbc:test", new Properties()));
+ });
+ assertTrue(entered.await(10, TimeUnit.SECONDS));
+ // The caller returns at its deadline while the interrupt callback is still blocked.
+ assertNotNull(result.get(2, TimeUnit.SECONDS));
+ assertTrue(callbackEntered.await(10, TimeUnit.SECONDS), "The worker must be interrupted");
+ assertNotSame(callerThread.get(), callbackThread.get());
+ assertTrue(callbackThread.get().getName().startsWith("jdbc-connect-cancel"));
+ assertThrows(
+ SQLTransientConnectionException.class,
+ () -> bounded.connect("jdbc:test", new Properties()));
+ verify(late, never()).close();
+ } finally {
+ releaseCallback.countDown();
+ releaseDriver.countDown();
+ callers.shutdownNow();
+ assertTrue(callers.awaitTermination(10, TimeUnit.SECONDS));
+ }
+ // The interrupt closed the driver's channel, so its connect fails instead of returning late.
+ workers.submit(() -> {}).get(10, TimeUnit.SECONDS);
+ verify(late, never()).close();
+ doReturn(late).when(driver).connect(anyString(), any());
+ assertSame(late, bounded.connect("jdbc:test", new Properties()));
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ @SuppressWarnings("removal")
+ void testInterruptCallbackPreservesCallerContext(boolean rejectFirst) throws Exception {
+ ExecutorService cancellers = Executors.newSingleThreadExecutor();
+ ClassLoader originalLoader =
+ cancellers.submit(() -> Thread.currentThread().getContextClassLoader()).get();
+ ClassLoader callerLoader = new ClassLoader(originalLoader) {};
+ Subject subject = new Subject();
+ CountDownLatch entered = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ CountDownLatch callback = new CountDownLatch(1);
+ AtomicReference<Subject> observedSubject = new AtomicReference<>();
+ AtomicReference<ClassLoader> observedLoader = new AtomicReference<>();
+ AtomicReference<Throwable> failure = new AtomicReference<>();
+ class ContextCheckingChannel extends AbstractInterruptibleChannel {
+ void register() {
+ begin();
+ }
+
+ void finish() throws IOException {
+ end(false);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ protected void implCloseChannel() {
+ observedSubject.set(Subject.getSubject(AccessController.getContext()));
+ observedLoader.set(Thread.currentThread().getContextClassLoader());
+ callback.countDown();
+ }
+ }
+ ContextCheckingChannel channel = new ContextCheckingChannel();
+ Driver driver = mock(Driver.class);
+ when(driver.connect(anyString(), any()))
+ .thenAnswer(
+ call -> {
+ channel.register();
+ entered.countDown();
+ try {
+ release.await();
+ } finally {
+ channel.finish();
+ }
+ return null;
+ });
+ ExecutorService submissions = mock(ExecutorService.class);
+ AtomicBoolean reject = new AtomicBoolean(rejectFirst);
+ doAnswer(
+ invocation -> {
+ if (reject.getAndSet(false)) {
+ throw new RejectedExecutionException("temporary handoff rejection");
+ }
+ cancellers.execute(invocation.getArgument(0));
+ return null;
+ })
+ .when(submissions)
+ .execute(any());
+ BoundedConnectionDriver bounded =
+ new BoundedConnectionDriver(driver, 30000, workers, submissions);
+ Thread caller =
+ new Thread(
+ () -> {
+ ClassLoader previous = Thread.currentThread().getContextClassLoader();
+ try {
+ Thread.currentThread().setContextClassLoader(callerLoader);
+ Subject.doAs(
+ subject,
+ (PrivilegedExceptionAction<Void>)
+ () -> {
+ assertThrows(
+ SQLTimeoutException.class,
+ () -> bounded.connect("jdbc:test", new Properties()));
+ assertTrue(Thread.currentThread().isInterrupted());
+ return null;
+ });
+ } catch (Throwable error) {
+ failure.set(error);
+ } finally {
+ Thread.currentThread().setContextClassLoader(previous);
+ }
+ });
+ try {
+ caller.start();
+ assertTrue(entered.await(10, TimeUnit.SECONDS));
+ caller.interrupt();
+ caller.join(10000);
+ assertFalse(caller.isAlive());
+ assertNull(failure.get());
+ assertTrue(callback.await(10, TimeUnit.SECONDS));
+ workers.submit(() -> {}).get(10, TimeUnit.SECONDS);
+ verify(submissions, times(rejectFirst ? 2 : 1)).execute(any());
+ assertAll(
+ () -> assertSame(subject, observedSubject.get()),
+ () -> assertSame(callerLoader, observedLoader.get()));
+ assertNull(cancellers.submit(() -> Subject.getSubject(AccessController.getContext())).get());
+ assertSame(
+ originalLoader,
+ cancellers.submit(() -> Thread.currentThread().getContextClassLoader()).get());
+ } finally {
+ release.countDown();
+ caller.interrupt();
+ caller.join(10000);
+ cancellers.shutdownNow();
+ assertTrue(cancellers.awaitTermination(10, TimeUnit.SECONDS));
+ }
+ }
+
+ @Test
+ void testTimeoutInterruptsWorkerSoItIsReleased() throws Exception {
+ Driver driver = mock(Driver.class);
+ Connection connection = mock(Connection.class);
+ CountDownLatch never = new CountDownLatch(1);
+ CountDownLatch interrupted = new CountDownLatch(1);
+ when(driver.connect(anyString(), any()))
+ .thenAnswer(
+ call -> {
+ try {
+ never.await(30, TimeUnit.SECONDS);
+ throw new AssertionError("The hung connect was not interrupted");
+ } catch (InterruptedException e) {
+ interrupted.countDown();
+ throw new SQLException("Interrupted", "08001", e);
+ }
+ })
+ .thenReturn(connection);
+ BoundedConnectionDriver bounded = new BoundedConnectionDriver(driver, 100, workers);
+ assertThrows(SQLTimeoutException.class, () -> bounded.connect("jdbc:test", new Properties()));
+ assertTrue(interrupted.await(10, TimeUnit.SECONDS));
+ // The single worker is free again and the quarantine is lifted.
+ workers.submit(() -> {}).get(10, TimeUnit.SECONDS);
+ assertSame(connection, bounded.connect("jdbc:test", new Properties()));
+ }
+
+ @Test
+ void testLateCancellationDoesNotInterruptNextAttemptOnSameWorker() throws Exception {
+ Driver driver = mock(Driver.class);
+ Connection first = mock(Connection.class);
+ Connection second = mock(Connection.class);
+ CountDownLatch releaseFirst = new CountDownLatch(1);
+ CountDownLatch secondEntered = new CountDownLatch(1);
+ CountDownLatch releaseSecond = new CountDownLatch(1);
+ AtomicReference<Boolean> secondInterrupted = new AtomicReference<>(false);
+ when(driver.connect(anyString(), any()))
+ .thenAnswer(
+ call -> {
+ awaitIgnoringInterrupts(releaseFirst);
+ return first;
+ })
+ .thenAnswer(
+ call -> {
+ secondEntered.countDown();
+ try {
+ releaseSecond.await(10, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ secondInterrupted.set(true);
+ }
+ return second;
+ });
+ // Hold the cancellation until the abandoned attempt has finished and the worker moved on.
+ AtomicReference<Runnable> cancellation = new AtomicReference<>();
+ ExecutorService manual = mock(ExecutorService.class);
+ doAnswer(
+ call -> {
+ cancellation.set(call.getArgument(0));
+ return null;
+ })
+ .when(manual)
+ .execute(any());
+ BoundedConnectionDriver bounded = new BoundedConnectionDriver(driver, 100, workers, manual);
+ assertThrows(SQLTimeoutException.class, () -> bounded.connect("jdbc:test", new Properties()));
+ releaseFirst.countDown();
+ workers.submit(() -> {}).get(10, TimeUnit.SECONDS);
+ verify(first).close();
+
+ ExecutorService callers = Executors.newSingleThreadExecutor();
+ try {
+ Future<Connection> next =
+ callers.submit(() -> bounded.connect("jdbc:test", new Properties()));
+ assertTrue(secondEntered.await(10, TimeUnit.SECONDS));
+ assertNotNull(cancellation.get());
+ cancellation.get().run();
+ releaseSecond.countDown();
+ assertSame(second, next.get(10, TimeUnit.SECONDS));
+ assertFalse(secondInterrupted.get(), "A stale cancellation must not reach a later attempt");
+ } finally {
+ releaseSecond.countDown();
+ callers.shutdownNow();
+ assertTrue(callers.awaitTermination(10, TimeUnit.SECONDS));
+ }
+ }
+
+ /**
+ * The canceller has decided to interrupt and is inside {@link Thread#interrupt} when the connect
+ * returns. The worker must wait for that interrupt instead of moving on, otherwise it would land
+ * on the next attempt that the same worker runs.
+ */
+ @Test
+ void testInFlightCancellationIsDeliveredBeforeWorkerMovesOn() throws Exception {
+ CountDownLatch interruptEntered = new CountDownLatch(1);
+ CountDownLatch releaseInterrupt = new CountDownLatch(1);
+ ExecutorService worker =
+ Executors.newSingleThreadExecutor(
+ task ->
+ new Thread(task) {
+ /** {@inheritDoc} */
+ @Override
+ public void interrupt() {
+ if (Thread.currentThread() != this) {
+ interruptEntered.countDown();
+ awaitIgnoringInterrupts(releaseInterrupt);
+ }
+ super.interrupt();
+ }
+ });
+ Driver driver = mock(Driver.class);
+ Connection first = mock(Connection.class);
+ Connection second = mock(Connection.class);
+ CountDownLatch releaseFirst = new CountDownLatch(1);
+ CountDownLatch secondEntered = new CountDownLatch(1);
+ CountDownLatch releaseSecond = new CountDownLatch(1);
+ AtomicReference<Boolean> secondInterrupted = new AtomicReference<>(false);
+ when(driver.connect(anyString(), any()))
+ .thenAnswer(
+ call -> {
+ awaitIgnoringInterrupts(releaseFirst);
+ return first;
+ })
+ .thenAnswer(
+ call -> {
+ secondEntered.countDown();
+ try {
+ releaseSecond.await(10, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ secondInterrupted.set(true);
+ }
+ return second;
+ });
+ AtomicReference<Runnable> cancellation = new AtomicReference<>();
+ ExecutorService manual = mock(ExecutorService.class);
+ doAnswer(
+ call -> {
+ cancellation.set(call.getArgument(0));
+ return null;
+ })
+ .when(manual)
+ .execute(any());
+ // A second datasource on the same shared workers, so its attempt is not quarantined.
+ BoundedConnectionDriver timedOut = new BoundedConnectionDriver(driver, 100, worker, manual);
+ BoundedConnectionDriver healthy = new BoundedConnectionDriver(driver, 10000, worker, manual);
+ ExecutorService callers = Executors.newSingleThreadExecutor();
+ Thread canceller = null;
+ try {
+ assertThrows(
+ SQLTimeoutException.class, () -> timedOut.connect("jdbc:test", new Properties()));
+ canceller = new Thread(cancellation.get());
+ canceller.start();
+ assertTrue(interruptEntered.await(10, TimeUnit.SECONDS));
+ releaseFirst.countDown();
+ Future<Connection> next =
+ callers.submit(() -> healthy.connect("jdbc:test", new Properties()));
+ assertFalse(
+ secondEntered.await(300, TimeUnit.MILLISECONDS),
+ "The worker must not start another attempt while an interrupt is being delivered");
+ releaseInterrupt.countDown();
+ canceller.join(10000);
+ assertTrue(secondEntered.await(10, TimeUnit.SECONDS));
+ releaseSecond.countDown();
+ assertSame(second, next.get(10, TimeUnit.SECONDS));
+ assertFalse(secondInterrupted.get(), "The cancellation must not reach the next attempt");
+ verify(first).close();
+ } finally {
+ releaseFirst.countDown();
+ releaseInterrupt.countDown();
+ releaseSecond.countDown();
+ if (canceller != null) {
+ canceller.join(10000);
+ }
+ callers.shutdownNow();
+ worker.shutdownNow();
+ assertTrue(callers.awaitTermination(10, TimeUnit.SECONDS));
+ assertTrue(worker.awaitTermination(10, TimeUnit.SECONDS));
+ }
+ }
+
+ @Test
+ void testBarrierRestoresInterruptionAfterCleanup() throws Exception {
+ CountDownLatch interruptEntered = new CountDownLatch(1);
+ CountDownLatch releaseInterrupt = new CountDownLatch(1);
+ AtomicBoolean firstInterrupt = new AtomicBoolean(true);
+ AtomicReference<Thread> workerThread = new AtomicReference<>();
+ ExecutorService worker =
+ Executors.newSingleThreadExecutor(
+ task -> {
+ Thread thread =
+ new Thread(task) {
+ /** {@inheritDoc} */
+ @Override
+ public void interrupt() {
+ if (Thread.currentThread() != this
+ && firstInterrupt.compareAndSet(true, false)) {
+ super.interrupt();
+ interruptEntered.countDown();
+ awaitIgnoringInterrupts(releaseInterrupt);
+ return;
+ }
+ super.interrupt();
+ }
+ };
+ workerThread.set(thread);
+ return thread;
+ });
+ worker.submit(() -> {}).get(10, TimeUnit.SECONDS);
+ CountDownLatch finished = new CountDownLatch(1);
+ AtomicReference<Boolean> interruptedAfterCleanup = new AtomicReference<>();
+ ExecutorService recording = mock(ExecutorService.class);
+ doAnswer(
+ invocation -> {
+ Runnable task = invocation.getArgument(0);
+ worker.execute(
+ () -> {
+ try {
+ task.run();
+ } finally {
+ interruptedAfterCleanup.set(Thread.currentThread().isInterrupted());
+ finished.countDown();
+ }
+ });
+ return null;
+ })
+ .when(recording)
+ .execute(any());
+ AtomicReference<Runnable> cancellation = new AtomicReference<>();
+ ExecutorService manual = mock(ExecutorService.class);
+ doAnswer(
+ invocation -> {
+ cancellation.set(invocation.getArgument(0));
+ return null;
+ })
+ .when(manual)
+ .execute(any());
+ CountDownLatch releaseConnect = new CountDownLatch(1);
+ CountDownLatch connectReturned = new CountDownLatch(1);
+ CountDownLatch connectConsumedInterrupt = new CountDownLatch(1);
+ Driver driver = mock(Driver.class);
+ Connection late = mock(Connection.class);
+ when(driver.connect(anyString(), any()))
+ .thenAnswer(
+ invocation -> {
+ while (true) {
+ try {
+ releaseConnect.await();
+ break;
+ } catch (InterruptedException ignored) {
+ // The driver consumes cancellation before returning, while its interrupt
+ // callback is still running on the canceller.
+ connectConsumedInterrupt.countDown();
+ }
+ }
+ connectReturned.countDown();
+ return late;
+ });
+ doAnswer(
+ invocation -> {
+ assertFalse(Thread.currentThread().isInterrupted());
+ return null;
+ })
+ .when(late)
+ .close();
+ BoundedConnectionDriver bounded = new BoundedConnectionDriver(driver, 500, recording, manual);
+ Thread canceller = null;
+ try {
+ assertThrows(SQLTimeoutException.class, () -> bounded.connect("jdbc:test", new Properties()));
+ canceller = new Thread(cancellation.get());
+ canceller.start();
+ assertTrue(interruptEntered.await(10, TimeUnit.SECONDS));
+ assertTrue(connectConsumedInterrupt.await(10, TimeUnit.SECONDS));
+ releaseConnect.countDown();
+ assertTrue(connectReturned.await(10, TimeUnit.SECONDS));
+ Awaitility.await()
+ .atMost(Duration.ofSeconds(10))
+ .until(() -> workerThread.get().getState() == Thread.State.WAITING);
+ // Deliver an independent interrupt while the cancellation callback is still running.
+ workerThread.get().interrupt();
+ Awaitility.await()
+ .atMost(Duration.ofSeconds(10))
+ .until(
+ () ->
+ workerThread.get().getState() == Thread.State.WAITING
+ && !workerThread.get().isInterrupted());
+ releaseInterrupt.countDown();
+ canceller.join(10000);
+ assertTrue(finished.await(10, TimeUnit.SECONDS));
+ assertEquals(true, interruptedAfterCleanup.get());
+ verify(late).close();
+ } finally {
+ releaseConnect.countDown();
+ releaseInterrupt.countDown();
+ if (canceller != null) {
+ canceller.join(10000);
+ }
+ worker.shutdownNow();
+ assertTrue(worker.awaitTermination(10, TimeUnit.SECONDS));
+ }
+ }
+
+ @Test
+ void testCancellationAfterConnectReturnsDoesNotInterruptCleanup() throws Exception {
+ Driver driver = mock(Driver.class);
+ Connection late = mock(Connection.class);
+ CountDownLatch release = new CountDownLatch(1);
+ CountDownLatch closeEntered = new CountDownLatch(1);
+ CountDownLatch releaseClose = new CountDownLatch(1);
+ AtomicReference<Boolean> closeInterrupted = new AtomicReference<>();
+ when(driver.connect(anyString(), any()))
+ .thenAnswer(
+ call -> {
+ awaitIgnoringInterrupts(release);
+ return late;
+ });
+ doAnswer(
+ call -> {
+ closeEntered.countDown();
+ awaitIgnoringInterrupts(releaseClose);
+ closeInterrupted.set(Thread.currentThread().isInterrupted());
+ return null;
+ })
+ .when(late)
+ .close();
+ AtomicReference<Runnable> cancellation = new AtomicReference<>();
+ ExecutorService manual = mock(ExecutorService.class);
+ doAnswer(
+ call -> {
+ cancellation.set(call.getArgument(0));
+ return null;
+ })
+ .when(manual)
+ .execute(any());
+ BoundedConnectionDriver bounded = new BoundedConnectionDriver(driver, 100, workers, manual);
+ try {
+ assertThrows(SQLTimeoutException.class, () -> bounded.connect("jdbc:test", new Properties()));
+ release.countDown();
+ assertTrue(closeEntered.await(10, TimeUnit.SECONDS));
+ // The connect has returned; cancelling now must not interrupt closing the late connection.
+ cancellation.get().run();
+ } finally {
+ release.countDown();
+ releaseClose.countDown();
+ }
+ workers.submit(() -> {}).get(10, TimeUnit.SECONDS);
+ assertEquals(false, closeInterrupted.get());
+ }
+
@Test
void testSuccessfulHandoffAndContextRestoration() throws Exception {
Driver driver = mock(Driver.class);
@@ -499,6 +1041,246 @@ class TestBoundedConnectionDriver {
}
}
+ @Test
+ void testTransientCancellationRejectionRecoversWorker() throws Exception {
+ ExecutorService cancellers = Executors.newSingleThreadExecutor();
+ ScheduledExecutorService retries = Executors.newSingleThreadScheduledExecutor();
+ Semaphore slots = new Semaphore(1);
+ ExecutorService flaky = mock(ExecutorService.class);
+ AtomicBoolean first = new AtomicBoolean(true);
+ doAnswer(
+ invocation -> {
+ if (first.getAndSet(false)) {
+ throw new RejectedExecutionException("temporary handoff rejection");
+ }
+ cancellers.execute(invocation.getArgument(0));
+ return null;
+ })
+ .when(flaky)
+ .execute(any());
+ CountDownLatch entered = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ CountDownLatch interrupted = new CountDownLatch(1);
+ Driver driver = mock(Driver.class);
+ when(driver.connect(anyString(), any()))
+ .thenAnswer(
+ invocation -> {
+ entered.countDown();
+ try {
+ release.await();
+ } catch (InterruptedException e) {
+ interrupted.countDown();
+ throw new SQLException("interrupted connect", e);
+ }
+ return null;
+ });
+ BoundedConnectionDriver bounded =
+ new BoundedConnectionDriver(driver, 500, workers, flaky, retries, slots);
+ try {
+ assertThrows(SQLTimeoutException.class, () -> bounded.connect("jdbc:test", new Properties()));
+ assertTrue(entered.await(10, TimeUnit.SECONDS));
+ assertTrue(interrupted.await(5, TimeUnit.SECONDS), "A transient rejection must be retried");
+ workers.submit(() -> {}).get(10, TimeUnit.SECONDS);
+ verify(flaky, times(2)).execute(any());
+ Awaitility.await().atMost(Duration.ofSeconds(10)).until(() -> slots.availablePermits() == 1);
+ doReturn(null).when(driver).connect(anyString(), any());
+ assertNull(bounded.connect("jdbc:test", new Properties()));
+ } finally {
+ release.countDown();
+ retries.shutdownNow();
+ assertTrue(retries.awaitTermination(10, TimeUnit.SECONDS));
+ cancellers.shutdownNow();
+ assertTrue(cancellers.awaitTermination(10, TimeUnit.SECONDS));
+ }
+ }
+
+ @Test
+ void testRejectedCancellationStillClosesLateConnection() throws Exception {
+ Driver driver = mock(Driver.class);
+ Connection late = mock(Connection.class);
+ CountDownLatch entered = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ AtomicReference<Boolean> interrupted = new AtomicReference<>(false);
+ when(driver.connect(anyString(), any()))
+ .thenAnswer(
+ invocation -> {
+ entered.countDown();
+ try {
+ release.await();
+ } catch (InterruptedException e) {
+ interrupted.set(true);
+ throw new SQLException("Unexpected caller-thread cancellation", e);
+ }
+ return late;
+ });
+ ExecutorService rejected = mock(ExecutorService.class);
+ doThrow(new RejectedExecutionException("cancellation pool full")).when(rejected).execute(any());
+ BlockingQueue<Runnable> pending = new LinkedBlockingQueue<>();
+ List<Long> delays = new ArrayList<>();
+ ScheduledExecutorService retries = manualRetries(pending, delays);
+ Semaphore slots = new Semaphore(1);
+ BoundedConnectionDriver bounded =
+ new BoundedConnectionDriver(driver, 500, workers, rejected, retries, slots);
+ try {
+ assertThrows(SQLTimeoutException.class, () -> bounded.connect("jdbc:test", new Properties()));
+ assertTrue(entered.await(10, TimeUnit.SECONDS));
+ assertEquals(0, slots.availablePermits());
+ for (int i = 0; i < 3; i++) {
+ takeRetry(pending).run();
+ }
+ assertEquals(List.of(10L, 20L, 40L), delays);
+ assertEquals(1, slots.availablePermits());
+ assertTrue(pending.isEmpty());
+ verify(rejected, times(4)).execute(any());
+ assertThrows(
+ SQLTransientConnectionException.class,
+ () -> bounded.connect("jdbc:test", new Properties()));
+ } finally {
+ release.countDown();
+ }
+ workers.submit(() -> {}).get(10, TimeUnit.SECONDS);
+ assertFalse(interrupted.get(), "Rejected cancellation must not fall back to the caller");
+ verify(late).close();
+ doReturn(null).when(driver).connect(anyString(), any());
+ assertNull(bounded.connect("jdbc:test", new Properties()));
+ }
+
+ @Test
+ void testRetryCapacityIsBoundedAndReleasedWhenAttemptFinishes() throws Exception {
+ ExecutorService rejected = mock(ExecutorService.class);
+ doThrow(new RejectedExecutionException("cancellation pool full")).when(rejected).execute(any());
+ BlockingQueue<Runnable> pending = new LinkedBlockingQueue<>();
+ ScheduledExecutorService retries = manualRetries(pending, new ArrayList<>());
+ Semaphore slots = new Semaphore(1);
+ ExecutorService otherWorkers = Executors.newSingleThreadExecutor();
+ CountDownLatch release = new CountDownLatch(1);
+ Driver driver = mock(Driver.class);
+ when(driver.connect(anyString(), any()))
+ .thenAnswer(
+ invocation -> {
+ release.await();
+ return null;
+ });
+ BoundedConnectionDriver first =
+ new BoundedConnectionDriver(driver, 500, workers, rejected, retries, slots);
+ BoundedConnectionDriver second =
+ new BoundedConnectionDriver(driver, 500, otherWorkers, rejected, retries, slots);
+ try {
+ assertThrows(SQLTimeoutException.class, () -> first.connect("jdbc:test", new Properties()));
+ assertThrows(SQLTimeoutException.class, () -> second.connect("jdbc:test", new Properties()));
+ assertEquals(0, slots.availablePermits());
+ assertEquals(1, pending.size(), "Retry admission must bound retained attempts");
+ verify(rejected, times(2)).execute(any());
+ assertThrows(
+ SQLTransientConnectionException.class,
+ () -> second.connect("jdbc:test", new Properties()));
+ release.countDown();
+ workers.submit(() -> {}).get(10, TimeUnit.SECONDS);
+ otherWorkers.submit(() -> {}).get(10, TimeUnit.SECONDS);
+ takeRetry(pending).run();
+ assertEquals(1, slots.availablePermits());
+ assertTrue(pending.isEmpty());
+ verify(rejected, times(2)).execute(any());
+ } finally {
+ release.countDown();
+ otherWorkers.shutdownNow();
+ assertTrue(otherWorkers.awaitTermination(10, TimeUnit.SECONDS));
+ }
+ }
+
+ @Test
+ void testObsoleteRetryDoesNotInterruptNextAttempt() throws Exception {
+ BlockingQueue<Runnable> pending = new LinkedBlockingQueue<>();
+ ScheduledExecutorService retries = manualRetries(pending, new ArrayList<>());
+ Semaphore slots = new Semaphore(1);
+ ExecutorService rejected = mock(ExecutorService.class);
+ doThrow(new RejectedExecutionException("temporary rejection")).when(rejected).execute(any());
+ CountDownLatch firstRelease = new CountDownLatch(1);
+ CountDownLatch secondEntered = new CountDownLatch(1);
+ CountDownLatch secondRelease = new CountDownLatch(1);
+ Connection late = mock(Connection.class);
+ Connection healthy = mock(Connection.class);
+ Driver driver = mock(Driver.class);
+ when(driver.connect(anyString(), any()))
+ .thenAnswer(
+ invocation -> {
+ firstRelease.await();
+ return late;
+ })
+ .thenAnswer(
+ invocation -> {
+ secondEntered.countDown();
+ secondRelease.await();
+ return healthy;
+ });
+ BoundedConnectionDriver bounded =
+ new BoundedConnectionDriver(driver, 500, workers, rejected, retries, slots);
+ ExecutorService callers = Executors.newSingleThreadExecutor();
+ try {
+ assertThrows(SQLTimeoutException.class, () -> bounded.connect("jdbc:test", new Properties()));
+ firstRelease.countDown();
+ workers.submit(() -> {}).get(10, TimeUnit.SECONDS);
+ verify(late).close();
+ Future<Connection> next =
+ callers.submit(() -> bounded.connect("jdbc:test", new Properties()));
+ assertTrue(secondEntered.await(10, TimeUnit.SECONDS));
+ takeRetry(pending).run();
+ verify(rejected, times(1)).execute(any());
+ assertEquals(1, slots.availablePermits());
+ secondRelease.countDown();
+ assertSame(healthy, next.get(10, TimeUnit.SECONDS));
+ } finally {
+ firstRelease.countDown();
+ secondRelease.countDown();
+ callers.shutdownNow();
+ assertTrue(callers.awaitTermination(10, TimeUnit.SECONDS));
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void testRejectedRetryScheduleReleasesCapacity(boolean rejectReschedule) throws Exception {
+ BlockingQueue<Runnable> pending = new LinkedBlockingQueue<>();
+ ScheduledExecutorService retries = manualRetries(pending, new ArrayList<>());
+ if (!rejectReschedule) {
+ doThrow(new RejectedExecutionException("retry dispatcher stopped"))
+ .when(retries)
+ .schedule(any(Runnable.class), anyLong(), eq(TimeUnit.MILLISECONDS));
+ }
+ ExecutorService rejected = mock(ExecutorService.class);
+ doThrow(new RejectedExecutionException("cancellation pool full")).when(rejected).execute(any());
+ Semaphore slots = new Semaphore(1);
+ CountDownLatch release = new CountDownLatch(1);
+ Driver driver = mock(Driver.class);
+ when(driver.connect(anyString(), any()))
+ .thenAnswer(
+ invocation -> {
+ release.await();
+ return null;
+ });
+ BoundedConnectionDriver bounded =
+ new BoundedConnectionDriver(driver, 500, workers, rejected, retries, slots);
+ try {
+ assertThrows(SQLTimeoutException.class, () -> bounded.connect("jdbc:test", new Properties()));
+ if (rejectReschedule) {
+ doThrow(new RejectedExecutionException("retry dispatcher stopped"))
+ .when(retries)
+ .schedule(any(Runnable.class), anyLong(), eq(TimeUnit.MILLISECONDS));
+ takeRetry(pending).run();
+ }
+ assertEquals(1, slots.availablePermits());
+ assertTrue(pending.isEmpty());
+ assertThrows(
+ SQLTransientConnectionException.class,
+ () -> bounded.connect("jdbc:test", new Properties()));
+ } finally {
+ release.countDown();
+ }
+ workers.submit(() -> {}).get(10, TimeUnit.SECONDS);
+ doReturn(null).when(driver).connect(anyString(), any());
+ assertNull(bounded.connect("jdbc:test", new Properties()));
+ }
+
@Test
void testLateCloseFailureDoesNotPinContextOrQuarantine() throws Exception {
Driver driver = mock(Driver.class);
@@ -528,6 +1310,25 @@ class TestBoundedConnectionDriver {
verify(late).close();
}
+ private static ScheduledExecutorService manualRetries(
+ BlockingQueue<Runnable> pending, List<Long> delays) {
+ ScheduledExecutorService retries = mock(ScheduledExecutorService.class);
+ when(retries.schedule(any(Runnable.class), anyLong(), eq(TimeUnit.MILLISECONDS)))
+ .thenAnswer(
+ invocation -> {
+ delays.add(invocation.getArgument(1));
+ pending.add(invocation.getArgument(0));
+ return mock(ScheduledFuture.class);
+ });
+ return retries;
+ }
+
+ private static Runnable takeRetry(BlockingQueue<Runnable> pending) throws InterruptedException {
+ Runnable retry = pending.poll(10, TimeUnit.SECONDS);
+ assertNotNull(retry, "A rejected cancellation must have a pending retry");
+ return retry;
+ }
+
private static void awaitIgnoringInterrupts(CountDownLatch latch) {
boolean interrupted = false;
while (true) {
diff --git a/docs/jdbc-catalog-connection-validation.md b/docs/jdbc-catalog-connection-validation.md
index e8e7a7d9d1..199769c43e 100644
--- a/docs/jdbc-catalog-connection-validation.md
+++ b/docs/jdbc-catalog-connection-validation.md
@@ -123,23 +123,44 @@ existing connector is automatically switched to this adapter by this addition.
Only `Driver.connect` runs on a worker. Metadata, validation and SQL remain on the caller;
this does not introduce delayed DDL or an automatic retry. A connection returned after
timeout/interruption is closed by the worker and never handed to the caller or pool.
-While an abandoned attempt is still connecting or closing, new attempts through that wrapper
-fail immediately. Pool waits, connection validation, SQL and total request duration retain
+While an abandoned attempt is connecting, waiting for an in-flight interrupt callback, or closing,
+new attempts through that wrapper fail immediately. Pool waits, connection validation, SQL and total request duration retain
their own budgets.
-The core-loaded adapter shares at most 64 daemon workers per server JVM, with no queue.
-Saturation fails new connects with `SQLTransientConnectionException`, including otherwise
-healthy connects. Cancellation is best effort: an uninterruptible driver or close can retain
-a worker and its driver resources until it returns or the server restarts. Completed workers
+The core-loaded adapter shares at most 64 daemon connection workers and 64 daemon cancellation
+threads per server JVM, with no queue in either pool. A single additional daemon thread dispatches
+bounded cancellation retries without running driver code. Saturation fails new connects with `SQLTransientConnectionException`, including otherwise
+healthy connects. An abandoned attempt's worker is interrupted from a separate cancellation thread,
+not the cancelling caller, because a driver's interrupt callback can block synchronously; the
+interrupt is delivered only while the worker is still connecting. It releases the worker only from
+interruptible waits: blocking `java.net` socket I/O is not interruptible on JDK 17, so a driver
+blocked in a socket connect or read keeps its worker until its own socket timeout, and a driver or
+close that never returns keeps it until the server restarts.
+Abandoned and completed-after-abandonment attempts are logged at INFO; worker-admission rejections
+are aggregated into at most one WARN log line a minute. A rejected cancellation can be submitted up to three more times, after delays of 10, 20 and 40 ms,
+with at most 64 attempts pending retry across the adapter. Only cancellation admission is retried;
+`Driver.connect` and SQL are never replayed. The retry dispatcher never interrupts a worker itself.
+Retries stop when the driver returns. Retry exhaustion, full retry capacity or a rejected retry
+schedule is logged at WARN. Its worker remains quarantined until the driver and cleanup return;
+if they never return, recovery requires a server restart. Cancellation is best-effort, not
+forced thread termination. Completed workers
restore their context class loader. The adapter does not bound arbitrary driver constructor
work or clean up driver-owned global threads.
-Each attempt and its late connection cleanup use the submitting caller's access-control
-context and JAAS subject. Shared workers are created without inheriting the first caller's
-subject, so reusing a worker does not reuse that caller's JAAS subject.
+Each attempt, its driver interrupt callback, and its late connection cleanup use the submitting
+caller's access-control context, JAAS subject, and context class loader. Cancellation threads
+restore their prior context after the callback. Interrupts consumed while waiting for cancellation
+are restored after connection cleanup. Shared workers are created without inheriting the first
+caller's subject, so reusing a worker does not reuse that caller's JAAS subject.
This guarantee covers access-control contexts and JAAS subjects, not arbitrary `ThreadLocal`
or `InheritableThreadLocal` state. Drivers using the shared workers must clean up their own
thread-local state and must not depend on inherited thread locals for caller authentication.
Drivers that cannot meet these requirements must not opt into this adapter. Isolating workers
by catalog alone would not isolate different users of the same catalog.
+
+A JDBC catalog whose driver does not enforce a login timeout can also bound its runtime physical
+connections with this adapter by overriding `JdbcCatalogOperations#configureDataSource` and
+installing it as the data source's driver. The hook must not borrow connections, start the pool,
+retain the data source, or change its validated URL, credentials and pool settings. Pool waits, SQL
+execution and tree-lock acquisition are separate from this physical connection deadline.