jerryshao commented on code in PR #14763:
URL: https://github.com/apache/gravitino/pull/14763#discussion_r4510042135
##########
core/src/main/java/org/apache/gravitino/utils/BoundedConnectionDriver.java:
##########
@@ -218,28 +249,207 @@ 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<>(),
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) {
Review Comment:
If the driver's interrupt callback blocks (the case this PR targets), the
worker waits here and cannot close a late connection that connect() already
returned. Is it intended that this connection stays open until the interrupt
returns, and is that documented?
--
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]