github-actions[bot] commented on code in PR #62183:
URL: https://github.com/apache/doris/pull/62183#discussion_r3094032324


##########
fe/fe-core/src/main/java/org/apache/doris/datasource/CatalogMgr.java:
##########
@@ -273,6 +273,20 @@ private void createCatalogImpl(CatalogIf catalog, String 
catalogName,
      * Create and hold the catalog instance and write the meta log.
      */
     public void createCatalog(CreateCatalogCommand cmd) throws UserException {
+        // Fast-path: skip connector/pool creation for catalogs that already 
exist.
+        // This avoids resource leaks from checkWhenCreating() when the 
catalog won't be registered.
+        // A TOCTOU race is benign — createCatalogImpl() also checks under 
write lock.
+        if (cmd.isSetIfNotExists()) {

Review Comment:
   This only avoids the leak for the simple `IF NOT EXISTS` case. A plain 
`CREATE CATALOG existing_name ...` still calls 
`CatalogFactory.createFromCommand()` first, which now builds a 
`PluginDrivenExternalCatalog` and runs `checkWhenCreating()` before 
`createCatalogImpl()` rejects the duplicate under the write lock. For JDBC 
catalogs that means opening connector-side resources and then dropping the 
object on the floor. The TOCTOU race is not benign either: if another thread 
creates the catalog after this read-lock check, the duplicate return in 
`createCatalogImpl()` still leaks the already-built connector. Please do the 
duplicate-name precheck unconditionally before `createFromCommand()`, or close 
the constructed catalog on the failure path.



##########
fe/fe-core/src/main/java/org/apache/doris/datasource/PluginDrivenExternalCatalog.java:
##########
@@ -0,0 +1,282 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.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.DefaultConnectorValidationContext;
+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.datasource.property.metastore.MetastoreProperties;
+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 happen under 
synchronized(this)
+    // via makeSureInitialized() → initLocalObjectsImpl(), or 
resetToUninitialized() → onClose().
+    private transient volatile Connector connector;
+
+    /** 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() {
+        // Always (re-)create the connector so it gets the proper engine 
context,
+        // including the catalog's execution authenticator for 
Kerberos/secured HMS.
+        // The connector created by CatalogFactory used a lightweight context
+        // without auth (the catalog didn't exist yet); we replace it now.
+        Connector newConnector = createConnectorFromProperties();
+        if (newConnector != null) {
+            connector = newConnector;

Review Comment:
   `CatalogFactory.createCatalog()` injects a pre-built connector here, and 
`checkWhenCreating()` can already have opened live resources on it. In the JDBC 
path, `connector.testConnection()` goes through 
`JdbcDorisConnector.getOrCreateClient()` and caches a 
`JdbcConnectorClient`/Hikari pool. Replacing `this.connector` without closing 
the old instance leaks that pool for every successfully created catalog. Please 
either close the previous connector before swapping, or avoid constructing two 
connector instances for the same catalog lifecycle.



##########
fe/fe-core/src/main/java/org/apache/doris/datasource/PluginDrivenExternalCatalog.java:
##########
@@ -0,0 +1,282 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.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.DefaultConnectorValidationContext;
+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.datasource.property.metastore.MetastoreProperties;
+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 happen under 
synchronized(this)
+    // via makeSureInitialized() → initLocalObjectsImpl(), or 
resetToUninitialized() → onClose().
+    private transient volatile Connector connector;
+
+    /** 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() {
+        // Always (re-)create the connector so it gets the proper engine 
context,
+        // including the catalog's execution authenticator for 
Kerberos/secured HMS.
+        // The connector created by CatalogFactory used a lightweight context
+        // without auth (the catalog didn't exist yet); we replace it now.
+        Connector newConnector = createConnectorFromProperties();
+        if (newConnector != null) {
+            connector = newConnector;
+        }
+        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.");
+        }
+        transactionManager = new PluginDrivenTransactionManager();
+        initPreExecutionAuthenticator();
+    }
+
+    @Override
+    protected synchronized void initPreExecutionAuthenticator() {
+        if (executionAuthenticator != null) {
+            return;
+        }
+        try {
+            MetastoreProperties msp = catalogProperty.getMetastoreProperties();
+            if (msp != null) {
+                executionAuthenticator = msp.getExecutionAuthenticator();
+                return;
+            }
+        } catch (Exception ignored) {
+            // Not all catalog types have metastore properties (e.g., JDBC, ES)
+        }
+        super.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, "");

Review Comment:
   This assumes migrated catalogs always persisted `catalogProperty["type"]`, 
but that is not true for old resource-backed JDBC/ES catalogs. `CatalogFactory` 
only backfills `type` on create/replay, while image deserialization now remaps 
`JdbcExternalCatalog`/`EsExternalCatalog` directly to 
`PluginDrivenExternalCatalog` via `GsonUtils.registerCompatibleSubtype(...)`. 
After upgrade, those catalogs can reach this code with `catalogType == ""` and 
then fail on first access even though the pre-upgrade catalog was valid. Please 
reconstruct `type` from the old resource/logType during migration, or make this 
path fall back to that information.



-- 
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]

Reply via email to