FANNG1 commented on code in PR #12541: URL: https://github.com/apache/gravitino/pull/12541#discussion_r3869186112
########## spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/GravitinoLakehouseRESTDiscoveryDriverPlugin.java: ########## @@ -0,0 +1,434 @@ +/* + * 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.gravitino.spark.connector.plugin; + +import static org.apache.gravitino.spark.connector.ConnectorConstants.COMMA; +import static org.apache.gravitino.spark.connector.utils.ConnectorUtil.removeDuplicateSparkExtensions; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Preconditions; +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.ServiceConfigurationError; +import java.util.ServiceLoader; +import java.util.Set; +import java.util.TreeMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.apache.commons.lang3.StringUtils; +import org.apache.spark.SparkConf; +import org.apache.spark.SparkContext; +import org.apache.spark.api.plugin.DriverPlugin; +import org.apache.spark.api.plugin.PluginContext; +import org.apache.spark.sql.catalyst.parser.CatalystSqlParser$; +import org.apache.spark.sql.internal.StaticSQLConf; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import scala.Tuple2; +import scala.collection.Seq; + +class GravitinoLakehouseRESTDiscoveryDriverPlugin implements DriverPlugin { + + @VisibleForTesting + static final String REGISTRATION_POLICY_CONFIG = "spark.sql.gravitino.REST.registrationPolicy"; + + private static final Logger LOG = + LoggerFactory.getLogger(GravitinoLakehouseRESTDiscoveryDriverPlugin.class); + private static final String GRAVITINO_PREFIX = "spark.sql.gravitino."; + private static final String SPARK_CATALOG_PREFIX = "spark.sql.catalog."; + private static final String URI_SUFFIX = "REST.uri"; + private static final String CATALOG_PROPERTIES_INFIX = "REST.catalogProperties."; + private static final Pattern PROVIDER_URI_PATTERN = + Pattern.compile("^spark\\.sql\\.gravitino\\.([A-Za-z][A-Za-z0-9]*)REST\\.uri$"); + private static final CatalogRegistrationPolicy DEFAULT_POLICY = (format, catalogName) -> true; + + private final List<LakehouseRESTCatalogProvider> providersForTesting; + + GravitinoLakehouseRESTDiscoveryDriverPlugin() { + this.providersForTesting = null; + } + + @VisibleForTesting + GravitinoLakehouseRESTDiscoveryDriverPlugin( + List<LakehouseRESTCatalogProvider> providersForTesting) { + this.providersForTesting = new ArrayList<>(providersForTesting); + } + + @Override + public Map<String, String> init(SparkContext sc, PluginContext pluginContext) { + initialize(sc.conf()); + return Collections.emptyMap(); + } + + @VisibleForTesting + void initialize(SparkConf sparkConf) { + validatePluginOrder(sparkConf); + SparkConf userConf = sparkConf.clone(); + Map<String, String> activeFormats = findActiveFormats(userConf); + if (activeFormats.isEmpty()) { + return; + } + + ClassLoader classLoader = contextClassLoader(); + Map<String, LakehouseRESTCatalogProvider> providers = loadProviders(classLoader); + CatalogRegistrationPolicy policy = loadRegistrationPolicy(userConf, classLoader); + List<CatalogRegistration> registrations = new ArrayList<>(); + Set<String> registeredNames = new LinkedHashSet<>(); + Set<String> extensions = new LinkedHashSet<>(); + + activeFormats.forEach( + (format, uri) -> { + LakehouseRESTCatalogProvider provider = providers.get(format); + Preconditions.checkArgument( + provider != null, + "No lakehouse REST catalog provider found for configured format: %s", + format); + validateProviderRuntime(provider, classLoader); + + Map<String, String> globalProperties = extractCatalogProperties(userConf, format); + List<String> advertisedCatalogs = + provider.listCatalogs(uri, Collections.unmodifiableMap(globalProperties)); + Preconditions.checkState( + advertisedCatalogs != null, + "Lakehouse REST catalog provider %s returned a null catalog list", + format); + + List<String> sortedCatalogs = new ArrayList<>(advertisedCatalogs); + Collections.sort(sortedCatalogs); + for (String catalogName : sortedCatalogs) { + addRegistration( + userConf, + provider, + policy, + format, + uri, + catalogName, + globalProperties, + registeredNames, + registrations); + } + extensions.addAll(Arrays.asList(provider.sparkExtensions())); + }); + + applyRegistrations(sparkConf, userConf, registrations); + registerSqlExtensions(sparkConf, extensions); + } + + private static void validatePluginOrder(SparkConf sparkConf) { + String configuredPlugins = sparkConf.get("spark.plugins", ""); + List<String> plugins = new ArrayList<>(); + for (String plugin : configuredPlugins.split(COMMA)) { + if (StringUtils.isNotBlank(plugin)) { + plugins.add(plugin.trim()); + } + } + + int discoveryPluginIndex = + plugins.indexOf(GravitinoLakehouseRESTDiscoveryPlugin.class.getName()); + int gravitinoPluginIndex = plugins.indexOf(GravitinoSparkPlugin.class.getName()); + Preconditions.checkArgument( + discoveryPluginIndex < 0 + || gravitinoPluginIndex < 0 + || discoveryPluginIndex < gravitinoPluginIndex, + "%s must be listed before %s in spark.plugins", + GravitinoLakehouseRESTDiscoveryPlugin.class.getName(), + GravitinoSparkPlugin.class.getName()); + } + + private static Map<String, String> findActiveFormats(SparkConf userConf) { + Map<String, String> activeFormats = new TreeMap<>(); + for (Tuple2<String, String> entry : userConf.getAll()) { + Matcher matcher = PROVIDER_URI_PATTERN.matcher(entry._1); + if (matcher.matches()) { + String format = matcher.group(1); + String uri = entry._2; + Preconditions.checkArgument( + StringUtils.isNotBlank(uri), + "%s%s%s must not be blank", + GRAVITINO_PREFIX, + format, + URI_SUFFIX); + activeFormats.put(format, uri); + } + } + return activeFormats; + } + + private Map<String, LakehouseRESTCatalogProvider> loadProviders(ClassLoader classLoader) { + List<LakehouseRESTCatalogProvider> loadedProviders = new ArrayList<>(); + if (providersForTesting != null) { + loadedProviders.addAll(providersForTesting); + } else { + try { + ServiceLoader.load(LakehouseRESTCatalogProvider.class, classLoader) + .forEach(loadedProviders::add); + } catch (ServiceConfigurationError e) { + throw new IllegalArgumentException("Failed to load lakehouse REST catalog providers", e); + } + } Review Comment: Fixed. The mechanism has been removed. now stores only format-to-provider-FQCN strings, and the driver reflectively loads only the provider for an active configured format after detecting its . The common package has no static reference to the Lance provider or Lance SDK classes. ########## spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/plugin/restcatalog/TestGravitinoLakehouseRESTDiscoveryDriverPlugin.java: ########## @@ -0,0 +1,317 @@ +/* + * 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.gravitino.spark.connector.plugin; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.google.common.collect.ImmutableMap; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import org.apache.spark.SparkConf; +import org.apache.spark.sql.internal.StaticSQLConf; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class TestGravitinoLakehouseRESTDiscoveryDriverPlugin { + + private static final String DISCOVERY_PLUGIN = + GravitinoLakehouseRESTDiscoveryPlugin.class.getName(); + private static final String GRAVITINO_PLUGIN = GravitinoSparkPlugin.class.getName(); + private static final String URI_CONFIG = "spark.sql.gravitino.fakeREST.uri"; + private static final String CATALOG_PREFIX = "spark.sql.catalog."; + + @BeforeEach + void resetPolicies() { + TrackingPolicy.invocationCount = 0; Review Comment: We do not enable JUnit 5 parallel execution in this project. Also, replacing this with an would make increments atomic but would not isolate the reset/increment sequence across concurrently executing test methods, so it would not solve the described interference. The counter is intentionally static because the policy instance is created reflectively, and it is reset in . ########## spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/plugin/restcatalog/TestGravitinoLakehouseRESTDiscoveryDriverPlugin.java: ########## @@ -0,0 +1,317 @@ +/* + * 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.gravitino.spark.connector.plugin; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.google.common.collect.ImmutableMap; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import org.apache.spark.SparkConf; +import org.apache.spark.sql.internal.StaticSQLConf; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class TestGravitinoLakehouseRESTDiscoveryDriverPlugin { + + private static final String DISCOVERY_PLUGIN = + GravitinoLakehouseRESTDiscoveryPlugin.class.getName(); + private static final String GRAVITINO_PLUGIN = GravitinoSparkPlugin.class.getName(); + private static final String URI_CONFIG = "spark.sql.gravitino.fakeREST.uri"; + private static final String CATALOG_PREFIX = "spark.sql.catalog."; + + @BeforeEach + void resetPolicies() { + TrackingPolicy.invocationCount = 0; + } + + @Test + void testRequiresDiscoveryPluginBeforeGravitinoPlugin() { + SparkConf sparkConf = + baseConf().set("spark.plugins", GRAVITINO_PLUGIN + "," + DISCOVERY_PLUGIN); + + IllegalArgumentException exception = + assertThrows(IllegalArgumentException.class, () -> driver().initialize(sparkConf)); + + assertTrue(exception.getMessage().contains("must be listed before")); + assertFalse(sparkConf.contains(CATALOG_PREFIX + "catalog_a")); + } + + @Test + void testNoConfiguredUriDoesNotChangeSparkConf() { + SparkConf sparkConf = + new SparkConf(false).set("spark.plugins", DISCOVERY_PLUGIN + "," + GRAVITINO_PLUGIN); + + new GravitinoLakehouseRESTDiscoveryDriverPlugin( + Collections.singletonList(new FailingProvider())) + .initialize(sparkConf); + + assertFalse(sparkConf.contains(StaticSQLConf.SPARK_SESSION_EXTENSIONS().key())); + } + + @Test + void testGeneratedConfigurationAndPrecedence() { + SparkConf sparkConf = + baseConf() + .set("spark.sql.gravitino.fakeREST.catalogProperties.impl", "global-impl") + .set("spark.sql.gravitino.fakeREST.catalogProperties.uri", "global-uri") + .set("spark.sql.gravitino.fakeREST.catalogProperties.extra", "global-extra") + .set(CATALOG_PREFIX + "catalog_a.uri", "user-uri") + .set( + StaticSQLConf.SPARK_SESSION_EXTENSIONS().key(), + "example.UserExtension,java.lang.Runnable"); + + driver().initialize(sparkConf); + + assertEquals(String.class.getName(), sparkConf.get(CATALOG_PREFIX + "catalog_a")); + assertEquals("rest", sparkConf.get(CATALOG_PREFIX + "catalog_a.impl")); + assertEquals("user-uri", sparkConf.get(CATALOG_PREFIX + "catalog_a.uri")); + assertEquals("catalog_a", sparkConf.get(CATALOG_PREFIX + "catalog_a.parent")); + assertEquals("global-extra", sparkConf.get(CATALOG_PREFIX + "catalog_a.extra")); + assertEquals( + "java.lang.Runnable,example.UserExtension", + sparkConf.get(StaticSQLConf.SPARK_SESSION_EXTENSIONS().key())); + } + + @Test + void testUserOwnedCatalogDoesNotReachPolicy() { + SparkConf sparkConf = + baseConf() + .set(CATALOG_PREFIX + "catalog_a", "example.UserCatalog") + .set( + GravitinoLakehouseRESTDiscoveryDriverPlugin.REGISTRATION_POLICY_CONFIG, + TrackingPolicy.class.getName()); + + driver().initialize(sparkConf); + + assertEquals(0, TrackingPolicy.invocationCount); + assertEquals("example.UserCatalog", sparkConf.get(CATALOG_PREFIX + "catalog_a")); + assertFalse(sparkConf.contains(CATALOG_PREFIX + "catalog_a.parent")); + } + + @Test + void testPolicyFiltersAndRenamesCatalogs() { + FakeProvider provider = new FakeProvider(Arrays.asList("catalog_a", "catalog_b")); + SparkConf sparkConf = + baseConf() + .set( + GravitinoLakehouseRESTDiscoveryDriverPlugin.REGISTRATION_POLICY_CONFIG, + RenamePolicy.class.getName()); + + new GravitinoLakehouseRESTDiscoveryDriverPlugin(Collections.singletonList(provider)) + .initialize(sparkConf); + + assertFalse(sparkConf.contains(CATALOG_PREFIX + "catalog_a")); + assertEquals(String.class.getName(), sparkConf.get(CATALOG_PREFIX + "renamed_b")); + assertEquals("catalog_b", sparkConf.get(CATALOG_PREFIX + "renamed_b.parent")); + } + + @Test + void testDuplicatePolicyOutputDoesNotPartiallyModifySparkConf() { + FakeProvider provider = new FakeProvider(Arrays.asList("catalog_a", "catalog_b")); + SparkConf sparkConf = + baseConf() + .set( + GravitinoLakehouseRESTDiscoveryDriverPlugin.REGISTRATION_POLICY_CONFIG, + DuplicatePolicy.class.getName()); + + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> + new GravitinoLakehouseRESTDiscoveryDriverPlugin(Collections.singletonList(provider)) + .initialize(sparkConf)); + + assertTrue(exception.getMessage().contains("duplicate name")); + assertFalse(sparkConf.contains(CATALOG_PREFIX + "duplicate")); + assertFalse(sparkConf.contains(StaticSQLConf.SPARK_SESSION_EXTENSIONS().key())); + } + + @Test + void testInvalidPolicyOutputFails() { + SparkConf sparkConf = + baseConf() + .set( + GravitinoLakehouseRESTDiscoveryDriverPlugin.REGISTRATION_POLICY_CONFIG, + InvalidNamePolicy.class.getName()); + + IllegalArgumentException exception = + assertThrows(IllegalArgumentException.class, () -> driver().initialize(sparkConf)); + + assertTrue(exception.getMessage().contains("invalid Spark identifier")); + assertFalse(sparkConf.contains(CATALOG_PREFIX + "invalid-name")); + } + + @Test + void testConfiguredFormatWithoutProviderFails() { + SparkConf sparkConf = baseConf(); + + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> + new GravitinoLakehouseRESTDiscoveryDriverPlugin(Collections.emptyList()) + .initialize(sparkConf)); + + assertTrue(exception.getMessage().contains("No lakehouse REST catalog provider")); + } + + private static SparkConf baseConf() { + return new SparkConf(false).set("spark.plugins", DISCOVERY_PLUGIN).set(URI_CONFIG, "rest-uri"); + } + + private static GravitinoLakehouseRESTDiscoveryDriverPlugin driver() { + return new GravitinoLakehouseRESTDiscoveryDriverPlugin( + Collections.singletonList(new FakeProvider(Collections.singletonList("catalog_a")))); + } + + private static class FakeProvider implements LakehouseRESTCatalogProvider { + private final List<String> catalogs; + + private FakeProvider(List<String> catalogs) { + this.catalogs = new ArrayList<>(catalogs); + } + + @Override + public String format() { + return "fake"; + } + + @Override + public List<String> listCatalogs(String uri, Map<String, String> catalogProperties) { + return catalogs; + } + + @Override + public String catalogClassName() { + return String.class.getName(); + } + + @Override + public Map<String, String> generatedCatalogProperties( + String uri, String advertisedCatalogName) { + return ImmutableMap.of("impl", "rest", "uri", uri, "parent", advertisedCatalogName); + } + + @Override + public String[] sparkExtensions() { + return new String[] {Runnable.class.getName()}; + } + } + + private static class FailingProvider implements LakehouseRESTCatalogProvider { + @Override + public String format() { + throw new AssertionError("Provider must not be loaded without a configured URI"); + } + + @Override + public List<String> listCatalogs(String uri, Map<String, String> catalogProperties) { + throw new AssertionError("Provider must not be called without a configured URI"); + } + + @Override + public String catalogClassName() { + throw new AssertionError("Provider must not be called without a configured URI"); + } + + @Override + public Map<String, String> generatedCatalogProperties( + String uri, String advertisedCatalogName) { + throw new AssertionError("Provider must not be called without a configured URI"); + } + + @Override + public String[] sparkExtensions() { + throw new AssertionError("Provider must not be called without a configured URI"); + } + } + + /** Policy used to verify user-owned catalogs are filtered before policy invocation. */ + public static class TrackingPolicy implements CatalogRegistrationPolicy { + private static int invocationCount; Review Comment: We do not enable JUnit 5 parallel execution in this project. Also, replacing this with an would make increments atomic but would not isolate the reset/increment sequence across concurrently executing test methods, so it would not solve the described interference. The counter is intentionally static because the policy instance is created reflectively, and it is reset in . -- 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]
