jerryshao commented on code in PR #14763:
URL: https://github.com/apache/gravitino/pull/14763#discussion_r4509207840


##########
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:
   If the canceller pool rejects the task, the worker is never interrupted and 
nothing retries, which is the exact leak this PR is meant to fix; the 64-thread 
cap can be reached when interrupt() blocks in a driver callback. Fall back to a 
bounded retry, or a dedicated single reaper thread, and add a test for this 
path.



##########
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 default hook is a no-op and no connector overrides it, so 
BoundedConnectionDriver is not used anywhere in production. Is wiring it into a 
connector planned in a follow-up, and should it be in scope for this 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:
   This WARN is logged for every abandoned attempt and is not rate limited, 
unlike the rejection log. Against an unreachable backend it can flood the logs; 
log at INFO or throttle it.



##########
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:
   endConnect swallows any InterruptedException, including interrupts that do 
not come from cancel() such as pool shutdown. Restore the interrupt flag if 
cancelling was not the cause.



-- 
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]

Reply via email to