FrankChen021 commented on code in PR #19951: URL: https://github.com/apache/druid/pull/19951#discussion_r3758121013
########## jdbc-driver/src/main/java/org/apache/druid/jdbc/http/DruidHttpClientImpl.java: ########## @@ -0,0 +1,474 @@ +/* + * 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.druid.jdbc.http; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.druid.jdbc.ClientProperties; +import org.apache.druid.jdbc.DruidConnectionUrl; +import org.apache.druid.jdbc.DruidJdbcException; +import org.apache.druid.jdbc.DruidSQLState; +import org.apache.druid.jdbc.StringUtils; + +import javax.annotation.Nullable; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import java.io.InputStream; +import java.net.ConnectException; +import java.net.URI; +import java.net.URLEncoder; +import java.net.UnknownHostException; +import java.net.http.HttpClient; +import java.net.http.HttpHeaders; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; +import java.security.cert.X509Certificate; +import java.sql.SQLException; +import java.time.Duration; +import java.util.Base64; +import java.util.Locale; + +/** + * Production implementation of {@link DruidHttpClient}, using the JDK {@link HttpClient}. + */ +public class DruidHttpClientImpl implements DruidHttpClient +{ + private static final Duration DEFAULT_CONNECT_TIMEOUT = Duration.ofSeconds(10); + private static final Duration CANCELLATION_TIMEOUT = Duration.ofSeconds(5); + private static final String CTX_SQL_QUERY_ID = "sqlQueryId"; + private static final String CONTENT_TYPE_JSON = "application/json"; + + private final HttpClient httpClient; + private final ObjectMapper jsonMapper; + private final String httpUrl; + private final ClientProperties clientProperties; + + private volatile int networkTimeoutMillis; + private volatile boolean closed; + + public DruidHttpClientImpl( + final DruidConnectionUrl connectionUrl, + final ObjectMapper jsonMapper + ) throws SQLException + { + this.httpUrl = connectionUrl.buildHttpUrl(); + this.clientProperties = connectionUrl.getClientProperties(); + + final HttpClient.Builder clientBuilder = + HttpClient.newBuilder() + .connectTimeout(DEFAULT_CONNECT_TIMEOUT) + .followRedirects(HttpClient.Redirect.NEVER); + + if (connectionUrl.isHttps() && !clientProperties.isVerifyTls()) { + try { + final SSLContext sslContext = createTrustAllSslContext(); + clientBuilder.sslContext(sslContext); + } + catch (Exception e) { + throw new DruidJdbcException(e, "Failed to configure TLS context: %s", e); + } + } + + this.httpClient = clientBuilder.build(); + this.jsonMapper = jsonMapper; + } + + @Override + public QueryResultsIterator runQuery(final SqlRequest request) throws SQLException + { + throwIfClosed(); + + try { + final byte[] requestJson = jsonMapper.writeValueAsBytes(request); + final HttpRequest.Builder requestBuilder = + createRequestBuilder(URI.create(httpUrl)) + .header("Content-Type", CONTENT_TYPE_JSON) + .POST(HttpRequest.BodyPublishers.ofByteArray(requestJson)); + + final String sqlQueryId = sqlQueryIdOf(request); + final HttpResponse<InputStream> response = executeQueryRequest(requestBuilder); + try { + return new QueryResultsIteratorImpl(response.body(), jsonMapper, sqlQueryId); + } + catch (Throwable e) { + try { + response.body().close(); + } + catch (Throwable e2) { + e.addSuppressed(e2); + } + throw e; + } + } + catch (SQLException e) { + throw e; + } + catch (Exception e) { + throw new DruidJdbcException(e, "Failed to execute SQL query: %s", e); + } + } + + @Override + public void cancelQuery(final String sqlQueryId) throws SQLException + { + throwIfClosed(); + + if (sqlQueryId == null || sqlQueryId.isEmpty()) { + throw new DruidJdbcException("sqlQueryId cannot be null or empty"); + } + + try { + final String cancellationUrl = + (httpUrl.endsWith("/") ? httpUrl.substring(0, httpUrl.length() - 1) : httpUrl) + + "/" + + encodePathComponent(sqlQueryId); + + final HttpRequest.Builder requestBuilder = + createRequestBuilder(URI.create(cancellationUrl)) + .DELETE() + .timeout(CANCELLATION_TIMEOUT); + + final HttpRequest request = requestBuilder.build(); + final HttpResponse<Void> response = httpClient.send(request, HttpResponse.BodyHandlers.discarding()); + + // Consider 404 or 2xx a success, any other return code a failure. + final int statusCode = response.statusCode(); + if (!(statusCode >= 200 && statusCode < 300) && statusCode != 404) { + throw new DruidJdbcException( + "Failed to cancel sqlQueryId[%s]: Received HTTP %s", sqlQueryId, statusCode); + } + } + catch (SQLException e) { + throw e; + } + catch (Exception e) { + throw new DruidJdbcException(e, "Failed to cancel sqlQueryId[%s]: %s", sqlQueryId, e); + } + } + + @Override + public String getUrl() + { + return httpUrl; + } + + @Override + public int getNetworkTimeoutMillis() + { + return networkTimeoutMillis; + } + + @Override + public void setNetworkTimeoutMillis(final int networkTimeoutMillis) + { + this.networkTimeoutMillis = networkTimeoutMillis; + } + + @Override + public boolean isClosed() + { + return closed; + } + + @Override + public void close() + { + try { + HttpClientUtils.close(httpClient); + } + catch (RuntimeException e) { + throw e; + } + catch (Exception e) { + throw new RuntimeException(e); + } + finally { + closed = true; + } + } + + /** + * Executes an HTTP request, returning the response as a stream if it succeeds. Throws an error for non-successful + * HTTP codes. + * + * @throws SQLException if the HTTP request fails + */ + private HttpResponse<InputStream> executeQueryRequest(final HttpRequest.Builder requestBuilder) throws SQLException + { + throwIfClosed(); + + try { + // Apply network timeout, if set, to the HTTP connection. + final int networkTimeoutMillisToUse = networkTimeoutMillis; + if (networkTimeoutMillisToUse > 0) { + requestBuilder.timeout(Duration.ofMillis(networkTimeoutMillisToUse)); Review Comment: [P2] Network timeout stops at response headers The request uses BodyHandlers.ofInputStream(), so HttpClient.send() can return after headers arrive while QueryResultsIteratorImpl reads the body later. If the server sends headers and then stalls, ResultSet.next() or hasNext() can block indefinitely despite a finite Connection.setNetworkTimeout(). Enforce a body-read or idle deadline, or cancel the request on expiry, and add a stalled-body test. ########## jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidStatement.java: ########## @@ -0,0 +1,613 @@ +/* + * 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.druid.jdbc; + +import org.apache.druid.jdbc.http.DruidHttpClient; +import org.apache.druid.jdbc.http.QueryResultsIterator; +import org.apache.druid.jdbc.http.SqlParameter; +import org.apache.druid.jdbc.http.SqlRequest; +import org.apache.druid.jdbc.sql.SetStatement; +import org.apache.druid.jdbc.sql.SqlScanner; + +import javax.annotation.Nullable; +import java.sql.BatchUpdateException; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.sql.Statement; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; + +/** + * Our implementation of JDBC {@link Statement}. Executes queries using Druid's SQL endpoint. + * + * <p>SET statements are intercepted in the driver so they may apply to future statements in the same connection. + * This is necessary because JDBC connections are a purely driver-side concept: the server is connectionless. + * + * <p><b>Thread safety:</b> {@link #close()}, {@link #isClosed()}, and {@link #cancel()} are safe to + * call from any thread. All other methods are not. + */ +public class DruidStatement implements Statement +{ + private final DruidConnection connection; + private final DruidHttpClient httpClient; + + /** + * The sqlQueryId of the currently-outstanding query. Used by {@link #cancel()}. + */ + private final AtomicReference<String> currentSqlQueryId = new AtomicReference<>(); + + /** + * Whether this statement is closed. Set by {@link #close()}. + */ + private final AtomicBoolean closed = new AtomicBoolean(false); + + /** + * Row limit set by {@link #setMaxRows(int)}, or null if unset. Applied to query context by + * {@link #applyMaxRows(Map)}. + */ + @Nullable + private Integer maxRows; + + /** + * Timeout set by {@link #setQueryTimeout(int)}, or null if unset. Applied to query context by + * {@link #applyQueryTimeout(Map)}. + */ + @Nullable + private Integer queryTimeoutSeconds; + + /** + * Flag set by {@link #closeOnCompletion()}. If set, this statement is closed when the associated result set + * is closed. + */ + private volatile boolean closeOnCompletion; + + /** + * Reference to the currently associated result set. + */ + private volatile ResultSet currentResultSet; + + public DruidStatement(final DruidConnection connection) + { + this.connection = connection; + this.httpClient = connection.getHttpClient(); + } + + @Override + public ResultSet executeQuery(final String sql) throws SQLException + { + if (execute(sql)) { + return currentResultSet; + } else { + throw new DruidJdbcException("Query did not return a result set"); + } + } + + @Override + public int executeUpdate(final String sql) throws SQLException + { + throwIfClosed(); + throw new DruidJdbcFeatureNotSupportedException("executeUpdate not supported"); + } + + @Override + public void close() throws SQLException + { + if (closed.compareAndSet(false, true)) { + try { + closeCurrentResultSet(); Review Comment: [P2] Closing during HTTP startup does not cancel the server query Statement.close() can race with executeSql() before httpClient.runQuery() returns. With no result set yet, closeCurrentResultSet() only clears currentSqlQueryId; when the request returns, executeSql() closes the new result stream but never calls cancelQuery. The server-side query can remain running after the statement is closed. Preserve and cancel the in-flight query ID, and add a blocked-request test. -- 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] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
