yuqi1129 commented on code in PR #14763:
URL: https://github.com/apache/gravitino/pull/14763#discussion_r4509323936
##########
core/src/main/java/org/apache/gravitino/utils/BoundedConnectionDriver.java:
##########
@@ -218,24 +223,111 @@ public java.util.logging.Logger getParentLogger() throws
SQLFeatureNotSupportedE
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<>(),
+ 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 boolean connecting;
+ private boolean cancelling;
synchronized void accept() {
accepted = true;
}
- synchronized void abandon() {
- if (!finished) {
+ void abandon() {
+ synchronized (this) {
+ if (finished) {
+ return;
+ }
abandoned = true;
abandonedAttempts.incrementAndGet();
- if (runner != null) {
- runner.interrupt();
+ }
+ LOG.warn(
+ "Abandoned a {} connection attempt (deadline {} ms); interrupting
its worker if it is "
+ + "still connecting",
+ driverName(),
+ timeoutMs);
+ try {
+ // 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.
+ cancellers.execute(this::cancel);
+ } catch (RejectedExecutionException e) {
+ LOG.warn("Could not schedule interruption of an abandoned JDBC
connection attempt", e);
Review Comment:
Fixed in bf0bff518c. A rejected cancellation submission now gets at most
three additional submissions after 10/20/40 ms delays. A single daemon
dispatcher only submits to the cancellation pool; it never calls interrupt or
driver code. Admission is bounded to 64 pending attempts, obsolete attempts are
dropped, and retry capacity is released on acceptance, exhaustion or scheduling
failure. Connect and SQL are never replayed.
Added coverage for transient rejection actually releasing the worker and
clearing quarantine (the regression fails before the fix), persistent
rejection, retry-capacity saturation, initial/rescheduled dispatcher rejection,
stale retries after worker reuse and caller context through a retried interrupt
callback. Permanently blocked drivers/callbacks still cannot be forcibly
terminated; final admission failure warns and retains quarantine until cleanup
finishes.
##########
core/src/main/java/org/apache/gravitino/utils/BoundedConnectionDriver.java:
##########
@@ -218,24 +223,111 @@ public java.util.logging.Logger getParentLogger() throws
SQLFeatureNotSupportedE
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<>(),
+ 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 boolean connecting;
+ private boolean cancelling;
synchronized void accept() {
accepted = true;
}
- synchronized void abandon() {
- if (!finished) {
+ void abandon() {
+ synchronized (this) {
+ if (finished) {
+ return;
+ }
abandoned = true;
abandonedAttempts.incrementAndGet();
- if (runner != null) {
- runner.interrupt();
+ }
+ LOG.warn(
+ "Abandoned a {} connection attempt (deadline {} ms); interrupting
its worker if it is "
+ + "still connecting",
+ driverName(),
+ timeoutMs);
+ try {
+ // 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.
+ cancellers.execute(this::cancel);
+ } catch (RejectedExecutionException e) {
+ LOG.warn("Could not schedule interruption of an abandoned JDBC
connection attempt", e);
+ }
+ }
+
+ /** 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; waits for an in-flight interrupt to be
delivered. */
+ private synchronized void endConnect() {
+ connecting = false;
+ while (cancelling) {
+ try {
+ wait();
Review Comment:
Fixed. endConnect now records interrupts consumed by the in-flight
cancellation barrier and restores the worker's interrupt flag after late
connection cleanup. Deferring restoration lets interrupt-sensitive close
complete while preserving external/shutdown interruption for the executor. The
regression injects an additional interrupt while the worker is waiting at that
barrier, verifies cleanup sees a clear flag, and verifies the signal is
restored afterward; it fails before the fix.
##########
core/src/main/java/org/apache/gravitino/utils/BoundedConnectionDriver.java:
##########
@@ -218,24 +223,111 @@ public java.util.logging.Logger getParentLogger() throws
SQLFeatureNotSupportedE
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<>(),
+ 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 boolean connecting;
+ private boolean cancelling;
synchronized void accept() {
accepted = true;
}
- synchronized void abandon() {
- if (!finished) {
+ void abandon() {
+ synchronized (this) {
+ if (finished) {
+ return;
+ }
abandoned = true;
abandonedAttempts.incrementAndGet();
- if (runner != null) {
- runner.interrupt();
+ }
+ LOG.warn(
+ "Abandoned a {} connection attempt (deadline {} ms); interrupting
its worker if it is "
Review Comment:
Changed the per-attempt abandonment and completion messages to INFO.
Worker-admission rejection warnings remain aggregated to at most one report per
minute. Cancellation admission now warns only when bounded retry
admission/scheduling fails or retries are exhausted; an initial rejection
recovered by retry does not emit that warning.
##########
catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/JdbcCatalogOperations.java:
##########
@@ -189,6 +195,29 @@ public void initialize(
}
}
+ /**
+ * 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, and must not 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)
{}
Review Comment:
The hook has a concrete downstream connector consumer that overrides it to
install BoundedConnectionDriver before the lazy DBCP pool's first borrow. I
have kept it in this PR and clarified the use case in the description. The
datasource is private, and replacing its driver after the first borrow is
ineffective, so the connector needs this initialization point before
driver-version probes or operation initialization can borrow a connection.
Bundled connectors keep their existing driver timeouts; enabling the adapter
for them requires driver-specific validation of its threading/context
requirements. The hook remains protected and default-no-op. Its Javadoc
specifies ownership and configuration constraints, and tests verify
first-borrow ordering, actual use of the installed driver, unchanged default
behavior, and failure cleanup with metrics enabled/disabled.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]