FrankChen021 commented on code in PR #20183: URL: https://github.com/apache/druid/pull/20183#discussion_r4367256564
########## server/src/main/java/org/apache/druid/server/system/handler/SystemTableQueryClient.java: ########## @@ -0,0 +1,923 @@ +/* + * 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.system.handler; + +import com.google.common.base.Preconditions; +import com.google.common.collect.Iterables; +import com.google.inject.Inject; +import io.netty.channel.ChannelException; +import org.apache.druid.client.DirectDruidClient; +import org.apache.druid.client.DirectDruidClientFactory; +import org.apache.druid.client.DruidServer; +import org.apache.druid.discovery.DiscoveryDruidNode; +import org.apache.druid.error.DruidException; +import org.apache.druid.guice.annotations.Self; +import org.apache.druid.java.util.common.JodaUtils; +import org.apache.druid.java.util.common.guava.BaseSequence; +import org.apache.druid.java.util.common.guava.LazySequence; +import org.apache.druid.java.util.common.guava.Sequence; +import org.apache.druid.java.util.common.guava.Sequences; +import org.apache.druid.java.util.common.guava.Yielder; +import org.apache.druid.java.util.common.guava.Yielders; +import org.apache.druid.query.DataSource; +import org.apache.druid.query.Druids; +import org.apache.druid.query.InlineDataSource; +import org.apache.druid.query.Query; +import org.apache.druid.query.QueryContext; +import org.apache.druid.query.QueryDataSource; +import org.apache.druid.query.QueryException; +import org.apache.druid.query.QueryInterruptedException; +import org.apache.druid.query.QueryPlus; +import org.apache.druid.query.QueryRunner; +import org.apache.druid.query.QuerySegmentWalker; +import org.apache.druid.query.QueryTimeoutException; +import org.apache.druid.query.SystemTableDataSource; +import org.apache.druid.query.context.QueryContextParameters; +import org.apache.druid.query.context.ResponseContext; +import org.apache.druid.query.filter.AndDimFilter; +import org.apache.druid.query.filter.DimFilter; +import org.apache.druid.query.operator.OperatorFactory; +import org.apache.druid.query.operator.ScanOperatorFactory; +import org.apache.druid.query.operator.WindowOperatorQuery; +import org.apache.druid.query.scan.ScanQuery; +import org.apache.druid.query.scan.ScanResultValue; +import org.apache.druid.segment.VirtualColumn; +import org.apache.druid.segment.VirtualColumns; +import org.apache.druid.server.DataSourceQueryHandler; +import org.apache.druid.server.DruidNode; +import org.apache.druid.server.QueryScheduler; +import org.apache.druid.server.coordination.ServerType; +import org.apache.druid.server.security.AuthenticationResult; +import org.apache.druid.server.security.AuthorizerMapper; +import org.apache.druid.server.security.Escalator; +import org.apache.druid.server.system.SystemTableNotLeaderException; +import org.apache.druid.server.system.table.SystemTableDescriptor; +import org.apache.druid.server.system.table.SystemTableRoutingMode; +import org.apache.druid.utils.CloseableUtils; + +import javax.annotation.Nullable; +import java.io.Closeable; +import java.io.EOFException; +import java.io.IOException; +import java.net.SocketException; +import java.net.UnknownHostException; +import java.nio.channels.ClosedChannelException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.TimeoutException; +import java.util.function.Supplier; + +/** + * Recursively replaces native system-table datasources with authorized inline rows fetched from nodes, then + * executes the rebuilt query through the Broker's normal native-query walker. + */ +public class SystemTableQueryClient implements DataSourceQueryHandler +{ + private static final String SYSTEM_TABLE_TIER = "_system"; + + private final SystemTableNodeLocator nodeLocator; + private final DirectDruidClientFactory directDruidClientFactory; + private final QueryScheduler queryScheduler; + private final QuerySegmentWalker querySegmentWalker; + private final Map<String, SystemTableDescriptor> tableDescriptors; + private final AuthorizerMapper authorizerMapper; + private final SystemTableQueryHandler localQueryHandler; + private final AuthenticationResult escalatedAuthenticationResult; + private final DruidNode selfNode; + + @Inject + public SystemTableQueryClient( + final SystemTableNodeLocator nodeLocator, + final DirectDruidClientFactory directDruidClientFactory, + final QueryScheduler queryScheduler, + final QuerySegmentWalker querySegmentWalker, + final Map<String, SystemTableDescriptor> tableDescriptors, + final AuthorizerMapper authorizerMapper, + final SystemTableQueryHandler localQueryHandler, + final Escalator escalator, + @Self final DruidNode selfNode + ) + { + this.nodeLocator = nodeLocator; + this.directDruidClientFactory = directDruidClientFactory; + this.queryScheduler = queryScheduler; + this.querySegmentWalker = querySegmentWalker; + this.tableDescriptors = tableDescriptors; + this.authorizerMapper = authorizerMapper; + this.localQueryHandler = localQueryHandler; + this.escalatedAuthenticationResult = escalator.createEscalatedAuthenticationResult(); + this.selfNode = selfNode; + } + + @Override + public <T> QueryRunner<T> createRunner( + final Query<T> query, + final AuthenticationResult authenticationResult, + final boolean executeLocally + ) + { + return (queryPlus, responseContext) -> { + final NodeSequencesCloser nodeSequencesCloser = new NodeSequencesCloser(queryScheduler); + try { + final DataSource resolvedDataSource = resolveDataSource( + query.getDataSource(), + query, + authenticationResult, + nodeSequencesCloser + ); + final Query<T> resolvedQuery = query.withDataSource(resolvedDataSource).withOverriddenContext( + QueryContextParameters.QUERY_RESOURCE_ID, + UUID.randomUUID().toString() + ); + final QueryRunner<T> queryRunner = querySegmentWalker.getQueryRunnerForIntervals( + resolvedQuery, + resolvedQuery.getIntervals() + ); + return Sequences.withBaggage( + queryRunner.run(queryPlus.withQuery(resolvedQuery), responseContext), + nodeSequencesCloser + ); + } + catch (Throwable t) { + throw CloseableUtils.closeAndWrapInCatch(t, nodeSequencesCloser); + } + }; + } + + private DataSource resolveDataSource( + final DataSource dataSource, + final Query<?> owningQuery, + final AuthenticationResult authenticationResult, + final NodeSequencesCloser nodeSequencesCloser + ) + { + if (dataSource instanceof SystemTableDataSource systemTableDataSource) { + return resolveSystemTableDataSource( + systemTableDataSource, + owningQuery, + authenticationResult, + nodeSequencesCloser + ); + } + + final Query<?> childOwningQuery; + final DataSource resolvedParent; + if (dataSource instanceof QueryDataSource queryDataSource) { + final Query<?> childQuery = queryDataSource.getQuery(); + // An inner query may tighten the outer guardrails, but must not discard them before node fanout. + childOwningQuery = childQuery.withOverriddenContext( + QueryContext.ofMap( + QueryContextParameters.QUERY_FAIL_TIME, + Math.min(getNodeFailTime(owningQuery), getNodeFailTime(childQuery)), + QueryContextParameters.MAX_SCATTER_GATHER_BYTES, + Math.min(owningQuery.context().getMaxScatterGatherBytes(), childQuery.context().getMaxScatterGatherBytes()) + ) + ); + resolvedParent = new QueryDataSource(childOwningQuery); + } else { + childOwningQuery = owningQuery; + resolvedParent = dataSource; + } + final List<DataSource> resolvedChildren = new ArrayList<>(); + for (final DataSource child : dataSource.getChildren()) { + resolvedChildren.add( + resolveDataSource( + child, + childOwningQuery, + authenticationResult, + nodeSequencesCloser + ) + ); + } + return resolvedParent.withChildren(resolvedChildren); + } + + private InlineDataSource resolveSystemTableDataSource( + final SystemTableDataSource dataSource, + final Query<?> owningQuery, + final AuthenticationResult authenticationResult, + final NodeSequencesCloser nodeSequencesCloser + ) + { + final SystemTableDescriptor descriptor = tableDescriptors.get(dataSource.getTable()); + if (descriptor == null) { + throw DruidException.defensive("No routing descriptor is registered for system table[%s]", dataSource.getTable()); + } + + final ScanQuery nodeQuery = makeNodeQuery(dataSource, descriptor, owningQuery); + final List<QueryRunner<ScanResultValue>> nodeRunners = makeNodeRunners( + nodeQuery, + descriptor, + nodeSequencesCloser + ); + if (nodeRunners.isEmpty() && !descriptor.isEmptyDiscoveryAllowed()) { + throw DruidException.forPersona(DruidException.Persona.OPERATOR) + .ofCategory(DruidException.Category.SERVICE_UNAVAILABLE) + .build("No node is available to serve system table[%s]", dataSource.getTable()); + } + + /* + * Keep the scan result transport lazy. The node response is a Sequence, so this lets the local query + * runner consume and process rows while the HTTP response is still arriving instead of materializing every + * node row in two Broker-side lists. The scan transport is intentionally kept behind this adapter so a + * future node-side aggregation mode can use a different result adapter without changing routing or + * authorization orchestration here. + */ + final NodeSequenceCloser nodeSequenceCloser = new NodeSequenceCloser(); + nodeSequencesCloser.add(nodeSequenceCloser); + // Node scans get their own response context. Sharing the caller's would add the node scans' row counts to the + // Broker query's, and a Scan with a limit returns no rows once that count reaches the limit. For example, the + // node scans of a join's right side would empty a limited Scan over the join before it read its left side. + final Iterable<Object[]> nodeRows = scanNodeRows( + nodeRunners, + nodeQuery, + DirectDruidClient.makeResponseContextForQuery(), Review Comment: [P2] Query-wide scatter-gather limit resets per system-table leaf **Finding:** This creates a fresh ResponseContext for every resolved system-table leaf. DirectDruidClient stores and checks maxScatterGatherBytes in that context, so a query with multiple system-table leaves, such as a self-join or UNION of sys.server_properties, gets a separate full byte budget per leaf; the counters are not merged into the caller's context. The documented query-wide guardrail can therefore be exceeded, allowing more response data to be buffered on the Broker than configured. **Suggestion:** Share an aggregate byte counter across the per-leaf response contexts while keeping row-scan counters isolated, then merge each leaf's byte total into the query-wide counter before subsequent leaf fan-out. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
