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
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
Expand Down Expand Up @@ -88,30 +87,23 @@ public final class ArrowFlightSqlClientHandler implements AutoCloseable {
@VisibleForTesting
static final CallOption CLOSE_SESSION_TIMEOUT = CallOptions.timeout(5, TimeUnit.SECONDS);

// No session to close: CloseSession is unsupported or unknown, none was created, or the
// client is not (or no longer) authenticated.
private static final Set<FlightStatusCode> NO_SESSION_STATUS_CODES =
EnumSet.of(
FlightStatusCode.UNIMPLEMENTED,
FlightStatusCode.INVALID_ARGUMENT,
FlightStatusCode.NOT_FOUND,
FlightStatusCode.UNAUTHENTICATED);

private final String cacheKey;
private final FlightSqlClient sqlClient;
private final Set<CallOption> options = new HashSet<>();
private final Builder builder;
private final boolean followEndpointLocations;
private final Optional<String> catalog;
private final @Nullable FlightClientCache flightClientCache;
private final ServerSessionTracker sessionTracker;

ArrowFlightSqlClientHandler(
final String cacheKey,
final FlightSqlClient sqlClient,
final Builder builder,
final Collection<CallOption> credentialOptions,
final Optional<String> catalog,
final @Nullable FlightClientCache flightClientCache) {
final @Nullable FlightClientCache flightClientCache,
final ServerSessionTracker sessionTracker) {
this.options.addAll(builder.options);
this.options.addAll(credentialOptions);
this.cacheKey = Preconditions.checkNotNull(cacheKey);
Expand All @@ -120,6 +112,7 @@ public final class ArrowFlightSqlClientHandler implements AutoCloseable {
this.followEndpointLocations = builder.followEndpointLocations;
this.catalog = catalog;
this.flightClientCache = flightClientCache;
this.sessionTracker = Preconditions.checkNotNull(sessionTracker);
}

/**
Expand All @@ -136,10 +129,17 @@ static ArrowFlightSqlClientHandler createNewHandler(
final Builder builder,
final Collection<CallOption> options,
final Optional<String> catalog,
final @Nullable FlightClientCache flightClientCache) {
final @Nullable FlightClientCache flightClientCache,
final ServerSessionTracker sessionTracker) {
final ArrowFlightSqlClientHandler handler =
new ArrowFlightSqlClientHandler(
cacheKey, new FlightSqlClient(client), builder, options, catalog, flightClientCache);
cacheKey,
new FlightSqlClient(client),
builder,
options,
catalog,
flightClientCache,
sessionTracker);
handler.setSetCatalogInSessionIfPresent();
return handler;
}
Expand Down Expand Up @@ -350,8 +350,13 @@ public void close() throws SQLException {
}
}

private void closeSession() throws SQLException {
if (!builder.ownsSession) {
/**
* Closes the server session, if the server may hold one. This is best effort: a server that does
* not support sessions may reject the call, and a session that is not closed expires on the
* server, so a failure is logged and does not fail {@link #close()}.
*/
private void closeSession() {
if (!builder.ownsSession || !sessionTracker.mayHaveSession()) {
return;
}
final CallOption[] baseOptions = getOptions();
Expand All @@ -360,11 +365,10 @@ private void closeSession() throws SQLException {
try {
sqlClient.closeSession(new CloseSessionRequest(), closeSessionOptions);
} catch (FlightRuntimeException fre) {
if (catalog.isEmpty() && NO_SESSION_STATUS_CODES.contains(fre.status().code())) {
logSuppressedCloseException(fre, "closing Flight SQL session");
if (sessionTracker.isSessionOptionsSet() && !isBenignCloseException(fre)) {
LOGGER.warn("Failed to close Flight SQL session", fre);
} else {
handleBenignCloseException(
fre, "Failed to close Flight SQL session.", "closing Flight SQL session");
logSuppressedCloseException(fre, "closing Flight SQL session");
}
}
}
Expand Down Expand Up @@ -510,6 +514,8 @@ public void setCatalog(final String catalog) throws SQLException {
ImmutableMap.of(CATALOG, SessionOptionValueFactory.makeSessionOptionValue(catalog)));
try {
final SetSessionOptionsResult result = sqlClient.setSessionOptions(request, getOptions());
// Even when it rejects an option, the server may have started a session for the request.
sessionTracker.onSessionOptionsSet();
if (result.hasErrors()) {
final Map<String, SetSessionOptionsResult.Error> errors = result.getErrors();
for (final Map.Entry<String, SetSessionOptionsResult.Error> error : errors.entrySet()) {
Expand Down Expand Up @@ -1272,6 +1278,8 @@ public ArrowFlightSqlClientHandler build() throws SQLException {
}

buildTimeMiddlewareFactories.add(new ClientCookieMiddleware.Factory());
final ServerSessionTracker sessionTracker = new ServerSessionTracker();
buildTimeMiddlewareFactories.add(sessionTracker);
buildTimeMiddlewareFactories.forEach(clientBuilder::intercept);
if (useEncryption) {
clientBuilder.useTls();
Expand Down Expand Up @@ -1349,7 +1357,13 @@ public ArrowFlightSqlClientHandler build() throws SQLException {
options.toArray(new CallOption[0])));
}
return ArrowFlightSqlClientHandler.createNewHandler(
getCacheKey(), client, this, credentialOptions, catalog, flightClientCache);
getCacheKey(),
client,
this,
credentialOptions,
catalog,
flightClientCache,
sessionTracker);

} catch (final IllegalArgumentException
| GeneralSecurityException
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.arrow.driver.jdbc.client;

import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.arrow.flight.CallHeaders;
import org.apache.arrow.flight.CallInfo;
import org.apache.arrow.flight.CallStatus;
import org.apache.arrow.flight.FlightClientMiddleware;

/**
* Records whether the server may hold a session for a connection, so that closing the connection
* only sends CloseSession when there can be a session to close.
*
* <p>Flight SQL leaves the session mechanism to the server, typically a cookie. A session can exist
* once the client has set session options, or once the server has sent a cookie.
*/
final class ServerSessionTracker implements FlightClientMiddleware.Factory {
private static final String SET_COOKIE_HEADER = "Set-Cookie";

private final AtomicBoolean sessionOptionsSet = new AtomicBoolean();
private final AtomicBoolean cookieReceived = new AtomicBoolean();

void onSessionOptionsSet() {
sessionOptionsSet.set(true);
}

boolean isSessionOptionsSet() {
return sessionOptionsSet.get();
}

boolean mayHaveSession() {
return sessionOptionsSet.get() || cookieReceived.get();
}

@Override
public FlightClientMiddleware onCallStarted(final CallInfo info) {
return new FlightClientMiddleware() {
@Override
public void onBeforeSendingHeaders(final CallHeaders outgoingHeaders) {}

@Override
public void onHeadersReceived(final CallHeaders incomingHeaders) {
if (incomingHeaders.containsKey(SET_COOKIE_HEADER)) {
cookieReceived.set(true);
}
}

@Override
public void onCallCompleted(final CallStatus status) {}
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@
import org.apache.arrow.driver.jdbc.utils.MockFlightSqlProducer;
import org.apache.arrow.flight.FlightMethod;
import org.apache.arrow.flight.FlightProducer.ServerStreamListener;
import org.apache.arrow.flight.FlightServer;
import org.apache.arrow.flight.Location;
import org.apache.arrow.flight.NoOpSessionOptionValueVisitor;
import org.apache.arrow.flight.SessionOptionValue;
import org.apache.arrow.flight.sql.FlightSqlProducer.Schemas;
Expand Down Expand Up @@ -650,8 +652,9 @@ public void testJdbcDriverVersionIntegration() throws Exception {
}
}

/** The test server sends a cookie, so the driver closes the session it may hold. */
@Test
public void testCloseWithoutCatalogClosesSession() throws Exception {
public void testCloseWithSessionCookieClosesSession() throws Exception {
final Properties properties = new Properties();
properties.put(ArrowFlightConnectionProperty.USER.camelName(), userTest);
properties.put(ArrowFlightConnectionProperty.PASSWORD.camelName(), passTest);
Expand All @@ -671,6 +674,30 @@ public void testCloseWithoutCatalogClosesSession() throws Exception {
assertEquals(closeSessionCountBefore + 1, PRODUCER.getCloseSessionCount());
}

@Test
public void testCloseOnlyClosesSessionAfterSessionOptionsAreSet() throws Exception {
final MockFlightSqlProducer producer = new MockFlightSqlProducer();
// Without the test extension's middleware, the server sends no cookie.
try (BufferAllocator allocator = new RootAllocator(Long.MAX_VALUE);
FlightServer server =
FlightServer.builder(allocator, Location.forGrpcInsecure("localhost", 0), producer)
.build()
.start()) {
final String url =
format("jdbc:arrow-flight-sql://localhost:%d/?useEncryption=false", server.getPort());

try (Connection connection = DriverManager.getConnection(url)) {
connection.getMetaData();
}
assertEquals(0, producer.getCloseSessionCount());

try (Connection connection = DriverManager.getConnection(url)) {
connection.setCatalog("new_catalog");
}
assertEquals(1, producer.getCloseSessionCount());
}
}

@Test
public void testSetCatalogShouldUpdateSessionOptions() throws Exception {
final Properties properties = new Properties();
Expand Down
Loading
Loading