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