diff --git a/docs/api-reference/json-querying-api.md b/docs/api-reference/json-querying-api.md index 26eb9c7e94a9..6573c31d2656 100644 --- a/docs/api-reference/json-querying-api.md +++ b/docs/api-reference/json-querying-api.md @@ -295,6 +295,19 @@ Content-Length: 817 ``` +## Observe running queries + +While a native query is running, you can find it in the list of running queries, `GET /druid/v2/sql/queries`. The list +is served by the Broker and covers every query that the Broker is executing, including the native queries submitted to +`/druid/v2`. Native queries have `"engine": "native"` and a `queryId`, but no `sqlQueryId`. + +If the Broker is configured with `druid.server.http.enableRunningQueryText`, you can retrieve the text of a running +query by its `queryId` from `GET /druid/v2/sql/queries/{queryId}/reports`. Query text is not captured by default +because it can include sensitive information. + +For the full API description, see [List running queries](sql-api.md#list-running-queries) and +[Get running query details](sql-api.md#get-running-query-details). + ## Get segment information for query Retrieves an array that contains objects with segment information, including the server locations associated with the query provided in the request body. diff --git a/docs/api-reference/sql-api.md b/docs/api-reference/sql-api.md index b9f037740549..b5f5879a9ccd 100644 --- a/docs/api-reference/sql-api.md +++ b/docs/api-reference/sql-api.md @@ -430,6 +430,120 @@ Host: http://ROUTER_IP:ROUTER_PORT A successful response results in an `HTTP 202` message code and an empty response body. +### List running queries + +Returns the queries that are currently running on the server, for each query engine that supports listing its queries. +The native engine and the Dart engine support this API. + +Although this API is served under `/druid/v2/sql/`, it is not limited to queries that were submitted with SQL. The +native engine entry includes native queries that were submitted directly to `/druid/v2`, as well as the native queries +that execute SQL statements. Use the `engine` field of each entry to tell which engine reported the query. + +For the native engine, the list contains the queries that are running on the server that receives the request. The +native engine runs a single native query per SQL statement, so each SQL query appears as a single entry. The list also +includes native queries that were submitted directly to the native query endpoint, `/druid/v2/`, and queries that the +server runs internally, such as segment metadata queries. + +Users with READ permission on the `STATE` resource see all running queries. Other users see only their own queries. + +#### URL + +`GET` `/druid/v2/sql/queries` + +#### Query parameters + +* `selfOnly`: If present, returns only queries that are running on this server. If absent, each engine may contact other +servers to build a complete list. The native engine always returns queries that are local to the server. +* `includeComplete`: If present, includes completed queries in the response. The number of completed queries returned is +determined by engine-specific retention settings. The native engine does not retain completed queries. + +For the native engine, the response does not include query text. To get the text of a running native query, use its +`sqlQueryId` or `queryId` with the [get running query details](#get-running-query-details) API. Native query text is +only captured when `druid.server.http.enableRunningQueryText` is enabled, because it can include sensitive information. +Entries from the Dart engine include the masked SQL text of the query. + +#### Sample request + +```shell +curl "http://ROUTER_IP:ROUTER_PORT/druid/v2/sql/queries" +``` + +#### Sample response + +The response contains one entry per running query. Engine-specific fields are included for each engine. For the native +engine, `queryId` is the ID to use with the cancel API for native queries, and `sqlQueryId` is the ID to use with the +cancel API for SQL queries. + +```json +{ + "queries": [ + { + "engine": "native", + "queryId": "b3a4a4a1-4e39-4a01-a4d7-66f5e2f49c54", + "sqlQueryId": "request01", + "queryType": "timeseries", + "datasources": ["wikipedia"], + "identity": "user", + "authenticator": "basic", + "startTime": "2026-11-26T06:11:46.887Z", + "state": "RUNNING" + } + ] +} +``` + +### Get running query details + +Returns the details of a single query, including its query text, for each SQL engine that supports query reports. The +native engine and the Dart engine support this API. + +For the native engine, the query can be looked up by its `sqlQueryId` or by its `queryId`, as returned by the +[list running queries](#list-running-queries) API. This also works for native queries that were submitted directly to +`/druid/v2`, which have a `queryId` but no `sqlQueryId`. The query text is only included when +`druid.server.http.enableRunningQueryText` is enabled on the server. Queries that are no longer running cannot be +looked up with this API. + +Users with READ permission on the `STATE` resource see any query. Other users can only look up their own queries, and +get `404` for other users' queries. + +#### URL + +`GET` `/druid/v2/sql/queries/{queryId}/reports` + +#### Query parameters + +* `selfOnly`: If present, checks this server only. The native engine always answers from the local server. + +#### Sample request + +```shell +curl "http://ROUTER_IP:ROUTER_PORT/druid/v2/sql/queries/b3a4a4a1-4e39-4a01-a4d7-66f5e2f49c54/reports" +``` + +#### Sample response + +For the native engine, the response contains the query details in `query`, including `sql` and `nativeQuery` when +captured, and an empty `report`. + +```json +{ + "query": { + "engine": "native", + "queryId": "b3a4a4a1-4e39-4a01-a4d7-66f5e2f49c54", + "sqlQueryId": "request01", + "queryType": "timeseries", + "datasources": ["wikipedia"], + "identity": "user", + "authenticator": "basic", + "sql": "SELECT COUNT(*) AS c FROM wikipedia", + "nativeQuery": "{\"queryType\":\"timeseries\",...}", + "startTime": "2026-11-26T06:11:46.887Z", + "state": "RUNNING" + }, + "report": {} +} +``` + ### Query output format The following table shows examples of how Druid returns the column names and data types based on the result format and the type request. diff --git a/docs/configuration/index.md b/docs/configuration/index.md index 255582fb7d2b..190180fdcc96 100644 --- a/docs/configuration/index.md +++ b/docs/configuration/index.md @@ -1638,6 +1638,7 @@ Druid uses Jetty to serve HTTP requests. |`druid.server.http.maxRequestHeaderSize`|Maximum size of a request header in bytes. Larger headers consume more memory and can make a server more vulnerable to denial of service attacks.|8 * 1024| |`druid.server.http.headerCacheSize`|Size of the cache Jetty keeps on each client connection to avoid re-parsing request headers that repeat across requests on that connection. Disabled (0) by default because the parsing it saves is negligible compared to the work of serving a Druid request, and each connection that uses the cache holds extra heap for as long as it stays open. Most deployments should leave this at 0.|0| |`druid.server.http.contentSecurityPolicy`|Content-Security-Policy header value to set on each non-POST response. Setting this property to an empty string, or omitting it, both result in the default `frame-ancestors: none` being set.|`frame-ancestors 'none'`| +|`druid.server.http.enableRunningQueryText`|Whether to capture the text of running queries, so that it can be returned by the [get running query details](../api-reference/sql-api.md#get-running-query-details) API. When enabled, each process keeps the native query, and the SQL text when the query came in through the SQL layer, of the queries that are running on it. The API is served by the Broker, so this exposes the query text of the queries that are running on the Broker. Query text can include sensitive information, so enable this only when needed.|false| ##### Processing @@ -1956,7 +1957,7 @@ The Druid SQL server is configured through the following properties on the Broke |`druid.sql.planner.useNativeQueryExplain`|If true, `EXPLAIN PLAN FOR` will return the explain plan as a JSON representation of equivalent native query(s), else it will return the original version of explain plan generated by Calcite. It can be overridden per query with `useNativeQueryExplain` context key.|true| |`druid.sql.planner.maxNumericInFilters`|Max limit for the amount of numeric values that can be compared for a string type dimension when the entire SQL WHERE clause of a query translates to an [OR](../querying/filters.md#or) of [Bound filter](../querying/filters.md#bound-filter). By default, Druid does not restrict the amount of numeric Bound Filters on String columns, although this situation may block other queries from running. Set this property to a smaller value to prevent Druid from running queries that have prohibitively long segment processing times. The optimal limit requires some trial and error; we recommend starting with 100. Users who submit a query that exceeds the limit of `maxNumericInFilters` should instead rewrite their queries to use strings in the `WHERE` clause instead of numbers. For example, `WHERE someString IN (‘123’, ‘456’)`. If this value is disabled, `maxNumericInFilters` set through query context is ignored.|`-1` (disabled)| |`druid.sql.approxCountDistinct.function`|Implementation to use for the [`APPROX_COUNT_DISTINCT` function](../querying/sql-aggregations.md). Without extensions loaded, the only valid value is `APPROX_COUNT_DISTINCT_BUILTIN` (a HyperLogLog, or HLL, based implementation). If the [DataSketches extension](../development/extensions-core/datasketches-extension.md) is loaded, this can also be `APPROX_COUNT_DISTINCT_DS_HLL` (alternative HLL implementation) or `APPROX_COUNT_DISTINCT_DS_THETA`.

Theta sketches use significantly more memory than HLL sketches, so you should prefer one of the two HLL implementations.|`APPROX_COUNT_DISTINCT_BUILTIN`| -|`druid.sql.planner.enableSysQueriesTable`|**Experimental.** Whether to enable the [`sys.queries` table](../querying/sql-metadata-tables.md#queries-table), which provides information about currently running and recently completed SQL queries. Currently only queries from the Dart (MSQ) engine are shown.|false| +|`druid.sql.planner.enableSysQueriesTable`|**Experimental.** Whether to enable the [`sys.queries` table](../querying/sql-metadata-tables.md#queries-table), which provides information about currently running and recently completed SQL queries. Queries from the Dart (MSQ) engine and the native engine are shown. The native engine only shows queries that are currently running on the Broker.|false| :::info Previous versions of Druid had properties named `druid.sql.planner.maxQueryCount` and `druid.sql.planner.maxSemiJoinRowsInMemory`. diff --git a/docs/querying/sql-metadata-tables.md b/docs/querying/sql-metadata-tables.md index c93b39ca821b..6fdc8a4f474f 100644 --- a/docs/querying/sql-metadata-tables.md +++ b/docs/querying/sql-metadata-tables.md @@ -381,18 +381,19 @@ WHERE deprecation IS NOT NULL :::info The `sys.queries` table is an experimental feature. You must enable it by setting the runtime property - `druid.sql.planner.enableSysQueriesTable=true` on Broker processes. The main reason this table is experimental - is that it only shows queries from the [Dart](dart.md) engine, which is also experimental. + `druid.sql.planner.enableSysQueriesTable=true` on Broker processes. The table only shows queries from SQL engines + that support listing their queries: the [Dart](dart.md) engine (`msq-dart`) and the native engine (`native`). + Dart is also experimental. ::: The queries table provides information about currently running and recently completed SQL queries. |Column|Type|Notes| |------|-----|-----| -|id|VARCHAR|Execution ID for the query. For Dart queries, this is the `dartQueryId`.| -|engine|VARCHAR|SQL engine that executed the query, e.g., `msq-dart`| +|id|VARCHAR|Execution ID for the query. For Dart queries, this is the `dartQueryId`. For native engine queries, this is the native query ID.| +|engine|VARCHAR|SQL engine that executed the query, e.g., `msq-dart` or `native`| |state|VARCHAR|Query status: `ACCEPTED`, `RUNNING`, `SUCCESS`, `FAILED`, or `CANCELED`| -|info|VARCHAR|JSON-serialized query information including `sqlQueryId`, `sql`, `identity`, `startTime`, and other engine-specific details| +|info|VARCHAR|JSON-serialized query information including `sqlQueryId`, `identity`, `startTime`, and other engine-specific details. Dart engine entries also include `sql`; native engine entries do not include query text.| For example, to retrieve all recently completed Dart queries: @@ -409,3 +410,37 @@ WHERE See `druid.msq.dart.controller.maxRetainedReportCount` and `druid.msq.dart.controller.maxRetainedReportDuration` for details on how long completed queries are retained. ::: + +#### Native engine queries + +For the native engine, the queries table lists the queries that are currently executing on the Broker that runs the +query. Completed queries are not retained, so `state` is always `RUNNING` for native engine queries. The `info` column +contains the following fields: + +|Field|Notes| +|-----|-----| +|`engine`|Engine that is running the query, always `native`.| +|`state`|State of the query, always `RUNNING`.| +|`queryId`|Native query ID. This is the ID to use with the cancel API, `DELETE /druid/v2/{queryId}`.| +|`sqlQueryId`|`sqlQueryId` of the SQL query that this native query belongs to, when the query came in through the SQL layer. This is the ID to use with the cancel API, `DELETE /druid/v2/sql/{sqlQueryId}`.| +|`queryType`|Native query type, such as `timeseries`, `topN`, or `groupBy`.| +|`datasources`|Names of the datasources queried by this native query.| +|`identity`|Identity of the user that submitted the query. Only included when the user has READ permission on the `STATE` resource.| +|`authenticator`|Authenticator that authenticated `identity`. Only included when the user has READ permission on the `STATE` resource.| +|`startTime`|Time at which the query started executing on this Broker.| + +The `info` column does not include query text. To get the text of a running native query, use its `queryId` or +`sqlQueryId` with the [get running query details](../api-reference/sql-api.md#get-running-query-details) API. Query +text is only captured when `druid.server.http.enableRunningQueryText` is enabled. + +The native engine runs a single native query per SQL statement, so a SQL query that uses the native engine appears as a +single row. Native queries that were submitted directly to `/druid/v2/`, and queries that the server runs internally, +also appear in the table, and have no `sqlQueryId`. + +For example, to retrieve all native engine queries that are currently running: + +```sql +SELECT id, "info" +FROM sys.queries +WHERE engine = 'native' +``` diff --git a/multi-stage-query/src/main/java/org/apache/druid/msq/dart/controller/sql/DartSqlEngine.java b/multi-stage-query/src/main/java/org/apache/druid/msq/dart/controller/sql/DartSqlEngine.java index 4b4d8faf3036..e573dd070e07 100644 --- a/multi-stage-query/src/main/java/org/apache/druid/msq/dart/controller/sql/DartSqlEngine.java +++ b/multi-stage-query/src/main/java/org/apache/druid/msq/dart/controller/sql/DartSqlEngine.java @@ -386,8 +386,9 @@ public GetQueryReportResponse getQueryReport( ); for (final GetQueryReportResponse otherReport : otherReports) { - // Check for non-null report with non-null content (a 404 response returns GetReportResponse with null fields) - if (otherReport != null && otherReport.getQueryInfo() != null) { + // Check for non-null report with non-null content (a 404 response returns GetReportResponse with null fields). + // Another engine, such as the native engine, may answer for the same query ID, so check the type. + if (otherReport != null && otherReport.getQueryInfo() instanceof DartQueryInfo) { infoAndReport = new QueryInfoAndReport( (DartQueryInfo) otherReport.getQueryInfo(), otherReport.getReportMap(), diff --git a/server/src/main/java/org/apache/druid/server/QueryLifecycle.java b/server/src/main/java/org/apache/druid/server/QueryLifecycle.java index 31cc81e06368..b6fa2e035cf2 100644 --- a/server/src/main/java/org/apache/druid/server/QueryLifecycle.java +++ b/server/src/main/java/org/apache/druid/server/QueryLifecycle.java @@ -99,6 +99,7 @@ public class QueryLifecycle private final AuthConfig authConfig; private final PolicyEnforcer policyEnforcer; private final QueryConfigSnapshot configSnapshot; + private final RunningQueryRegistry runningQueryRegistry; private final long startMs; private final long startNs; @@ -108,6 +109,13 @@ public class QueryLifecycle @MonotonicNonNull private Query baseQuery; + + /** + * SQL text of this query, when it came in through the SQL layer. Null for native queries. + */ + @Nullable + private String sqlText; + /** * Context keys as received, i.e. the candidate set for {@link AuthConfig#contextKeysToAuthorize}. */ @@ -124,6 +132,7 @@ public QueryLifecycle( final AuthConfig authConfig, final PolicyEnforcer policyEnforcer, final QueryConfigSnapshot configSnapshot, + final RunningQueryRegistry runningQueryRegistry, final long startMs, final long startNs ) @@ -137,6 +146,7 @@ public QueryLifecycle( this.authConfig = authConfig; this.policyEnforcer = policyEnforcer; this.configSnapshot = configSnapshot; + this.runningQueryRegistry = runningQueryRegistry; this.startMs = startMs; this.startNs = startNs; } @@ -174,6 +184,22 @@ public QueryResponse runSimple( @Nullable final Set clientProvidedQueryContextKeys ) { + return runSimple(query, authenticationResult, authorizationResult, clientProvidedQueryContextKeys, null); + } + + /** + * As {@link #runSimple(Query, AuthenticationResult, AuthorizationResult, Set)}, but also takes the SQL text of the + * query, for the running query registry. See {@link RunningQueryRegistry}. + */ + public QueryResponse runSimple( + final Query query, + final AuthenticationResult authenticationResult, + final AuthorizationResult authorizationResult, + @Nullable final Set clientProvidedQueryContextKeys, + @Nullable final String sqlText + ) + { + this.sqlText = sqlText; initialize(query, clientProvidedQueryContextKeys); final Sequence results; @@ -417,6 +443,8 @@ public QueryResponse execute() { transition(State.AUTHORIZED, State.EXECUTING); + runningQueryRegistry.register(baseQuery, sqlText, authenticationResult); + final ResponseContext responseContext = DirectDruidClient.makeResponseContextForQuery(); @SuppressWarnings("unchecked") @@ -450,6 +478,8 @@ public void emitLogsAndMetrics( return; } + runningQueryRegistry.unregister(baseQuery.getId()); + if (state == State.DONE) { log.warn("Tried to emit logs and metrics twice for query[%s]!", baseQuery.getId()); } diff --git a/server/src/main/java/org/apache/druid/server/QueryLifecycleFactory.java b/server/src/main/java/org/apache/druid/server/QueryLifecycleFactory.java index d22d24ed3efb..8e1fc1ab7fb6 100644 --- a/server/src/main/java/org/apache/druid/server/QueryLifecycleFactory.java +++ b/server/src/main/java/org/apache/druid/server/QueryLifecycleFactory.java @@ -19,6 +19,7 @@ package org.apache.druid.server; +import com.google.common.annotations.VisibleForTesting; import com.google.inject.Inject; import org.apache.druid.client.BrokerViewOfBrokerConfig; import org.apache.druid.guice.LazySingleton; @@ -48,6 +49,7 @@ public class QueryLifecycleFactory private final AuthConfig authConfig; private final PolicyEnforcer policyEnforcer; private final BrokerViewOfBrokerConfig brokerViewOfBrokerConfig; + private final RunningQueryRegistry runningQueryRegistry; @Inject public QueryLifecycleFactory( @@ -60,7 +62,8 @@ public QueryLifecycleFactory( final PolicyEnforcer policyEnforcer, final AuthorizerMapper authorizerMapper, final QueryConfigProvider queryConfigProvider, - @Nullable final BrokerViewOfBrokerConfig brokerViewOfBrokerConfig + @Nullable final BrokerViewOfBrokerConfig brokerViewOfBrokerConfig, + final RunningQueryRegistry runningQueryRegistry ) { this.conglomerate = conglomerate; @@ -73,6 +76,39 @@ public QueryLifecycleFactory( this.authConfig = authConfig; this.policyEnforcer = policyEnforcer; this.brokerViewOfBrokerConfig = brokerViewOfBrokerConfig; + this.runningQueryRegistry = runningQueryRegistry; + } + + /** + * Constructor used by tests, which do not need a running-query registry. + */ + @VisibleForTesting + public QueryLifecycleFactory( + final QueryRunnerFactoryConglomerate conglomerate, + final QuerySegmentWalker texasRanger, + final GenericQueryMetricsFactory queryMetricsFactory, + final ServiceEmitter emitter, + final RequestLogger requestLogger, + final AuthConfig authConfig, + final PolicyEnforcer policyEnforcer, + final AuthorizerMapper authorizerMapper, + final QueryConfigProvider queryConfigProvider, + @Nullable final BrokerViewOfBrokerConfig brokerViewOfBrokerConfig + ) + { + this( + conglomerate, + texasRanger, + queryMetricsFactory, + emitter, + requestLogger, + authConfig, + policyEnforcer, + authorizerMapper, + queryConfigProvider, + brokerViewOfBrokerConfig, + new RunningQueryRegistry() + ); } public QueryLifecycle factorize() @@ -93,6 +129,7 @@ public QueryLifecycle factorize() authConfig, policyEnforcer, configSnapshot, + runningQueryRegistry, System.currentTimeMillis(), System.nanoTime() ); diff --git a/server/src/main/java/org/apache/druid/server/RunningQueryRegistry.java b/server/src/main/java/org/apache/druid/server/RunningQueryRegistry.java new file mode 100644 index 000000000000..4d290bed9f0a --- /dev/null +++ b/server/src/main/java/org/apache/druid/server/RunningQueryRegistry.java @@ -0,0 +1,233 @@ +/* + * 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.server; + +import com.google.common.annotations.VisibleForTesting; +import com.google.inject.Inject; +import org.apache.druid.guice.LazySingleton; +import org.apache.druid.java.util.common.DateTimes; +import org.apache.druid.query.Query; +import org.apache.druid.server.initialization.ServerConfig; +import org.apache.druid.server.security.AuthenticationResult; +import org.joda.time.DateTime; + +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Registry of the queries that are currently executing on this process. + *

+ * Queries are added by {@link QueryLifecycle} when execution starts, and removed when execution finishes. The registry + * is a best-effort, in-memory view of in-flight queries: it is local to this process and is not persisted. It is used + * by the "list running queries" APIs, such as {@code GET /druid/v2/sql/queries} and {@code sys.queries}. + *

+ * This class is thread-safe. {@link #register} and {@link #unregister} are called by query execution threads, and + * {@link #getAll} is called by HTTP threads. All state lives in a {@link ConcurrentHashMap}, so readers and writers do + * not block each other. {@link #getAll} returns a snapshot, and the returned entries are immutable. + */ +@LazySingleton +public class RunningQueryRegistry +{ + private final ServerConfig serverConfig; + private final Map entries = new ConcurrentHashMap<>(); + + @Inject + public RunningQueryRegistry(final ServerConfig serverConfig) + { + this.serverConfig = serverConfig; + } + + @VisibleForTesting + public RunningQueryRegistry() + { + this(new ServerConfig()); + } + + /** + * Registers a query that is about to start executing. + * + * @param query query that is starting + * @param sqlText SQL text of the query, when the query came in through the SQL layer + * @param authenticationResult authentication result for the user that submitted the query + */ + public void register( + final Query query, + @Nullable final String sqlText, + @Nullable final AuthenticationResult authenticationResult + ) + { + final String queryId = query.getId(); + if (queryId == null) { + return; + } + + String capturedSqlText = null; + Query capturedNativeQuery = null; + + if (serverConfig.isEnableRunningQueryText()) { + capturedSqlText = sqlText; + capturedNativeQuery = query; + } + + entries.put( + queryId, + new Entry( + queryId, + query.getSqlQueryId(), + query.getType(), + List.copyOf(query.getDataSource().getTableNames()), + authenticationResult == null ? null : authenticationResult.getIdentity(), + authenticationResult == null ? null : authenticationResult.getAuthenticatedBy(), + capturedSqlText, + capturedNativeQuery, + DateTimes.nowUtc() + ) + ); + } + + /** + * Removes a query that has finished executing. Does nothing if the query was never registered. + */ + public void unregister(final String queryId) + { + if (queryId != null) { + entries.remove(queryId); + } + } + + /** + * Returns a snapshot of all currently executing queries, sorted by start time. + */ + public List getAll() + { + final List retVal = new ArrayList<>(entries.values()); + retVal.sort(Comparator.comparing(Entry::getStartTime).thenComparing(Entry::getQueryId)); + return retVal; + } + + /** + * Information about a single running query. Instances are immutable. + */ + public static class Entry + { + private final String queryId; + @Nullable + private final String sqlQueryId; + private final String queryType; + private final List datasources; + @Nullable + private final String identity; + @Nullable + private final String authenticator; + @Nullable + private final String sql; + @Nullable + private final Query nativeQuery; + private final DateTime startTime; + + public Entry( + final String queryId, + @Nullable final String sqlQueryId, + final String queryType, + final List datasources, + @Nullable final String identity, + @Nullable final String authenticator, + @Nullable final String sql, + @Nullable final Query nativeQuery, + final DateTime startTime + ) + { + this.queryId = queryId; + this.sqlQueryId = sqlQueryId; + this.queryType = queryType; + this.datasources = datasources; + this.identity = identity; + this.authenticator = authenticator; + this.sql = sql; + this.nativeQuery = nativeQuery; + this.startTime = startTime; + } + + public String getQueryId() + { + return queryId; + } + + /** + * The {@code sqlQueryId} of the SQL query that this native query belongs to, or null for native queries that were + * not created by the SQL layer. + */ + @Nullable + public String getSqlQueryId() + { + return sqlQueryId; + } + + public String getQueryType() + { + return queryType; + } + + public List getDatasources() + { + return datasources; + } + + @Nullable + public String getIdentity() + { + return identity; + } + + @Nullable + public String getAuthenticator() + { + return authenticator; + } + + /** + * SQL text of this query, when the query came in through the SQL layer. Null unless + * {@link ServerConfig#isEnableRunningQueryText()} is enabled. + */ + @Nullable + public String getSql() + { + return sql; + } + + /** + * Native query that is running. Null unless {@link ServerConfig#isEnableRunningQueryText()} is enabled. + */ + @Nullable + public Query getNativeQuery() + { + return nativeQuery; + } + + public DateTime getStartTime() + { + return startTime; + } + } +} diff --git a/server/src/main/java/org/apache/druid/server/initialization/ServerConfig.java b/server/src/main/java/org/apache/druid/server/initialization/ServerConfig.java index 5715c2a43670..bc6a9cc6a38f 100644 --- a/server/src/main/java/org/apache/druid/server/initialization/ServerConfig.java +++ b/server/src/main/java/org/apache/druid/server/initialization/ServerConfig.java @@ -121,7 +121,8 @@ public ServerConfig( uriCompliance, enforceStrictSNIHostChecking, true, - DEFAULT_HEADER_CACHE_SIZE + DEFAULT_HEADER_CACHE_SIZE, + false ); } @@ -151,7 +152,8 @@ public ServerConfig( @Nullable UriCompliance uriCompliance, boolean enforceStrictSNIHostChecking, boolean enableQueryRequestsQueuing, - int headerCacheSize + int headerCacheSize, + boolean enableRunningQueryText ) { this.numThreads = numThreads; @@ -180,6 +182,7 @@ public ServerConfig( this.enforceStrictSNIHostChecking = enforceStrictSNIHostChecking; this.enableQueryRequestsQueuing = enableQueryRequestsQueuing; this.headerCacheSize = headerCacheSize; + this.enableRunningQueryText = enableRunningQueryText; } public ServerConfig() @@ -240,6 +243,9 @@ public ServerConfig(@NotNull ErrorResponseTransformStrategy errorResponseTransfo @JsonProperty private int maxRequestHeaderSize = 8 * 1024; + @JsonProperty + private boolean enableRunningQueryText = false; + @JsonProperty @NotNull private Period gracefulShutdownTimeout = Period.seconds(30); @@ -319,6 +325,15 @@ public boolean isEnableRequestLimit() return enableRequestLimit; } + /** + * Whether to capture the text of running queries, so that it can be returned by the "list running queries" APIs. + * This is disabled by default, since the query text can include sensitive information. + */ + public boolean isEnableRunningQueryText() + { + return enableRunningQueryText; + } + public Period getMaxIdleTime() { return maxIdleTime; @@ -416,7 +431,8 @@ private ServerConfig withShutdownTimings( uriCompliance, enforceStrictSNIHostChecking, enableQueryRequestsQueuing, - headerCacheSize + headerCacheSize, + enableRunningQueryText ); } @@ -521,7 +537,8 @@ public boolean equals(Object o) enableQueryRequestsQueuing == that.enableQueryRequestsQueuing && Objects.equals(uriCompliance, that.uriCompliance) && enforceStrictSNIHostChecking == that.enforceStrictSNIHostChecking && - headerCacheSize == that.headerCacheSize; + headerCacheSize == that.headerCacheSize && + enableRunningQueryText == that.enableRunningQueryText; } @Override @@ -553,7 +570,8 @@ public int hashCode() enableQueryRequestsQueuing, uriCompliance, enforceStrictSNIHostChecking, - headerCacheSize + headerCacheSize, + enableRunningQueryText ); } @@ -587,6 +605,7 @@ public String toString() ", uriCompliance=" + uriCompliance + ", enforceStrictSNIHostChecking=" + enforceStrictSNIHostChecking + ", headerCacheSize=" + headerCacheSize + + ", enableRunningQueryText=" + enableRunningQueryText + '}'; } diff --git a/server/src/main/java/org/apache/druid/server/initialization/jetty/CliIndexerServerModule.java b/server/src/main/java/org/apache/druid/server/initialization/jetty/CliIndexerServerModule.java index 6c41b4e7dcc4..40ff92ea49ae 100644 --- a/server/src/main/java/org/apache/druid/server/initialization/jetty/CliIndexerServerModule.java +++ b/server/src/main/java/org/apache/druid/server/initialization/jetty/CliIndexerServerModule.java @@ -165,7 +165,8 @@ public ServerConfig makeAdjustedServerConfig(ServerConfig oldConfig) oldConfig.getUriCompliance(), oldConfig.isEnforceStrictSNIHostChecking(), oldConfig.isEnableQueryRequestsQueuing(), - oldConfig.getHeaderCacheSize() + oldConfig.getHeaderCacheSize(), + oldConfig.isEnableRunningQueryText() ); } } diff --git a/server/src/test/java/org/apache/druid/initialization/ServerConfigTest.java b/server/src/test/java/org/apache/druid/initialization/ServerConfigTest.java index b0b96cc158b2..b82f4022f57a 100644 --- a/server/src/test/java/org/apache/druid/initialization/ServerConfigTest.java +++ b/server/src/test/java/org/apache/druid/initialization/ServerConfigTest.java @@ -75,7 +75,8 @@ public void testSerde() throws Exception UriCompliance.RFC3986, false, true, - 512 + 512, + true ); String modifiedConfigJson = OBJECT_MAPPER.writeValueAsString(modifiedConfig); ServerConfig modifiedConfig2 = OBJECT_MAPPER.readValue(modifiedConfigJson, ServerConfig.class); @@ -93,6 +94,7 @@ public void testSerde() throws Exception Assertions.assertEquals(UriCompliance.RFC3986, modifiedConfig2.getUriCompliance()); Assertions.assertFalse(modifiedConfig2.isEnforceStrictSNIHostChecking()); Assertions.assertEquals(512, modifiedConfig2.getHeaderCacheSize()); + Assertions.assertTrue(modifiedConfig2.isEnableRunningQueryText()); } @Test diff --git a/server/src/test/java/org/apache/druid/server/PerSegmentTimeoutInjectionTest.java b/server/src/test/java/org/apache/druid/server/PerSegmentTimeoutInjectionTest.java index 0b510046cde0..adf8e23618a4 100644 --- a/server/src/test/java/org/apache/druid/server/PerSegmentTimeoutInjectionTest.java +++ b/server/src/test/java/org/apache/druid/server/PerSegmentTimeoutInjectionTest.java @@ -191,6 +191,7 @@ private QueryLifecycle createLifecycle(Map resolvedDefaultQueryC new AuthConfig(), NoopPolicyEnforcer.instance(), new QueryConfigSnapshot(QueryContext.of(resolvedDefaultQueryContext), dynamicConfig), + new RunningQueryRegistry(), System.currentTimeMillis(), System.nanoTime() ); diff --git a/server/src/test/java/org/apache/druid/server/QueryLifecycleTest.java b/server/src/test/java/org/apache/druid/server/QueryLifecycleTest.java index 92c9db80a996..e50e8614ea9e 100644 --- a/server/src/test/java/org/apache/druid/server/QueryLifecycleTest.java +++ b/server/src/test/java/org/apache/druid/server/QueryLifecycleTest.java @@ -63,6 +63,7 @@ import org.apache.druid.query.timeseries.TimeseriesQuery; import org.apache.druid.server.broker.BrokerDynamicConfig; import org.apache.druid.server.broker.QueryConfigSnapshot; +import org.apache.druid.server.initialization.ServerConfig; import org.apache.druid.server.log.RequestLogger; import org.apache.druid.server.security.Access; import org.apache.druid.server.security.Action; @@ -85,6 +86,7 @@ import java.util.EnumSet; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Optional; @@ -94,6 +96,7 @@ public class QueryLifecycleTest private static final String DATASOURCE = "some_datasource"; private static final String IDENTITY = "some_identity"; private static final String AUTHORIZER = "some_authorizer"; + private static final String AUTHENTICATOR = "some_authenticator"; private static final Resource RESOURCE = new Resource(DATASOURCE, ResourceType.DATASOURCE); @@ -157,12 +160,16 @@ public void setup() runner = EasyMock.createMock(QueryRunner.class); metrics = EasyMock.createNiceMock(QueryMetrics.class); authenticationResult = EasyMock.createMock(AuthenticationResult.class); + EasyMock.expect(authenticationResult.getAuthenticatedBy()).andReturn(AUTHENTICATOR).anyTimes(); authConfig = new AuthConfig(); policyEnforcer = NoopPolicyEnforcer.instance(); injector = Guice.createInjector( BoundFieldModule.of(this), - binder -> binder.bindScope(LazySingleton.class, Scopes.SINGLETON) + binder -> { + binder.bindScope(LazySingleton.class, Scopes.SINGLETON); + binder.bind(ServerConfig.class).toInstance(new ServerConfig()); + } ); } @@ -209,6 +216,57 @@ public void testRunSimple_preauthorizedAsSuperuser() lifecycle.runSimple(query, authenticationResult, AuthorizationResult.ALLOW_NO_RESTRICTION); } + @Test + public void testRunSimple_registersRunningQuery() + { + final RunningQueryRegistry registry = new RunningQueryRegistry(); + final QueryLifecycle lifecycle = new QueryLifecycle( + conglomerate, + texasRanger, + metricsFactory, + emitter, + requestLogger, + authzMapper, + authConfig, + policyEnforcer, + new QueryConfigSnapshot(QueryContext.empty(), null), + registry, + System.currentTimeMillis(), + System.nanoTime() + ); + + EasyMock.expect(queryConfig.getContext()).andReturn(QueryContext.empty()).anyTimes(); + EasyMock.expect(authenticationResult.getIdentity()).andReturn(IDENTITY).anyTimes(); + EasyMock.expect(conglomerate.getToolChest(EasyMock.anyObject())) + .andReturn(toolChest) + .once(); + EasyMock.expect(texasRanger.getQueryRunnerForIntervals(EasyMock.anyObject(), EasyMock.anyObject())) + .andReturn(runner) + .once(); + EasyMock.expect(toolChest.makeMetrics(EasyMock.anyObject())).andReturn(metrics).once(); + EasyMock.expect(runner.run(EasyMock.anyObject(), EasyMock.anyObject())) + .andAnswer(() -> { + // While the query is running, it is present in the registry. + final List runningQueries = registry.getAll(); + Assertions.assertEquals(1, runningQueries.size()); + Assertions.assertEquals(lifecycle.getQueryId(), runningQueries.get(0).getQueryId()); + Assertions.assertEquals("timeseries", runningQueries.get(0).getQueryType()); + Assertions.assertEquals(ImmutableList.of(DATASOURCE), runningQueries.get(0).getDatasources()); + Assertions.assertEquals(IDENTITY, runningQueries.get(0).getIdentity()); + return Sequences.empty(); + }) + .once(); + + replayAll(); + + lifecycle.runSimple(query, authenticationResult, AuthorizationResult.ALLOW_NO_RESTRICTION) + .getResults() + .toList(); + + // Once the query finishes, it is removed from the registry. + Assertions.assertTrue(registry.getAll().isEmpty()); + } + @Test public void testRunSimpleUnauthorized() { @@ -904,6 +962,7 @@ public void testRunSimple_queryBlocklisted() QueryContext.empty(), BrokerDynamicConfig.builder().withQueryBlocklist(ImmutableList.of(rule)).build() ), + new RunningQueryRegistry(), System.currentTimeMillis(), System.nanoTime() ); @@ -956,6 +1015,7 @@ public void testRunSimple_queryNotBlocklisted() QueryContext.empty(), BrokerDynamicConfig.builder().withQueryBlocklist(ImmutableList.of(rule)).build() ), + new RunningQueryRegistry(), System.currentTimeMillis(), System.nanoTime() ); diff --git a/server/src/test/java/org/apache/druid/server/QueryResourceTest.java b/server/src/test/java/org/apache/druid/server/QueryResourceTest.java index 1a2be37558d1..aaf62f5155f1 100644 --- a/server/src/test/java/org/apache/druid/server/QueryResourceTest.java +++ b/server/src/test/java/org/apache/druid/server/QueryResourceTest.java @@ -835,6 +835,7 @@ public QueryLifecycle factorize() new AuthConfig(), NoopPolicyEnforcer.instance(), new QueryConfigSnapshot(overrideConfig.getContext(), null), + new RunningQueryRegistry(), System.currentTimeMillis(), System.nanoTime() ) diff --git a/server/src/test/java/org/apache/druid/server/RunningQueryRegistryTest.java b/server/src/test/java/org/apache/druid/server/RunningQueryRegistryTest.java new file mode 100644 index 000000000000..9b777e397ad8 --- /dev/null +++ b/server/src/test/java/org/apache/druid/server/RunningQueryRegistryTest.java @@ -0,0 +1,184 @@ +/* + * 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.server; + +import org.apache.druid.jackson.DefaultObjectMapper; +import org.apache.druid.query.Query; +import org.apache.druid.query.TableDataSource; +import org.apache.druid.server.initialization.ServerConfig; +import org.apache.druid.server.security.AuthenticationResult; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import java.util.List; + +public class RunningQueryRegistryTest +{ + private static final AuthenticationResult AUTHENTICATION_RESULT = + new AuthenticationResult("user", "basicAuthorizer", "basic", null); + + private RunningQueryRegistry registry; + + @BeforeEach + public void setUp() + { + registry = new RunningQueryRegistry(); + } + + @Test + public void testRegisterAndGetAll() + { + registry.register(createQuery("query-1", "timeseries", "sql-1", "foo"), null, AUTHENTICATION_RESULT); + + final List entries = registry.getAll(); + Assertions.assertEquals(1, entries.size()); + + final RunningQueryRegistry.Entry entry = entries.get(0); + Assertions.assertEquals("query-1", entry.getQueryId()); + Assertions.assertEquals("sql-1", entry.getSqlQueryId()); + Assertions.assertEquals("timeseries", entry.getQueryType()); + Assertions.assertEquals(List.of("foo"), entry.getDatasources()); + Assertions.assertEquals("user", entry.getIdentity()); + Assertions.assertEquals("basic", entry.getAuthenticator()); + Assertions.assertNotNull(entry.getStartTime()); + } + + @Test + public void testRegisterWithoutSqlQueryId() + { + registry.register(createQuery("query-1", "groupBy", null, "foo"), null, AUTHENTICATION_RESULT); + + Assertions.assertNull(registry.getAll().get(0).getSqlQueryId()); + } + + @Test + public void testRegisterWithoutAuthenticationResult() + { + registry.register(createQuery("query-1", "timeseries", null, "foo"), null, null); + + final RunningQueryRegistry.Entry entry = registry.getAll().get(0); + Assertions.assertNull(entry.getIdentity()); + Assertions.assertNull(entry.getAuthenticator()); + } + + @Test + public void testUnregister() + { + registry.register(createQuery("query-1", "timeseries", null, "foo"), null, AUTHENTICATION_RESULT); + Assertions.assertEquals(1, registry.getAll().size()); + + registry.unregister("query-1"); + Assertions.assertTrue(registry.getAll().isEmpty()); + + // Unregistering an unknown query is a no-op. + registry.unregister("query-1"); + registry.unregister("nonexistent"); + Assertions.assertTrue(registry.getAll().isEmpty()); + } + + @Test + public void testGetAllIsSortedByStartTime() + { + registry.register(createQuery("query-2", "timeseries", null, "bar"), null, null); + registry.register(createQuery("query-1", "timeseries", null, "foo"), null, null); + + final List entries = registry.getAll(); + Assertions.assertEquals(2, entries.size()); + Assertions.assertTrue(entries.get(0).getStartTime().compareTo(entries.get(1).getStartTime()) <= 0); + } + + @Test + public void testRegisterReplacesExistingEntry() + { + final Query query = createQuery("query-1", "timeseries", null, "foo"); + registry.register(query, null, null); + registry.register(query, null, null); + + Assertions.assertEquals(1, registry.getAll().size()); + } + + @Test + public void testRegisterWithoutQueryIdIsIgnored() + { + final Query query = Mockito.mock(Query.class); + Mockito.when(query.getId()).thenReturn(null); + + registry.register(query, null, AUTHENTICATION_RESULT); + Assertions.assertTrue(registry.getAll().isEmpty()); + } + + @Test + public void testUnregisterNullOrUnknownQueryIdIsNoOp() + { + registry.register(createQuery("query-1", "timeseries", null, "foo"), null, AUTHENTICATION_RESULT); + + registry.unregister(null); + registry.unregister("unknown"); + + Assertions.assertEquals(1, registry.getAll().size()); + } + + @Test + public void testQueryTextIsNotCapturedByDefault() throws Exception + { + registry.register(createQuery("query-1", "timeseries", null, "foo"), "SELECT * FROM foo", AUTHENTICATION_RESULT); + + final RunningQueryRegistry.Entry entry = registry.getAll().get(0); + Assertions.assertNull(entry.getSql()); + Assertions.assertNull(entry.getNativeQuery()); + } + + @Test + public void testQueryTextIsCapturedWhenEnabled() throws Exception + { + final Query query = createQuery("query-1", "timeseries", null, "foo"); + final RunningQueryRegistry registryWithText = new RunningQueryRegistry(createServerConfig(true)); + registryWithText.register(query, "SELECT * FROM foo", AUTHENTICATION_RESULT); + + final RunningQueryRegistry.Entry entry = registryWithText.getAll().get(0); + Assertions.assertEquals("SELECT * FROM foo", entry.getSql()); + Assertions.assertSame(query, entry.getNativeQuery()); + } + + private static Query createQuery( + final String queryId, + final String queryType, + final String sqlQueryId, + final String datasource + ) + { + final Query query = Mockito.mock(Query.class); + Mockito.when(query.getId()).thenReturn(queryId); + Mockito.when(query.getType()).thenReturn(queryType); + Mockito.when(query.getSqlQueryId()).thenReturn(sqlQueryId); + Mockito.when(query.getDataSource()).thenReturn(new TableDataSource(datasource)); + return query; + } + + private static ServerConfig createServerConfig(final boolean enableRunningQueryText) throws Exception + { + return new DefaultObjectMapper().readValue( + "{\"enableRunningQueryText\":" + enableRunningQueryText + "}", + ServerConfig.class + ); + } +} diff --git a/sql/src/main/java/org/apache/druid/sql/calcite/run/NativeQueryMaker.java b/sql/src/main/java/org/apache/druid/sql/calcite/run/NativeQueryMaker.java index 5ba0ab28c26f..481b0d98b7f1 100644 --- a/sql/src/main/java/org/apache/druid/sql/calcite/run/NativeQueryMaker.java +++ b/sql/src/main/java/org/apache/druid/sql/calcite/run/NativeQueryMaker.java @@ -207,7 +207,8 @@ private QueryResponse execute( authenticationResult, authorizationResult, // The user-set keys, as distinct from the defaults SQL merged into the context. - plannerContext.authContextKeys() + plannerContext.authContextKeys(), + plannerContext.getSql() ); return mapResultSequence( diff --git a/sql/src/main/java/org/apache/druid/sql/calcite/run/NativeSqlEngine.java b/sql/src/main/java/org/apache/druid/sql/calcite/run/NativeSqlEngine.java index c22ba01ee20a..3b4005428482 100644 --- a/sql/src/main/java/org/apache/druid/sql/calcite/run/NativeSqlEngine.java +++ b/sql/src/main/java/org/apache/druid/sql/calcite/run/NativeSqlEngine.java @@ -28,17 +28,30 @@ import org.apache.calcite.rel.type.RelDataTypeFactory; import org.apache.druid.error.InvalidSqlInput; import org.apache.druid.guice.LazySingleton; +import org.apache.druid.indexer.report.TaskReport; import org.apache.druid.java.util.common.logger.Logger; import org.apache.druid.query.JoinAlgorithm; +import org.apache.druid.query.Query; import org.apache.druid.query.QueryContext; import org.apache.druid.query.context.QueryContextParameters; import org.apache.druid.server.QueryLifecycleFactory; import org.apache.druid.server.QueryScheduler; +import org.apache.druid.server.RunningQueryRegistry; +import org.apache.druid.server.security.AuthenticationResult; +import org.apache.druid.server.security.AuthorizationResult; import org.apache.druid.sql.SqlStatementFactory; import org.apache.druid.sql.SqlToolbox; import org.apache.druid.sql.calcite.planner.PlannerContext; import org.apache.druid.sql.destination.IngestDestination; +import org.apache.druid.sql.http.GetQueriesResponse; +import org.apache.druid.sql.http.GetQueryReportResponse; +import org.apache.druid.sql.http.NativeQueryInfo; +import org.apache.druid.sql.http.QueryInfo; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; @@ -62,17 +75,20 @@ public class NativeSqlEngine implements SqlEngine private final QueryLifecycleFactory queryLifecycleFactory; private final ObjectMapper jsonMapper; private final SqlStatementFactory sqlStatementFactory; + private final RunningQueryRegistry runningQueryRegistry; @Inject public NativeSqlEngine( final QueryLifecycleFactory queryLifecycleFactory, final ObjectMapper jsonMapper, - final SqlToolbox toolbox + final SqlToolbox toolbox, + final RunningQueryRegistry runningQueryRegistry ) { this.queryLifecycleFactory = queryLifecycleFactory; this.jsonMapper = jsonMapper; this.sqlStatementFactory = new SqlStatementFactory(toolbox.withEngine(this)); + this.runningQueryRegistry = runningQueryRegistry; } @VisibleForTesting @@ -81,10 +97,22 @@ public NativeSqlEngine( final ObjectMapper jsonMapper, final SqlStatementFactory sqlStatementFactory ) + { + this(queryLifecycleFactory, jsonMapper, sqlStatementFactory, new RunningQueryRegistry()); + } + + @VisibleForTesting + public NativeSqlEngine( + final QueryLifecycleFactory queryLifecycleFactory, + final ObjectMapper jsonMapper, + final SqlStatementFactory sqlStatementFactory, + final RunningQueryRegistry runningQueryRegistry + ) { this.queryLifecycleFactory = queryLifecycleFactory; this.jsonMapper = jsonMapper; this.sqlStatementFactory = sqlStatementFactory; + this.runningQueryRegistry = runningQueryRegistry; } @Override @@ -93,6 +121,128 @@ public String name() return NAME; } + /** + * Returns the queries that are currently executing on this server. Completed queries are not retained by the native + * engine, so the {@code includeComplete} parameter has no effect. This engine has no way to collect queries from + * other servers, so the list is always local to this server, regardless of the {@code selfOnly} parameter. + */ + @Override + public GetQueriesResponse getQueries( + final boolean selfOnly, + final boolean includeComplete, + final AuthenticationResult authenticationResult, + final AuthorizationResult stateReadAuthorization + ) + { + final boolean canViewAllQueries = stateReadAuthorization.allowAccessWithNoRestriction(); + final List queries = new ArrayList<>(); + + for (final RunningQueryRegistry.Entry entry : runningQueryRegistry.getAll()) { + // Compute the ownership check and the redacted view for every query, so that the visibility decision never + // depends on which queries the caller happens to own. + final boolean ownQuery = isOwnQuery(authenticationResult, entry); + final NativeQueryInfo queryInfo = NativeQueryInfo.fromEntry(entry); + final NativeQueryInfo queryInfoWithoutAuthenticationResult = queryInfo.withoutAuthenticationResult(); + + if (canViewAllQueries || ownQuery) { + // Users with READ permission on the STATE resource see all queries, including authentication details. Other + // users see only their own queries, without authentication details. + queries.add(canViewAllQueries ? queryInfo : queryInfoWithoutAuthenticationResult); + } + } + + return new GetQueriesResponse(queries); + } + + /** + * Returns the query info, including query text, for a query that is running on this server. The query can be + * looked up by its {@code sqlQueryId} or by its query ID. Returns null if the query is not running, or if the + * caller is not allowed to see it. + */ + @Nullable + @Override + public GetQueryReportResponse getQueryReport( + final String sqlQueryId, + final boolean selfOnly, + final AuthenticationResult authenticationResult, + final AuthorizationResult stateReadAuthorization + ) + { + final boolean canViewAllQueries = stateReadAuthorization.allowAccessWithNoRestriction(); + + for (final RunningQueryRegistry.Entry entry : runningQueryRegistry.getAll()) { + // Compute the ownership check for every query, so that the visibility decision never depends on which queries + // the caller happens to own. + final boolean ownQuery = isOwnQuery(authenticationResult, entry); + + final boolean idMatches = + sqlQueryId.equals(entry.getSqlQueryId()) || sqlQueryId.equals(entry.getQueryId()); + + if (!idMatches) { + continue; + } + + if (!canViewAllQueries && !ownQuery) { + continue; + } + + final NativeQueryInfo queryInfo = + NativeQueryInfo.fromEntryWithText(entry, serializeQuery(entry.getNativeQuery())); + final NativeQueryInfo queryInfoWithoutAuthenticationResult = queryInfo.withoutAuthenticationResult(); + + return new GetQueryReportResponse( + canViewAllQueries ? queryInfo : queryInfoWithoutAuthenticationResult, + new TaskReport.ReportMap() + ); + } + + return null; + } + + /** + * Serializes the given native query, for the running queries API. Returns null when there is no query, or when the + * query cannot be serialized. + */ + @Nullable + private String serializeQuery(@Nullable final Query query) + { + if (query == null) { + return null; + } + + try { + return jsonMapper.writeValueAsString(query); + } + catch (Exception e) { + LOG.warn(e, "Could not serialize query[%s] for the running queries API", query.getId()); + return null; + } + } + + /** + * Returns whether the given query belongs to the authenticated user, following the same rules as + * {@code DartSqlEngine#isOwnQuery}. + */ + private static boolean isOwnQuery( + final AuthenticationResult authenticationResult, + final RunningQueryRegistry.Entry entry + ) + { + return isOwnQuery(authenticationResult, entry.getAuthenticator(), entry.getIdentity()); + } + + private static boolean isOwnQuery( + final AuthenticationResult authenticationResult, + @Nullable final String authenticator, + @Nullable final String identity + ) + { + return authenticationResult.getAuthenticatedBy() != null + && authenticationResult.getIdentity() != null + && Objects.equals(authenticationResult.getAuthenticatedBy(), authenticator) + && Objects.equals(authenticationResult.getIdentity(), identity); + } + @Override public void validateContext(QueryContext queryContext) { diff --git a/sql/src/main/java/org/apache/druid/sql/guice/SqlModule.java b/sql/src/main/java/org/apache/druid/sql/guice/SqlModule.java index 8fee6e2a2f98..5fefe56d0b56 100644 --- a/sql/src/main/java/org/apache/druid/sql/guice/SqlModule.java +++ b/sql/src/main/java/org/apache/druid/sql/guice/SqlModule.java @@ -19,6 +19,8 @@ package org.apache.druid.sql.guice; +import com.fasterxml.jackson.databind.jsontype.NamedType; +import com.fasterxml.jackson.databind.module.SimpleModule; import com.google.common.base.Preconditions; import com.google.inject.Binder; import com.google.inject.Inject; @@ -30,6 +32,7 @@ import org.apache.druid.guice.LazySingleton; import org.apache.druid.guice.PolyBind; import org.apache.druid.guice.annotations.NativeQuery; +import org.apache.druid.initialization.DruidModule; import org.apache.druid.java.util.emitter.service.ServiceEmitter; import org.apache.druid.server.QueryScheduler; import org.apache.druid.server.log.RequestLogger; @@ -51,11 +54,14 @@ import org.apache.druid.sql.calcite.view.DruidViewModule; import org.apache.druid.sql.calcite.view.NoopViewManager; import org.apache.druid.sql.calcite.view.ViewManager; +import org.apache.druid.sql.http.NativeQueryInfo; import org.apache.druid.sql.http.SqlHttpModule; +import java.util.Collections; +import java.util.List; import java.util.Properties; -public class SqlModule implements Module +public class SqlModule implements DruidModule { public static final String PROPERTY_SQL_ENABLE = "druid.sql.enable"; public static final String PROPERTY_SQL_ENABLE_JSON_OVER_HTTP = "druid.sql.http.enable"; @@ -204,4 +210,17 @@ public void configure(Binder binder) // Do nothing, this class exists for the Provider methods } } + + @Override + public List getJacksonModules() + { + return Collections.singletonList( + new SimpleModule("SqlModule").registerSubtypes( + new NamedType( + NativeQueryInfo.class, + NativeSqlEngine.NAME + ) + ) + ); + } } diff --git a/sql/src/main/java/org/apache/druid/sql/http/NativeQueryInfo.java b/sql/src/main/java/org/apache/druid/sql/http/NativeQueryInfo.java new file mode 100644 index 000000000000..656124029ef1 --- /dev/null +++ b/sql/src/main/java/org/apache/druid/sql/http/NativeQueryInfo.java @@ -0,0 +1,243 @@ +/* + * 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.sql.http; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.druid.server.RunningQueryRegistry; +import org.apache.druid.sql.calcite.run.NativeSqlEngine; +import org.joda.time.DateTime; + +import javax.annotation.Nullable; +import java.util.List; + +/** + * Class included in {@link GetQueriesResponse} for queries running on the {@link NativeSqlEngine}. Instances are + * created from {@link RunningQueryRegistry.Entry}. + */ +public class NativeQueryInfo implements QueryInfo +{ + private final String queryId; + @Nullable + private final String sqlQueryId; + private final String queryType; + private final List datasources; + @Nullable + private final String identity; + @Nullable + private final String authenticator; + @Nullable + private final String sql; + @Nullable + private final String nativeQuery; + private final DateTime startTime; + + @JsonCreator + public NativeQueryInfo( + @JsonProperty("queryId") final String queryId, + @JsonProperty("sqlQueryId") @Nullable final String sqlQueryId, + @JsonProperty("queryType") final String queryType, + @JsonProperty("datasources") final List datasources, + @JsonProperty("identity") @Nullable final String identity, + @JsonProperty("authenticator") @Nullable final String authenticator, + @JsonProperty("sql") @Nullable final String sql, + @JsonProperty("nativeQuery") @Nullable final String nativeQuery, + @JsonProperty("startTime") final DateTime startTime + ) + { + this.queryId = queryId; + this.sqlQueryId = sqlQueryId; + this.queryType = queryType; + this.datasources = datasources; + this.identity = identity; + this.authenticator = authenticator; + this.sql = sql; + this.nativeQuery = nativeQuery; + this.startTime = startTime; + } + + public static NativeQueryInfo fromEntry(final RunningQueryRegistry.Entry entry) + { + return fromEntry(entry, null, null); + } + + /** + * Returns the info for a query, including its text. The text is only included if the server captured it; see + * {@code druid.server.http.enableRunningQueryText}. + */ + public static NativeQueryInfo fromEntryWithText( + final RunningQueryRegistry.Entry entry, + @Nullable final String nativeQuery + ) + { + return fromEntry(entry, entry.getSql(), nativeQuery); + } + + private static NativeQueryInfo fromEntry( + final RunningQueryRegistry.Entry entry, + @Nullable final String sql, + @Nullable final String nativeQuery + ) + { + return new NativeQueryInfo( + entry.getQueryId(), + entry.getSqlQueryId(), + entry.getQueryType(), + entry.getDatasources(), + entry.getIdentity(), + entry.getAuthenticator(), + sql, + nativeQuery, + entry.getStartTime() + ); + } + + /** + * Returns a copy of this object without the identity and authenticator, for callers that are not authorized to see + * details about other users' queries. + */ + public NativeQueryInfo withoutAuthenticationResult() + { + return new NativeQueryInfo(queryId, sqlQueryId, queryType, datasources, null, null, sql, nativeQuery, startTime); + } + + @Override + public String engine() + { + return NativeSqlEngine.NAME; + } + + /** + * Always {@link StandardQueryState#RUNNING}, because the native engine does not retain completed queries, so + * {@code includeComplete} has no effect on it. + */ + @Override + public String state() + { + return StandardQueryState.RUNNING; + } + + @JsonProperty + public String getState() + { + return state(); + } + + @Override + public String executionId() + { + return queryId; + } + + /** + * ID of this native query. This is the ID that can be passed to {@code DELETE /druid/v2/{queryId}} to cancel it. + */ + @JsonProperty + public String getQueryId() + { + return queryId; + } + + /** + * The {@code sqlQueryId} of the SQL query that this native query belongs to, if this query was created by the SQL + * layer. This is the ID that can be passed to {@code DELETE /druid/v2/sql/{sqlQueryId}} to cancel it. + */ + @JsonProperty + @JsonInclude(JsonInclude.Include.NON_NULL) + @Nullable + public String getSqlQueryId() + { + return sqlQueryId; + } + + /** + * Native query type, such as "timeseries", "topN", or "groupBy". + */ + @JsonProperty + public String getQueryType() + { + return queryType; + } + + /** + * Names of the datasources being queried. + */ + @JsonProperty + public List getDatasources() + { + return datasources; + } + + /** + * Identity of the user that submitted this query. + */ + @JsonProperty + @JsonInclude(JsonInclude.Include.NON_NULL) + @Nullable + public String getIdentity() + { + return identity; + } + + /** + * Authenticator that authenticated the identity from {@link #getIdentity()}. + */ + @JsonProperty + @JsonInclude(JsonInclude.Include.NON_NULL) + @Nullable + public String getAuthenticator() + { + return authenticator; + } + + /** + * SQL text of the query, when the query came in through the SQL layer. Only included when the server is configured + * to capture running query text with {@code druid.server.http.enableRunningQueryText}. + */ + @JsonProperty + @JsonInclude(JsonInclude.Include.NON_NULL) + @Nullable + public String getSql() + { + return sql; + } + + /** + * JSON-serialized native query. Only included when the server is configured to capture running query text with + * {@code druid.server.http.enableRunningQueryText}. + */ + @JsonProperty + @JsonInclude(JsonInclude.Include.NON_NULL) + @Nullable + public String getNativeQuery() + { + return nativeQuery; + } + + /** + * Time at which this query started executing on this server. + */ + @JsonProperty + public DateTime getStartTime() + { + return startTime; + } +} diff --git a/sql/src/main/java/org/apache/druid/sql/http/SqlResource.java b/sql/src/main/java/org/apache/druid/sql/http/SqlResource.java index 3132b42fb734..01a8ea74b732 100644 --- a/sql/src/main/java/org/apache/druid/sql/http/SqlResource.java +++ b/sql/src/main/java/org/apache/druid/sql/http/SqlResource.java @@ -142,7 +142,9 @@ public Response doPost( } /** - * API to list all running queries, for all engines that supports such listings. + * API to list all running queries, for all engines that supports such listings. Although this API lives under + * {@code /druid/v2/sql/}, it is not limited to SQL queries: the native engine also reports the native queries that + * were submitted directly to {@code /druid/v2/}. * * @param selfOnly if present, return queries running on this server only. If absent, return queries * running on all servers. @@ -188,7 +190,7 @@ public Response doGetRunningQueries( /** * API to get query reports, for all engines that support such reports. * - * @param sqlQueryId SQL query ID + * @param sqlQueryId SQL query ID, or native query ID for engines that support native queries * @param selfOnly if true, check reports from this server only. If false, check reports on all servers. * @param request http request. */ diff --git a/sql/src/test/java/org/apache/druid/sql/calcite/run/NativeSqlEngineTest.java b/sql/src/test/java/org/apache/druid/sql/calcite/run/NativeSqlEngineTest.java new file mode 100644 index 000000000000..7fc511317447 --- /dev/null +++ b/sql/src/test/java/org/apache/druid/sql/calcite/run/NativeSqlEngineTest.java @@ -0,0 +1,367 @@ +/* + * 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.sql.calcite.run; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.druid.jackson.DefaultObjectMapper; +import org.apache.druid.query.Query; +import org.apache.druid.query.TableDataSource; +import org.apache.druid.server.RunningQueryRegistry; +import org.apache.druid.server.initialization.ServerConfig; +import org.apache.druid.server.security.AuthenticationResult; +import org.apache.druid.server.security.AuthorizationResult; +import org.apache.druid.sql.SqlStatementFactory; +import org.apache.druid.sql.guice.SqlModule; +import org.apache.druid.sql.http.GetQueriesResponse; +import org.apache.druid.sql.http.GetQueryReportResponse; +import org.apache.druid.sql.http.NativeQueryInfo; +import org.apache.druid.sql.http.QueryInfo; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import java.util.List; + +public class NativeSqlEngineTest +{ + private static final AuthenticationResult USER = + new AuthenticationResult("user", "basicAuthorizer", "basic", null); + private static final AuthenticationResult OTHER_USER = + new AuthenticationResult("other", "basicAuthorizer", "basic", null); + + private RunningQueryRegistry registry; + private NativeSqlEngine engine; + + @BeforeEach + public void setUp() + { + registry = new RunningQueryRegistry(); + engine = new NativeSqlEngine(null, null, (SqlStatementFactory) null, registry); + } + + @Test + public void testGetQueriesReturnsRunningQueries() throws Exception + { + registry.register(createQuery("query-1", "timeseries", "sql-1", "foo"), null, USER); + + final GetQueriesResponse response = + engine.getQueries(false, false, USER, AuthorizationResult.ALLOW_NO_RESTRICTION); + + Assertions.assertEquals(1, response.getQueries().size()); + final QueryInfo queryInfo = response.getQueries().get(0); + Assertions.assertTrue(queryInfo instanceof NativeQueryInfo); + Assertions.assertEquals(NativeSqlEngine.NAME, queryInfo.engine()); + Assertions.assertEquals("RUNNING", queryInfo.state()); + Assertions.assertEquals("query-1", queryInfo.executionId()); + + final NativeQueryInfo nativeQueryInfo = (NativeQueryInfo) queryInfo; + Assertions.assertEquals("query-1", nativeQueryInfo.getQueryId()); + Assertions.assertEquals("sql-1", nativeQueryInfo.getSqlQueryId()); + Assertions.assertEquals("timeseries", nativeQueryInfo.getQueryType()); + Assertions.assertEquals(List.of("foo"), nativeQueryInfo.getDatasources()); + Assertions.assertEquals("user", nativeQueryInfo.getIdentity()); + Assertions.assertEquals("basic", nativeQueryInfo.getAuthenticator()); + } + + @Test + public void testGetQueriesFiltersByIdentityWithoutStateRead() + { + registry.register(createQuery("query-1", "timeseries", null, "foo"), null, USER); + registry.register(createQuery("query-2", "timeseries", null, "bar"), null, OTHER_USER); + + final GetQueriesResponse ownQueries = engine.getQueries(false, false, USER, AuthorizationResult.DENY); + Assertions.assertEquals(1, ownQueries.getQueries().size()); + Assertions.assertEquals("query-1", ownQueries.getQueries().get(0).executionId()); + + final GetQueriesResponse allQueries = + engine.getQueries(false, false, USER, AuthorizationResult.ALLOW_NO_RESTRICTION); + Assertions.assertEquals(2, allQueries.getQueries().size()); + } + + @Test + public void testGetQueriesDoesNotMatchIdentityFromDifferentAuthenticator() + { + registry.register(createQuery("query-1", "timeseries", null, "foo"), null, USER); + + // Same identity string, but a different authenticator: the query must not be visible. + final AuthenticationResult otherAuthenticator = + new AuthenticationResult("user", "basicAuthorizer", "ldap", null); + final GetQueriesResponse response = engine.getQueries(false, false, otherAuthenticator, AuthorizationResult.DENY); + + Assertions.assertTrue(response.getQueries().isEmpty()); + } + + @Test + public void testGetQueriesHidesQueriesWithoutIdentity() + { + registry.register(createQuery("query-1", "timeseries", null, "foo"), null, null); + + final GetQueriesResponse response = engine.getQueries(false, false, USER, AuthorizationResult.DENY); + Assertions.assertTrue(response.getQueries().isEmpty()); + } + + @Test + public void testGetQueriesWithoutStateReadHidesIdentity() + { + registry.register(createQuery("query-1", "timeseries", null, "foo"), null, USER); + + final NativeQueryInfo ownQuery = (NativeQueryInfo) engine.getQueries(false, false, USER, AuthorizationResult.DENY) + .getQueries() + .get(0); + Assertions.assertNull(ownQuery.getIdentity()); + Assertions.assertNull(ownQuery.getAuthenticator()); + + final NativeQueryInfo allQuery = + (NativeQueryInfo) engine.getQueries(false, false, USER, AuthorizationResult.ALLOW_NO_RESTRICTION) + .getQueries() + .get(0); + Assertions.assertEquals("user", allQuery.getIdentity()); + Assertions.assertEquals("basic", allQuery.getAuthenticator()); + } + + @Test + public void testGetQueriesWithoutIdentityOrAuthenticatorIsEmpty() + { + registry.register(createQuery("query-1", "timeseries", null, "foo"), null, USER); + + // Requests without an authenticated identity or authenticator see no queries. + Assertions.assertTrue( + engine.getQueries(false, false, new AuthenticationResult("user", "basicAuthorizer", null, null), + AuthorizationResult.DENY) + .getQueries() + .isEmpty() + ); + Assertions.assertTrue( + engine.getQueries(false, false, new AuthenticationResult(null, "basicAuthorizer", "basic", null), + AuthorizationResult.DENY) + .getQueries() + .isEmpty() + ); + } + + @Test + public void testGetQueriesDoesNotIncludeQueryText() throws Exception + { + final ObjectMapper jsonMapper = Mockito.mock(ObjectMapper.class); + Mockito.when(jsonMapper.writeValueAsString(Mockito.any())).thenReturn("{\"queryType\":\"timeseries\"}"); + + final RunningQueryRegistry registryWithText = new RunningQueryRegistry(createServerConfig(true)); + final NativeSqlEngine engineWithText = + new NativeSqlEngine(null, jsonMapper, (SqlStatementFactory) null, registryWithText); + + registryWithText.register( + createQuery("query-1", "timeseries", "sql-1", "foo"), + "SELECT * FROM foo", + USER + ); + + final NativeQueryInfo queryInfo = (NativeQueryInfo) engineWithText.getQueries( + false, + false, + USER, + AuthorizationResult.ALLOW_NO_RESTRICTION + ).getQueries().get(0); + + Assertions.assertNull(queryInfo.getSql()); + Assertions.assertNull(queryInfo.getNativeQuery()); + } + + @Test + public void testGetQueryReportIncludesQueryText() throws Exception + { + final ObjectMapper jsonMapper = Mockito.mock(ObjectMapper.class); + Mockito.when(jsonMapper.writeValueAsString(Mockito.any())).thenReturn("{\"queryType\":\"timeseries\"}"); + + final RunningQueryRegistry registryWithText = new RunningQueryRegistry(createServerConfig(true)); + final NativeSqlEngine engineWithText = + new NativeSqlEngine(null, jsonMapper, (SqlStatementFactory) null, registryWithText); + + registryWithText.register( + createQuery("query-1", "timeseries", "sql-1", "foo"), + "SELECT * FROM foo", + USER + ); + + // Look up by sqlQueryId. + final GetQueryReportResponse bySqlQueryId = engineWithText.getQueryReport( + "sql-1", + true, + USER, + AuthorizationResult.ALLOW_NO_RESTRICTION + ); + Assertions.assertNotNull(bySqlQueryId); + final NativeQueryInfo queryInfo = (NativeQueryInfo) bySqlQueryId.getQueryInfo(); + Assertions.assertEquals("SELECT * FROM foo", queryInfo.getSql()); + Assertions.assertEquals("{\"queryType\":\"timeseries\"}", queryInfo.getNativeQuery()); + + // Look up by query ID. + Assertions.assertNotNull( + engineWithText.getQueryReport("query-1", true, USER, AuthorizationResult.ALLOW_NO_RESTRICTION) + ); + } + + @Test + public void testGetQueryReportIsEmptyForUnknownQuery() throws Exception + { + final NativeSqlEngine engineWithText = new NativeSqlEngine( + null, + new DefaultObjectMapper(), + (SqlStatementFactory) null, + new RunningQueryRegistry() + ); + + Assertions.assertNull( + engineWithText.getQueryReport("unknown", true, USER, AuthorizationResult.ALLOW_NO_RESTRICTION) + ); + } + + @Test + public void testGetQueryReportIsEmptyForOtherUsersQueryWithoutStateRead() throws Exception + { + final RunningQueryRegistry registryWithText = new RunningQueryRegistry(); + final NativeSqlEngine engineWithText = new NativeSqlEngine( + null, + new DefaultObjectMapper(), + (SqlStatementFactory) null, + registryWithText + ); + + registryWithText.register( + createQuery("query-1", "timeseries", "sql-1", "foo"), + null, + OTHER_USER + ); + + Assertions.assertNull(engineWithText.getQueryReport("sql-1", true, USER, AuthorizationResult.DENY)); + Assertions.assertNotNull( + engineWithText.getQueryReport("sql-1", true, USER, AuthorizationResult.ALLOW_NO_RESTRICTION) + ); + } + + @Test + public void testGetQueryReportSkipsOtherUsersQueriesWithTheSameId() throws Exception + { + final RunningQueryRegistry registryWithText = new RunningQueryRegistry(createServerConfig(true)); + final NativeSqlEngine engineWithText = new NativeSqlEngine( + null, + new DefaultObjectMapper(), + (SqlStatementFactory) null, + registryWithText + ); + + // Another user's query with the same sqlQueryId, started first. + registryWithText.register( + createQuery("query-1", "timeseries", "shared-id", "foo"), + "SELECT 1", + OTHER_USER + ); + registryWithText.register( + createQuery("query-2", "groupBy", "shared-id", "foo"), + "SELECT 2", + USER + ); + + // The user must see their own query, not the first query with the matching ID. + final GetQueryReportResponse report = + engineWithText.getQueryReport("shared-id", true, USER, AuthorizationResult.DENY); + Assertions.assertNotNull(report); + Assertions.assertEquals("query-2", report.getQueryInfo().executionId()); + } + + @Test + public void testGetQueryReportHasNoTextWhenCaptureIsDisabled() throws Exception + { + final RunningQueryRegistry registryWithoutText = new RunningQueryRegistry(); + final NativeSqlEngine engineWithoutText = new NativeSqlEngine( + null, + new DefaultObjectMapper(), + (SqlStatementFactory) null, + registryWithoutText + ); + + registryWithoutText.register( + createQuery("query-1", "timeseries", "sql-1", "foo"), + "SELECT * FROM foo", + USER + ); + + final GetQueryReportResponse report = + engineWithoutText.getQueryReport("sql-1", true, USER, AuthorizationResult.ALLOW_NO_RESTRICTION); + Assertions.assertNotNull(report); + final NativeQueryInfo queryInfo = (NativeQueryInfo) report.getQueryInfo(); + Assertions.assertNull(queryInfo.getSql()); + Assertions.assertNull(queryInfo.getNativeQuery()); + } + + @Test + public void testGetQueriesReturnsEmptyAfterUnregister() + { + registry.register(createQuery("query-1", "timeseries", null, "foo"), null, USER); + registry.unregister("query-1"); + + final GetQueriesResponse response = + engine.getQueries(false, false, USER, AuthorizationResult.ALLOW_NO_RESTRICTION); + + Assertions.assertTrue(response.getQueries().isEmpty()); + } + + @Test + public void testGetQueriesSerialization() throws Exception + { + registry.register(createQuery("query-1", "timeseries", "sql-1", "foo"), null, USER); + + final ObjectMapper mapper = new DefaultObjectMapper(); + new SqlModule().getJacksonModules().forEach(mapper::registerModule); + + final String json = mapper.writeValueAsString( + engine.getQueries(false, false, USER, AuthorizationResult.ALLOW_NO_RESTRICTION) + ); + + Assertions.assertTrue(json.contains("\"engine\":\"native\""), json); + Assertions.assertTrue(json.contains("\"queryId\":\"query-1\""), json); + Assertions.assertTrue(json.contains("\"sqlQueryId\":\"sql-1\""), json); + Assertions.assertTrue(json.contains("\"state\":\"RUNNING\""), json); + Assertions.assertTrue(json.contains("\"datasources\":[\"foo\"]"), json); + } + + private static Query createQuery( + final String queryId, + final String queryType, + final String sqlQueryId, + final String datasource + ) + { + final Query query = Mockito.mock(Query.class); + Mockito.when(query.getId()).thenReturn(queryId); + Mockito.when(query.getType()).thenReturn(queryType); + Mockito.when(query.getSqlQueryId()).thenReturn(sqlQueryId); + Mockito.when(query.getDataSource()).thenReturn(new TableDataSource(datasource)); + return query; + } + + private static ServerConfig createServerConfig(final boolean enableRunningQueryText) throws Exception + { + return new DefaultObjectMapper().readValue( + "{\"enableRunningQueryText\":" + enableRunningQueryText + "}", + ServerConfig.class + ); + } +} diff --git a/sql/src/test/java/org/apache/druid/sql/http/NativeSqlEngineRunningQueriesTest.java b/sql/src/test/java/org/apache/druid/sql/http/NativeSqlEngineRunningQueriesTest.java new file mode 100644 index 000000000000..bcca25ad3ddb --- /dev/null +++ b/sql/src/test/java/org/apache/druid/sql/http/NativeSqlEngineRunningQueriesTest.java @@ -0,0 +1,282 @@ +/* + * 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.sql.http; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableSet; +import org.apache.druid.jackson.DefaultObjectMapper; +import org.apache.druid.java.util.common.guava.Sequence; +import org.apache.druid.java.util.common.io.Closer; +import org.apache.druid.query.DefaultGenericQueryMetricsFactory; +import org.apache.druid.query.DefaultQueryConfig; +import org.apache.druid.query.Query; +import org.apache.druid.query.QueryPlus; +import org.apache.druid.query.QueryRunner; +import org.apache.druid.query.QueryRunnerFactoryConglomerate; +import org.apache.druid.query.QuerySegmentWalker; +import org.apache.druid.query.SegmentDescriptor; +import org.apache.druid.query.context.ResponseContext; +import org.apache.druid.query.policy.NoopPolicyEnforcer; +import org.apache.druid.server.DruidNode; +import org.apache.druid.server.QueryLifecycleFactory; +import org.apache.druid.server.QueryScheduler; +import org.apache.druid.server.QueryStackTests; +import org.apache.druid.server.ResponseContextConfig; +import org.apache.druid.server.RunningQueryRegistry; +import org.apache.druid.server.SpecificSegmentsQuerySegmentWalker; +import org.apache.druid.server.initialization.ServerConfig; +import org.apache.druid.server.log.NoopRequestLogger; +import org.apache.druid.server.metrics.NoopServiceEmitter; +import org.apache.druid.server.mocks.MockHttpServletRequest; +import org.apache.druid.server.mocks.MockHttpServletResponse; +import org.apache.druid.server.scheduling.HiLoQueryLaningStrategy; +import org.apache.druid.server.scheduling.ManualQueryPrioritizationStrategy; +import org.apache.druid.server.security.AuthConfig; +import org.apache.druid.server.security.AuthorizationResult; +import org.apache.druid.sql.SqlLifecycleManager; +import org.apache.druid.sql.SqlToolbox; +import org.apache.druid.sql.calcite.planner.CalciteRulesManager; +import org.apache.druid.sql.calcite.planner.CatalogResolver; +import org.apache.druid.sql.calcite.planner.PlannerConfig; +import org.apache.druid.sql.calcite.planner.PlannerFactory; +import org.apache.druid.sql.calcite.run.NativeSqlEngine; +import org.apache.druid.sql.calcite.schema.DruidSchemaCatalogProvider; +import org.apache.druid.sql.calcite.util.CalciteTests; +import org.apache.druid.sql.calcite.util.QueryFrameworkUtils; +import org.apache.druid.sql.hook.DruidHookDispatcher; +import org.joda.time.Interval; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.File; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; + +/** + * Functional test for the "list running queries" API: runs a real SQL query through {@link SqlResource} and verifies + * that the query is reported as running while it executes, and that it disappears once it completes. + */ +public class NativeSqlEngineRunningQueriesTest +{ + private static final ObjectMapper JSON_MAPPER = new DefaultObjectMapper(); + private static final DruidNode DUMMY_DRUID_NODE = new DruidNode("dummy", "dummy", false, 1, null, true, false); + private static final ResponseContextConfig RESPONSE_CONTEXT_CONFIG = ResponseContextConfig.newConfig(false); + + @TempDir + File tempDir; + + private Closer closer; + private QueryRunnerFactoryConglomerate conglomerate; + private SpecificSegmentsQuerySegmentWalker walker; + + @BeforeEach + public void setUp() + { + closer = Closer.create(); + conglomerate = QueryStackTests.createQueryRunnerFactoryConglomerate(closer); + walker = CalciteTests.createMockWalker(conglomerate, tempDir); + closer.register(walker); + } + + @AfterEach + public void tearDown() throws Exception + { + closer.close(); + } + + @Test + public void testQueryIsVisibleWhileRunning() throws Exception + { + final RunningQueryRegistry registry = new RunningQueryRegistry( + new DefaultObjectMapper().readValue("{\"enableRunningQueryText\":true}", ServerConfig.class) + ); + final AtomicReference engineRef = new AtomicReference<>(); + final AtomicReference runningQuerySeenDuringExecution = new AtomicReference<>(); + final AtomicReference reportSeenDuringExecution = new AtomicReference<>(); + + // Wraps the real test walker, so that we can observe the API from within query execution. + final QuerySegmentWalker observingWalker = new QuerySegmentWalker() + { + @Override + public QueryRunner getQueryRunnerForIntervals(final Query query, final Iterable intervals) + { + return observe(walker.getQueryRunnerForIntervals(query, intervals)); + } + + @Override + public QueryRunner getQueryRunnerForSegments( + final Query query, + final Iterable specs + ) + { + return observe(walker.getQueryRunnerForSegments(query, specs)); + } + + private QueryRunner observe(final QueryRunner runner) + { + return new QueryRunner() + { + @Override + public Sequence run(final QueryPlus queryPlus, final ResponseContext responseContext) + { + final List runningQueries = + engineRef.get() + .getQueries( + false, + false, + CalciteTests.SUPER_USER_AUTH_RESULT, + AuthorizationResult.ALLOW_NO_RESTRICTION + ) + .getQueries(); + final NativeQueryInfo runningQuery = (NativeQueryInfo) runningQueries.get(0); + runningQuerySeenDuringExecution.set(runningQuery); + reportSeenDuringExecution.set( + engineRef.get() + .getQueryReport( + runningQuery.executionId(), + true, + CalciteTests.SUPER_USER_AUTH_RESULT, + AuthorizationResult.ALLOW_NO_RESTRICTION + ) + ); + return runner.run(queryPlus, responseContext); + } + }; + } + }; + + final QueryLifecycleFactory queryLifecycleFactory = new QueryLifecycleFactory( + conglomerate, + observingWalker, + new DefaultGenericQueryMetricsFactory(), + NoopServiceEmitter.instance(), + NoopRequestLogger.instance(), + new AuthConfig(), + NoopPolicyEnforcer.instance(), + CalciteTests.TEST_AUTHORIZER_MAPPER, + new DefaultQueryConfig(Map.of()), + null, + registry + ); + + final SqlLifecycleManager lifecycleManager = new SqlLifecycleManager(); + final QueryScheduler scheduler = new QueryScheduler( + 5, + ManualQueryPrioritizationStrategy.INSTANCE, + new HiLoQueryLaningStrategy(40), + new ServerConfig(false) + ); + final PlannerConfig plannerConfig = PlannerConfig.builder().build(); + final DruidSchemaCatalogProvider schemaProvider = CalciteTests.createMockRootSchemaProvider( + conglomerate, + walker, + plannerConfig, + CalciteTests.TEST_AUTHORIZER_MAPPER + ); + final PlannerFactory plannerFactory = new PlannerFactory( + schemaProvider, + CalciteTests.createOperatorTable(), + CalciteTests.createExprMacroTable(), + plannerConfig, + CalciteTests.TEST_AUTHORIZER_MAPPER, + CalciteTests.getJsonMapper(), + CalciteTests.DRUID_SCHEMA_NAME, + new CalciteRulesManager(ImmutableSet.of()), + CalciteTests.createJoinableFactoryWrapper(), + CatalogResolver.NULL_RESOLVER, + new AuthConfig(), + NoopPolicyEnforcer.instance(), + new DruidHookDispatcher() + ); + final SqlToolbox sqlToolbox = new SqlToolbox( + null, + plannerFactory, + NoopServiceEmitter.instance(), + NoopRequestLogger.instance(), + scheduler, + lifecycleManager + ); + + final NativeSqlEngine engine = new NativeSqlEngine(queryLifecycleFactory, JSON_MAPPER, sqlToolbox, registry); + engineRef.set(engine); + + final SqlResource resource = new SqlResource( + CalciteTests.TEST_AUTHORIZER_MAPPER, + lifecycleManager, + new SqlEngineRegistry(Set.of(engine)), + new SqlResourceQueryResultPusherFactory( + JSON_MAPPER, + new ServerConfig(), + RESPONSE_CONTEXT_CONFIG, + DUMMY_DRUID_NODE + ), + DefaultQueryConfig.NIL, + new ServerConfig(), + QueryFrameworkUtils.TEST_QUERY_CONTEXT_CONFIG + ); + + final MockHttpServletRequest req = new MockHttpServletRequest(); + req.attributes.put(AuthConfig.DRUID_AUTHENTICATION_RESULT, CalciteTests.SUPER_USER_AUTH_RESULT); + req.remoteAddr = "1.2.3.4"; + final MockHttpServletResponse response = MockHttpServletResponse.forRequest(req); + + Assertions.assertNull( + resource.doPost( + new SqlQuery( + "SELECT COUNT(*) AS c FROM druid.foo", + ResultFormat.OBJECT, + false, + false, + false, + null, + null + ), + req + ) + ); + + Assertions.assertEquals(200, response.getStatus()); + + // While the native query was executing, the list API reported it without query text. + final NativeQueryInfo runningQuery = runningQuerySeenDuringExecution.get(); + Assertions.assertNotNull(runningQuery); + Assertions.assertNull(runningQuery.getSql()); + Assertions.assertNull(runningQuery.getNativeQuery()); + + // The per-query report API returns the SQL text and the native query. + final GetQueryReportResponse report = reportSeenDuringExecution.get(); + Assertions.assertNotNull(report); + final NativeQueryInfo reportQuery = (NativeQueryInfo) report.getQueryInfo(); + Assertions.assertEquals("SELECT COUNT(*) AS c FROM druid.foo", reportQuery.getSql()); + Assertions.assertNotNull(reportQuery.getNativeQuery()); + + // Once the query completed, it is no longer reported. + Assertions.assertTrue( + engine.getQueries(false, false, CalciteTests.SUPER_USER_AUTH_RESULT, AuthorizationResult.ALLOW_NO_RESTRICTION) + .getQueries() + .isEmpty() + ); + } +} diff --git a/sql/src/test/java/org/apache/druid/sql/http/SqlResourceTest.java b/sql/src/test/java/org/apache/druid/sql/http/SqlResourceTest.java index d8a3813c421d..df4952721d22 100644 --- a/sql/src/test/java/org/apache/druid/sql/http/SqlResourceTest.java +++ b/sql/src/test/java/org/apache/druid/sql/http/SqlResourceTest.java @@ -61,6 +61,7 @@ import org.apache.druid.query.QueryTimeoutException; import org.apache.druid.query.QueryUnsupportedException; import org.apache.druid.query.ResourceLimitExceededException; +import org.apache.druid.query.TableDataSource; import org.apache.druid.query.context.QueryContextConfig; import org.apache.druid.query.context.QueryContextParameters; import org.apache.druid.query.context.ResponseContext; @@ -71,6 +72,7 @@ import org.apache.druid.server.QueryScheduler; import org.apache.druid.server.QueryStackTests; import org.apache.druid.server.ResponseContextConfig; +import org.apache.druid.server.RunningQueryRegistry; import org.apache.druid.server.SpecificSegmentsQuerySegmentWalker; import org.apache.druid.server.initialization.ServerConfig; import org.apache.druid.server.log.TestRequestLogger; @@ -110,6 +112,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.mockito.Mockito; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -2454,6 +2457,109 @@ private void validateQueryIds( } } + @Test + public void testListRunningQueries() + { + final RunningQueryRegistry registry = new RunningQueryRegistry(); + + final Query ownQuery = Mockito.mock(Query.class); + Mockito.when(ownQuery.getId()).thenReturn("query-1"); + Mockito.when(ownQuery.getType()).thenReturn("timeseries"); + Mockito.when(ownQuery.getSqlQueryId()).thenReturn("sql-1"); + Mockito.when(ownQuery.getDataSource()).thenReturn(new TableDataSource(CalciteTests.DATASOURCE1)); + final AuthenticationResult regularUser = + new AuthenticationResult("regularUser", "testAuthorizer", "testAuthenticator", null); + registry.register(ownQuery, null, regularUser); + + final Query otherQuery = Mockito.mock(Query.class); + Mockito.when(otherQuery.getId()).thenReturn("query-2"); + Mockito.when(otherQuery.getType()).thenReturn("groupBy"); + Mockito.when(otherQuery.getDataSource()).thenReturn(new TableDataSource(CalciteTests.DATASOURCE1)); + registry.register(otherQuery, null, CalciteTests.SUPER_USER_AUTH_RESULT); + + final NativeSqlEngine nativeEngine = + new NativeSqlEngine(null, JSON_MAPPER, (SqlStatementFactory) null, registry); + final SqlResource nativeResource = new SqlResource( + CalciteTests.TEST_AUTHORIZER_MAPPER, + lifecycleManager, + new SqlEngineRegistry(Set.of(nativeEngine)), + new SqlResourceQueryResultPusherFactory( + JSON_MAPPER, + new ServerConfig(), + TEST_RESPONSE_CONTEXT_CONFIG, + DUMMY_DRUID_NODE + ), + DefaultQueryConfig.NIL, + new ServerConfig(), + QueryFrameworkUtils.TEST_QUERY_CONTEXT_CONFIG + ); + + // Users with STATE READ permission see all running queries. + final GetQueriesResponse superUserResult = + (GetQueriesResponse) nativeResource.doGetRunningQueries(null, null, makeSuperUserReq()).getEntity(); + Assertions.assertEquals(2, superUserResult.getQueries().size()); + + // Other users see only their own running queries. + final GetQueriesResponse regularUserResult = + (GetQueriesResponse) nativeResource.doGetRunningQueries(null, null, makeExpectedReq(regularUser)).getEntity(); + Assertions.assertEquals(1, regularUserResult.getQueries().size()); + Assertions.assertEquals("query-1", regularUserResult.getQueries().get(0).executionId()); + } + + @Test + public void testGetRunningQueryReport() throws Exception + { + final RunningQueryRegistry registry = new RunningQueryRegistry( + new DefaultObjectMapper().readValue("{\"enableRunningQueryText\":true}", ServerConfig.class) + ); + + final Query ownQuery = Mockito.mock(Query.class); + Mockito.when(ownQuery.getId()).thenReturn("query-1"); + Mockito.when(ownQuery.getType()).thenReturn("timeseries"); + Mockito.when(ownQuery.getSqlQueryId()).thenReturn("sql-1"); + Mockito.when(ownQuery.getDataSource()).thenReturn(new TableDataSource(CalciteTests.DATASOURCE1)); + final AuthenticationResult regularUser = + new AuthenticationResult("regularUser", "testAuthorizer", "testAuthenticator", null); + registry.register(ownQuery, "SELECT COUNT(*) AS c FROM foo", regularUser); + + final ObjectMapper jsonMapper = Mockito.mock(ObjectMapper.class); + Mockito.when(jsonMapper.writeValueAsString(Mockito.any())).thenReturn("{\"queryType\":\"timeseries\"}"); + + final NativeSqlEngine nativeEngine = + new NativeSqlEngine(null, jsonMapper, (SqlStatementFactory) null, registry); + final SqlResource nativeResource = new SqlResource( + CalciteTests.TEST_AUTHORIZER_MAPPER, + lifecycleManager, + new SqlEngineRegistry(Set.of(nativeEngine)), + new SqlResourceQueryResultPusherFactory( + JSON_MAPPER, + new ServerConfig(), + TEST_RESPONSE_CONTEXT_CONFIG, + DUMMY_DRUID_NODE + ), + DefaultQueryConfig.NIL, + new ServerConfig(), + QueryFrameworkUtils.TEST_QUERY_CONTEXT_CONFIG + ); + + // The list API does not include query text. + final GetQueriesResponse listResult = + (GetQueriesResponse) nativeResource.doGetRunningQueries(null, null, makeSuperUserReq()).getEntity(); + Assertions.assertEquals(1, listResult.getQueries().size()); + Assertions.assertNull(((NativeQueryInfo) listResult.getQueries().get(0)).getSql()); + + // The report API returns the query text for a known query ID. + final Response reportResponse = nativeResource.doGetQueryReport("sql-1", "true", makeSuperUserReq()); + Assertions.assertEquals(200, reportResponse.getStatus()); + final GetQueryReportResponse report = (GetQueryReportResponse) reportResponse.getEntity(); + final NativeQueryInfo reportQuery = (NativeQueryInfo) report.getQueryInfo(); + Assertions.assertEquals("SELECT COUNT(*) AS c FROM foo", reportQuery.getSql()); + Assertions.assertEquals("{\"queryType\":\"timeseries\"}", reportQuery.getNativeQuery()); + + // Unknown query IDs return 404. + Assertions.assertEquals(404, nativeResource.doGetQueryReport("unknown", "true", makeSuperUserReq()).getStatus()); + } + private MockHttpServletRequest makeSuperUserReq() { return makeExpectedReq(CalciteTests.SUPER_USER_AUTH_RESULT);