From f35a8ff726143bfeb7c44e486ef888cb9103cee7 Mon Sep 17 00:00:00 2001 From: Abhishek Prajapati <215712201+Ap-95671@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:52:06 +0530 Subject: [PATCH] GH-1268: [JDBC] Honor DriverManager login timeout Bound Flight SQL login, cancel in-flight connection setup when the deadline expires, and close resources from failed or abandoned attempts. Assisted-by: Codex --- docs/source/flight_sql_jdbc_driver.rst | 7 + .../driver/jdbc/ArrowFlightConnection.java | 77 +++++------ .../jdbc/ArrowFlightJdbcDataSource.java | 2 +- .../driver/jdbc/ArrowFlightJdbcDriver.java | 91 ++++++++++++- .../client/ArrowFlightSqlClientHandler.java | 48 ++++--- .../jdbc/ArrowFlightJdbcDriverTest.java | 126 +++++++++++++++++- .../ArrowFlightSqlClientHandlerTest.java | 3 + 7 files changed, 293 insertions(+), 61 deletions(-) diff --git a/docs/source/flight_sql_jdbc_driver.rst b/docs/source/flight_sql_jdbc_driver.rst index fe731fcaaf..a685e2a799 100644 --- a/docs/source/flight_sql_jdbc_driver.rst +++ b/docs/source/flight_sql_jdbc_driver.rst @@ -195,6 +195,13 @@ DriverManager#getConnection() the username and password supplied on the URI supercede the username and password arguments to the function call. +Use ``DriverManager.setLoginTimeout(seconds)`` to limit the time the driver +waits for a connection, including the authentication handshake and initial +session setup. On expiration, the driver cancels pending login RPCs and throws +``SQLTimeoutException``. A value of zero disables the login timeout. The +``connectTimeoutMs`` property separately controls the Netty socket connection +timeout. + OAuth 2.0 Authentication ======================== diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java index 3662230678..5338bfdc8a 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java @@ -104,12 +104,18 @@ static ArrowFlightConnection createNewConnection( final Properties properties, final BufferAllocator allocator) throws SQLException { - url = replaceSemiColons(url); - final ArrowFlightConnectionConfigImpl config = new ArrowFlightConnectionConfigImpl(properties); - final ArrowFlightSqlClientHandler clientHandler = - createNewClientHandler(config, allocator, driver.getDriverVersion()); - return new ArrowFlightConnection( - driver, factory, url, properties, config, allocator, clientHandler); + ArrowFlightSqlClientHandler clientHandler = null; + try { + url = replaceSemiColons(url); + final ArrowFlightConnectionConfigImpl config = + new ArrowFlightConnectionConfigImpl(properties); + clientHandler = createNewClientHandler(config, allocator, driver.getDriverVersion()); + return new ArrowFlightConnection( + driver, factory, url, properties, config, allocator, clientHandler); + } catch (SQLException | RuntimeException | Error e) { + AutoCloseables.close(e, clientHandler, allocator); + throw e; + } } private static ArrowFlightSqlClientHandler createNewClientHandler( @@ -117,40 +123,31 @@ private static ArrowFlightSqlClientHandler createNewClientHandler( final BufferAllocator allocator, final DriverVersion driverVersion) throws SQLException { - try { - return new ArrowFlightSqlClientHandler.Builder() - .withHost(config.getHost()) - .withPort(config.getPort()) - .withUsername(config.getUser()) - .withPassword(config.getPassword()) - .withTrustStorePath(config.getTrustStorePath()) - .withTrustStorePassword(config.getTrustStorePassword()) - .withSystemTrustStore(config.useSystemTrustStore()) - .withTlsRootCertificates(config.getTlsRootCertificatesPath()) - .withClientCertificate(config.getClientCertificatePath()) - .withClientKey(config.getClientKeyPath()) - .withBufferAllocator(allocator) - .withEncryption(config.useEncryption()) - .withDisableCertificateVerification(config.getDisableCertificateVerification()) - .withHostnameOverride(config.getHostnameOverride()) - .withToken(config.getToken()) - .withCallOptions(config.toCallOption()) - .withRetainCookies(config.retainCookies()) - .withRetainAuth(config.retainAuth()) - .withCatalog(config.getCatalog()) - .withClientCache(config.useClientCache() ? new FlightClientCache() : null) - .withConnectTimeout(config.getConnectTimeout()) - .withDriverVersion(driverVersion) - .withOAuthConfiguration(config.getOauthConfiguration()) - .build(); - } catch (final SQLException e) { - try { - allocator.close(); - } catch (final Exception allocatorCloseEx) { - e.addSuppressed(allocatorCloseEx); - } - throw e; - } + return new ArrowFlightSqlClientHandler.Builder() + .withHost(config.getHost()) + .withPort(config.getPort()) + .withUsername(config.getUser()) + .withPassword(config.getPassword()) + .withTrustStorePath(config.getTrustStorePath()) + .withTrustStorePassword(config.getTrustStorePassword()) + .withSystemTrustStore(config.useSystemTrustStore()) + .withTlsRootCertificates(config.getTlsRootCertificatesPath()) + .withClientCertificate(config.getClientCertificatePath()) + .withClientKey(config.getClientKeyPath()) + .withBufferAllocator(allocator) + .withEncryption(config.useEncryption()) + .withDisableCertificateVerification(config.getDisableCertificateVerification()) + .withHostnameOverride(config.getHostnameOverride()) + .withToken(config.getToken()) + .withCallOptions(config.toCallOption()) + .withRetainCookies(config.retainCookies()) + .withRetainAuth(config.retainAuth()) + .withCatalog(config.getCatalog()) + .withClientCache(config.useClientCache() ? new FlightClientCache() : null) + .withConnectTimeout(config.getConnectTimeout()) + .withDriverVersion(driverVersion) + .withOAuthConfiguration(config.getOauthConfiguration()) + .build(); } void reset() throws SQLException { diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDataSource.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDataSource.java index 0b5d7fd368..068062a053 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDataSource.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDataSource.java @@ -87,7 +87,7 @@ public ArrowFlightConnection getConnection() throws SQLException { public ArrowFlightConnection getConnection(final String username, final String password) throws SQLException { final Properties properties = getProperties(username, password); - return new ArrowFlightJdbcDriver().connect(config.url(), properties); + return new ArrowFlightJdbcDriver().connect(config.url(), properties, 0); } @Override diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDriver.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDriver.java index 12ef8030d7..99d3b58156 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDriver.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDriver.java @@ -18,6 +18,7 @@ import static org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty.replaceSemiColons; +import io.grpc.Context; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -25,11 +26,19 @@ import java.io.Reader; import java.net.URI; import java.nio.charset.StandardCharsets; +import java.sql.DriverManager; import java.sql.SQLException; +import java.sql.SQLTimeoutException; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Properties; +import java.util.concurrent.Callable; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.logging.Level; import java.util.logging.Logger; import org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty; import org.apache.arrow.driver.jdbc.utils.UrlParser; @@ -74,6 +83,11 @@ public Logger getParentLogger() { @Override public ArrowFlightConnection connect(final String url, final Properties info) throws SQLException { + return connect(url, info, DriverManager.getLoginTimeout()); + } + + ArrowFlightConnection connect(final String url, final Properties info, final int timeoutSeconds) + throws SQLException { final Properties properties = new Properties(info); if (info != null) { properties.putAll(info); @@ -88,14 +102,89 @@ public ArrowFlightConnection connect(final String url, final Properties info) properties.putAll(propertiesFromUrl); } + final Properties connectionProperties = lowerCasePropertyKeys(properties); + if (timeoutSeconds <= 0) { + return openConnection(url, connectionProperties); + } + return connectWithTimeout(() -> openConnection(url, connectionProperties), timeoutSeconds); + } + + private ArrowFlightConnection openConnection(final String url, final Properties properties) + throws SQLException { try { return ArrowFlightConnection.createNewConnection( - this, factory, url, lowerCasePropertyKeys(properties), new RootAllocator(Long.MAX_VALUE)); + this, factory, url, properties, new RootAllocator(Long.MAX_VALUE)); } catch (final FlightRuntimeException e) { throw new SQLException("Failed to connect.", e); } } + @VisibleForTesting + static ArrowFlightConnection connectWithTimeout( + final Callable connect, final int timeoutSeconds) throws SQLException { + final CompletableFuture result = new CompletableFuture<>(); + // Closing the context cancels any in-flight login RPCs. + try (Context.CancellableContext context = Context.current().withCancellation()) { + final Thread worker = + new Thread( + context.wrap( + () -> { + if (result.isDone()) { + return; + } + try { + final ArrowFlightConnection connection = connect.call(); + // A timed-out attempt still owns any connection it manages to open. + if (!result.complete(connection)) { + closeAbandonedConnection(connection); + } + } catch (Exception | Error e) { + result.completeExceptionally(e); + } + }), + "arrow-flight-jdbc-connect"); + worker.setDaemon(true); + result.orTimeout(timeoutSeconds, TimeUnit.SECONDS); + worker.start(); + + try { + return result.get(); + } catch (InterruptedException e) { + if (!result.completeExceptionally(e)) { + result.thenAcceptAsync( + connection -> context.run(() -> closeAbandonedConnection(connection))); + } + Thread.currentThread().interrupt(); + throw new SQLException("Interrupted while connecting.", e); + } catch (ExecutionException e) { + final Throwable cause = e.getCause(); + if (cause instanceof TimeoutException) { + throw new SQLTimeoutException( + "Login timed out after " + timeoutSeconds + " seconds.", cause); + } + if (cause instanceof SQLException sqlException) { + throw sqlException; + } + if (cause instanceof RuntimeException runtimeException) { + throw runtimeException; + } + if (cause instanceof Error error) { + throw error; + } + throw new SQLException("Failed to connect.", cause); + } + } + } + + private static void closeAbandonedConnection(final ArrowFlightConnection connection) { + try { + connection.close(); + } catch (SQLException | RuntimeException e) { + Logger.getLogger(ArrowFlightJdbcDriver.class.getPackageName()) + .log(Level.WARNING, "Failed to close an abandoned flight SQL connection.", e); + } + } + @Override protected String getFactoryClassName(final JdbcVersion jdbcVersion) { return ArrowFlightJdbcFactory.class.getName(); diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java index 97108e599b..9c168126a4 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java @@ -17,6 +17,7 @@ package org.apache.arrow.driver.jdbc.client; import com.google.common.collect.ImmutableMap; +import io.grpc.ManagedChannel; import io.grpc.netty.NettyChannelBuilder; import io.netty.channel.ChannelOption; import java.io.IOException; @@ -291,6 +292,19 @@ public long executeUpdate(final String query) { @Override public void close() throws SQLException { + try { + AutoCloseables.close(this::closeCatalogSession, sqlClient); + } catch (FlightRuntimeException fre) { + handleBenignCloseException( + fre, "Failed to clean up client resources.", "closing Flight SQL client"); + } catch (SQLException e) { + throw e; + } catch (final Exception e) { + throw new SQLException("Failed to clean up client resources.", e); + } + } + + private void closeCatalogSession() throws SQLException { if (catalog.isPresent()) { try { sqlClient.closeSession(new CloseSessionRequest(), getOptions()); @@ -299,14 +313,6 @@ public void close() throws SQLException { fre, "Failed to close Flight SQL session.", "closing Flight SQL session"); } } - try { - AutoCloseables.close(sqlClient); - } catch (FlightRuntimeException fre) { - handleBenignCloseException( - fre, "Failed to clean up client resources.", "closing Flight SQL client"); - } catch (final Exception e) { - throw new SQLException("Failed to clean up client resources.", e); - } } /** @@ -1125,6 +1131,7 @@ public ArrowFlightSqlClientHandler build() throws SQLException { // itself. Set buildTimeMiddlewareFactories = new HashSet<>(this.middlewareFactories); + ManagedChannel channel = null; FlightClient client = null; boolean isUsingUserPasswordAuth = username != null && token == null; @@ -1192,9 +1199,8 @@ public ArrowFlightSqlClientHandler build() throws SQLException { channelBuilder.withOption( ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) connectTimeout.toMillis()); } - client = - FlightGrpcUtils.createFlightClient( - allocator, channelBuilder.build(), clientBuilder.middleware()); + channel = channelBuilder.build(); + client = FlightGrpcUtils.createFlightClient(allocator, channel, clientBuilder.middleware()); final ArrayList credentialOptions = new ArrayList<>(); // Authentication priority: OAuth > token > username/password if (oauthConfig != null) { @@ -1229,14 +1235,20 @@ public ArrowFlightSqlClientHandler build() throws SQLException { | IOException | FlightRuntimeException e) { final SQLException originalException = new SQLException(e); - if (client != null) { - try { - client.close(); - } catch (final InterruptedException interruptedException) { - originalException.addSuppressed(interruptedException); - } - } + closeFailedClient(originalException, client, channel); throw originalException; + } catch (RuntimeException | Error e) { + closeFailedClient(e, client, channel); + throw e; + } + } + + private static void closeFailedClient( + Throwable failure, @Nullable FlightClient client, @Nullable ManagedChannel channel) { + if (client != null) { + AutoCloseables.close(failure, client); + } else if (channel != null) { + AutoCloseables.close(failure, channel::shutdownNow); } } } diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDriverTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDriverTest.java index 88fb9889b6..878cff2d29 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDriverTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDriverTest.java @@ -21,24 +21,42 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; - +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.verify; + +import io.grpc.Attributes; +import io.grpc.MethodDescriptor; +import io.grpc.Server; +import io.grpc.ServerBuilder; +import io.grpc.ServerCall; +import io.grpc.ServerServiceDefinition; +import io.grpc.ServerTransportFilter; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.SQLException; +import java.sql.SQLTimeoutException; import java.util.Collection; import java.util.Map; import java.util.Properties; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import org.apache.arrow.driver.jdbc.authentication.UserPasswordAuthentication; import org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty; import org.apache.arrow.driver.jdbc.utils.MockFlightSqlProducer; +import org.apache.arrow.flight.impl.FlightServiceGrpc; import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.memory.RootAllocator; import org.apache.arrow.util.AutoCloseables; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.parallel.ResourceLock; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; /** Tests for {@link ArrowFlightJdbcDriver}. */ public class ArrowFlightJdbcDriverTest { @@ -91,6 +109,112 @@ public void testDriverIsRegisteredInDriverManager() throws Exception { instanceof ArrowFlightJdbcDriver); } + @ParameterizedTest(name = "connection setup with catalog={0}") + @ValueSource(booleans = {false, true}) + @Timeout(15) + @ResourceLock("DriverManager.loginTimeout") + public void testDriverManagerLoginTimeoutCancelsConnectionSetup(boolean catalog) + throws Exception { + final CountDownLatch loginRpcStarted = new CountDownLatch(1); + final CountDownLatch loginRpcCancelled = new CountDownLatch(1); + final CountDownLatch transportClosed = new CountDownLatch(1); + final MethodDescriptor loginMethod = + catalog ? FlightServiceGrpc.getDoActionMethod() : FlightServiceGrpc.getHandshakeMethod(); + final Server server = + ServerBuilder.forPort(0) + .addTransportFilter( + new ServerTransportFilter() { + @Override + public void transportTerminated(Attributes transportAttributes) { + transportClosed.countDown(); + } + }) + .addService(stalledLoginService(loginMethod, loginRpcStarted, loginRpcCancelled)) + .build() + .start(); + final int previousTimeout = DriverManager.getLoginTimeout(); + try { + DriverManager.setLoginTimeout(2); + final String url = + "jdbc:arrow-flight-sql://localhost:" + server.getPort() + "?useEncryption=false"; + final Properties properties = new Properties(); + if (catalog) { + properties.setProperty("catalog", "test"); + } else { + properties.setProperty("user", "user"); + properties.setProperty("password", "pass"); + } + // Other tests register additional Arrow drivers, which DriverManager would also try. + final Driver driver = DriverManager.getDriver(url); + assertThrows(SQLTimeoutException.class, () -> driver.connect(url, properties)); + assertEquals(0, loginRpcStarted.getCount(), "The server should have received the login RPC"); + assertTrue(loginRpcCancelled.await(5, TimeUnit.SECONDS), "The login RPC should be cancelled"); + assertTrue(transportClosed.await(5, TimeUnit.SECONDS), "The client channel should close"); + } finally { + DriverManager.setLoginTimeout(previousTimeout); + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + + private static ServerServiceDefinition stalledLoginService( + MethodDescriptor method, + CountDownLatch started, + CountDownLatch cancelled) { + return ServerServiceDefinition.builder(FlightServiceGrpc.SERVICE_NAME) + .addMethod( + method, + (call, headers) -> { + call.request(1); + started.countDown(); + return new ServerCall.Listener() { + @Override + public void onCancel() { + cancelled.countDown(); + } + }; + }) + .build(); + } + + @ParameterizedTest + @ValueSource(ints = {0, 10}) + @ResourceLock("DriverManager.loginTimeout") + public void testDriverManagerConnectsWithLoginTimeout(int loginTimeout) throws Exception { + final int previousTimeout = DriverManager.getLoginTimeout(); + try { + DriverManager.setLoginTimeout(loginTimeout); + final String url = + "jdbc:arrow-flight-sql://localhost:" + + FLIGHT_SERVER_TEST_EXTENSION.getPort() + + "?useEncryption=false"; + try (Connection connection = DriverManager.getConnection(url, "user1", "pass1")) { + assertTrue(connection.isValid(0)); + } + } finally { + DriverManager.setLoginTimeout(previousTimeout); + } + } + + @Test + public void testConnectionCompletedAfterLoginTimeoutIsClosed() throws Exception { + final ArrowFlightConnection connection = mock(ArrowFlightConnection.class); + final CountDownLatch finishConnecting = new CountDownLatch(1); + try { + assertThrows( + SQLTimeoutException.class, + () -> + ArrowFlightJdbcDriver.connectWithTimeout( + () -> { + assertTrue(finishConnecting.await(5, TimeUnit.SECONDS)); + return connection; + }, + 1)); + } finally { + finishConnecting.countDown(); + } + verify(connection, timeout(5000)).close(); + } + /** * Tests whether the {@link ArrowFlightJdbcDriver} returns null when provided with an unsupported * URL prefix. diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerTest.java index b44b310eb5..4d37b91102 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerTest.java @@ -24,6 +24,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -145,6 +146,7 @@ public void testCloseHandlesFlightRuntimeException( } else { assertThrows(SQLException.class, sqlClientHandler::close); } + verify(sqlClient).close(); } private static Object[] testCloseHandlesFlightRuntimeException() { @@ -163,6 +165,7 @@ private static Object[] testCloseHandlesFlightRuntimeException() { new Object[] {false, unavailableError, true}, new Object[] {true, unknownError, false}, new Object[] {false, unknownError, false}, + new Object[] {true, CallStatus.CANCELLED, false}, }; } }