Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/source/flight_sql_jdbc_driver.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
========================

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,53 +104,50 @@ 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(
final ArrowFlightConnectionConfigImpl config,
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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,27 @@

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;
import java.io.InputStreamReader;
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;
Expand Down Expand Up @@ -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);
Expand All @@ -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<ArrowFlightConnection> connect, final int timeoutSeconds) throws SQLException {
final CompletableFuture<ArrowFlightConnection> 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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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());
Expand All @@ -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);
}
}

/**
Expand Down Expand Up @@ -1125,6 +1131,7 @@ public ArrowFlightSqlClientHandler build() throws SQLException {
// itself.
Set<FlightClientMiddleware.Factory> buildTimeMiddlewareFactories =
new HashSet<>(this.middlewareFactories);
ManagedChannel channel = null;
FlightClient client = null;
boolean isUsingUserPasswordAuth = username != null && token == null;

Expand Down Expand Up @@ -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<CallOption> credentialOptions = new ArrayList<>();
// Authentication priority: OAuth > token > username/password
if (oauthConfig != null) {
Expand Down Expand Up @@ -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);
}
}
}
Expand Down
Loading
Loading