924060929 commented on code in PR #71133: URL: https://github.com/apache/doris/pull/71133#discussion_r4763653681
########## fe/fe-core/src/main/java/org/apache/doris/tablefunction/PluginMetadataTableValuedFunction.java: ########## @@ -0,0 +1,361 @@ +// 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.doris.tablefunction; + +import org.apache.doris.analysis.UserIdentity; +import org.apache.doris.catalog.Column; +import org.apache.doris.catalog.Env; +import org.apache.doris.catalog.TableIf; +import org.apache.doris.common.AnalysisException; +import org.apache.doris.common.ErrorCode; +import org.apache.doris.connector.ConnectorFactory; +import org.apache.doris.connector.PluginMetadataTableFunction; +import org.apache.doris.connector.spi.ConnectorColumn; +import org.apache.doris.connector.spi.ConnectorMetadata; +import org.apache.doris.connector.spi.ConnectorSession; +import org.apache.doris.connector.spi.DorisConnectorException; +import org.apache.doris.connector.spi.handle.ConnectorTableHandle; +import org.apache.doris.connector.spi.metadatatable.ConnectorMetadataTableOps; +import org.apache.doris.datasource.CatalogIf; +import org.apache.doris.datasource.connector.converter.ConnectorColumnConverter; +import org.apache.doris.datasource.plugin.PluginDrivenExternalCatalog; +import org.apache.doris.datasource.plugin.PluginDrivenExternalTable; +import org.apache.doris.datasource.plugin.PluginDrivenMetadata; +import org.apache.doris.mysql.privilege.PrivPredicate; +import org.apache.doris.nereids.analyzer.UnboundSlot; +import org.apache.doris.nereids.exceptions.ParseException; +import org.apache.doris.nereids.parser.NereidsParser; +import org.apache.doris.nereids.trees.expressions.Expression; +import org.apache.doris.qe.ConnectContext; +import org.apache.doris.thrift.TCell; +import org.apache.doris.thrift.TConnectorTableFunctionParams; +import org.apache.doris.thrift.TFetchSchemaTableDataResult; +import org.apache.doris.thrift.TMetaScanRange; +import org.apache.doris.thrift.TMetadataTableRequestParams; +import org.apache.doris.thrift.TMetadataType; +import org.apache.doris.thrift.TRow; +import org.apache.doris.thrift.TStatus; +import org.apache.doris.thrift.TStatusCode; + +import com.google.common.base.Preconditions; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; + +/** + * A metadata table function a connector plugin declares ({@link PluginMetadataTableFunction}), such as + * {@code my_index_entries("table" = "ctl.db.tbl")}. + * + * <p>Analysis checks the arguments and the user's SHOW privilege on the table as written, before any lookup that + * could initialize the catalog; then the catalog must be one the declaring plugin serves, with metadata that + * implements {@link ConnectorMetadataTableOps}, and the table must exist. The scan relays the call through a BE to + * the master FE, which checks the privilege again for the user the BE names, resolves the table the same way and + * asks the connector for the rows ({@link #fetchRows}).</p> + */ +public class PluginMetadataTableValuedFunction extends MetadataTableValuedFunction { + private static final Logger LOG = LogManager.getLogger(PluginMetadataTableValuedFunction.class); + private static final String TABLE = "table"; + private static final String FULLY_QUALIFIED_TABLE_NAME_ERROR = + "'table' must be a fully qualified catalog.database.table name"; + + private final PluginMetadataTableFunction function; + private final Map<String, String> arguments; + private final String catalogName; + private final String databaseName; + private final String tableName; + private final List<Column> columns; + + public PluginMetadataTableValuedFunction(PluginMetadataTableFunction function, Map<String, String> properties) + throws AnalysisException { + this.function = function; + String name = function.getName(); + Map<String, String> normalized = normalizeArguments(properties, function); + String table = normalized.remove(TABLE); + if (table == null || table.trim().isEmpty()) { + throw new AnalysisException("Missing required " + name + " property 'table'"); + } + List<String> names = parseTableName(table.trim()); + // Before the catalog is looked up, which may initialize it. + checkShowPrivilege(ConnectContext.get(), names.get(0), names.get(1), names.get(2)); + PluginDrivenExternalCatalog catalog = findCatalog(function, names.get(0)); + ConnectorSession session = catalog.buildConnectorSession(); + ConnectorMetadata metadata = PluginDrivenMetadata.get(session, catalog.getConnector()); + if (!(metadata instanceof ConnectorMetadataTableOps)) { + throw new AnalysisException(unsupportedCatalog(catalog.getName(), name)); + } + PluginDrivenExternalTable sourceTable = findTable(catalog, names.get(1), names.get(2)); + if (!sourceTable.resolveConnectorTableHandle(session, metadata).isPresent()) { + throw new AnalysisException(tableNotFound(names)); + } + this.arguments = Collections.unmodifiableMap(normalized); + this.catalogName = catalog.getName(); + this.databaseName = sourceTable.getDatabase().getFullName(); + this.tableName = sourceTable.getName(); + this.columns = ConnectorColumnConverter.convertColumns(function.getDeclaration().getColumns()); + } + + @Override + public TMetadataType getMetadataType() { + return TMetadataType.CONNECTOR_TABLE_FUNCTION; + } + + @Override + public TMetaScanRange getMetaScanRange(List<String> requiredFields) { + TConnectorTableFunctionParams params = new TConnectorTableFunctionParams() + .setFunctionName(function.getName()) + .setCatalog(catalogName) + .setDatabase(databaseName) + .setTable(tableName) + .setProperties(new LinkedHashMap<>(arguments)); + return new TMetaScanRange() + .setMetadataType(TMetadataType.CONNECTOR_TABLE_FUNCTION) + .setConnectorTableFunctionParams(params); + } + + @Override + public String getTableName() { + return "PluginMetadataTableValuedFunction<" + function.getName() + ">"; + } + + @Override + public List<Column> getTableColumns() { + return columns; + } + + /** The position of {@code columnName} in a row of the function the request names, for column pruning. */ + public static Integer getColumnIndexFromColumnName(String columnName, TMetadataTableRequestParams params) + throws AnalysisException { + String name = params.getConnectorTableFunctionParams().getFunctionName(); + Optional<PluginMetadataTableFunction> function = ConnectorFactory.getMetadataTableFunction(name); + if (!function.isPresent()) { + throw new AnalysisException("Could not find table function " + name); + } + List<ConnectorColumn> declared = function.get().getDeclaration().getColumns(); + for (int i = 0; i < declared.size(); i++) { + if (declared.get(i).getName().equalsIgnoreCase(columnName)) { + return i; + } + } + throw new AnalysisException("Table function " + name + "() has no column '" + columnName + "'"); + } + + /** + * Serves a call the BE relays to the master FE: checks the SHOW privilege again for the user the BE names, + * since the request carries no session, resolves the table as analysis did and returns the connector's rows, + * one cell per declared column. + */ + public static TFetchSchemaTableDataResult fetchRows(TMetadataTableRequestParams params) { + if (!params.isSetConnectorTableFunctionParams()) { + return MetadataGenerator.errorResult("Connector table function params is not set."); + } + TConnectorTableFunctionParams call = params.getConnectorTableFunctionParams(); + if (!call.isSetFunctionName() || !call.isSetCatalog() || !call.isSetDatabase() || !call.isSetTable()) { + return MetadataGenerator.errorResult("Connector table function params are incomplete."); + } + String name = call.getFunctionName(); + if (!params.isSetCurrentUserIdent()) { + return MetadataGenerator.errorResult("Current user identity is not set for " + name + "()."); + } + Optional<PluginMetadataTableFunction> function = ConnectorFactory.getMetadataTableFunction(name); + if (!function.isPresent()) { + return MetadataGenerator.errorResult("Could not find table function " + name); + } + UserIdentity user = UserIdentity.fromThrift(params.getCurrentUserIdent()); + if (!Env.getCurrentEnv().getAccessManager().checkTblPriv(user, call.getCatalog(), call.getDatabase(), + call.getTable(), PrivPredicate.SHOW)) { + return MetadataGenerator.errorResult(ErrorCode.ERR_TABLEACCESS_DENIED_ERROR.formatErrorMsg("SHOW", + user.getQualifiedUser(), user.getHost(), call.getDatabase() + ": " + call.getTable())); + } + Map<String, String> arguments = call.isSetProperties() ? call.getProperties() : Collections.emptyMap(); + try { + PluginDrivenExternalCatalog catalog = findCatalog(function.get(), call.getCatalog()); + PluginDrivenExternalTable table = findTable(catalog, call.getDatabase(), call.getTable()); + ConnectorSession session = catalog.buildRelayedMetadataSession(user.getQualifiedUser()); + try { + ConnectorMetadata metadata = PluginDrivenMetadata.get(session, catalog.getConnector()); + if (!(metadata instanceof ConnectorMetadataTableOps)) { + return MetadataGenerator.errorResult(unsupportedCatalog(catalog.getName(), name)); + } + PluginDrivenExternalTable.MetadataRead read = table.observeConnectorMetadata(session, metadata); + Optional<ConnectorTableHandle> handle = table.resolveConnectorTableHandle(session, metadata); + if (!handle.isPresent()) { + return MetadataGenerator.errorResult(tableNotFound( + Arrays.asList(call.getCatalog(), call.getDatabase(), call.getTable()))); + } + List<List<Object>> rows = read.execute(() -> ((ConnectorMetadataTableOps) metadata) + .listMetadataTableRows(session, name, handle.get(), table.getDatabase().getFullName(), + table.getName(), arguments)); + TFetchSchemaTableDataResult result = new TFetchSchemaTableDataResult(); + result.setDataBatch(toRows(name, function.get().getDeclaration().getColumns(), rows)); + result.setStatus(new TStatus(TStatusCode.OK)); + return result; + } finally { + session.getStatementScope().closeAll(); + } + } catch (AnalysisException | DorisConnectorException | MalformedRowException e) { + // The connector's messages are for the user; it keeps credentials out of them. + return MetadataGenerator.errorResult(e.getMessage()); + } catch (RuntimeException e) { + LOG.warn("Failed to read {}() over {}.{}.{}", name, call.getCatalog(), call.getDatabase(), + call.getTable(), e); + return MetadataGenerator.errorResult("Failed to read " + name + "()."); + } + } + + /** One {@link TRow} per connector row, each value converted by the type of its declared column. */ + static List<TRow> toRows(String name, List<ConnectorColumn> columns, List<List<Object>> rows) { + List<TRow> result = new ArrayList<>(rows.size()); + for (List<Object> row : rows) { + if (row == null || row.size() != columns.size()) { + throw new MalformedRowException(name + "() returned a row of " + + (row == null ? "null" : row.size() + " values") + " for " + columns.size() + " columns"); + } + TRow trow = new TRow(); + for (int i = 0; i < columns.size(); i++) { + trow.addToColumnValue(toCell(name, columns.get(i), row.get(i))); + } + result.add(trow); + } + return result; + } + + private static TCell toCell(String name, ConnectorColumn column, Object value) { + if (value == null) { + if (!column.isNullable()) { + throw new MalformedRowException(name + "() returned NULL for NOT NULL column '" + + column.getName() + "'"); + } + return new TCell().setIsNull(true); + } + String type = column.getType().getTypeName(); + switch (type) { + case "BOOLEAN": + return new TCell().setBoolVal(cast(name, column, value, Boolean.class)); + case "TINYINT": + return new TCell().setIntVal(cast(name, column, value, Byte.class)); + case "SMALLINT": + return new TCell().setIntVal(cast(name, column, value, Short.class)); + case "INT": + return new TCell().setIntVal(cast(name, column, value, Integer.class)); + case "BIGINT": + return new TCell().setLongVal(cast(name, column, value, Long.class)); + case "FLOAT": + return new TCell().setDoubleVal(cast(name, column, value, Float.class)); + case "DOUBLE": + return new TCell().setDoubleVal(cast(name, column, value, Double.class)); + case "CHAR": + case "VARCHAR": + case "STRING": + return new TCell().setStringVal(cast(name, column, value, String.class)); + default: + // ConnectorMetadataTableFunction admits only the types above. + throw new IllegalStateException(name + "() column '" + column.getName() + "' has type " + type); + } + } + + private static <T> T cast(String name, ConnectorColumn column, Object value, Class<T> javaType) { + if (!javaType.isInstance(value)) { + throw new MalformedRowException(name + "() returned a " + value.getClass().getSimpleName() + + " for " + column.getType().getTypeName() + " column '" + column.getName() + "'"); + } + return javaType.cast(value); + } + + /** The arguments by lower-case name: 'table' and those the function declares, each once. */ + private static Map<String, String> normalizeArguments(Map<String, String> properties, + PluginMetadataTableFunction function) throws AnalysisException { + String name = function.getName(); + Map<String, String> normalized = new LinkedHashMap<>(); + for (Map.Entry<String, String> entry : properties.entrySet()) { + String key = entry.getKey().toLowerCase(Locale.ROOT); + if (!key.equals(TABLE) && !function.getDeclaration().getArguments().contains(key)) { + throw new AnalysisException("'" + entry.getKey() + "' is an invalid property for " + name); + } + if (normalized.put(key, entry.getValue()) != null) { + throw new AnalysisException("Duplicate " + name + " property '" + key + "'"); + } + } + return normalized; + } + + private static List<String> parseTableName(String value) throws AnalysisException { + Expression expression; + try { + expression = new NereidsParser().parseExpression(value); + } catch (ParseException e) { + throw new AnalysisException(FULLY_QUALIFIED_TABLE_NAME_ERROR, e); + } + if (!(expression instanceof UnboundSlot) || ((UnboundSlot) expression).getNameParts().size() != 3) { + throw new AnalysisException(FULLY_QUALIFIED_TABLE_NAME_ERROR); + } + return ((UnboundSlot) expression).getNameParts(); + } + + private static void checkShowPrivilege(ConnectContext context, String catalog, String database, String table) + throws AnalysisException { + if (!Env.getCurrentEnv().getAccessManager().checkTblPriv(context, catalog, database, table, + PrivPredicate.SHOW)) { + throw new AnalysisException(ErrorCode.ERR_TABLEACCESS_DENIED_ERROR.formatErrorMsg("SHOW", + context.getQualifiedUser(), context.getRemoteIP(), database + ": " + table)); + } + } + + private static PluginDrivenExternalCatalog findCatalog(PluginMetadataTableFunction function, String catalogName) + throws AnalysisException { + CatalogIf<?> catalog = Env.getCurrentEnv().getCatalogMgr().getCatalog(catalogName); + if (catalog == null) { + throw new AnalysisException("Catalog '" + catalogName + "' does not exist"); + } + if (!(catalog instanceof PluginDrivenExternalCatalog) + || !function.isDeclaredFor((PluginDrivenExternalCatalog) catalog)) { + throw new AnalysisException(unsupportedCatalog(catalogName, function.getName())); + } + return (PluginDrivenExternalCatalog) catalog; + } + + private static PluginDrivenExternalTable findTable(PluginDrivenExternalCatalog catalog, String database, + String table) throws AnalysisException { + TableIf found = catalog.getDbOrAnalysisException(database).getTableOrAnalysisException(table); + Preconditions.checkState(found instanceof PluginDrivenExternalTable, + "plugin catalog %s returned a %s", catalog.getName(), found.getClass().getName()); Review Comment: [P1] `findTable()` hits `Preconditions.checkState(found instanceof PluginDrivenExternalTable, ...)` when the user queries a Doris-owned system table under a plugin catalog, e.g. `lance_index_entries("table" = "lance_ctl.information_schema.tables")` or `lance_ctl.mysql.user`. `ExternalCatalog.getDbOrAnalysisException()` returns `ExternalInfoSchemaDatabase` / `ExternalMysqlDatabase`, whose tables are not `PluginDrivenExternalTable`, causing an `IllegalStateException` that leaks the internal class name to the user (and logs a WARN in `fetchRows()`). `ShowIndexCommand.connectorIndexRows()` already guards against these system databases — please handle them here with a user-facing `AnalysisException` and add a unit test. ########## fe/fe-core/src/main/java/org/apache/doris/tablefunction/MetadataGenerator.java: ########## @@ -287,6 +287,9 @@ public static TFetchSchemaTableDataResult getMetadataTable(TFetchSchemaTableData case PARTITION_VALUES: result = partitionValuesMetadataResult(params); break; + case CONNECTOR_TABLE_FUNCTION: Review Comment: [P2] During a 4.2 -> master rolling upgrade, `be/src/exec/scan/meta_scanner.cpp` keeps relaying `TMetadataType::LANCE_INDEX_ENTRIES` (15) for old FEs, but `MetadataGenerator.getMetadataTable()` only handles `CONNECTOR_TABLE_FUNCTION` (17). If the master FE is upgraded before followers, `LANCE_INDEX_ENTRIES` requests planned by 4.2 followers will hit the `default` branch and fail with `"Metadata table params is not set."`. Please confirm whether mixed-FE compatibility is intentionally out of scope (and document it if so), or route `LANCE_INDEX_ENTRIES` here if needed. -- 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]
