github-actions[bot] commented on code in PR #62183: URL: https://github.com/apache/doris/pull/62183#discussion_r3087757371
########## fe/fe-core/src/main/java/org/apache/doris/datasource/PluginDrivenExternalCatalog.java: ########## @@ -0,0 +1,298 @@ +// 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.datasource; + +import org.apache.doris.common.DdlException; +import org.apache.doris.connector.ConnectorFactory; +import org.apache.doris.connector.ConnectorSessionBuilder; +import org.apache.doris.connector.DefaultConnectorContext; +import org.apache.doris.connector.api.Connector; +import org.apache.doris.connector.api.ConnectorSession; +import org.apache.doris.connector.api.ConnectorTestResult; +import org.apache.doris.qe.ConnectContext; +import org.apache.doris.transaction.PluginDrivenTransactionManager; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.IOException; +import java.util.List; +import java.util.Map; + +/** + * An {@link ExternalCatalog} backed by a Connector SPI plugin. + * + * <p>This adapter bridges the connector SPI ({@link Connector}) with the existing + * ExternalCatalog hierarchy. Metadata operations are delegated to the connector's + * {@link org.apache.doris.connector.api.ConnectorMetadata} implementation.</p> + * + * <p>When created via {@link CatalogFactory}, the Connector instance is provided + * directly. After GSON deserialization (FE restart), the Connector is recreated + * from catalog properties during {@link #initLocalObjectsImpl()}.</p> + */ +public class PluginDrivenExternalCatalog extends ExternalCatalog { + + private static final Logger LOG = LogManager.getLogger(PluginDrivenExternalCatalog.class); + + // Volatile for cross-thread visibility; all mutations also happen under synchronized(this). + private transient volatile Connector connector; + + // When true, onClose() skips closing the connector because notifyPropertiesUpdated() + // manages the connector lifecycle (create-before-swap pattern). + private transient volatile boolean connectorSwapInProgress = false; + + /** No-arg constructor for GSON deserialization. */ + public PluginDrivenExternalCatalog() { + } + + /** + * Creates a plugin-driven catalog with an already-created Connector. + * + * @param catalogId unique catalog id + * @param name catalog name + * @param resource optional resource name + * @param props catalog properties + * @param comment catalog comment + * @param connector the SPI connector instance + */ + public PluginDrivenExternalCatalog(long catalogId, String name, String resource, + Map<String, String> props, String comment, Connector connector) { + super(catalogId, name, InitCatalogLog.Type.PLUGIN, comment); + this.catalogProperty = new CatalogProperty(resource, props); + this.connector = connector; + } + + @Override + protected void initLocalObjectsImpl() { + if (connector != null) { + transactionManager = new PluginDrivenTransactionManager(); + initPreExecutionAuthenticator(); + return; + } + connector = createConnectorFromProperties(); + if (connector == null) { + String catalogType = catalogProperty.getOrDefault(CatalogMgr.CATALOG_TYPE_PROP, ""); + throw new RuntimeException("No ConnectorProvider found for plugin-driven catalog: " + + name + ", type: " + catalogType + + ". Ensure the connector plugin is installed."); + } + LOG.info("Recreated connector for plugin-driven catalog {}:{}, type={}", + name, id, catalogProperty.getOrDefault(CatalogMgr.CATALOG_TYPE_PROP, "")); + transactionManager = new PluginDrivenTransactionManager(); + initPreExecutionAuthenticator(); + } + + /** + * Creates a new Connector from catalog properties. Extracted as a protected method + * so tests can override without depending on the static ConnectorFactory registry. + */ + protected Connector createConnectorFromProperties() { + String catalogType = catalogProperty.getOrDefault(CatalogMgr.CATALOG_TYPE_PROP, ""); + return ConnectorFactory.createConnector(catalogType, + catalogProperty.getProperties(), + new DefaultConnectorContext(name, id)); + } + + @Override + public void checkProperties() throws DdlException { + super.checkProperties(); + String catalogType = catalogProperty.getOrDefault(CatalogMgr.CATALOG_TYPE_PROP, ""); + try { + ConnectorFactory.validateProperties(catalogType, catalogProperty.getProperties()); + } catch (IllegalArgumentException e) { + throw new DdlException(e.getMessage()); + } + // Validate function_rules JSON if present (shared across all connector types). + String functionRules = catalogProperty.getOrDefault("function_rules", null); + ExternalFunctionRules.check(functionRules); + } + + @Override + public void checkWhenCreating() throws DdlException { + boolean testConnection = Boolean.parseBoolean( + catalogProperty.getOrDefault(ExternalCatalog.TEST_CONNECTION, + String.valueOf(ExternalCatalog.DEFAULT_TEST_CONNECTION))); + if (!testConnection) { + return; + } + // Delegate connectivity testing to the connector SPI. + ConnectorSession session = buildConnectorSession(); + ConnectorTestResult result = connector.testConnection(session); + if (!result.isSuccess()) { + throw new DdlException("Connectivity test failed for catalog '" + + name + "': " + result.getMessage()); + } + LOG.info("Connectivity test passed for plugin-driven catalog '{}': {}", name, result); + } + + /** + * Handles catalog property updates with a create-before-swap pattern to avoid + * race conditions between ALTER CATALOG and concurrent queries. + * + * <p>The old implementation had a TOCTOU race: {@code super.notifyPropertiesUpdated()} + * called {@code resetToUninitialized()} which closed the connector via {@code onClose()}, + * leaving a window where concurrent queries could trigger {@code initLocalObjectsImpl()} + * and create an orphaned connector that was immediately overwritten.</p> + * + * <p>New approach: + * <ol> + * <li>Create the replacement connector <b>first</b> (outside lock — may involve I/O).</li> + * <li>Atomically swap the connector and set {@code connectorSwapInProgress} to suppress + * {@code onClose()} from closing the new connector during reset.</li> + * <li>Let the parent reset catalog state (caches, objectCreated, etc.).</li> + * <li>Close the old connector <b>after</b> the swap, outside any lock.</li> + * </ol></p> + */ + @Override + public void notifyPropertiesUpdated(Map<String, String> updatedProps) { + // 1. Create replacement connector FIRST (may involve I/O — outside any lock). + Connector newConnector = createConnectorFromProperties(); + if (newConnector == null) { + LOG.warn("Failed to create replacement connector for catalog '{}', " + + "falling back to full reset", name); + super.notifyPropertiesUpdated(updatedProps); + return; + } + + // 2. Atomically swap connector and suppress onClose() from closing it during reset. + Connector oldConnector; + synchronized (this) { + oldConnector = connector; + connector = newConnector; + connectorSwapInProgress = true; + } + try { + // 3. Let parent reset catalog state (caches, objectCreated, etc.). + // resetToUninitialized() → onClose() sees connectorSwapInProgress and skips close. + // After reset, concurrent makeSureInitialized() will find connector != null + // and reuse the new connector without creating an orphan. + super.notifyPropertiesUpdated(updatedProps); + } finally { + synchronized (this) { + connectorSwapInProgress = false; + } + } + + // 4. Close old connector outside any lock. + if (oldConnector != null) { + try { + oldConnector.close(); Review Comment: Closing the old connector immediately here breaks any in-flight plan that already captured that connector instance. `PluginDrivenScanNode.create()` and `PluginDrivenEsScanNode.create()` stash `catalog.getConnector()` in a field and call `getMetadata()` / `getScanPlanProvider()` later during planning/execution. For JDBC connectors `close()` flips `closed=true`, so a concurrent `ALTER CATALOG ... SET PROPERTIES` can start failing already-running queries with `JdbcDorisConnector has been closed`. ########## fe/fe-core/src/main/java/org/apache/doris/tablefunction/QueryTableValueFunction.java: ########## @@ -71,7 +71,7 @@ public static QueryTableValueFunction createQueryTableValueFunction(Map<String, if (catalogIf == null) { throw new AnalysisException("Catalog not found: " + catalogName); } - if (catalogIf instanceof JdbcExternalCatalog) { Review Comment: `JdbcQueryTableValueFunction` is still JDBC-specific: it unconditionally calls `ConnectorMetadata.getColumnsFromQuery()` and builds a plugin scan around a passthrough query handle. Broadening the guard from `JdbcExternalCatalog` to every `PluginDrivenExternalCatalog` makes `query(catalog => ...)` start accepting ES/Hive/Iceberg/etc. catalogs that do not implement those capabilities, then fail later with `DorisConnectorException`. This needs capability/type gating, not just `instanceof PluginDrivenExternalCatalog`. ########## fe/fe-connector/fe-connector-jdbc/src/main/java/org/apache/doris/connector/jdbc/client/JdbcConnectorClient.java: ########## @@ -0,0 +1,676 @@ +// 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.connector.jdbc.client; + +import org.apache.doris.connector.api.ConnectorType; +import org.apache.doris.connector.api.DorisConnectorException; +import org.apache.doris.connector.jdbc.JdbcDbType; + +import com.zaxxer.hikari.HikariDataSource; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.Closeable; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; + +/** + * Base JDBC metadata client. Mirrors the structure of fe-core's {@code JdbcClient} + * but returns {@link ConnectorType} instead of Doris {@code Type}. + * + * <p>Subclasses override {@link #jdbcTypeToConnectorType} and optionally + * metadata-discovery methods for database-specific behaviour.</p> + */ +public abstract class JdbcConnectorClient implements Closeable { + + static { + // HikariCP reads this once at class-load time to decide whether ConcurrentBag + // should use WeakReferences for connection tracking. Set it early and globally. + System.setProperty("com.zaxxer.hikari.useWeakReferences", "true"); + } + + private static final Logger LOG = LogManager.getLogger(JdbcConnectorClient.class); + protected static final int JDBC_DATETIME_SCALE = 6; + protected static final int MAX_DECIMAL128_PRECISION = 38; + + private static final Map<URL, RefCountedClassLoader> CLASS_LOADER_MAP = new ConcurrentHashMap<>(); + + /** + * Pairs a ClassLoader with a reference count so the map entry can be removed + * when the last client using that driver URL is closed. + */ + static final class RefCountedClassLoader { + final ClassLoader loader; + final AtomicInteger refCount = new AtomicInteger(1); + + RefCountedClassLoader(ClassLoader loader) { + this.loader = loader; + } + } + + protected final String catalogName; + protected final JdbcDbType dbType; + protected final String jdbcUrl; + protected final boolean onlySpecifiedDatabase; + protected final Map<String, Boolean> includeDatabaseMap; + protected final Map<String, Boolean> excludeDatabaseMap; + protected final boolean enableMappingVarbinary; + protected final boolean enableMappingTimestampTz; + protected ClassLoader classLoader; + private URL classLoaderUrl; + protected HikariDataSource dataSource; + + /** + * Factory method to create the correct client subclass for the given DB type. + */ + @SuppressWarnings("checkstyle:ParameterNumber") + public static JdbcConnectorClient create( + JdbcDbType dbType, String catalogName, + String jdbcUrl, String user, String password, + String driverUrl, String driverClass, + int poolMinSize, int poolMaxSize, + int poolMaxWaitTime, int poolMaxLifeTime, + boolean onlySpecifiedDatabase, + Map<String, String> allProperties, + boolean enableMappingVarbinary, + boolean enableMappingTimestampTz) { + Map<String, Boolean> includeMap = parseDatabaseMap( + allProperties.get("include_database_list")); + Map<String, Boolean> excludeMap = parseDatabaseMap( + allProperties.get("exclude_database_list")); + + JdbcConnectorClient client; + switch (dbType) { + case MYSQL: + client = new JdbcMySQLConnectorClient( + catalogName, dbType, jdbcUrl, onlySpecifiedDatabase, + includeMap, excludeMap, enableMappingVarbinary, + enableMappingTimestampTz); + break; + case POSTGRESQL: + client = new JdbcPostgreSQLConnectorClient( + catalogName, dbType, jdbcUrl, onlySpecifiedDatabase, + includeMap, excludeMap, enableMappingVarbinary, + enableMappingTimestampTz); + break; + case ORACLE: + client = new JdbcOracleConnectorClient( + catalogName, dbType, jdbcUrl, onlySpecifiedDatabase, + includeMap, excludeMap, enableMappingVarbinary, + enableMappingTimestampTz); + break; + case CLICKHOUSE: + client = new JdbcClickHouseConnectorClient( + catalogName, dbType, jdbcUrl, onlySpecifiedDatabase, + includeMap, excludeMap, enableMappingVarbinary, + enableMappingTimestampTz); + break; + case SQLSERVER: + client = new JdbcSQLServerConnectorClient( + catalogName, dbType, jdbcUrl, onlySpecifiedDatabase, + includeMap, excludeMap, enableMappingVarbinary, + enableMappingTimestampTz); + break; + case SAP_HANA: + client = new JdbcSapHanaConnectorClient( + catalogName, dbType, jdbcUrl, onlySpecifiedDatabase, + includeMap, excludeMap, enableMappingVarbinary, + enableMappingTimestampTz); + break; + case TRINO: + case PRESTO: + client = new JdbcTrinoConnectorClient( + catalogName, dbType, jdbcUrl, onlySpecifiedDatabase, + includeMap, excludeMap, enableMappingVarbinary, + enableMappingTimestampTz); + break; + case OCEANBASE: + client = new JdbcOceanBaseConnectorClient( + catalogName, dbType, jdbcUrl, onlySpecifiedDatabase, + includeMap, excludeMap, enableMappingVarbinary, + enableMappingTimestampTz); + break; + case DB2: + client = new JdbcDB2ConnectorClient( + catalogName, dbType, jdbcUrl, onlySpecifiedDatabase, + includeMap, excludeMap, enableMappingVarbinary, + enableMappingTimestampTz); + break; + case GBASE: + client = new JdbcGbaseConnectorClient( + catalogName, dbType, jdbcUrl, onlySpecifiedDatabase, + includeMap, excludeMap, enableMappingVarbinary, + enableMappingTimestampTz); + break; + default: + throw new DorisConnectorException("Unsupported JDBC DB type: " + dbType); + } + client.initializeClassLoader(driverUrl); + client.initializeDataSource(jdbcUrl, user, password, driverClass, + poolMinSize, poolMaxSize, poolMaxWaitTime, poolMaxLifeTime); + client.postInitialize(); + return client; + } + + protected JdbcConnectorClient( + String catalogName, JdbcDbType dbType, String jdbcUrl, + boolean onlySpecifiedDatabase, + Map<String, Boolean> includeDatabaseMap, + Map<String, Boolean> excludeDatabaseMap, + boolean enableMappingVarbinary, + boolean enableMappingTimestampTz) { + this.catalogName = catalogName; + this.dbType = dbType; + this.jdbcUrl = jdbcUrl; + this.onlySpecifiedDatabase = onlySpecifiedDatabase; + this.includeDatabaseMap = includeDatabaseMap != null ? includeDatabaseMap : Collections.emptyMap(); + this.excludeDatabaseMap = excludeDatabaseMap != null ? excludeDatabaseMap : Collections.emptyMap(); + this.enableMappingVarbinary = enableMappingVarbinary; + this.enableMappingTimestampTz = enableMappingTimestampTz; + } + + // -- lifecycle -- + + /** + * Hook called after class loader and data source are fully initialized. + * Subclasses can override to perform additional setup that requires a live connection. + */ + protected void postInitialize() { + } + + private void initializeDataSource(String url, String user, String password, + String driverClass, int poolMin, int poolMax, int maxWait, int maxLife) { + ClassLoader old = Thread.currentThread().getContextClassLoader(); + try { + Thread.currentThread().setContextClassLoader(this.classLoader); + dataSource = new HikariDataSource(); + dataSource.setDriverClassName(driverClass); + dataSource.setJdbcUrl(url); Review Comment: The old FE JDBC client ran the URL through `SecurityChecker.getSafeJdbcUrl()` before giving it to Hikari. The SPI path now passes `url` straight through, so catalogs created via the new connector module bypass the cluster's configured `security_checker_class_name` / JDBC URL policy. That is a security regression relative to the existing JDBC catalog behavior. ########## fe/fe-connector/fe-connector-jdbc/src/main/java/org/apache/doris/connector/jdbc/client/JdbcConnectorClient.java: ########## @@ -0,0 +1,676 @@ +// 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.connector.jdbc.client; + +import org.apache.doris.connector.api.ConnectorType; +import org.apache.doris.connector.api.DorisConnectorException; +import org.apache.doris.connector.jdbc.JdbcDbType; + +import com.zaxxer.hikari.HikariDataSource; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.Closeable; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; + +/** + * Base JDBC metadata client. Mirrors the structure of fe-core's {@code JdbcClient} + * but returns {@link ConnectorType} instead of Doris {@code Type}. + * + * <p>Subclasses override {@link #jdbcTypeToConnectorType} and optionally + * metadata-discovery methods for database-specific behaviour.</p> + */ +public abstract class JdbcConnectorClient implements Closeable { + + static { + // HikariCP reads this once at class-load time to decide whether ConcurrentBag + // should use WeakReferences for connection tracking. Set it early and globally. + System.setProperty("com.zaxxer.hikari.useWeakReferences", "true"); + } + + private static final Logger LOG = LogManager.getLogger(JdbcConnectorClient.class); + protected static final int JDBC_DATETIME_SCALE = 6; + protected static final int MAX_DECIMAL128_PRECISION = 38; + + private static final Map<URL, RefCountedClassLoader> CLASS_LOADER_MAP = new ConcurrentHashMap<>(); + + /** + * Pairs a ClassLoader with a reference count so the map entry can be removed + * when the last client using that driver URL is closed. + */ + static final class RefCountedClassLoader { + final ClassLoader loader; + final AtomicInteger refCount = new AtomicInteger(1); + + RefCountedClassLoader(ClassLoader loader) { + this.loader = loader; + } + } + + protected final String catalogName; + protected final JdbcDbType dbType; + protected final String jdbcUrl; + protected final boolean onlySpecifiedDatabase; + protected final Map<String, Boolean> includeDatabaseMap; + protected final Map<String, Boolean> excludeDatabaseMap; + protected final boolean enableMappingVarbinary; + protected final boolean enableMappingTimestampTz; + protected ClassLoader classLoader; + private URL classLoaderUrl; + protected HikariDataSource dataSource; + + /** + * Factory method to create the correct client subclass for the given DB type. + */ + @SuppressWarnings("checkstyle:ParameterNumber") + public static JdbcConnectorClient create( + JdbcDbType dbType, String catalogName, + String jdbcUrl, String user, String password, + String driverUrl, String driverClass, + int poolMinSize, int poolMaxSize, + int poolMaxWaitTime, int poolMaxLifeTime, + boolean onlySpecifiedDatabase, + Map<String, String> allProperties, + boolean enableMappingVarbinary, + boolean enableMappingTimestampTz) { + Map<String, Boolean> includeMap = parseDatabaseMap( + allProperties.get("include_database_list")); + Map<String, Boolean> excludeMap = parseDatabaseMap( + allProperties.get("exclude_database_list")); + + JdbcConnectorClient client; + switch (dbType) { + case MYSQL: + client = new JdbcMySQLConnectorClient( + catalogName, dbType, jdbcUrl, onlySpecifiedDatabase, + includeMap, excludeMap, enableMappingVarbinary, + enableMappingTimestampTz); + break; + case POSTGRESQL: + client = new JdbcPostgreSQLConnectorClient( + catalogName, dbType, jdbcUrl, onlySpecifiedDatabase, + includeMap, excludeMap, enableMappingVarbinary, + enableMappingTimestampTz); + break; + case ORACLE: + client = new JdbcOracleConnectorClient( + catalogName, dbType, jdbcUrl, onlySpecifiedDatabase, + includeMap, excludeMap, enableMappingVarbinary, + enableMappingTimestampTz); + break; + case CLICKHOUSE: + client = new JdbcClickHouseConnectorClient( + catalogName, dbType, jdbcUrl, onlySpecifiedDatabase, + includeMap, excludeMap, enableMappingVarbinary, + enableMappingTimestampTz); + break; + case SQLSERVER: + client = new JdbcSQLServerConnectorClient( + catalogName, dbType, jdbcUrl, onlySpecifiedDatabase, + includeMap, excludeMap, enableMappingVarbinary, + enableMappingTimestampTz); + break; + case SAP_HANA: + client = new JdbcSapHanaConnectorClient( + catalogName, dbType, jdbcUrl, onlySpecifiedDatabase, + includeMap, excludeMap, enableMappingVarbinary, + enableMappingTimestampTz); + break; + case TRINO: + case PRESTO: + client = new JdbcTrinoConnectorClient( + catalogName, dbType, jdbcUrl, onlySpecifiedDatabase, + includeMap, excludeMap, enableMappingVarbinary, + enableMappingTimestampTz); + break; + case OCEANBASE: + client = new JdbcOceanBaseConnectorClient( + catalogName, dbType, jdbcUrl, onlySpecifiedDatabase, + includeMap, excludeMap, enableMappingVarbinary, + enableMappingTimestampTz); + break; + case DB2: + client = new JdbcDB2ConnectorClient( + catalogName, dbType, jdbcUrl, onlySpecifiedDatabase, + includeMap, excludeMap, enableMappingVarbinary, + enableMappingTimestampTz); + break; + case GBASE: + client = new JdbcGbaseConnectorClient( + catalogName, dbType, jdbcUrl, onlySpecifiedDatabase, + includeMap, excludeMap, enableMappingVarbinary, + enableMappingTimestampTz); + break; + default: + throw new DorisConnectorException("Unsupported JDBC DB type: " + dbType); + } + client.initializeClassLoader(driverUrl); + client.initializeDataSource(jdbcUrl, user, password, driverClass, + poolMinSize, poolMaxSize, poolMaxWaitTime, poolMaxLifeTime); + client.postInitialize(); + return client; + } + + protected JdbcConnectorClient( + String catalogName, JdbcDbType dbType, String jdbcUrl, + boolean onlySpecifiedDatabase, + Map<String, Boolean> includeDatabaseMap, + Map<String, Boolean> excludeDatabaseMap, + boolean enableMappingVarbinary, + boolean enableMappingTimestampTz) { + this.catalogName = catalogName; + this.dbType = dbType; + this.jdbcUrl = jdbcUrl; + this.onlySpecifiedDatabase = onlySpecifiedDatabase; + this.includeDatabaseMap = includeDatabaseMap != null ? includeDatabaseMap : Collections.emptyMap(); + this.excludeDatabaseMap = excludeDatabaseMap != null ? excludeDatabaseMap : Collections.emptyMap(); + this.enableMappingVarbinary = enableMappingVarbinary; + this.enableMappingTimestampTz = enableMappingTimestampTz; + } + + // -- lifecycle -- + + /** + * Hook called after class loader and data source are fully initialized. + * Subclasses can override to perform additional setup that requires a live connection. + */ + protected void postInitialize() { + } + + private void initializeDataSource(String url, String user, String password, + String driverClass, int poolMin, int poolMax, int maxWait, int maxLife) { + ClassLoader old = Thread.currentThread().getContextClassLoader(); + try { + Thread.currentThread().setContextClassLoader(this.classLoader); + dataSource = new HikariDataSource(); + dataSource.setDriverClassName(driverClass); + dataSource.setJdbcUrl(url); + dataSource.setUsername(user); + dataSource.setPassword(password); + dataSource.setMinimumIdle(poolMin); + dataSource.setMaximumPoolSize(poolMax); + dataSource.setConnectionTimeout(maxWait); + dataSource.setMaxLifetime(maxLife); + dataSource.setIdleTimeout(maxLife / 2L); + dataSource.setConnectionTestQuery(getTestQuery()); + LOG.info("JdbcConnectorClient set PoolMin={}, PoolMax={}, MaxWait={}, MaxLife={}", + poolMin, poolMax, maxWait, maxLife); + } catch (Exception e) { + throw new DorisConnectorException("Failed to initialize JDBC data source: " + e.getMessage(), e); + } finally { + Thread.currentThread().setContextClassLoader(old); + } + } + + private synchronized void initializeClassLoader(String driverUrl) { + if (driverUrl == null || driverUrl.isEmpty()) { + this.classLoader = getClass().getClassLoader(); + return; + } + try { + URL[] urls = {new URL(resolveDriverUrl(driverUrl))}; Review Comment: Using `resolveDriverUrl()` here drops the `JdbcResource.getFullDriverUrl()` behavior from the old path. That helper handled bare driver filenames in both default driver directories, enforced `jdbc_driver_secure_path` / `jdbc_driver_url_white_list`, and did the cloud-download fallback. With this change, existing catalogs that rely on `driver_url = "xxx.jar"` or on the secure-path whitelist can stop working after the SPI migration. ########## fe/fe-connector/fe-connector-hudi/src/main/java/org/apache/doris/connector/hudi/HudiConnector.java: ########## @@ -0,0 +1,115 @@ +// 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.connector.hudi; + +import org.apache.doris.connector.api.Connector; +import org.apache.doris.connector.api.ConnectorMetadata; +import org.apache.doris.connector.api.ConnectorSession; +import org.apache.doris.connector.api.DorisConnectorException; +import org.apache.doris.connector.api.scan.ConnectorScanPlanProvider; +import org.apache.doris.connector.hms.HmsClient; +import org.apache.doris.connector.hms.HmsClientConfig; +import org.apache.doris.connector.hms.ThriftHmsClient; +import org.apache.doris.connector.spi.ConnectorContext; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.IOException; +import java.util.Collections; +import java.util.Map; + +/** + * Hudi connector implementation. Manages the lifecycle of an + * {@link HmsClient} for HMS table discovery and provides Hadoop + * configuration for building {@code HoodieTableMetaClient}. + * + * <p>Phase 1 provides read-only metadata operations (list databases, + * list tables, get schema via Hudi's Avro schema). Phase 2 adds scan + * planning for COW and MOR tables (snapshot reads).</p> + */ +public class HudiConnector implements Connector { + + private static final Logger LOG = LogManager.getLogger(HudiConnector.class); + + private final Map<String, String> properties; + private final ConnectorContext context; + private volatile HmsClient hmsClient; + + public HudiConnector(Map<String, String> properties, ConnectorContext context) { + this.properties = Collections.unmodifiableMap(properties); + this.context = context; + } + + @Override + public ConnectorMetadata getMetadata(ConnectorSession session) { + return new HudiConnectorMetadata(getOrCreateClient(), properties); + } + + @Override + public ConnectorScanPlanProvider getScanPlanProvider() { + return new HudiScanPlanProvider(properties); + } + + private HmsClient getOrCreateClient() { + if (hmsClient == null) { + synchronized (this) { + if (hmsClient == null) { + hmsClient = createClient(); + } + } + } + return hmsClient; + } + + private HmsClient createClient() { + String metastoreUri = properties.get(HudiConnectorProperties.HIVE_METASTORE_URIS); + if (metastoreUri == null || metastoreUri.isEmpty()) { + metastoreUri = properties.get("uri"); + } + if (metastoreUri == null || metastoreUri.isEmpty()) { + throw new DorisConnectorException( + "HMS URI ('" + HudiConnectorProperties.HIVE_METASTORE_URIS + "') is required for Hudi connector"); + } + + int poolSize = HudiConnectorProperties.getInt( + properties, HudiConnectorProperties.HMS_CLIENT_POOL_SIZE, + HudiConnectorProperties.DEFAULT_HMS_CLIENT_POOL_SIZE); + + HmsClientConfig config = new HmsClientConfig(properties, poolSize); + LOG.info("Creating Hudi connector HMS client for catalog='{}', uri={}, poolSize={}", + context.getCatalogName(), config.getMetastoreUri(), poolSize); + + ThriftHmsClient.AuthAction simpleAuth = new ThriftHmsClient.AuthAction() { Review Comment: Hudi still reaches HMS through the same `ThriftHmsClient` path, so using the same no-op `AuthAction` here regresses secured deployments for the Hudi connector as well. Previously the HMS calls ran under the catalog's execution authenticator; now they run as the FE process user. ########## fe/fe-core/src/main/java/org/apache/doris/datasource/PluginDrivenExternalCatalog.java: ########## @@ -0,0 +1,298 @@ +// 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.datasource; + +import org.apache.doris.common.DdlException; +import org.apache.doris.connector.ConnectorFactory; +import org.apache.doris.connector.ConnectorSessionBuilder; +import org.apache.doris.connector.DefaultConnectorContext; +import org.apache.doris.connector.api.Connector; +import org.apache.doris.connector.api.ConnectorSession; +import org.apache.doris.connector.api.ConnectorTestResult; +import org.apache.doris.qe.ConnectContext; +import org.apache.doris.transaction.PluginDrivenTransactionManager; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.IOException; +import java.util.List; +import java.util.Map; + +/** + * An {@link ExternalCatalog} backed by a Connector SPI plugin. + * + * <p>This adapter bridges the connector SPI ({@link Connector}) with the existing + * ExternalCatalog hierarchy. Metadata operations are delegated to the connector's + * {@link org.apache.doris.connector.api.ConnectorMetadata} implementation.</p> + * + * <p>When created via {@link CatalogFactory}, the Connector instance is provided + * directly. After GSON deserialization (FE restart), the Connector is recreated + * from catalog properties during {@link #initLocalObjectsImpl()}.</p> + */ +public class PluginDrivenExternalCatalog extends ExternalCatalog { + + private static final Logger LOG = LogManager.getLogger(PluginDrivenExternalCatalog.class); + + // Volatile for cross-thread visibility; all mutations also happen under synchronized(this). + private transient volatile Connector connector; + + // When true, onClose() skips closing the connector because notifyPropertiesUpdated() + // manages the connector lifecycle (create-before-swap pattern). + private transient volatile boolean connectorSwapInProgress = false; + + /** No-arg constructor for GSON deserialization. */ + public PluginDrivenExternalCatalog() { + } + + /** + * Creates a plugin-driven catalog with an already-created Connector. + * + * @param catalogId unique catalog id + * @param name catalog name + * @param resource optional resource name + * @param props catalog properties + * @param comment catalog comment + * @param connector the SPI connector instance + */ + public PluginDrivenExternalCatalog(long catalogId, String name, String resource, + Map<String, String> props, String comment, Connector connector) { + super(catalogId, name, InitCatalogLog.Type.PLUGIN, comment); + this.catalogProperty = new CatalogProperty(resource, props); + this.connector = connector; + } + + @Override + protected void initLocalObjectsImpl() { + if (connector != null) { + transactionManager = new PluginDrivenTransactionManager(); + initPreExecutionAuthenticator(); + return; + } + connector = createConnectorFromProperties(); + if (connector == null) { + String catalogType = catalogProperty.getOrDefault(CatalogMgr.CATALOG_TYPE_PROP, ""); + throw new RuntimeException("No ConnectorProvider found for plugin-driven catalog: " + + name + ", type: " + catalogType + + ". Ensure the connector plugin is installed."); + } + LOG.info("Recreated connector for plugin-driven catalog {}:{}, type={}", + name, id, catalogProperty.getOrDefault(CatalogMgr.CATALOG_TYPE_PROP, "")); + transactionManager = new PluginDrivenTransactionManager(); + initPreExecutionAuthenticator(); + } + + /** + * Creates a new Connector from catalog properties. Extracted as a protected method + * so tests can override without depending on the static ConnectorFactory registry. + */ + protected Connector createConnectorFromProperties() { + String catalogType = catalogProperty.getOrDefault(CatalogMgr.CATALOG_TYPE_PROP, ""); + return ConnectorFactory.createConnector(catalogType, + catalogProperty.getProperties(), + new DefaultConnectorContext(name, id)); + } + + @Override + public void checkProperties() throws DdlException { + super.checkProperties(); + String catalogType = catalogProperty.getOrDefault(CatalogMgr.CATALOG_TYPE_PROP, ""); + try { + ConnectorFactory.validateProperties(catalogType, catalogProperty.getProperties()); + } catch (IllegalArgumentException e) { + throw new DdlException(e.getMessage()); + } + // Validate function_rules JSON if present (shared across all connector types). + String functionRules = catalogProperty.getOrDefault("function_rules", null); + ExternalFunctionRules.check(functionRules); + } + + @Override + public void checkWhenCreating() throws DdlException { + boolean testConnection = Boolean.parseBoolean( + catalogProperty.getOrDefault(ExternalCatalog.TEST_CONNECTION, + String.valueOf(ExternalCatalog.DEFAULT_TEST_CONNECTION))); + if (!testConnection) { + return; + } + // Delegate connectivity testing to the connector SPI. + ConnectorSession session = buildConnectorSession(); + ConnectorTestResult result = connector.testConnection(session); Review Comment: This generic connectivity check is materially weaker than the previous JDBC create path. `JdbcExternalCatalog.checkWhenCreating()` computed/validated the driver checksum and exercised both FE->JDBC and BE->JDBC connectivity before accepting the catalog. Here we only call `connector.testConnection()`, and `JdbcDorisConnector.testConnection()` just lists databases on FE. That means a catalog can now be created successfully even when BEs cannot load/reach the driver JAR, and `checksum` is never auto-filled/validated. The failure moves from CREATE time to the first query/insert. ########## fe/fe-connector/fe-connector-hive/src/main/java/org/apache/doris/connector/hive/HiveConnector.java: ########## @@ -0,0 +1,112 @@ +// 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.connector.hive; + +import org.apache.doris.connector.api.Connector; +import org.apache.doris.connector.api.ConnectorMetadata; +import org.apache.doris.connector.api.ConnectorSession; +import org.apache.doris.connector.api.DorisConnectorException; +import org.apache.doris.connector.api.scan.ConnectorScanPlanProvider; +import org.apache.doris.connector.hms.HmsClient; +import org.apache.doris.connector.hms.HmsClientConfig; +import org.apache.doris.connector.hms.ThriftHmsClient; +import org.apache.doris.connector.spi.ConnectorContext; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.IOException; +import java.util.Collections; +import java.util.Map; + +/** + * Hive connector implementation. Manages the lifecycle of + * an {@link HmsClient} for HMS operations and provides scan planning. + */ +public class HiveConnector implements Connector { + + private static final Logger LOG = LogManager.getLogger(HiveConnector.class); + + private final Map<String, String> properties; + private final ConnectorContext context; + private volatile HmsClient hmsClient; + + public HiveConnector(Map<String, String> properties, ConnectorContext context) { + this.properties = Collections.unmodifiableMap(properties); + this.context = context; + } + + @Override + public ConnectorMetadata getMetadata(ConnectorSession session) { + return new HiveConnectorMetadata(getOrCreateClient(), properties); + } + + @Override + public ConnectorScanPlanProvider getScanPlanProvider() { + return new HiveScanPlanProvider(getOrCreateClient(), properties); + } + + private HmsClient getOrCreateClient() { + if (hmsClient == null) { + synchronized (this) { + if (hmsClient == null) { + hmsClient = createClient(); + } + } + } + return hmsClient; + } + + private HmsClient createClient() { + String metastoreUri = properties.get(HiveConnectorProperties.HIVE_METASTORE_URIS); + if (metastoreUri == null || metastoreUri.isEmpty()) { + // Also check the "uri" short form + metastoreUri = properties.get("uri"); + } + if (metastoreUri == null || metastoreUri.isEmpty()) { + throw new DorisConnectorException( + "HMS URI ('" + HiveConnectorProperties.HIVE_METASTORE_URIS + "') is required"); + } + + int poolSize = HiveConnectorProperties.getInt( + properties, HiveConnectorProperties.HMS_CLIENT_POOL_SIZE, + HiveConnectorProperties.DEFAULT_HMS_CLIENT_POOL_SIZE); + + HmsClientConfig config = new HmsClientConfig(properties, poolSize); + LOG.info("Creating Hive connector client for catalog='{}', uri={}, type={}, poolSize={}", + context.getCatalogName(), config.getMetastoreUri(), + config.getMetastoreType(), poolSize); + + ThriftHmsClient.AuthAction simpleAuth = new ThriftHmsClient.AuthAction() { Review Comment: Using a no-op `AuthAction` here drops the metastore execution authenticator that `HMSExternalCatalog` / `ThriftHMSCachedClient` used to apply around every HMS call. In secured deployments (Kerberos / doAs / custom authenticator), the new connector will call HMS as the FE process user and fail even though the old Hive catalog worked. The SPI context needs a way to pass the catalog's execution authenticator through. ########## fe/fe-connector/fe-connector-jdbc/src/main/java/org/apache/doris/connector/jdbc/JdbcUrlNormalizer.java: ########## @@ -0,0 +1,136 @@ +// 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.connector.jdbc; + +/** + * Normalizes JDBC URLs by adding required parameters for correct behavior. + * Replicates the logic from {@code JdbcResource.handleJdbcUrl()} in fe-core, + * ensuring the connector module produces identical behavior to the old path. + */ +public final class JdbcUrlNormalizer { + + private JdbcUrlNormalizer() { + } + + /** + * Normalize a JDBC URL by setting required parameters based on the database type. + * + * <p>For MySQL/OceanBase: + * <ul> + * <li>{@code yearIsDateType=false} — prevent YEAR returning java.sql.Date</li> + * <li>{@code tinyInt1isBit=false} — prevent TINYINT(1) → Boolean conversion</li> + * <li>{@code useUnicode=true}</li> + * <li>{@code characterEncoding=utf-8}</li> + * <li>{@code rewriteBatchedStatements=true}</li> + * </ul> + * + * <p>For OceanBase additionally: + * <ul> + * <li>{@code useCursorFetch=true} — enables binary protocol for full precision</li> + * </ul> + * + * <p>For PostgreSQL: + * <ul> + * <li>{@code reWriteBatchedInserts=true}</li> + * </ul> + * + * <p>For SQL Server: + * <ul> + * <li>{@code useBulkCopyForBatchInsert=true}</li> + * </ul> + */ + public static String normalize(String jdbcUrl, JdbcDbType dbType) { + if (jdbcUrl == null || jdbcUrl.isEmpty()) { + return jdbcUrl; + } + String url = jdbcUrl.replaceAll(" ", ""); + + switch (dbType) { + case MYSQL: + url = setParam(url, dbType, "yearIsDateType", "true", "false"); + url = setParam(url, dbType, "tinyInt1isBit", "true", "false"); + url = setParam(url, dbType, "useUnicode", "false", "true"); + url = setParamIfAbsent(url, dbType, "characterEncoding", "utf-8"); + url = setParam(url, dbType, "rewriteBatchedStatements", "false", "true"); + break; + case OCEANBASE: + url = setParam(url, dbType, "yearIsDateType", "true", "false"); + url = setParam(url, dbType, "tinyInt1isBit", "true", "false"); + url = setParam(url, dbType, "useUnicode", "false", "true"); + url = setParamIfAbsent(url, dbType, "characterEncoding", "utf-8"); + url = setParam(url, dbType, "rewriteBatchedStatements", "false", "true"); + url = setParam(url, dbType, "useCursorFetch", "false", "true"); + break; + case POSTGRESQL: + url = setParam(url, dbType, "reWriteBatchedInserts", "false", "true"); + break; + case SQLSERVER: Review Comment: `JdbcResource.handleJdbcUrl()` also honored `Config.force_sqlserver_jdbc_encrypt_false` by forcing `encrypt=false` before appending `useBulkCopyForBatchInsert=true`. That compatibility branch is missing here. Clusters that rely on `force_sqlserver_jdbc_encrypt_false=true` will start using the driver's default encrypt setting after migrating to the SPI JDBC path. -- 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]
