World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#12554] improvement(trino-connector): Route lakehouse-iceberg catalogs through the Iceberg REST server (#12555)
Yuhuib3b177706cb3
diff --git a/build.gradle.kts b/build.gradle.ktsindex fbf55b7c19..090cfd31f7 100644--- a/build.gradle.kts+++ b/build.gradle.kts@@ -434,16 +434,7 @@ subprojects {java {toolchain {- // Some JDK vendors like Homebrew installed OpenJDK 17 have problems in building trino-connector:- // It will cause tests of Trino-connector hanging forever on macOS, to avoid this issue and- // other vendor-related problems, Gravitino will use the specified AMAZON OpenJDK 17 to build- // Trino-connector on macOS.- if (project.name == "trino-connector") {- if (OperatingSystem.current().isMacOsX) {- vendor.set(JvmVendorSpec.AMAZON)- }- languageVersion.set(JavaLanguageVersion.of(17))- } else if (compatibleWithJDK8(project)) {+ if (compatibleWithJDK8(project)) {languageVersion.set(JavaLanguageVersion.of(17))sourceCompatibility = JavaVersion.VERSION_1_8targetCompatibility = JavaVersion.VERSION_1_8diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoClientBase.java b/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoClientBase.javaindex 996c149591..07c7e9cca6 100644--- a/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoClientBase.java+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoClientBase.java@@ -29,10 +29,12 @@ import java.net.URI;import java.net.URISyntaxException;import java.util.Collections;import java.util.Map;+import java.util.Optional;import org.apache.commons.lang3.StringUtils;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;import org.apache.gravitino.Version;+import org.apache.gravitino.dto.responses.IcebergRESTServiceResponse;import org.apache.gravitino.dto.responses.MetalakeResponse;import org.apache.gravitino.dto.responses.VersionResponse;import org.apache.gravitino.exceptions.GravitinoRuntimeException;@@ -185,6 +187,27 @@ public abstract class GravitinoClientBase implements Closeable {return new GravitinoVersion(resp.getVersion());}+ /**+ * Retrieves the endpoint of the Gravitino Iceberg REST server, if it is running and serves the+ * given metalake.+ *+ * @param metalakeName the metalake the caller intends to route through the Iceberg REST server+ * @return the Iceberg REST server endpoint, or empty if it is not running or serves a different+ * metalake+ */+ public Optional<String> icebergRestServiceUri(String metalakeName) {+ IcebergRESTServiceResponse resp =+ restClient.get(+ "api/system/iceberg-rest",+ ImmutableMap.of("metalake", metalakeName),+ IcebergRESTServiceResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.restErrorHandler());+ resp.validate();++ return Optional.ofNullable(resp.getUri());+ }+/** Closes the GravitinoClient and releases any underlying resources. */@Overridepublic void close() {diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/TestIcebergRestServiceUri.java b/clients/client-java/src/test/java/org/apache/gravitino/client/TestIcebergRestServiceUri.javanew file mode 100644index 0000000000..2186118e99--- /dev/null+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/TestIcebergRestServiceUri.java@@ -0,0 +1,82 @@+/*+ * 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.client;++import com.fasterxml.jackson.core.JsonProcessingException;+import com.google.common.collect.ImmutableMap;+import java.util.Optional;+import org.apache.gravitino.dto.responses.ErrorResponse;+import org.apache.gravitino.dto.responses.IcebergRESTServiceResponse;+import org.apache.hc.core5.http.HttpStatus;+import org.apache.hc.core5.http.Method;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++public class TestIcebergRestServiceUri extends TestBase {++ private static final String ICEBERG_REST_PATH = withSlash("api/system/iceberg-rest");++ @Test+ public void testIcebergRestServiceUriPresent() throws JsonProcessingException {+ IcebergRESTServiceResponse resp =+ new IcebergRESTServiceResponse("http://irc-host:9001/iceberg");+ buildMockResource(+ Method.GET,+ ICEBERG_REST_PATH,+ ImmutableMap.of("metalake", "test"),+ null,+ resp,+ HttpStatus.SC_OK);++ Optional<String> uri = client.icebergRestServiceUri("test");++ Assertions.assertTrue(uri.isPresent());+ Assertions.assertEquals("http://irc-host:9001/iceberg", uri.get());+ }++ @Test+ public void testIcebergRestServiceUriAbsent() throws JsonProcessingException {+ IcebergRESTServiceResponse resp = new IcebergRESTServiceResponse(null);+ buildMockResource(+ Method.GET,+ ICEBERG_REST_PATH,+ ImmutableMap.of("metalake", "test"),+ null,+ resp,+ HttpStatus.SC_OK);++ Optional<String> uri = client.icebergRestServiceUri("test");++ Assertions.assertFalse(uri.isPresent());+ }++ @Test+ public void testIcebergRestServiceUriPropagatesServerError() throws JsonProcessingException {+ ErrorResponse errResp = ErrorResponse.internalError("internal error");+ buildMockResource(+ Method.GET,+ ICEBERG_REST_PATH,+ ImmutableMap.of("metalake", "test"),+ null,+ errResp,+ HttpStatus.SC_INTERNAL_SERVER_ERROR);++ Assertions.assertThrows(RuntimeException.class, () -> client.icebergRestServiceUri("test"));+ }+}diff --git a/common/src/main/java/org/apache/gravitino/dto/responses/IcebergRESTServiceResponse.java b/common/src/main/java/org/apache/gravitino/dto/responses/IcebergRESTServiceResponse.javanew file mode 100644index 0000000000..89c071dfcc--- /dev/null+++ b/common/src/main/java/org/apache/gravitino/dto/responses/IcebergRESTServiceResponse.java@@ -0,0 +1,56 @@+/*+ * 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.dto.responses;++import com.fasterxml.jackson.annotation.JsonProperty;+import javax.annotation.Nullable;+import lombok.EqualsAndHashCode;+import lombok.Getter;+import lombok.ToString;++/**+ * Represents a response reporting the endpoint of the Gravitino Iceberg REST server, if it is+ * running and serves the requested metalake.+ */+@Getter+@EqualsAndHashCode(callSuper = true)+@ToString+public class IcebergRESTServiceResponse extends BaseResponse {++ @Nullable+ @JsonProperty("uri")+ private final String uri;++ /**+ * Constructor for IcebergRESTServiceResponse.+ *+ * @param uri the Iceberg REST server endpoint, or {@code null} when it is not running or does not+ * serve the requested metalake+ */+ public IcebergRESTServiceResponse(@Nullable String uri) {+ super(0);+ this.uri = uri;+ }++ /** Default constructor for IcebergRESTServiceResponse. (Used for Jackson deserialization.) */+ public IcebergRESTServiceResponse() {+ super();+ this.uri = null;+ }+}diff --git a/core/src/main/java/org/apache/gravitino/GravitinoEnv.java b/core/src/main/java/org/apache/gravitino/GravitinoEnv.javaindex 551283c3d1..9de4db1b34 100644--- a/core/src/main/java/org/apache/gravitino/GravitinoEnv.java+++ b/core/src/main/java/org/apache/gravitino/GravitinoEnv.java@@ -252,6 +252,15 @@ public class GravitinoEnv {return config;}+ /**+ * Get the auxiliary service manager associated with the Gravitino environment.+ *+ * @return The auxiliary service manager instance.+ */+ public AuxiliaryServiceManager auxServiceManager() {+ return auxServiceManager;+ }+/*** Get the EntityStore associated with the Gravitino environment.*diff --git a/core/src/main/java/org/apache/gravitino/auxiliary/AuxiliaryServiceManager.java b/core/src/main/java/org/apache/gravitino/auxiliary/AuxiliaryServiceManager.javaindex 08444abb3f..9c67a93583 100644--- a/core/src/main/java/org/apache/gravitino/auxiliary/AuxiliaryServiceManager.java+++ b/core/src/main/java/org/apache/gravitino/auxiliary/AuxiliaryServiceManager.java@@ -32,6 +32,8 @@ import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.ServiceLoader;+import java.util.Set;+import java.util.concurrent.ConcurrentHashMap;import java.util.function.Consumer;import java.util.stream.Collectors;import org.apache.commons.lang3.StringUtils;@@ -53,6 +55,9 @@ public class AuxiliaryServiceManager {private static final Splitter splitter = Splitter.on(",");private static final Joiner DOT = Joiner.on(".");+ // Tracks which deprecated keys have already been warned about, since getAuxServiceConfig+ // re-extracts the config on every call.+ private static final Set<String> warnedDeprecatedAuxServiceKeys = ConcurrentHashMap.newKeySet();private Map<String, GravitinoAuxiliaryService> auxServices = new HashMap<>();private Map<String, IsolatedClassLoader> auxServiceClassLoaders = new HashMap<>();@@ -94,11 +99,39 @@ public class AuxiliaryServiceManager {});}+ /**+ * Returns whether the given auxiliary service was configured and registered.+ *+ * @param auxServiceName the auxiliary service's short name, e.g. {@code iceberg-rest}+ * @return true if the service is registered+ */+ public boolean isAuxServiceRegistered(String auxServiceName) {+ return auxServices.containsKey(auxServiceName);+ }+@VisibleForTestingpublic IsolatedClassLoader getIsolatedClassLoader(List<String> classPaths) {return IsolatedClassLoader.buildClassLoader(classPaths);}+ /**+ * Returns the effective configuration for one auxiliary service, with keys stripped of the {@code+ * gravitino.<name>.} prefix (or the deprecated {@code gravitino.auxService.<name>.} prefix, which+ * is still honored) — the same map the service itself receives in {@link+ * GravitinoAuxiliaryService#serviceInit}. Callers outside this service (e.g. reporting an+ * auxiliary service's own endpoint) should read its config through this method rather than the+ * raw {@code gravitino.<name>.} prefix directly, so both config forms are honored consistently.+ *+ * @param gravitinoConfig the Gravitino server's configuration+ * @param auxServiceName the auxiliary service's short name, e.g. {@code iceberg-rest}+ * @return the auxiliary service's own configuration, with keys unprefixed+ */+ public static Map<String, String> getAuxServiceConfig(+ Config gravitinoConfig, String auxServiceName) {+ Map<String, String> serviceConfigs = extractAuxiliaryServiceConfigs(gravitinoConfig);+ return MapUtils.getPrefixMap(serviceConfigs, DOT.join(auxServiceName, ""));+ }+@VisibleForTestingstatic String getValidPath(String auxServiceName, String pathString) {Path path = Paths.get(pathString);@@ -240,10 +273,12 @@ public class AuxiliaryServiceManager {.forEach(entry -> {String extractKey = entry.getKey().substring(GRAVITINO_AUX_SERVICE_PREFIX.length());- LOG.warn(- "The configuration {} is deprecated(still working), please use gravitino.{} instead.",- entry.getKey(),- extractKey);+ if (warnedDeprecatedAuxServiceKeys.add(entry.getKey())) {+ LOG.warn(+ "The configuration {} is deprecated(still working), please use gravitino.{} instead.",+ entry.getKey(),+ extractKey);+ }serviceConfigs.put(extractKey, entry.getValue());});splitterdiff --git a/core/src/test/java/org/apache/gravitino/auxiliary/TestAuxiliaryServiceManager.java b/core/src/test/java/org/apache/gravitino/auxiliary/TestAuxiliaryServiceManager.javaindex d5ff499fc8..0148321038 100644--- a/core/src/test/java/org/apache/gravitino/auxiliary/TestAuxiliaryServiceManager.java+++ b/core/src/test/java/org/apache/gravitino/auxiliary/TestAuxiliaryServiceManager.java@@ -112,6 +112,72 @@ public class TestAuxiliaryServiceManager {verify(auxService2, times(1)).serviceStop();}+ @Test+ public void testIsAuxServiceRegistered() throws Exception {+ GravitinoAuxiliaryService auxService = mock(GravitinoAuxiliaryService.class);+ IsolatedClassLoader isolatedClassLoader =+ new IsolatedClassLoader(+ Collections.emptyList(), Collections.emptyList(), Collections.emptyList());++ AuxiliaryServiceManager auxServiceManager = new AuxiliaryServiceManager();+ AuxiliaryServiceManager spyAuxManager = spy(auxServiceManager);+ doReturn(isolatedClassLoader).when(spyAuxManager).getIsolatedClassLoader(anyList());+ doReturn(auxService).when(spyAuxManager).loadAuxService("iceberg-rest", isolatedClassLoader);++ Assertions.assertFalse(spyAuxManager.isAuxServiceRegistered("iceberg-rest"));++ spyAuxManager.serviceInit(+ DummyConfig.of(+ ImmutableMap.of(+ AuxiliaryServiceManager.GRAVITINO_AUX_SERVICE_PREFIX+ + AuxiliaryServiceManager.AUX_SERVICE_NAMES,+ "iceberg-rest",+ "gravitino.iceberg-rest." + AuxiliaryServiceManager.AUX_SERVICE_CLASSPATH,+ "/tmp")));++ Assertions.assertTrue(spyAuxManager.isAuxServiceRegistered("iceberg-rest"));+ Assertions.assertFalse(spyAuxManager.isAuxServiceRegistered("lance-rest"));+ }++ @Test+ void testGetAuxServiceConfig() {+ DummyConfig config =+ DummyConfig.of(+ ImmutableMap.of(+ AuxiliaryServiceManager.GRAVITINO_AUX_SERVICE_PREFIX+ + AuxiliaryServiceManager.AUX_SERVICE_NAMES,+ "iceberg-rest",+ "gravitino.iceberg-rest.host",+ "irc-host",+ "gravitino.iceberg-rest.httpPort",+ "9001"));++ Map<String, String> resolved =+ AuxiliaryServiceManager.getAuxServiceConfig(config, "iceberg-rest");++ Assertions.assertEquals("irc-host", resolved.get("host"));+ Assertions.assertEquals("9001", resolved.get("httpPort"));+ }++ @Test+ void testGetAuxServiceConfigHonorsDeprecatedPrefix() {+ // gravitino.auxService.<name>.<key> is deprecated but still honored; the effective config a+ // caller reads through this method must match what the service itself receives.+ DummyConfig config =+ DummyConfig.of(+ ImmutableMap.of(+ AuxiliaryServiceManager.GRAVITINO_AUX_SERVICE_PREFIX+ + AuxiliaryServiceManager.AUX_SERVICE_NAMES,+ "iceberg-rest",+ AuxiliaryServiceManager.GRAVITINO_AUX_SERVICE_PREFIX + "iceberg-rest.host",+ "irc-host"));++ Map<String, String> resolved =+ AuxiliaryServiceManager.getAuxServiceConfig(config, "iceberg-rest");++ Assertions.assertEquals("irc-host", resolved.get("host"));+ }+@Testvoid testAuxiliaryServiceConfigs() {Map<String, String> m =diff --git a/docs/trino-connector/authentication.md b/docs/trino-connector/authentication.mdindex 9793e7749f..42c7932f6b 100644--- a/docs/trino-connector/authentication.md+++ b/docs/trino-connector/authentication.md@@ -193,7 +193,24 @@ Whether the coordinator can populate this extra-credential depends on the TrinoThe `gravitino.client.oauth2.*` properties above still configure the shared bootstrap/admin client used for catalog discovery — they are unrelated to the per-user forwarded token.-For an Iceberg catalog with `catalog-backend=rest` (backed by an Iceberg REST Catalog), the connector does not set `iceberg.rest-catalog.security`/`iceberg.rest-catalog.session` on its own — that catalog's own `gravitino.client.*` config is unrelated to how its underlying Iceberg REST catalog authenticates. To also forward the end user's token to the REST catalog itself, set `trino.bypass.iceberg.rest-catalog.security=OAUTH2` and `trino.bypass.iceberg.rest-catalog.session=USER` explicitly on that catalog's properties, alongside its bootstrap `trino.bypass.iceberg.rest-catalog.oauth2.*` credentials; see the worked example below.+For an Iceberg catalog reached through the Gravitino Iceberg REST server (IRC) — every+`lakehouse-iceberg` catalog for which the Gravitino server reports a running IRC; see [Iceberg+catalog](./catalog-iceberg.md#how-trino-reaches-the-catalog) — the IRC's own authentication is+configured once per Trino cluster with the `gravitino.iceberg.rest-catalog.` prefix, and+`iceberg.rest-catalog.session=USER` is set automatically when `forwardUser=true`:++```properties+gravitino.iceberg.rest-catalog.security=OAUTH2+gravitino.iceberg.rest-catalog.oauth2.credential=service-account-id:service-account-secret+gravitino.iceberg.rest-catalog.oauth2.server-uri=http://your-idp/realms/gravitino/protocol/openid-connect/token+gravitino.iceberg.rest-catalog.oauth2.scope=email+```++This is a completely separate credential from the one the connector uses against the main Gravitino+server; it is not reused automatically.++For an Iceberg catalog with `catalog-backend=rest` (pointing at an Iceberg REST Catalog of its own,+which the connector does not re-route), the connector does not set `iceberg.rest-catalog.security`/`iceberg.rest-catalog.session` on its own — that catalog's own `gravitino.client.*` config is unrelated to how its underlying Iceberg REST catalog authenticates. To also forward the end user's token to the REST catalog itself, set `trino.bypass.iceberg.rest-catalog.security=OAUTH2` and `trino.bypass.iceberg.rest-catalog.session=USER` explicitly on that catalog's properties, alongside its bootstrap `trino.bypass.iceberg.rest-catalog.oauth2.*` credentials; see the worked example below.**Configuration properties:**diff --git a/docs/trino-connector/catalog-iceberg.md b/docs/trino-connector/catalog-iceberg.mdindex fbecbcb7d0..4fc7b35336 100644--- a/docs/trino-connector/catalog-iceberg.md+++ b/docs/trino-connector/catalog-iceberg.md@@ -20,6 +20,122 @@ To use Iceberg, you need:- ORC- Parquet (default)+## How Trino Reaches the Catalog++The Gravitino Trino connector loads every `lakehouse-iceberg` catalog through the Gravitino Iceberg+REST server (IRC), regardless of the catalog's `catalog-backend`. `catalog-backend` describes how+Gravitino stores the catalog's metadata; it does not decide how the query engine reaches the data.++This is what makes [credential vending](../security/credential-vending.md) work. Trino only consumes+vended credentials in its `rest` Iceberg catalog type — the `jdbc` and `hive_metastore` types have+nowhere to put the session token of an STS temporary credential — so a catalog with+`credential-providers=s3-token` produces no usable credential on those paths. Routing through the+IRC means every table access gets a freshly issued temporary credential over the Iceberg REST+protocol.++The connector already connects to the Gravitino server (it is how catalogs are discovered in the+first place), so it also asks that server whether it has an Iceberg REST server running as an+[auxiliary service](../iceberg-rest-service.md) for the connector's metalake. By default, a+non-REST `lakehouse-iceberg` catalog is not registered until an endpoint is discovered or configured+explicitly. It is retried during every metadata refresh rather than silently falling back and+disabling credential vending. To retain the behavior from older connector versions, set+`gravitino.iceberg.rest-routing-enabled=false`; this skips discovery and translates the catalog's+`catalog-backend` into the corresponding native Trino Iceberg configuration.++Only the coordinator polls the Gravitino server, so the coordinator resolves the endpoint when a+catalog is registered or refreshed and hands it to every node (coordinator and workers alike)+as part of that catalog's own definition — the same way Trino replicates any other catalog property+cluster-wide. A catalog that could not be registered before the IRC started is registered+automatically after a later discovery poll succeeds; no Trino restart is required.++Set `gravitino.iceberg.rest-uri` to override the discovered endpoint, and it is required — not just+an override — for a standalone IRC (its own process, not the Gravitino server's auxiliary service):+the Gravitino server has no way to know a standalone IRC exists, so discovery never finds one. See+[Limitations](#limitations).++```properties+connector.name=gravitino+gravitino.metalake=test+gravitino.uri=http://gravitino-host:8090++gravitino.iceberg.rest-uri=http://gravitino-host:9001/iceberg+```++The connector derives everything else from the catalog itself. The Gravitino catalog name is passed+as both `iceberg.rest-catalog.warehouse` and `iceberg.rest-catalog.prefix` — the Iceberg client+selects the catalog twice over, first as the query parameter of the `GET /v1/config` call that+discovers it, then as the path segment of every request after that.++The Trino native file system is derived from the catalog's `warehouse` scheme, because vended+credentials are only consumed by Trino's native file systems:++| Warehouse scheme | Derived properties |+|:------------------------------------------------|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------|+| `s3://`, `s3a://`, `s3n://` | `fs.native-s3.enabled`, plus `s3.region`, `s3.endpoint` and `s3.path-style-access` where the catalog defines `s3-region`, `s3-endpoint` and `s3-path-style-access` |+| `gs://` | `fs.native-gcs.enabled` |+| `abfs://`, `abfss://`, `wasb://`, `wasbs://` | `fs.native-azure.enabled` |+| anything else (`hdfs://`, `file://`, `oss://`) | none — only `fs.hadoop.enabled` |++A scheme in the last row has no Trino native file system, so a catalog that vends credentials for it+cannot have them applied; the connector logs a warning when it detects that combination.++On the Gravitino side, the IRC must run with the dynamic config provider so it can serve catalogs+defined in Gravitino:++```properties+gravitino.auxService.names = iceberg-rest+gravitino.iceberg-rest.catalog-config-provider = dynamic-config-provider+gravitino.iceberg-rest.gravitino-metalake = test+```++### Authenticating to the Iceberg REST Server++If the IRC has authentication enabled, the internal Iceberg REST catalog that the connector builds+must authenticate to it on its own. This is a separate credential from the one the connector uses+against the main Gravitino server, and it is not reused automatically. Any property prefixed with+`gravitino.iceberg.rest-catalog.` is passed through to the internal catalog with the prefix+rewritten to `iceberg.rest-catalog.`:++```properties+gravitino.iceberg.rest-catalog.security=OAUTH2+gravitino.iceberg.rest-catalog.oauth2.credential=client_id:client_secret+gravitino.iceberg.rest-catalog.oauth2.server-uri=http://your-idp/token+gravitino.iceberg.rest-catalog.oauth2.scope=email+```++Omitting this block against an authenticated IRC surfaces as an authentication error rather than a+missing-configuration error, which is easy to misdiagnose.++Four keys are reserved: `iceberg.rest-catalog.uri`, `.warehouse`, `.prefix` and+`iceberg.catalog.type`. The connector always derives these itself, so setting them through either+`gravitino.iceberg.rest-catalog.` or a catalog's `trino.bypass.` has no effect — the connector logs+when it ignores one.++When `gravitino.client.session.forwardUser=true`, the connector also sets+`iceberg.rest-catalog.session=USER` so that each query carries the end user's identity to the IRC,+keeping per-user credential vending and per-user authorization intact. Set+`gravitino.iceberg.rest-catalog.session` explicitly to override it. See+[Authentication](./authentication.md) for the full setup.++### Limitations++- One IRC serves exactly one metalake, fixed at startup by+ `gravitino.iceberg-rest.gravitino-metalake`. The Gravitino server only reports the IRC's endpoint+ for that metalake. In multi-metalake mode (`gravitino.use-single-metalake=false`), a non-REST+ Iceberg catalog in another metalake therefore requires a metalake-scoped manual URI or remains+ unregistered while REST routing is enabled.+- A catalog created with `catalog-backend=rest` keeps pointing at its own configured `uri` and is+ not re-routed, since it already reaches an Iceberg REST catalog directly.+- A deployment that does not run the IRC must set+ `gravitino.iceberg.rest-routing-enabled=false` to translate non-REST `lakehouse-iceberg` catalogs+ into Trino's `jdbc` or `hive_metastore` catalog types as before.+- Discovery only works for an IRC running as a Gravitino auxiliary service+ (`gravitino.auxService.names=iceberg-rest`), embedded in the same process as the Gravitino server.+ A standalone IRC — its own process, started with `GravitinoIcebergRESTServer` and its own+ `gravitino-iceberg-rest-server.conf` — never registers with the Gravitino server, so the server+ has no way to know it exists; the Gravitino server reports no endpoint even while a standalone IRC+ is running. Set `gravitino.iceberg.rest-uri` manually in this case.+## Schema Operations### Create a Schemadiff --git a/docs/trino-connector/configuration.md b/docs/trino-connector/configuration.mdindex ec5f42011a..cf8e562c31 100644--- a/docs/trino-connector/configuration.md+++ b/docs/trino-connector/configuration.md@@ -29,13 +29,27 @@ license: "This software is licensed under the Apache License version 2."| gravitino.client. | string | (none) | The configuration key prefix for the Gravitino client config. | No || gravitino.trino.skip-catalog-patterns | string | (none) | The `gravitino.trino.skip-catalog-patterns` defines a comma-separated list of catalog name regex patterns that should be excluded from loading. For example, `test_.*, .*_tmp` excludes all catalogs starting with `test_` or ending with `_tmp`. | No || gravitino.use-single-metalake | boolean | true | If `true`, only one metalake is used and catalogs are identified by `<catalog_name>`. If `false`, multi-metalake mode is enabled and catalogs are identified by `<metalake_name>.<catalog_name>`. | No |+| gravitino.iceberg.rest-routing-enabled | boolean | true | Whether non-REST `lakehouse-iceberg` catalogs must be routed through the Gravitino Iceberg REST server. When enabled, a catalog is not registered until discovery succeeds or `gravitino.iceberg.rest-uri` is configured. Set this to `false` to retain legacy `catalog-backend` translation and skip discovery. | No |+| gravitino.iceberg.rest-uri | string | (none) | The endpoint of the Gravitino Iceberg REST server (IRC). It is discovered automatically from the Gravitino server for this connector's metalake; set this only to override the discovered value. When available, eligible `lakehouse-iceberg` catalogs are loaded through IRC, enabling credential vending. | No |+| gravitino.iceberg.rest-catalog. | string | (none) | Prefix for properties passed to the internal Trino Iceberg REST catalog. The prefix is rewritten to `iceberg.rest-catalog.`. The `uri`, `warehouse`, and `prefix` keys are reserved and derived by the connector. | No |To configure the Gravitino client, use properties prefixed with `gravitino.client.`. These properties will directly passed to the Gravitino client.**Note:** Invalid configuration properties will result in exceptions. Please see [Gravitino Java client configurations](../how-to-use-gravitino-client.md#java-client-configuration) for more support client configuration.+When upgrading a deployment that does not provide an Iceberg REST endpoint, either configure+`gravitino.iceberg.rest-uri` or set `gravitino.iceberg.rest-routing-enabled=false` to retain the+legacy `catalog-backend` translation. Otherwise, non-REST `lakehouse-iceberg` catalogs remain+unregistered until discovery succeeds. See+[Iceberg catalog](./catalog-iceberg.md#how-trino-reaches-the-catalog).+Multi-metalake mode (`gravitino.use-single-metalake=false`) is supported on Trino connector versions 440-445 and 469-478. On versions 446-468, a warning is logged and the connector initializes, but the mode is not fully supported and some operations may fail.+**Note:** In multi-metalake mode, `gravitino.iceberg.rest-uri` is only honored when scoped to a+metalake, as `gravitino.iceberg.rest-uri.<metalake_name>` — the unscoped form is ignored, since a+single Iceberg REST server serves exactly one metalake and applying it to every metalake would+misroute the others. The unscoped form remains valid in single-metalake mode.+## Connecting to a TLS-enabled coordinatorThe Gravitino Trino connector registers catalogs by connecting back to the Trino coordinator overdiff --git a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/BaseIT.java b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/BaseIT.javaindex 8dc0d8d209..a2bae427b2 100644--- a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/BaseIT.java+++ b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/BaseIT.java@@ -122,6 +122,8 @@ public class BaseIT {public static final String DOWNLOAD_SQLITE_JDBC_DRIVER_URL ="https://repo1.maven.org/maven2/org/xerial/sqlite-jdbc/3.42.0.0/sqlite-jdbc-3.42.0.0.jar";+ public static final String GRAVITINO_ICEBERG_REST_PREFIX = "gravitino.iceberg-rest.";+public static final Map<String, Pattern> SUPPORTED_CLEAN_CONFLICTS_DRIVER_TYPES =ImmutableMap.of("mysql", Pattern.compile("mysql-connector-java-([\\d.]+)\\.jar"),@@ -674,9 +676,21 @@ public class BaseIT {return null;}+ /**+ * Enables the Iceberg REST auxiliary service before the server starts. Callers that hold a {@link+ * BaseIT} instance rather than extending it use this instead of the protected fields.+ *+ * @param icebergRestConfigs extra server configs, typically the dynamic config provider and the+ * metalake the Iceberg REST service should serve+ */+ public void enableIcebergAuxRestService(Map<String, String> icebergRestConfigs) {+ this.ignoreIcebergAuxRestService = false;+ this.customConfigs.putAll(icebergRestConfigs);+ }+protected String getIcebergRestServiceUri() {JettyServerConfig jettyServerConfig =- JettyServerConfig.fromConfig(serverConfig, String.format("gravitino.iceberg-rest."));+ JettyServerConfig.fromConfig(serverConfig, GRAVITINO_ICEBERG_REST_PREFIX);return String.format("http://%s:%d/iceberg/", jettyServerConfig.getHost(), jettyServerConfig.getHttpPort());}diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/IcebergRESTServiceOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/IcebergRESTServiceOperations.javanew file mode 100644index 0000000000..05969db42f--- /dev/null+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/IcebergRESTServiceOperations.java@@ -0,0 +1,199 @@+/*+ * 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.server.web.rest;++import com.codahale.metrics.annotation.ResponseMetered;+import com.codahale.metrics.annotation.Timed;+import java.util.Map;+import javax.servlet.http.HttpServletRequest;+import javax.ws.rs.Consumes;+import javax.ws.rs.GET;+import javax.ws.rs.Path;+import javax.ws.rs.Produces;+import javax.ws.rs.QueryParam;+import javax.ws.rs.core.Context;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;+import org.apache.commons.lang3.StringUtils;+import org.apache.gravitino.GravitinoEnv;+import org.apache.gravitino.auxiliary.AuxiliaryServiceManager;+import org.apache.gravitino.dto.responses.IcebergRESTServiceResponse;+import org.apache.gravitino.metrics.MetricNames;+import org.apache.gravitino.server.web.Utils;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++/**+ * Reports the endpoint of the Gravitino Iceberg REST server, so that clients which already connect+ * to this Gravitino server can discover it instead of requiring it to be configured separately.+ */+@Path("/system/iceberg-rest")+@Consumes(MediaType.APPLICATION_JSON)+@Produces(MediaType.APPLICATION_JSON)+public class IcebergRESTServiceOperations {++ private static final Logger LOG = LoggerFactory.getLogger(IcebergRESTServiceOperations.class);++ // Matches gravitino.auxService.names / AuxiliaryServiceManager's registration key.+ private static final String AUX_SERVICE_NAME = "iceberg-rest";+ // Keys below are read from AuxiliaryServiceManager.getAuxServiceConfig, which already strips+ // the gravitino.iceberg-rest. (or deprecated gravitino.auxService.iceberg-rest.) prefix, so+ // they must NOT be re-prefixed here.+ // The provider name used by the Iceberg REST server itself; see+ // IcebergConstants.ICEBERG_REST_CATALOG_CONFIG_PROVIDER and DynamicIcebergConfigProvider. The+ // server module cannot depend on iceberg-common/catalog-common, hence the literal here.+ private static final String CATALOG_CONFIG_PROVIDER_KEY = "catalog-config-provider";+ private static final String DYNAMIC_CATALOG_CONFIG_PROVIDER_NAME = "dynamic-config-provider";+ // The post-strip key used by the Iceberg REST server itself; see+ // IcebergConstants.GRAVITINO_METALAKE and DynamicIcebergConfigProvider.+ private static final String SERVED_METALAKE_KEY = "gravitino-metalake";+ private static final String HOST_KEY = "host";+ private static final String HTTP_PORT_KEY = "httpPort";+ private static final String HTTPS_PORT_KEY = "httpsPort";+ private static final String ENABLE_HTTPS_KEY = "enableHttps";+ // Match IcebergConfig.DEFAULT_ICEBERG_REST_SERVICE_HTTP_PORT/HTTPS_PORT: the server module+ // cannot depend on iceberg-common, and JettyServerConfig's own defaults are the Gravitino+ // server's (8090/8433), not the Iceberg REST server's — reading raw values with these+ // defaults avoids silently reporting the wrong port when httpPort is not set explicitly.+ private static final int DEFAULT_HTTP_PORT = 9001;+ private static final int DEFAULT_HTTPS_PORT = 9433;+ private static final String DEFAULT_HOST = "0.0.0.0";++ @Context private HttpServletRequest httpRequest;++ /**+ * Reports the Iceberg REST server's endpoint for the requested metalake.+ *+ * @param metalake the metalake the caller intends to route through the Iceberg REST server; may+ * be blank, in which case the endpoint is reported regardless of which metalake it serves+ * @return a response whose {@code uri} is {@code null} when the Iceberg REST server is not+ * running, or does not serve the requested metalake+ */+ @GET+ @Produces("application/vnd.gravitino.v1+json")+ @Timed(name = "iceberg-rest-service." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)+ @ResponseMetered(name = "iceberg-rest-service", absolute = true)+ public Response getIcebergRestServiceUri(@QueryParam("metalake") String metalake) {+ // The reported host can depend on the caller's own Host header (see resolveUri), so this+ // response must never be cached and replayed to a different caller.+ return Response.fromResponse(Utils.ok(new IcebergRESTServiceResponse(resolveUri(metalake))))+ .header("Cache-Control", "no-store")+ .build();+ }++ // Overridable so tests can inject a fixture without bootstrapping GravitinoEnv, matching+ // HealthOperations's testing pattern.+ AuxiliaryServiceManager getAuxServiceManager() {+ return GravitinoEnv.getInstance().auxServiceManager();+ }++ // Resolved through AuxiliaryServiceManager.getAuxServiceConfig rather than reading+ // gravitino.iceberg-rest.* directly, so the deprecated gravitino.auxService.iceberg-rest.*+ // config form is honored too — the same precedence the Iceberg REST server itself sees.+ Map<String, String> getIcebergRestServiceConfig() {+ return AuxiliaryServiceManager.getAuxServiceConfig(+ GravitinoEnv.getInstance().config(), AUX_SERVICE_NAME);+ }++ HttpServletRequest getHttpRequest() {+ return httpRequest;+ }++ private String resolveUri(String metalake) {+ if (!getAuxServiceManager().isAuxServiceRegistered(AUX_SERVICE_NAME)) {+ return null;+ }++ Map<String, String> config = getIcebergRestServiceConfig();+ String provider = config.getOrDefault(CATALOG_CONFIG_PROVIDER_KEY, "");+ if (!DYNAMIC_CATALOG_CONFIG_PROVIDER_NAME.equals(provider)) {+ // Only the dynamic catalog config provider maps Iceberg REST catalog names onto Gravitino+ // catalogs; the default static provider serves statically-declared catalogs unrelated to+ // Gravitino catalog names, so routing at it would 404 on every request.+ LOG.debug(+ "Iceberg REST service does not use the dynamic catalog config provider "+ + "(catalog-config-provider={}); not reporting its endpoint for auto-discovery.",+ provider);+ return null;+ }++ String servedMetalake = config.getOrDefault(SERVED_METALAKE_KEY, "");+ if (StringUtils.isNotBlank(metalake)+ && StringUtils.isNotBlank(servedMetalake)+ && !servedMetalake.equals(metalake)) {+ // The Iceberg REST server serves exactly one metalake. Routing a different metalake's+ // catalogs at it would 404 on every request, so report it as unavailable instead.+ LOG.debug(+ "Iceberg REST service serves metalake {}, not the requested metalake {}; not "+ + "reporting its endpoint for auto-discovery.",+ servedMetalake,+ metalake);+ return null;+ }++ String host = config.getOrDefault(HOST_KEY, DEFAULT_HOST);+ if (isWildcardHost(host)) {+ // The Iceberg REST server binds to all interfaces, so it has no single externally+ // reachable address of its own. The caller already reached this Gravitino server at some+ // resolvable host, so reuse it — this holds whenever both services share a host, which is+ // the common case, and callers with a genuinely split topology can still set+ // gravitino.iceberg.rest-uri manually.+ host = getHttpRequest().getServerName();+ }+ boolean enableHttps = Boolean.parseBoolean(config.getOrDefault(ENABLE_HTTPS_KEY, "false"));+ String scheme = enableHttps ? "https" : "http";+ int port =+ parsePort(+ config,+ enableHttps ? HTTPS_PORT_KEY : HTTP_PORT_KEY,+ enableHttps ? DEFAULT_HTTPS_PORT : DEFAULT_HTTP_PORT);+ return String.format("%s://%s:%d/iceberg", scheme, bracketIfIPv6(host), port);+ }++ // An IPv6 literal host (e.g. "::1", from an explicit config value or from+ // HttpServletRequest#getServerName()) must be bracketed to form a valid URI authority;+ // otherwise its colons are parsed as the port separator. A hostname or IPv4 address never+ // contains a colon, so this only ever fires for IPv6.+ private static String bracketIfIPv6(String host) {+ if (host.contains(":") && !host.startsWith("[")) {+ return "[" + host + "]";+ }+ return host;+ }++ private static int parsePort(Map<String, String> config, String key, int defaultPort) {+ String value = config.getOrDefault(key, "");+ if (StringUtils.isBlank(value)) {+ return defaultPort;+ }+ try {+ return Integer.parseInt(value.trim());+ } catch (NumberFormatException e) {+ return defaultPort;+ }+ }++ private static boolean isWildcardHost(String host) {+ return StringUtils.isBlank(host)+ || "0.0.0.0".equals(host)+ || "::".equals(host)+ || "[::]".equals(host)+ || "0:0:0:0:0:0:0:0".equals(host);+ }+}diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestIcebergRESTServiceOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestIcebergRESTServiceOperations.javanew file mode 100644index 0000000000..3db9f8fa43--- /dev/null+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestIcebergRESTServiceOperations.java@@ -0,0 +1,234 @@+/*+ * 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.server.web.rest;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++import com.google.common.collect.ImmutableMap;+import java.util.Map;+import javax.servlet.http.HttpServletRequest;+import javax.ws.rs.Produces;+import javax.ws.rs.core.Response;+import org.apache.gravitino.auxiliary.AuxiliaryServiceManager;+import org.apache.gravitino.dto.responses.IcebergRESTServiceResponse;+import org.junit.jupiter.api.Test;++public class TestIcebergRESTServiceOperations {++ private static final String DYNAMIC_PROVIDER = "dynamic-config-provider";++ @Test+ public void testDiscoveryEndpointProducesVersionedJson() throws Exception {+ Produces produces =+ IcebergRESTServiceOperations.class+ .getMethod("getIcebergRestServiceUri", String.class)+ .getAnnotation(Produces.class);++ assertEquals("application/vnd.gravitino.v1+json", produces.value()[0]);+ }++ private static Map<String, String> withDynamicProvider(Map<String, String> extra) {+ return ImmutableMap.<String, String>builder()+ .put("catalog-config-provider", DYNAMIC_PROVIDER)+ .putAll(extra)+ .buildKeepingLast();+ }++ private IcebergRESTServiceOperations newOps(+ boolean registered, Map<String, String> icebergConfig, String requestServerName) {+ AuxiliaryServiceManager auxServiceManager = mock(AuxiliaryServiceManager.class);+ when(auxServiceManager.isAuxServiceRegistered("iceberg-rest")).thenReturn(registered);+ HttpServletRequest request = mock(HttpServletRequest.class);+ when(request.getServerName()).thenReturn(requestServerName);++ return new IcebergRESTServiceOperations() {+ @Override+ AuxiliaryServiceManager getAuxServiceManager() {+ return auxServiceManager;+ }++ @Override+ Map<String, String> getIcebergRestServiceConfig() {+ return icebergConfig;+ }++ @Override+ HttpServletRequest getHttpRequest() {+ return request;+ }+ };+ }++ private String uriOf(Response response) {+ return ((IcebergRESTServiceResponse) response.getEntity()).getUri();+ }++ @Test+ public void testReturnsNullWhenAuxServiceNotRegistered() {+ IcebergRESTServiceOperations ops = newOps(false, ImmutableMap.of(), "gravitino-host");+ assertNull(uriOf(ops.getIcebergRestServiceUri("test")));+ }++ @Test+ public void testReturnsNullWhenNotUsingDynamicConfigProvider() {+ // Regression test: the default (static) catalog config provider serves statically-declared+ // catalogs unrelated to Gravitino catalog names, so it must never be reported for+ // auto-discovery — even with a blank/absent catalog-config-provider, which is what the+ // common no-provider-configured deployment looks like.+ IcebergRESTServiceOperations ops =+ newOps(true, ImmutableMap.of("host", "irc-host"), "gravitino-host");+ assertNull(uriOf(ops.getIcebergRestServiceUri("test")));+ }++ @Test+ public void testReturnsNullWhenStaticConfigProviderExplicit() {+ IcebergRESTServiceOperations ops =+ newOps(+ true,+ ImmutableMap.of("catalog-config-provider", "static-config-provider", "host", "h"),+ "gravitino-host");+ assertNull(uriOf(ops.getIcebergRestServiceUri("test")));+ }++ @Test+ public void testDefaultPortIsTheIcebergRestDefaultNotTheGravitinoServerDefault() {+ // Regression test: without an explicit httpPort, the reported port must be the Iceberg REST+ // server's own default (9001), not the Gravitino webserver's default (8090) that+ // JettyServerConfig would otherwise fall back to.+ IcebergRESTServiceOperations ops =+ newOps(true, withDynamicProvider(ImmutableMap.of("host", "irc-host")), "gravitino-host");+ assertEquals("http://irc-host:9001/iceberg", uriOf(ops.getIcebergRestServiceUri("")));+ }++ @Test+ public void testHttpsUsesTheHttpsPortNotTheHttpPort() {+ IcebergRESTServiceOperations ops =+ newOps(+ true,+ withDynamicProvider(+ ImmutableMap.of(+ "host", "irc-host",+ "enableHttps", "true")),+ "gravitino-host");+ assertEquals("https://irc-host:9433/iceberg", uriOf(ops.getIcebergRestServiceUri("")));+ }++ @Test+ public void testExplicitPortIsHonored() {+ IcebergRESTServiceOperations ops =+ newOps(+ true,+ withDynamicProvider(+ ImmutableMap.of(+ "host", "irc-host",+ "httpPort", "19001")),+ "gravitino-host");+ assertEquals("http://irc-host:19001/iceberg", uriOf(ops.getIcebergRestServiceUri("")));+ }++ @Test+ public void testMalformedPortFallsBackToDefaultPort() {+ IcebergRESTServiceOperations ops =+ newOps(+ true,+ withDynamicProvider(ImmutableMap.of("host", "irc-host", "httpPort", "not-a-number")),+ "gravitino-host");+ assertEquals("http://irc-host:9001/iceberg", uriOf(ops.getIcebergRestServiceUri("")));+ }++ @Test+ public void testWildcardHostFallsBackToRequestServerName() {+ IcebergRESTServiceOperations ops =+ newOps(+ true, withDynamicProvider(ImmutableMap.of("host", "0.0.0.0")), "host.docker.internal");+ assertEquals(+ "http://host.docker.internal:9001/iceberg", uriOf(ops.getIcebergRestServiceUri("")));+ }++ @Test+ public void testExplicitIPv6HostIsBracketed() {+ IcebergRESTServiceOperations ops =+ newOps(true, withDynamicProvider(ImmutableMap.of("host", "::1")), "gravitino-host");+ assertEquals("http://[::1]:9001/iceberg", uriOf(ops.getIcebergRestServiceUri("")));+ }++ @Test+ public void testWildcardHostFallsBackToIPv6RequestServerName() {+ IcebergRESTServiceOperations ops =+ newOps(true, withDynamicProvider(ImmutableMap.of("host", "::")), "::1");+ assertEquals("http://[::1]:9001/iceberg", uriOf(ops.getIcebergRestServiceUri("")));+ }++ @Test+ public void testBlankHostIsTreatedAsWildcard() {+ IcebergRESTServiceOperations ops =+ newOps(true, withDynamicProvider(ImmutableMap.of()), "gravitino-host");+ assertEquals("http://gravitino-host:9001/iceberg", uriOf(ops.getIcebergRestServiceUri("")));+ }++ @Test+ public void testMismatchedMetalakeReturnsNull() {+ IcebergRESTServiceOperations ops =+ newOps(+ true,+ withDynamicProvider(+ ImmutableMap.of(+ "host", "irc-host",+ "gravitino-metalake", "prod")),+ "gravitino-host");+ assertNull(uriOf(ops.getIcebergRestServiceUri("test")));+ }++ @Test+ public void testMatchingMetalakeIsReported() {+ IcebergRESTServiceOperations ops =+ newOps(+ true,+ withDynamicProvider(+ ImmutableMap.of(+ "host", "irc-host",+ "gravitino-metalake", "test")),+ "gravitino-host");+ assertEquals("http://irc-host:9001/iceberg", uriOf(ops.getIcebergRestServiceUri("test")));+ }++ @Test+ public void testBlankRequestedMetalakeSkipsTheMetalakeCheck() {+ IcebergRESTServiceOperations ops =+ newOps(+ true,+ withDynamicProvider(+ ImmutableMap.of(+ "host", "irc-host",+ "gravitino-metalake", "prod")),+ "gravitino-host");+ assertEquals("http://irc-host:9001/iceberg", uriOf(ops.getIcebergRestServiceUri("")));+ }++ @Test+ public void testResponseIsNotCacheable() {+ IcebergRESTServiceOperations ops =+ newOps(true, withDynamicProvider(ImmutableMap.of()), "gravitino-host");+ Response response = ops.getIcebergRestServiceUri("");+ assertEquals("no-store", response.getHeaderString("Cache-Control"));+ }+}diff --git a/trino-connector/integration-test/build.gradle.kts b/trino-connector/integration-test/build.gradle.ktsindex bd39ae2c2e..8264535b6c 100644--- a/trino-connector/integration-test/build.gradle.kts+++ b/trino-connector/integration-test/build.gradle.kts@@ -34,6 +34,7 @@ dependencies {}testImplementation(project(":api"))+ testImplementation(project(":catalogs:catalog-common"))testImplementation(project(":clients:client-java"))testImplementation(project(":common"))testImplementation(project(":core"))diff --git a/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoConnectorIT.java b/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoConnectorIT.javaindex 10eb37db74..7b04f21da6 100644--- a/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoConnectorIT.java+++ b/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoConnectorIT.java@@ -33,6 +33,7 @@ import java.util.concurrent.TimeUnit;import org.apache.gravitino.Catalog;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Schema;+import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;import org.apache.gravitino.client.GravitinoMetalake;import org.apache.gravitino.integration.test.container.ContainerSuite;import org.apache.gravitino.integration.test.container.HiveContainer;@@ -90,6 +91,21 @@ public class TrinoConnectorIT extends BaseIT {private static GravitinoMetalake metalake;private static Catalog catalog;+ // Set from an instance initializer rather than an overridden @BeforeAll: BaseIT is PER_CLASS, so+ // the instance exists before any lifecycle method runs, and JUnit only guarantees that a+ // superclass @BeforeAll precedes a subclass one — two @BeforeAll methods declared on this same+ // class would have no defined order relative to each other.+ {+ // The Trino connector loads every lakehouse-iceberg catalog through the Iceberg REST server,+ // so the auxiliary service has to run and serve this test's metalake.+ enableIcebergAuxRestService(+ ImmutableMap.of(+ GRAVITINO_ICEBERG_REST_PREFIX + IcebergConstants.ICEBERG_REST_CATALOG_CONFIG_PROVIDER,+ IcebergConstants.DYNAMIC_ICEBERG_CATALOG_CONFIG_PROVIDER_NAME,+ GRAVITINO_ICEBERG_REST_PREFIX + IcebergConstants.GRAVITINO_METALAKE,+ metalakeName));+ }+@BeforeAllpublic void startDockerContainer() throws TException, InterruptedException {String trinoConfDir = System.getenv("TRINO_CONF_DIR");diff --git a/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoQueryITBase.java b/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoQueryITBase.javaindex bbfc257244..e393027747 100644--- a/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoQueryITBase.java+++ b/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoQueryITBase.java@@ -20,6 +20,7 @@ package org.apache.gravitino.trino.connector.integration.test;import static java.lang.Thread.sleep;+import com.google.common.collect.ImmutableMap;import java.io.File;import java.io.IOException;import java.nio.charset.StandardCharsets;@@ -32,6 +33,7 @@ import org.apache.gravitino.Catalog;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;import org.apache.gravitino.SupportsSchemas;+import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;import org.apache.gravitino.client.GravitinoAdminClient;import org.apache.gravitino.client.GravitinoMetalake;import org.apache.gravitino.exceptions.RESTException;@@ -96,6 +98,15 @@ public class TrinoQueryITBase {private void setEnv() throws Exception {baseIT = new BaseIT();if (autoStart) {+ // The Trino connector loads every lakehouse-iceberg catalog through the Iceberg REST server,+ // so the auxiliary service has to run and serve this test's metalake.+ baseIT.enableIcebergAuxRestService(+ ImmutableMap.of(+ BaseIT.GRAVITINO_ICEBERG_REST_PREFIX+ + IcebergConstants.ICEBERG_REST_CATALOG_CONFIG_PROVIDER,+ IcebergConstants.DYNAMIC_ICEBERG_CATALOG_CONFIG_PROVIDER_NAME,+ BaseIT.GRAVITINO_ICEBERG_REST_PREFIX + IcebergConstants.GRAVITINO_METALAKE,+ metalakeName));baseIT.startIntegrationTest();gravitinoClient = baseIT.getGravitinoClient();gravitinoUri = String.format("http://127.0.0.1:%d", baseIT.getGravitinoServerPort());diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.javaindex f109b37c7e..553e091e4d 100644--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java@@ -31,6 +31,7 @@ import java.util.List;import java.util.Locale;import java.util.Map;import java.util.Properties;+import java.util.concurrent.ConcurrentHashMap;import java.util.regex.Pattern;import java.util.stream.Collectors;import org.apache.commons.lang3.StringUtils;@@ -76,9 +77,22 @@ public class GravitinoConfig {public static final String GRAVITINO_DYNAMIC_CONNECTOR_CATALOG_CONFIG ="__gravitino.dynamic.connector.catalog.config";+ /** The Trino Iceberg REST catalog property prefix. */+ private static final String TRINO_ICEBERG_REST_CATALOG_PREFIX = "iceberg.rest-catalog.";++ /** Prefix for environment-variable references propagated to dynamic catalogs. */+ static final String GRAVITINO_DYNAMIC_CATALOG_ENV_PREFIX =+ "gravitino.dynamic-catalog.environment-variable.";++ private static final Pattern ENVIRONMENT_VARIABLE_NAME =+ Pattern.compile("[A-Za-z_][A-Za-z0-9_]*");+private static final Map<String, ConfigEntry> CONFIG_DEFINITIONS = new HashMap<>();private final Map<String, String> config;private final List<Pattern> skipCatalogPatternList;+ // Iceberg REST server endpoints discovered from the Gravitino server, keyed by metalake. Written+ // by the catalog connector manager's periodic poll and read on every Iceberg catalog load.+ private final Map<String, String> discoveredIcebergRestUriByMetalake = new ConcurrentHashMap<>();// Gravitino config entityprivate static final ConfigEntry GRAVITINO_URI =@@ -263,6 +277,33 @@ public class GravitinoConfig {"3600",false);+ private static final ConfigEntry GRAVITINO_ICEBERG_REST_URI =+ new ConfigEntry(+ "gravitino.iceberg.rest-uri",+ "The endpoint of the Gravitino Iceberg REST server. Discovered automatically from the "+ + "Gravitino server by default; set this only to override the discovered value, "+ + "for example when the Iceberg REST server is not reachable at the address the "+ + "Gravitino server itself reports.",+ "",+ false);++ private static final ConfigEntry GRAVITINO_ICEBERG_REST_ROUTING_ENABLED =+ new ConfigEntry(+ "gravitino.iceberg.rest-routing-enabled",+ "Whether non-REST Iceberg catalogs must be routed through the Gravitino Iceberg REST "+ + "server. Disable this only to retain the legacy catalog-backend translation.",+ "true",+ false);++ private static final ConfigEntry GRAVITINO_ICEBERG_REST_CATALOG_CONFIG_PREFIX =+ new ConfigEntry(+ "gravitino.iceberg.rest-catalog.",+ "Prefix for properties passed through to the internal Trino Iceberg REST catalog. Any "+ + "property beginning with this prefix is rewritten to iceberg.rest-catalog. and "+ + "passed through (e.g., gravitino.iceberg.rest-catalog.security=OAUTH2).",+ "",+ false);+/*** Constructs a new GravitinoConfig with the specified configuration.*@@ -596,16 +637,42 @@ public class GravitinoConfig {continue;}String value = config.get(entry.getKey());- if (value != null) {+ if (value != null+ && !GravitinoConnectorFactory.isSecuritySensitivePropertyName(entry.getKey())) {stringList.add(String.format("\"%s\"='%s'", entry.getKey(), value));}}- // copy the configuration by the prefix of GRAVITINO_CLIENT_CONFIG_PREFIX+ // copy the configuration by the prefix of GRAVITINO_CLIENT_CONFIG_PREFIX and+ // GRAVITINO_ICEBERG_REST_CATALOG_CONFIG_PREFIXconfig.entrySet().stream()- .filter(entry -> entry.getKey().startsWith(GRAVITINO_CLIENT_CONFIG_PREFIX.key))+ .filter(+ entry ->+ (entry.getKey().startsWith(GRAVITINO_CLIENT_CONFIG_PREFIX.key)+ || entry+ .getKey()+ .startsWith(GRAVITINO_ICEBERG_REST_CATALOG_CONFIG_PREFIX.key))+ && !GravitinoConnectorFactory.isSecuritySensitivePropertyName(entry.getKey())).forEach(entry ->stringList.add(String.format("\"%s\"='%s'", entry.getKey(), entry.getValue())));+ config.entrySet().stream()+ .filter(entry -> entry.getKey().startsWith(GRAVITINO_DYNAMIC_CATALOG_ENV_PREFIX))+ .forEach(+ entry -> {+ String propertyName =+ entry.getKey().substring(GRAVITINO_DYNAMIC_CATALOG_ENV_PREFIX.length());+ String environmentVariable = entry.getValue();+ if (propertyName.isEmpty()+ || !ENVIRONMENT_VARIABLE_NAME.matcher(environmentVariable).matches()) {+ throw new TrinoException(+ GravitinoErrorCode.GRAVITINO_ILLEGAL_ARGUMENT,+ String.format(+ "Invalid dynamic catalog environment-variable mapping '%s'='%s'",+ entry.getKey(), environmentVariable));+ }+ stringList.add(+ String.format("\"%s\"='${ENV:%s}'", propertyName, environmentVariable));+ });return StringUtils.join(stringList, ',');}@@ -678,6 +745,124 @@ public class GravitinoConfig {return parseLongConfigEntry(GRAVITINO_SESSION_CACHE_EXPIRE_AFTER_ACCESS_SECONDS);}+ /**+ * Sets the Iceberg REST server endpoint discovered from the Gravitino server for the given+ * metalake. Called only by the catalog connector manager's periodic metalake poll, which runs on+ * the coordinator only — {@link #getDiscoveredIcebergRestUri} is therefore not by itself a valid+ * routing signal on a worker node. The coordinator is responsible for embedding the discovered+ * value into each catalog's own properties at registration time, so that it travels to every node+ * through the {@code CREATE CATALOG} statement Trino replicates cluster-wide; see {@code+ * CatalogRegister.generateCreateCatalogCommand}.+ *+ * @param metalake the metalake the endpoint was discovered for+ * @param uri the discovered endpoint, or {@code null} when the Iceberg REST server is not running+ * or does not serve this metalake+ */+ public void setDiscoveredIcebergRestUri(String metalake, String uri) {+ if (StringUtils.isBlank(uri)) {+ discoveredIcebergRestUriByMetalake.remove(metalake);+ } else {+ discoveredIcebergRestUriByMetalake.put(metalake, uri);+ }+ }++ /**+ * Retrieves the Iceberg REST server endpoint discovered from the Gravitino server for the given+ * metalake, with no fallback to the manually configured endpoint. Only valid on the node that+ * runs the periodic discovery poll (the coordinator); see {@link #setDiscoveredIcebergRestUri}.+ *+ * @param metalake the metalake to resolve the endpoint for+ * @return the discovered endpoint, or an empty string when none is available+ */+ public String getDiscoveredIcebergRestUri(String metalake) {+ return discoveredIcebergRestUriByMetalake.getOrDefault(metalake, "");+ }++ /**+ * Returns whether non-REST Iceberg catalogs must be routed through the Gravitino Iceberg REST+ * server.+ *+ * @return {@code true} when Iceberg REST routing is enabled+ */+ public boolean isIcebergRestRoutingEnabled() {+ String value =+ config.getOrDefault(+ GRAVITINO_ICEBERG_REST_ROUTING_ENABLED.key,+ GRAVITINO_ICEBERG_REST_ROUTING_ENABLED.defaultValue);+ return parseBooleanConfig(GRAVITINO_ICEBERG_REST_ROUTING_ENABLED.key, value);+ }++ /**+ * Retrieves the manually configured Iceberg REST server endpoint for the given metalake, if any.+ * Unlike the discovered endpoint, this is plain local file configuration and is therefore+ * identical and valid on every node — coordinator and workers alike.+ *+ * <p>{@code gravitino.iceberg.rest-uri.<metalake>} is checked first. The unscoped {@code+ * gravitino.iceberg.rest-uri} is honored only in single-metalake mode, where it is unambiguous;+ * in multi-metalake mode it is ignored, since a single Iceberg REST server serves exactly one+ * metalake and applying it to every metalake would misroute the others.+ *+ * @param metalake the metalake to resolve the override for+ * @return the manually configured Iceberg REST server endpoint, or an empty string when unset+ */+ public String getManualIcebergRestUri(String metalake) {+ String scopedValue = config.get(GRAVITINO_ICEBERG_REST_URI.key + "." + metalake);+ if (StringUtils.isNotBlank(scopedValue)) {+ return scopedValue;+ }+ if (singleMetalakeMode()) {+ return config.getOrDefault(+ GRAVITINO_ICEBERG_REST_URI.key, GRAVITINO_ICEBERG_REST_URI.defaultValue);+ }+ return GRAVITINO_ICEBERG_REST_URI.defaultValue;+ }++ /**+ * Retrieves the properties passed through to the internal Trino Iceberg REST catalog, with the+ * {@code gravitino.iceberg.rest-catalog.} prefix rewritten to {@code iceberg.rest-catalog.}.+ *+ * @return the Trino Iceberg REST catalog properties+ */+ public Map<String, String> getIcebergRestCatalogConfig() {+ String prefix = GRAVITINO_ICEBERG_REST_CATALOG_CONFIG_PREFIX.key;+ Map<String, String> restCatalogConfig = new HashMap<>();++ if ("oauth2".equalsIgnoreCase(config.get(GravitinoAuthProvider.AUTH_TYPE_KEY))) {+ restCatalogConfig.put(TRINO_ICEBERG_REST_CATALOG_PREFIX + "security", "OAUTH2");+ putIfNotBlank(+ restCatalogConfig,+ TRINO_ICEBERG_REST_CATALOG_PREFIX + "oauth2.credential",+ config.get(GravitinoAuthProvider.OAUTH_CREDENTIAL_KEY));+ putIfNotBlank(+ restCatalogConfig,+ TRINO_ICEBERG_REST_CATALOG_PREFIX + "oauth2.scope",+ config.get(GravitinoAuthProvider.OAUTH_SCOPE_KEY));++ String serverUri = config.get(GravitinoAuthProvider.OAUTH_SERVER_URI_KEY);+ String path = config.get(GravitinoAuthProvider.OAUTH_PATH_KEY);+ if (StringUtils.isNotBlank(serverUri) && StringUtils.isNotBlank(path)) {+ restCatalogConfig.put(+ TRINO_ICEBERG_REST_CATALOG_PREFIX + "oauth2.server-uri",+ StringUtils.removeEnd(serverUri, "/") + "/" + StringUtils.removeStart(path, "/"));+ }+ }++ config.entrySet().stream()+ .filter(entry -> entry.getKey().startsWith(prefix))+ .forEach(+ entry ->+ restCatalogConfig.put(+ TRINO_ICEBERG_REST_CATALOG_PREFIX + entry.getKey().substring(prefix.length()),+ entry.getValue()));+ return restCatalogConfig;+ }++ private static void putIfNotBlank(Map<String, String> target, String key, String value) {+ if (StringUtils.isNotBlank(value)) {+ target.put(key, value);+ }+ }+private long parseLongConfigEntry(ConfigEntry entry) {String value = config.getOrDefault(entry.key, entry.defaultValue);try {diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory.javaindex 222fb0e99f..df83dd387e 100644--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory.java+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory.java@@ -125,11 +125,15 @@ public class GravitinoConnectorFactory implements ConnectorFactory {CatalogRegister catalogRegister = new CatalogRegister();CatalogConnectorFactory catalogConnectorFactory = createCatalogConnectorFactory(config);- catalogConnectorManager =+ CatalogConnectorManager newCatalogConnectorManager =new CatalogConnectorManager(catalogRegister, catalogConnectorFactory, this::getTrinoCatalogName);- catalogConnectorManager.config(config, client);+ newCatalogConnectorManager.config(config, client);+ // Publish the manager only after it has been configured successfully. Otherwise a+ // failed client initialization leaves a shared manager with a null Gravitino client,+ // causing later connector creation attempts to fail with a misleading NPE.+ catalogConnectorManager = newCatalogConnectorManager;gravitinoSystemTableFactory = new GravitinoSystemTableFactory(catalogConnectorManager);}@@ -243,6 +247,9 @@ public class GravitinoConnectorFactory implements ConnectorFactory {@VisibleForTestingstatic boolean isSecuritySensitivePropertyName(String propertyName) {+ if (propertyName.startsWith(GravitinoConfig.GRAVITINO_DYNAMIC_CATALOG_ENV_PREFIX)) {+ return false;+ }String normalizedPropertyName = propertyName.toLowerCase(Locale.ROOT).replaceAll("[._-]", "");return SECURITY_SENSITIVE_PROPERTY_SUFFIXES.stream().anyMatch(normalizedPropertyName::endsWith);}diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorPluginManager.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorPluginManager.javaindex 192f272d55..daaa73bfbe 100644--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorPluginManager.java+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorPluginManager.java@@ -52,6 +52,16 @@ public class GravitinoConnectorPluginManager {private static final String PLUGIN_NAME_PREFIX = "gravitino-";private static final String PLUGIN_CLASSLOADER_CLASS_NAME = "io.trino.server.PluginClassLoader";+ static final List<String> PARENT_FIRST_PACKAGES =+ List.of(+ "io.trino.spi.",+ "com.fasterxml.jackson.annotation.",+ "io.airlift.slice.",+ "io.airlift.log.",+ "org.openjdk.jol.",+ "io.opentelemetry.api.",+ "io.opentelemetry.context.",+ "io.starburst.ai.model.");private static volatile GravitinoConnectorPluginManager instance;@@ -174,18 +184,7 @@ public class GravitinoConnectorPluginManager {String classLoaderName = PLUGIN_NAME_PREFIX + pluginName;// Load Trino SPI package and other dependencies refer to io.trino.server.PluginClassLoaderObject pluginClassLoader =- constructor.newInstance(- classLoaderName,- urls,- appClassloader,- List.of(- "io.trino.spi.",- "com.fasterxml.jackson.annotation.",- "io.airlift.slice.",- "io.airlift.log.",- "org.openjdk.jol.",- "io.opentelemetry.api.",- "io.opentelemetry.context."));+ constructor.newInstance(classLoaderName, urls, appClassloader, PARENT_FIRST_PACKAGES);ServiceLoader<Plugin> serviceLoader =ServiceLoader.load(Plugin.class, (ClassLoader) pluginClassLoader);diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.javaindex 045c5d80fb..4c93045330 100644--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java@@ -43,6 +43,8 @@ import org.apache.gravitino.client.GravitinoMetalake;import org.apache.gravitino.exceptions.NoSuchMetalakeException;import org.apache.gravitino.trino.connector.GravitinoConfig;import org.apache.gravitino.trino.connector.GravitinoErrorCode;+import org.apache.gravitino.trino.connector.catalog.iceberg.IcebergConnectorAdapter;+import org.apache.gravitino.trino.connector.catalog.iceberg.IcebergRestUriDiscovery;import org.apache.gravitino.trino.connector.metadata.GravitinoCatalog;import org.apache.gravitino.trino.connector.security.GravitinoAuthProvider;@@ -73,6 +75,7 @@ public class CatalogConnectorManager {private String targetMetalake;private final Map<String, GravitinoMetalake> metalakes = new ConcurrentHashMap<>();+ private final IcebergRestUriDiscovery icebergRestUriDiscovery = new IcebergRestUriDiscovery();private GravitinoAdminClient gravitinoClient;private GravitinoConfig config;@@ -157,6 +160,9 @@ public class CatalogConnectorManager {this.config = config;this.metadataUpdateIntervalSecond = Integer.parseInt(config.getMetadataRefreshIntervalSecond());this.targetMetalake = config.getMetalake();+ // Parsed eagerly so a misconfigured value fails startup instead of surfacing every poll as an+ // unrelated "Load Metalake failed" error.+ config.isIcebergRestRoutingEnabled();}/**@@ -197,6 +203,7 @@ public class CatalogConnectorManager {try {GravitinoMetalake metalake = metalakes.get(usedMetalake);LOG.debug("Load metalake: %s", usedMetalake);+ icebergRestUriDiscovery.refresh(usedMetalake, config, gravitinoClient);loadCatalogs(metalake);} catch (Exception e) {LOG.error(e, "Load Metalake %s failed.", usedMetalake);@@ -291,7 +298,12 @@ public class CatalogConnectorManager {private void reloadCatalog(GravitinoCatalog catalog) {String catalogFullName = getTrinoCatalogName(catalog);GravitinoCatalog oldCatalog = catalogConnectors.get(catalogFullName).getCatalog();- if (catalog.getLastModifiedTime() <= oldCatalog.getLastModifiedTime()) {+ // The discovered Iceberg REST endpoint is embedded into the catalog independently of+ // Gravitino's own lastModifiedTime, so it is checked as a separate reload trigger.+ boolean icebergRestUriChanged =+ IcebergConnectorAdapter.hasDiscoveredIcebergRestUriChanged(catalog, oldCatalog, config);+ if (catalog.getLastModifiedTime() <= oldCatalog.getLastModifiedTime()+ && !icebergRestUriChanged) {return;}diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.javaindex fab43b70ed..db06918904 100644--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java@@ -36,9 +36,12 @@ import java.sql.Statement;import java.util.Map;import java.util.Properties;import java.util.Set;+import java.util.regex.Matcher;+import java.util.regex.Pattern;import org.apache.commons.lang3.StringUtils;import org.apache.gravitino.trino.connector.GravitinoConfig;import org.apache.gravitino.trino.connector.GravitinoErrorCode;+import org.apache.gravitino.trino.connector.catalog.iceberg.IcebergConnectorAdapter;import org.apache.gravitino.trino.connector.metadata.GravitinoCatalog;/**@@ -57,6 +60,24 @@ public class CatalogRegister {private static final String SSL_VERIFICATION_NONE = "NONE";private static final Set<String> SSL_VERIFICATION_MODES =ImmutableSet.of(SSL_VERIFICATION_FULL, SSL_VERIFICATION_CA, SSL_VERIFICATION_NONE);+ // Best-effort keyword match on the property key; it cannot catch a sensitive value under a name+ // that doesn't contain one of these words. Kept as a single constant so the SQL and JSON+ // variants below can't drift apart when a keyword is added.+ private static final String SECRET_KEY_NAME_PATTERN =+ "credential|token|secret|password|passphrase|passcode";++ private static final Pattern SECRET_PROPERTY_PATTERN =+ Pattern.compile(+ "\"([^\"]*(?:" + SECRET_KEY_NAME_PATTERN + ")[^\"]*)\"\\s*=\\s*'([^']*)'",+ Pattern.CASE_INSENSITIVE);++ // Matches "key":"value" style secret assignments inside the serialized GravitinoCatalog JSON+ // that GRAVITINO_DYNAMIC_CONNECTOR_CATALOG_CONFIG carries (e.g. "jdbc-password":"..." or+ // "s3-secret-key":"..."), which SECRET_PROPERTY_PATTERN's SQL-assignment shape does not match.+ private static final Pattern SECRET_JSON_PROPERTY_PATTERN =+ Pattern.compile(+ "\"([^\"]*(?:" + SECRET_KEY_NAME_PATTERN + ")[^\"]*)\"\\s*:\\s*\"([^\"]*)\"",+ Pattern.CASE_INSENSITIVE);private Connection connection;private boolean isStarted = false;@@ -301,17 +322,63 @@ public class CatalogRegister {}}- private String generateCreateCatalogCommand(String name, GravitinoCatalog gravitinoCatalog)+ @VisibleForTesting+ void setConfigForTesting(GravitinoConfig config) {+ this.config = config;+ }++ @VisibleForTesting+ String generateCreateCatalogCommand(String name, GravitinoCatalog gravitinoCatalog)throws Exception {+ GravitinoCatalog catalogToRegister =+ IcebergConnectorAdapter.embedDiscoveredIcebergRestUri(gravitinoCatalog, config);return String.format("CREATE CATALOG %s USING gravitino WITH ( \"%s\" = 'true', \"%s\" = '%s', %s)",name,GRAVITINO_DYNAMIC_CONNECTOR,GRAVITINO_DYNAMIC_CONNECTOR_CATALOG_CONFIG,- GravitinoCatalog.toJson(gravitinoCatalog),+ GravitinoCatalog.toJson(catalogToRegister),config.toCatalogConfig());}+ @VisibleForTesting+ static String redactSecrets(String createCatalogCommand) {+ return redactJsonSecrets(redactSqlSecrets(createCatalogCommand));+ }++ // Some JDBC drivers echo the failing statement back in the exception message, which for a+ // failed CREATE CATALOG would otherwise carry its embedded credentials into every caller and+ // log line downstream. The original exception is deliberately not kept as the cause, since a+ // logged stack trace prints causes' messages too and would defeat the redaction.+ private static SQLException redactedSqlException(SQLException e) {+ String message = e.getMessage() == null ? null : redactSecrets(e.getMessage());+ SQLException redacted = new SQLException(message, e.getSQLState(), e.getErrorCode());+ redacted.setStackTrace(e.getStackTrace());+ return redacted;+ }++ private static String redactSqlSecrets(String createCatalogCommand) {+ Matcher matcher = SECRET_PROPERTY_PATTERN.matcher(createCatalogCommand);+ StringBuffer redacted = new StringBuffer();+ while (matcher.find()) {+ matcher.appendReplacement(+ redacted, Matcher.quoteReplacement("\"" + matcher.group(1) + "\"='***'"));+ }+ matcher.appendTail(redacted);+ return redacted.toString();+ }++ private static String redactJsonSecrets(String createCatalogCommand) {+ Matcher matcher = SECRET_JSON_PROPERTY_PATTERN.matcher(createCatalogCommand);+ StringBuffer redacted = new StringBuffer();+ while (matcher.find()) {+ matcher.appendReplacement(+ redacted, Matcher.quoteReplacement("\"" + matcher.group(1) + "\":\"***\""));+ }+ matcher.appendTail(redacted);+ return redacted.toString();+ }+private String generateDropCatalogCommand(String name) {return String.format("DROP CATALOG %s", name);}@@ -348,9 +415,13 @@ public class CatalogRegister {}String createCatalogCommand = generateCreateCatalogCommand(name, catalog);executeSql(createCatalogCommand);- LOG.info("Register catalog %s successfully: %s", name, createCatalogCommand);+ LOG.info("Register catalog %s successfully: %s", name, redactSecrets(createCatalogCommand));} catch (SQLException e) {- throw new TrinoException(GravitinoErrorCode.GRAVITINO_RUNTIME_ERROR, e.getMessage(), e);+ // Some JDBC drivers echo the failing statement back in their error message; redact it the+ // same way the retry-loop log does, so a syntax or duplicate-catalog error on a CREATE+ // CATALOG statement never surfaces its embedded credentials to the caller.+ String message = e.getMessage() == null ? e.toString() : redactSecrets(e.getMessage());+ throw new TrinoException(GravitinoErrorCode.GRAVITINO_RUNTIME_ERROR, message, e);} catch (Exception e) {String message = String.format("Failed to register catalog %s", name);LOG.error(e, message);@@ -406,17 +477,17 @@ public class CatalogRegister {statement.execute(sql);return;} catch (SQLException e) {- throw e;+ throw redactedSqlException(e);} catch (Exception e) {failedException = e;- LOG.warn(e, "Failed to execute command: %s", sql);+ LOG.warn(e, "Failed to execute command: %s", redactSecrets(sql));Thread.sleep(EXECUTE_QUERY_BACKOFF_TIME_SECOND * 1000);}}throw failedException;} catch (Exception e) {throw new TrinoException(- GravitinoErrorCode.GRAVITINO_RUNTIME_ERROR, "Failed to execute query: " + sql, e);+ GravitinoErrorCode.GRAVITINO_RUNTIME_ERROR, "Failed to execute query", e);}}diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/DefaultCatalogConnectorFactory.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/DefaultCatalogConnectorFactory.javaindex 890293384a..319fe1a9f3 100644--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/DefaultCatalogConnectorFactory.java+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/DefaultCatalogConnectorFactory.java@@ -71,7 +71,7 @@ public class DefaultCatalogConnectorFactory implements CatalogConnectorFactory {new CatalogConnectorContext.Builder(new MemoryConnectorAdapter()));catalogBuilders.put(ICEBERG_CONNECTOR_PROVIDER_NAME,- new CatalogConnectorContext.Builder(new IcebergConnectorAdapter()));+ new CatalogConnectorContext.Builder(new IcebergConnectorAdapter(config)));catalogBuilders.put(MYSQL_CONNECTOR_PROVIDER_NAME,new CatalogConnectorContext.Builder(new MySQLConnectorAdapter()));diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergCatalogPropertyConverter.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergCatalogPropertyConverter.javaindex d6459b5988..4c1d2f3e66 100644--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergCatalogPropertyConverter.java+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergCatalogPropertyConverter.java@@ -22,16 +22,25 @@ package org.apache.gravitino.trino.connector.catalog.iceberg;import com.google.common.collect.Sets;import io.trino.spi.TrinoException;import java.util.HashMap;+import java.util.List;+import java.util.Locale;import java.util.Map;import java.util.Set;+import org.apache.commons.lang3.StringUtils;import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergPropertiesUtils;import org.apache.gravitino.credential.AzureAccountKeyCredential;import org.apache.gravitino.credential.Credential;+import org.apache.gravitino.credential.CredentialConstants;import org.apache.gravitino.credential.JdbcCredential;import org.apache.gravitino.credential.S3SecretKeyCredential;+import org.apache.gravitino.storage.S3Properties;+import org.apache.gravitino.trino.connector.GravitinoConfig;import org.apache.gravitino.trino.connector.GravitinoErrorCode;import org.apache.gravitino.trino.connector.catalog.CatalogPropertyConverter;+import org.apache.gravitino.trino.connector.metadata.GravitinoCatalog;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;/*** A property converter for Iceberg catalogs that handles the conversion between Trino and Gravitino@@ -40,12 +49,38 @@ import org.apache.gravitino.trino.connector.catalog.CatalogPropertyConverter;*/public class IcebergCatalogPropertyConverter extends CatalogPropertyConverter {+ private static final Logger LOG = LoggerFactory.getLogger(IcebergCatalogPropertyConverter.class);+private static final Set<String> JDBC_BACKEND_REQUIRED_PROPERTIES = Set.of("jdbc-driver", "uri");private static final Set<String> HIVE_BACKEND_REQUIRED_PROPERTIES = Set.of("uri");private static final Set<String> REST_BACKEND_REQUIRED_PROPERTIES = Set.of("uri");+ private static final String TRINO_ICEBERG_CATALOG_TYPE = "iceberg.catalog.type";+ private static final String TRINO_ICEBERG_CATALOG_TYPE_REST = "rest";+ private static final String TRINO_ICEBERG_REST_URI = "iceberg.rest-catalog.uri";+ private static final String TRINO_ICEBERG_REST_PREFIX = "iceberg.rest-catalog.prefix";+ private static final String TRINO_ICEBERG_REST_WAREHOUSE = "iceberg.rest-catalog.warehouse";+ private static final String TRINO_ICEBERG_REST_VENDED_CREDENTIALS =+ "iceberg.rest-catalog.vended-credentials-enabled";+ private static final String TRINO_ICEBERG_REST_SESSION = "iceberg.rest-catalog.session";+ private static final String TRINO_FS_HADOOP_ENABLED = "fs.hadoop.enabled";+ private static final String TRINO_FS_NATIVE_S3_ENABLED = "fs.native-s3.enabled";+ private static final String TRINO_FS_NATIVE_GCS_ENABLED = "fs.native-gcs.enabled";+ private static final String TRINO_FS_NATIVE_AZURE_ENABLED = "fs.native-azure.enabled";+ private static final String TRINO_S3_REGION = "s3.region";+ private static final String TRINO_S3_ENDPOINT = "s3.endpoint";+ private static final String TRINO_S3_PATH_STYLE_ACCESS = "s3.path-style-access";++ /** Routing keys the connector always derives itself; they cannot be overridden. */+ private static final List<String> RESERVED_REST_PROPERTIES =+ List.of(+ TRINO_ICEBERG_CATALOG_TYPE,+ TRINO_ICEBERG_REST_URI,+ TRINO_ICEBERG_REST_WAREHOUSE,+ TRINO_ICEBERG_REST_PREFIX);+/*** Injects credentials from credential vending into the Iceberg catalog config. Applies JDBC* user/password for the JDBC backend and S3 credentials for S3-backed storage.@@ -80,7 +115,9 @@ public class IcebergCatalogPropertyConverter extends CatalogPropertyConverter {throw new TrinoException(GravitinoErrorCode.GRAVITINO_MISSING_REQUIRED_PROPERTY,"Missing required property 'catalog-backend'");- switch (backend) {+ // Gravitino accepts the backend as an enum value, and its own consumers upper-case it before+ // resolving, so the value reaching here may be in any case.+ switch (backend.toLowerCase(Locale.ROOT)) {case "hive":stringStringMap = buildHiveBackendProperties(properties);break;@@ -94,13 +131,72 @@ public class IcebergCatalogPropertyConverter extends CatalogPropertyConverter {throw new UnsupportedOperationException("Unsupported backend type: " + backend);}Map<String, String> config = new HashMap<>();- // The order of put operations determines the priority of parameters.+ // Later put/putAll calls override earlier ones for the same key; this is call-order+ // precedence, unrelated to HashMap's (unspecified) iteration order.config.putAll(super.gravitinoToEngineProperties(properties));config.putAll(stringStringMap);config.put("fs.hadoop.enabled", "true");return config;}+ /**+ * Builds the Trino Iceberg connector config that reaches this catalog through the Gravitino+ * Iceberg REST server, regardless of the catalog backend Gravitino uses to store its metadata.+ *+ * <p>This is the only path on which <em>temporary</em> credentials work — {@code s3-token} and+ * its GCS and ADLS counterparts. The Iceberg REST protocol issues a fresh one per table access,+ * while Trino's jdbc and hive_metastore Iceberg catalog types have nowhere to put the session+ * token of an STS credential. Static-key credentials are unaffected: they are still injected on+ * the backend path by {@link #applyCredentials}.+ *+ * @param catalog the Gravitino catalog to load+ * @param gravitinoConfig the connector configuration holding the Iceberg REST catalog's+ * authentication and other pass-through settings+ * @param restUri the Iceberg REST server endpoint to route through, resolved by the caller+ * @return the Trino Iceberg connector config+ * @throws TrinoException if {@code restUri} is blank+ */+ public Map<String, String> buildIcebergRestProperties(+ GravitinoCatalog catalog, GravitinoConfig gravitinoConfig, String restUri) {+ if (StringUtils.isBlank(restUri)) {+ // The caller only reaches this method once it has already confirmed a non-blank URI, so+ // this is defensive: it can only fire if that URI disappeared between the two calls.+ throw new TrinoException(+ GravitinoErrorCode.GRAVITINO_MISSING_CONFIG,+ "No Iceberg REST server endpoint is available for metalake '"+ + catalog.getMetalake()+ + "'. Set 'gravitino.iceberg.rest-uri' to override the address the Gravitino "+ + "server reports.");+ }++ Map<String, String> config = new HashMap<>();+ // Later put/putAll calls override earlier ones for the same key; this is call-order+ // precedence, unrelated to HashMap's (unspecified) iteration order.+ config.putAll(buildStorageProperties(catalog.getProperties()));+ config.put(TRINO_ICEBERG_REST_VENDED_CREDENTIALS, "true");+ if (gravitinoConfig.isForwardUser()) {+ config.put(TRINO_ICEBERG_REST_SESSION, "USER");+ }+ // The catalog's own trino.bypass properties override the defaults above, so that a Trino+ // release renaming one of them can be worked around without a connector change.+ config.putAll(super.gravitinoToEngineProperties(catalog.getProperties()));+ // The IRC's own authentication is a cluster-level operational setting, so it takes precedence+ // over anything set on a single catalog.+ config.putAll(gravitinoConfig.getIcebergRestCatalogConfig());++ warnOnReservedOverrides(catalog, config);++ config.put(TRINO_ICEBERG_CATALOG_TYPE, TRINO_ICEBERG_CATALOG_TYPE_REST);+ config.put(TRINO_ICEBERG_REST_URI, restUri);+ // The Iceberg client selects the catalog twice over: `warehouse` is the query parameter of the+ // initial GET /v1/config that discovers the catalog, and `prefix` is the path segment of every+ // request after it. Setting only the latter leaves the config call without a catalog name.+ // The server echoes `prefix` back as a config default, so setting it here is belt-and-braces.+ config.put(TRINO_ICEBERG_REST_WAREHOUSE, catalog.getName());+ config.put(TRINO_ICEBERG_REST_PREFIX, catalog.getName());+ return config;+ }+private Map<String, String> buildHiveBackendProperties(Map<String, String> properties) {Set<String> missingProperty =Sets.difference(HIVE_BACKEND_REQUIRED_PROPERTIES, properties.keySet());@@ -152,6 +248,102 @@ public class IcebergCatalogPropertyConverter extends CatalogPropertyConverter {return jdbcProperties;}+ // Called before the reserved keys (type/uri/warehouse/prefix) are put into `config` below, so+ // any value already present at this point came from the catalog's own properties or bypass+ // config and is about to be silently overwritten; this logs that so it isn't a silent no-op.+ private void warnOnReservedOverrides(GravitinoCatalog catalog, Map<String, String> config) {+ for (String reserved : RESERVED_REST_PROPERTIES) {+ if (config.containsKey(reserved)) {+ LOG.info(+ "Property '{}' set on catalog '{}' is ignored; the connector always derives it when "+ + "routing through the Iceberg REST server.",+ reserved,+ catalog.getName());+ }+ }+ }++ /**+ * Derives the Trino file system config from the catalog's warehouse location. Vended credentials+ * are only consumed by Trino's native file systems, so the native implementation matching the+ * warehouse scheme has to be enabled.+ */+ private Map<String, String> buildStorageProperties(Map<String, String> properties) {+ Map<String, String> storageProperties = new HashMap<>();+ // Always available as the fallback; where a native file system is also enabled below, that one+ // takes precedence for its own scheme.+ storageProperties.put(TRINO_FS_HADOOP_ENABLED, "true");++ String warehouse = properties.get(IcebergConstants.WAREHOUSE);+ if (StringUtils.isBlank(warehouse)) {+ return storageProperties;+ }++ String scheme = StringUtils.substringBefore(warehouse, "://").toLowerCase(Locale.ROOT);+ switch (scheme) {+ case "s3":+ case "s3a":+ case "s3n":+ storageProperties.put(TRINO_FS_NATIVE_S3_ENABLED, "true");+ copyProperty(+ properties, S3Properties.GRAVITINO_S3_REGION, storageProperties, TRINO_S3_REGION);+ copyProperty(+ properties, S3Properties.GRAVITINO_S3_ENDPOINT, storageProperties, TRINO_S3_ENDPOINT);+ // Required by S3-compatible stores such as MinIO and Ceph, which a custom endpoint implies.+ copyProperty(+ properties,+ S3Properties.GRAVITINO_S3_PATH_STYLE_ACCESS,+ storageProperties,+ TRINO_S3_PATH_STYLE_ACCESS);+ break;+ case "gs":+ storageProperties.put(TRINO_FS_NATIVE_GCS_ENABLED, "true");+ break;+ case "abfs":+ case "abfss":+ case "wasb":+ case "wasbs":+ storageProperties.put(TRINO_FS_NATIVE_AZURE_ENABLED, "true");+ break;+ default:+ warnOnSchemeWithoutNativeFileSystem(properties, warehouse, scheme);+ break;+ }+ return storageProperties;+ }++ /**+ * Warns when a warehouse scheme has no Trino native file system but the catalog vends+ * credentials. The Hadoop file system cannot consume a vended credential, so table access would+ * fail at read time with a storage authentication error far from its cause.+ */+ private void warnOnSchemeWithoutNativeFileSystem(+ Map<String, String> properties, String warehouse, String scheme) {+ // hdfs and file legitimately run on the Hadoop file system, and a warehouse without a scheme+ // is a plain path. None of them vend credentials.+ if (!warehouse.contains("://") || "hdfs".equals(scheme) || "file".equals(scheme)) {+ return;+ }+ if (StringUtils.isBlank(properties.get(CredentialConstants.CREDENTIAL_PROVIDERS))) {+ return;+ }+ LOG.warn(+ "Warehouse scheme '{}' has no Trino native file system, so the credentials vended by "+ + "'{}' cannot be applied. Table access falls back to the Hadoop file system and may "+ + "fail to authenticate. Schemes with a native file system: s3/s3a/s3n, gs, "+ + "abfs/abfss/wasb/wasbs.",+ scheme,+ properties.get(CredentialConstants.CREDENTIAL_PROVIDERS));+ }++ private void copyProperty(+ Map<String, String> source, String sourceKey, Map<String, String> target, String targetKey) {+ String value = source.get(sourceKey);+ if (StringUtils.isNotBlank(value)) {+ target.put(targetKey, value);+ }+ }+private Map<String, String> buildRestBackendProperties(Map<String, String> properties) {Set<String> missingProperty =Sets.difference(REST_BACKEND_REQUIRED_PROPERTIES, properties.keySet());@@ -162,8 +354,8 @@ public class IcebergCatalogPropertyConverter extends CatalogPropertyConverter {}Map<String, String> restProperties = new HashMap<>();- restProperties.put("iceberg.catalog.type", "rest");- restProperties.put("iceberg.rest-catalog.uri", properties.get(IcebergConstants.URI));+ restProperties.put(TRINO_ICEBERG_CATALOG_TYPE, TRINO_ICEBERG_CATALOG_TYPE_REST);+ restProperties.put(TRINO_ICEBERG_REST_URI, properties.get(IcebergConstants.URI));if (properties.containsKey(IcebergConstants.WAREHOUSE)) {restProperties.put("iceberg.rest-catalog.warehouse", properties.get(IcebergConstants.WAREHOUSE));diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergConnectorAdapter.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergConnectorAdapter.javaindex 8900775fb7..29536a8d0e 100644--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergConnectorAdapter.java+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergConnectorAdapter.java@@ -20,15 +20,22 @@ package org.apache.gravitino.trino.connector.catalog.iceberg;import static java.util.Collections.emptyList;+import com.google.common.collect.ImmutableMap;+import io.trino.spi.TrinoException;import io.trino.spi.session.PropertyMetadata;import java.util.HashMap;import java.util.List;import java.util.Map;-import org.apache.gravitino.catalog.property.PropertyConverter;+import org.apache.commons.lang3.StringUtils;+import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;import org.apache.gravitino.credential.Credential;+import org.apache.gravitino.trino.connector.GravitinoConfig;+import org.apache.gravitino.trino.connector.GravitinoErrorCode;import org.apache.gravitino.trino.connector.catalog.CatalogConnectorAdapter;import org.apache.gravitino.trino.connector.catalog.CatalogConnectorMetadataAdapter;import org.apache.gravitino.trino.connector.metadata.GravitinoCatalog;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;/*** Transforming Apache Iceberg connector configuration and components into Apache Gravitino@@ -36,26 +43,148 @@ import org.apache.gravitino.trino.connector.metadata.GravitinoCatalog;*/public class IcebergConnectorAdapter implements CatalogConnectorAdapter {+ private static final Logger LOG = LoggerFactory.getLogger(IcebergConnectorAdapter.class);+private static final String CONNECTOR_ICEBERG = "iceberg";+ private static final String REST_CATALOG_BACKEND = "rest";+ private static final String ICEBERG_PROVIDER = "lakehouse-iceberg";++ /**+ * Synthetic catalog property carrying the Iceberg REST server endpoint the coordinator discovered+ * for this catalog's metalake. {@link GravitinoConfig}'s own discovered-endpoint map is populated+ * only on the coordinator (the periodic discovery poll never runs on a worker), so it cannot be+ * read directly when building a catalog's internal connector config: every node needs the same+ * routing decision for the same catalog. Embedding the resolved endpoint into the catalog itself,+ * at registration time, means it travels to every node through the {@code CREATE CATALOG}+ * statement Trino replicates cluster-wide, the same way any other catalog property does.+ */+ static final String DISCOVERED_ICEBERG_REST_URI_PROPERTY = "__gravitino.iceberg.rest-uri";+private final IcebergPropertyMeta propertyMetadata;- private final PropertyConverter catalogConverter;+ private final IcebergCatalogPropertyConverter catalogConverter;+ private final GravitinoConfig config;/*** Constructs a new IcebergConnectorAdapter. Initializes the property metadata and catalog* converter for handling Iceberg-specific configurations.+ *+ * @param config the Gravitino connector configuration*/- public IcebergConnectorAdapter() {+ public IcebergConnectorAdapter(GravitinoConfig config) {this.propertyMetadata = new IcebergPropertyMeta();this.catalogConverter = new IcebergCatalogPropertyConverter();+ this.config = config;}@Overridepublic Map<String, String> buildInternalConnectorConfig(GravitinoCatalog catalog, Credential[] credentials) throws Exception {- Map<String, String> config =+ // The catalog backend describes how Gravitino stores the metadata; it does not decide how+ // Trino reaches the data. Whenever an Iceberg REST server endpoint is available for this+ // catalog's metalake, the catalog is loaded through it, the only path that supports temporary+ // credentials. A catalog that already has a REST backend keeps pointing at its own configured+ // endpoint. If no endpoint is available, routing is required unless the compatibility switch+ // explicitly enables the legacy catalog-backend translation.+ //+ // The manual override is plain local config, so it is valid on every node as-is. The+ // discovered endpoint is coordinator-only knowledge, so it is read from the catalog's own+ // properties, where the coordinator embeds it at registration time (see+ // embedDiscoveredIcebergRestUri), rather than from GravitinoConfig directly.+ String restUri = config.getManualIcebergRestUri(catalog.getMetalake());+ if (StringUtils.isBlank(restUri)) {+ restUri = catalog.getProperty(DISCOVERED_ICEBERG_REST_URI_PROPERTY, "");+ }+ if (StringUtils.isNotBlank(restUri)+ && !REST_CATALOG_BACKEND.equalsIgnoreCase(+ catalog.getProperty(IcebergConstants.CATALOG_BACKEND, null))) {+ // `credentials` is intentionally unused here: with vended credentials enabled, Trino obtains+ // a fresh one per table access over the REST protocol, rather than the catalog-level+ // snapshot applyCredentials installs.+ LOG.debug(+ "Routing catalog '{}' through the Iceberg REST server; its {} catalog-level credential(s)"+ + " are not applied because the REST protocol vends one per table access.",+ catalog.getName(),+ credentials.length);+ return catalogConverter.buildIcebergRestProperties(catalog, config, restUri);+ }++ String catalogBackend = catalog.getProperty(IcebergConstants.CATALOG_BACKEND, null);+ if (config.isIcebergRestRoutingEnabled()+ && StringUtils.isBlank(restUri)+ && !REST_CATALOG_BACKEND.equalsIgnoreCase(catalogBackend)) {+ throw new TrinoException(+ GravitinoErrorCode.GRAVITINO_RUNTIME_ERROR,+ String.format(+ "Cannot register Iceberg catalog '%s' in metalake '%s': no Iceberg REST endpoint "+ + "is available. Configure gravitino.iceberg.rest-uri, use a Gravitino server "+ + "that supports /api/system/iceberg-rest, or set "+ + "gravitino.iceberg.rest-routing-enabled=false to use legacy backend "+ + "translation.",+ catalog.getName(), catalog.getMetalake()));+ }++ Map<String, String> connectorConfig =new HashMap<>(catalogConverter.gravitinoToEngineProperties(catalog.getProperties()));- IcebergCatalogPropertyConverter.applyCredentials(credentials, config);- return config;+ IcebergCatalogPropertyConverter.applyCredentials(credentials, connectorConfig);+ return connectorConfig;+ }++ /**+ * Returns a copy of {@code catalog} with the Iceberg REST server endpoint the coordinator+ * discovered for its metalake embedded as a synthetic property, if the catalog is a+ * lakehouse-iceberg catalog and a discovered endpoint exists. Called only on the coordinator,+ * before a catalog is registered with Trino, so that the routing decision reaches every node+ * through the {@code CREATE CATALOG} statement — see {@link+ * #DISCOVERED_ICEBERG_REST_URI_PROPERTY}.+ *+ * @param catalog the catalog about to be registered+ * @param config the connector configuration holding the discovered endpoints+ * @return {@code catalog} unchanged if it is not a lakehouse-iceberg catalog or no endpoint was+ * discovered for its metalake; otherwise a copy with the endpoint embedded+ */+ public static GravitinoCatalog embedDiscoveredIcebergRestUri(+ GravitinoCatalog catalog, GravitinoConfig config) {+ if (!ICEBERG_PROVIDER.equals(catalog.getProvider())) {+ return catalog;+ }+ String discoveredUri = config.getDiscoveredIcebergRestUri(catalog.getMetalake());+ if (StringUtils.isBlank(discoveredUri)) {+ return catalog;+ }+ Map<String, String> properties =+ ImmutableMap.<String, String>builder()+ .putAll(catalog.getProperties())+ .put(DISCOVERED_ICEBERG_REST_URI_PROPERTY, discoveredUri)+ .buildKeepingLast();+ return new GravitinoCatalog(+ catalog.getMetalake(),+ catalog.getProvider(),+ catalog.getName(),+ properties,+ catalog.getLastModifiedTime());+ }++ /**+ * Returns whether the Iceberg REST server endpoint currently discovered for {@code catalog}'s+ * metalake differs from the one embedded into {@code oldCatalog} the last time it was registered.+ * The catalog's Gravitino {@code lastModifiedTime} does not advance when only Iceberg REST+ * availability changes, so callers that use it to decide whether to reload a catalog need this as+ * a separate signal.+ *+ * @param catalog the freshly loaded catalog+ * @param oldCatalog the previously registered version of the same catalog+ * @param config the connector configuration holding the discovered endpoints+ * @return {@code true} if {@code catalog} is a lakehouse-iceberg catalog and the discovered+ * endpoint for its metalake differs from what {@code oldCatalog} was registered with+ */+ public static boolean hasDiscoveredIcebergRestUriChanged(+ GravitinoCatalog catalog, GravitinoCatalog oldCatalog, GravitinoConfig config) {+ if (!ICEBERG_PROVIDER.equals(catalog.getProvider())) {+ return false;+ }+ String currentUri = config.getDiscoveredIcebergRestUri(catalog.getMetalake());+ String previousUri = oldCatalog.getProperty(DISCOVERED_ICEBERG_REST_URI_PROPERTY, "");+ return !currentUri.equals(previousUri);}@Overridediff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergRestUriDiscovery.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergRestUriDiscovery.javanew file mode 100644index 0000000000..69e3ee8bf0--- /dev/null+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergRestUriDiscovery.java@@ -0,0 +1,78 @@+/*+ * 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.trino.connector.catalog.iceberg;++import io.airlift.log.Logger;+import java.util.Set;+import java.util.concurrent.ConcurrentHashMap;+import org.apache.commons.lang3.StringUtils;+import org.apache.gravitino.client.GravitinoAdminClient;+import org.apache.gravitino.trino.connector.GravitinoConfig;++/**+ * Periodically asks the Gravitino server whether it has an Iceberg REST server running for a+ * metalake, and caches the answer on the shared {@link GravitinoConfig} for {@link+ * IcebergConnectorAdapter} to read on the next catalog load. Owns the Iceberg-specific decision of+ * whether discovery is needed at all (routing enabled, no manual override configured) so that the+ * generic catalog connector manager only needs to call {@link #refresh} once per poll.+ */+public class IcebergRestUriDiscovery {++ private static final Logger LOG = Logger.get(IcebergRestUriDiscovery.class);++ // Tracks which metalakes' discovery is currently failing, so a failure is logged at INFO only+ // on the transition out of that state rather than on every poll.+ private final Set<String> failing = ConcurrentHashMap.newKeySet();++ /**+ * Refreshes the discovered Iceberg REST server endpoint for {@code metalakeName}, if Iceberg REST+ * routing is enabled and no manual endpoint is configured for it. Failures — including talking to+ * a Gravitino server older than this endpoint — must not interrupt catalog loading, so they are+ * swallowed here; Iceberg catalogs simply keep their last known routing decision until the next+ * successful poll. A failure is logged at ERROR on every poll because routing through Iceberg+ * REST is required when enabled.+ *+ * @param metalakeName the metalake to refresh the discovered endpoint for+ * @param config the connector configuration to read routing settings from and cache the result on+ * @param client the Gravitino client to query+ */+ public void refresh(String metalakeName, GravitinoConfig config, GravitinoAdminClient client) {+ if (!config.isIcebergRestRoutingEnabled()+ || StringUtils.isNotBlank(config.getManualIcebergRestUri(metalakeName))) {+ return;+ }+ try {+ config.setDiscoveredIcebergRestUri(+ metalakeName, client.icebergRestServiceUri(metalakeName).orElse(null));+ if (failing.remove(metalakeName)) {+ LOG.info("Iceberg REST service discovery for metalake %s recovered.", metalakeName);+ }+ } catch (Exception e) {+ failing.add(metalakeName);+ LOG.error(+ e,+ "Failed to query the Iceberg REST service endpoint for metalake %s; Iceberg catalogs "+ + "without a configured REST endpoint cannot be registered until discovery "+ + "recovers. Set gravitino.iceberg.rest-uri explicitly, upgrade the Gravitino "+ + "server to one that supports discovery, or disable Iceberg REST routing with "+ + "gravitino.iceberg.rest-routing-enabled=false to use legacy backend translation.",+ metalakeName);+ }+ }+}diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.javaindex 2d486b52c0..c42b3e761d 100644--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java@@ -300,6 +300,184 @@ public class TestGravitinoConfig {assertTrue(config.isTrinoJdbcSslEnabled());}+ @Test+ public void testIcebergRestConfigDefaults() {+ GravitinoConfig config = new GravitinoConfig(ImmutableMap.of("gravitino.metalake", "user_001"));++ // Nothing configured, and nothing discovered yet.+ assertEquals("", config.getManualIcebergRestUri("user_001"));+ assertEquals("", config.getDiscoveredIcebergRestUri("user_001"));+ assertTrue(config.isIcebergRestRoutingEnabled());+ assertTrue(config.getIcebergRestCatalogConfig().isEmpty());+ }++ @Test+ public void testIcebergRestRoutingCanBeDisabled() {+ GravitinoConfig config =+ new GravitinoConfig(+ ImmutableMap.of(+ "gravitino.metalake", "user_001",+ "gravitino.iceberg.rest-routing-enabled", "false"));++ assertFalse(config.isIcebergRestRoutingEnabled());+ assertTrue(+ config.toCatalogConfig().contains("\"gravitino.iceberg.rest-routing-enabled\"='false'"));+ }++ @Test+ public void testIcebergRestRoutingRejectsInvalidBoolean() {+ GravitinoConfig config =+ new GravitinoConfig(+ ImmutableMap.of(+ "gravitino.metalake", "user_001",+ "gravitino.iceberg.rest-routing-enabled", "yes"));++ assertThrows(TrinoException.class, config::isIcebergRestRoutingEnabled);+ }++ @Test+ public void testIcebergRestConfig() {+ GravitinoConfig config =+ new GravitinoConfig(+ ImmutableMap.of(+ "gravitino.metalake", "user_001",+ "gravitino.iceberg.rest-uri", "http://127.0.0.1:9001/iceberg",+ "gravitino.iceberg.rest-catalog.security", "OAUTH2",+ "gravitino.iceberg.rest-catalog.oauth2.credential", "client_id:client_secret"));++ // The unscoped URI is honored as-is in single-metalake mode.+ assertEquals("http://127.0.0.1:9001/iceberg", config.getManualIcebergRestUri("user_001"));++ Map<String, String> restCatalogConfig = config.getIcebergRestCatalogConfig();+ assertEquals(2, restCatalogConfig.size());+ assertEquals("OAUTH2", restCatalogConfig.get("iceberg.rest-catalog.security"));+ assertEquals(+ "client_id:client_secret", restCatalogConfig.get("iceberg.rest-catalog.oauth2.credential"));+ }++ @Test+ public void testIcebergRestOAuthDefaultsToGravitinoClientOAuth() {+ GravitinoConfig config =+ new GravitinoConfig(+ ImmutableMap.<String, String>builder()+ .put("gravitino.metalake", "user_001")+ .put("gravitino.client.authType", "oauth2")+ .put("gravitino.client.oauth2.serverUri", "https://oauth.example.com/")+ .put("gravitino.client.oauth2.path", "/realms/gravitino/token")+ .put("gravitino.client.oauth2.credential", "shared-client:shared-secret")+ .put("gravitino.client.oauth2.scope", "openid")+ .build());++ Map<String, String> restCatalogConfig = config.getIcebergRestCatalogConfig();+ assertEquals("OAUTH2", restCatalogConfig.get("iceberg.rest-catalog.security"));+ assertEquals(+ "shared-client:shared-secret",+ restCatalogConfig.get("iceberg.rest-catalog.oauth2.credential"));+ assertEquals("openid", restCatalogConfig.get("iceberg.rest-catalog.oauth2.scope"));+ assertEquals(+ "https://oauth.example.com/realms/gravitino/token",+ restCatalogConfig.get("iceberg.rest-catalog.oauth2.server-uri"));+ }++ @Test+ public void testIcebergRestOAuthOverridesGravitinoClientOAuthByField() {+ GravitinoConfig config =+ new GravitinoConfig(+ ImmutableMap.<String, String>builder()+ .put("gravitino.metalake", "user_001")+ .put("gravitino.client.authType", "oauth2")+ .put("gravitino.client.oauth2.serverUri", "https://oauth.example.com")+ .put("gravitino.client.oauth2.path", "realms/gravitino/token")+ .put("gravitino.client.oauth2.credential", "shared-client:shared-secret")+ .put("gravitino.client.oauth2.scope", "openid")+ .put("gravitino.iceberg.rest-catalog.oauth2.credential", "irc-client:irc-secret")+ .put("gravitino.iceberg.rest-catalog.oauth2.scope", "irc-scope")+ .build());++ Map<String, String> restCatalogConfig = config.getIcebergRestCatalogConfig();+ assertEquals(+ "irc-client:irc-secret", restCatalogConfig.get("iceberg.rest-catalog.oauth2.credential"));+ assertEquals("irc-scope", restCatalogConfig.get("iceberg.rest-catalog.oauth2.scope"));+ assertEquals(+ "https://oauth.example.com/realms/gravitino/token",+ restCatalogConfig.get("iceberg.rest-catalog.oauth2.server-uri"));+ }++ @Test+ public void testIcebergRestConfigScopedToMetalakeInMultiMetalakeMode() {+ ImmutableMap<String, String> configMap =+ ImmutableMap.of(+ "gravitino.metalake",+ "metalake_a",+ "gravitino.use-single-metalake",+ "false",+ "gravitino.iceberg.rest-uri",+ "http://unscoped:9001/iceberg",+ "gravitino.iceberg.rest-uri.metalake_a",+ "http://metalake-a:9001/iceberg");+ GravitinoConfig config = new GravitinoConfig(configMap);++ // The scoped key wins for the metalake it names.+ assertEquals("http://metalake-a:9001/iceberg", config.getManualIcebergRestUri("metalake_a"));+ // The unscoped key is ignored in multi-metalake mode, since it would otherwise misroute every+ // metalake other than the one the Iceberg REST server actually serves.+ assertEquals("", config.getManualIcebergRestUri("metalake_b"));+ }++ @Test+ public void testDiscoveredIcebergRestUriIsPerMetalake() {+ GravitinoConfig config = new GravitinoConfig(ImmutableMap.of("gravitino.metalake", "user_001"));++ config.setDiscoveredIcebergRestUri("metalake_a", "http://irc-a:9001/iceberg");+ config.setDiscoveredIcebergRestUri("metalake_b", "http://irc-b:9001/iceberg");++ assertEquals("http://irc-a:9001/iceberg", config.getDiscoveredIcebergRestUri("metalake_a"));+ assertEquals("http://irc-b:9001/iceberg", config.getDiscoveredIcebergRestUri("metalake_b"));+ assertEquals("", config.getDiscoveredIcebergRestUri("metalake_c"));+ config.setDiscoveredIcebergRestUri("metalake_a", null);+ assertEquals("", config.getDiscoveredIcebergRestUri("metalake_a"));+ }++ @Test+ public void testToCatalogConfigWithIcebergRestProperties() {+ GravitinoConfig config =+ new GravitinoConfig(+ ImmutableMap.of(+ "gravitino.metalake", "user_001",+ "gravitino.iceberg.rest-uri", "http://127.0.0.1:9001/iceberg",+ "gravitino.iceberg.rest-catalog.security", "OAUTH2"));++ String catalogConfig = config.toCatalogConfig();+ assertTrue(+ catalogConfig.contains("\"gravitino.iceberg.rest-uri\"='http://127.0.0.1:9001/iceberg'"));+ assertTrue(catalogConfig.contains("\"gravitino.iceberg.rest-catalog.security\"='OAUTH2'"));+ }++ @Test+ public void testToCatalogConfigPropagatesSecretReferencesInsteadOfSecretValues() {+ GravitinoConfig config =+ new GravitinoConfig(+ ImmutableMap.of(+ "gravitino.metalake", "user_001",+ "gravitino.client.oauth2.credential", "client:management-secret",+ "gravitino.iceberg.rest-catalog.oauth2.credential", "client:irc-secret",+ "gravitino.dynamic-catalog.environment-variable.gravitino.client.oauth2.credential",+ "GRAVITINO_CLIENT_CREDENTIAL",+ "gravitino.dynamic-catalog.environment-variable.gravitino.iceberg.rest-catalog.oauth2.credential",+ "IRC_CLIENT_CREDENTIAL"));++ String catalogConfig = config.toCatalogConfig();++ assertFalse(catalogConfig.contains("management-secret"));+ assertFalse(catalogConfig.contains("irc-secret"));+ assertTrue(+ catalogConfig.contains(+ "\"gravitino.client.oauth2.credential\"='${ENV:GRAVITINO_CLIENT_CREDENTIAL}'"));+ assertTrue(+ catalogConfig.contains(+ "\"gravitino.iceberg.rest-catalog.oauth2.credential\"='${ENV:IRC_CLIENT_CREDENTIAL}'"));+ }+private static boolean skipCatalog(String catalogName, GravitinoConfig config) {for (Pattern pattern : config.getSkipCatalogPatterns()) {if (pattern.matcher(catalogName).matches()) {diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorFactory.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorFactory.javaindex 0b0c71c6b6..7c30ced137 100644--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorFactory.java+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorFactory.java@@ -39,6 +39,9 @@ class TestGravitinoConnectorFactory {Map.entry("hive.s3.aws-secret-key", "secret-key"),Map.entry("authentication.token", "token"),Map.entry("oauth2.credential", "credential"),+ Map.entry(+ "gravitino.dynamic-catalog.environment-variable.oauth2.credential",+ "OAUTH_CREDENTIAL"),Map.entry("tls.private_key", "private-key"),Map.entry("gravitino.uri", "uri"));diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorFactoryStart.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorFactoryStart.javaindex b104b4d509..cc189815df 100644--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorFactoryStart.java+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorFactoryStart.java@@ -20,6 +20,7 @@ package org.apache.gravitino.trino.connector;import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertNull;import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.Mockito.mock;@@ -127,6 +128,21 @@ public class TestGravitinoConnectorFactoryStart {assertTrue(factory.isCatalogConnectorManagerStartTriggered());}+ @Test+ public void testFailedClientInitializationDoesNotPublishManager() {+ CoordinatorFactory factory = new CoordinatorFactory(null);+ Map<String, String> brokenDynamicConfig = dynamicConfig();+ brokenDynamicConfig.put("gravitino.client.authType", "oauth2");++ assertThrows(+ Exception.class,+ () -> factory.create("broken_catalog", brokenDynamicConfig, mockContext()));++ assertNull(factory.getCatalogConnectorManager());+ assertNotNull(factory.create("gravitino", staticConfig(), mockContext()));+ assertTrue(factory.isCatalogConnectorManagerStartTriggered());+ }+@Testpublic void testStartIsAttemptedOnlyOnce() {CoordinatorFactory factory = newFactory();diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorPluginManager.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorPluginManager.javanew file mode 100644index 0000000000..99a6718804--- /dev/null+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorPluginManager.java@@ -0,0 +1,32 @@+/*+ * 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.trino.connector;++import static org.assertj.core.api.Assertions.assertThat;++import org.junit.jupiter.api.Test;++class TestGravitinoConnectorPluginManager {++ @Test+ void testStarburstAiModelUsesApplicationClassLoader() {+ assertThat(GravitinoConnectorPluginManager.PARENT_FIRST_PACKAGES)+ .contains("io.starburst.ai.model.");+ }+}diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorManager.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorManager.javaindex 781cf6755c..33a8047a67 100644--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorManager.java+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorManager.java@@ -25,14 +25,20 @@ import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.any;import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.times;+import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;import com.google.common.collect.ImmutableMap;import io.trino.spi.TrinoException;import io.trino.spi.connector.ConnectorContext;import java.util.Map;+import java.util.Optional;import org.apache.gravitino.Catalog;import org.apache.gravitino.client.GravitinoAdminClient;+import org.apache.gravitino.client.GravitinoMetalake;+import org.apache.gravitino.exceptions.RESTException;import org.apache.gravitino.secret.SupportsSecrets;import org.apache.gravitino.trino.connector.GravitinoConfig;import org.apache.gravitino.trino.connector.GravitinoErrorCode;@@ -143,6 +149,147 @@ public class TestCatalogConnectorManager {assertFalse(manager.skipCatalog("b2"));}+ @Test+ public void testRefreshIcebergRestUriCachesDiscoveredUri() throws Exception {+ GravitinoAdminClient client = mock(GravitinoAdminClient.class);+ CatalogRegister catalogRegister = mock(CatalogRegister.class);+ when(catalogRegister.isTrinoStarted()).thenReturn(true);+ when(client.loadMetalake("test")).thenReturn(mock(GravitinoMetalake.class));+ when(client.icebergRestServiceUri("test"))+ .thenReturn(Optional.of("http://irc-host:9001/iceberg"));++ CatalogConnectorManager manager =+ new CatalogConnectorManager(catalogRegister, createCatalogConnectorFactory(), null);+ GravitinoConfig config =+ new GravitinoConfig(+ ImmutableMap.of(+ "gravitino.uri", "http://127.0.0.1:8090",+ "gravitino.metalake", "test",+ "gravitino.use-single-metalake", "true"));+ manager.config(config, client);++ manager.loadMetalakeSync();++ assertEquals("http://irc-host:9001/iceberg", config.getDiscoveredIcebergRestUri("test"));+ }++ @Test+ public void testRefreshIcebergRestUriSwallowsFailureAndKeepsCatalogLoadingGoing()+ throws Exception {+ GravitinoAdminClient client = mock(GravitinoAdminClient.class);+ CatalogRegister catalogRegister = mock(CatalogRegister.class);+ when(catalogRegister.isTrinoStarted()).thenReturn(true);+ when(client.loadMetalake("test")).thenReturn(mock(GravitinoMetalake.class));+ when(client.icebergRestServiceUri("test"))+ .thenThrow(new RESTException("simulated: endpoint not found on an older server"));++ CatalogConnectorManager manager =+ new CatalogConnectorManager(catalogRegister, createCatalogConnectorFactory(), null);+ GravitinoConfig config =+ new GravitinoConfig(+ ImmutableMap.of(+ "gravitino.uri", "http://127.0.0.1:8090",+ "gravitino.metalake", "test",+ "gravitino.use-single-metalake", "true"));+ manager.config(config, client);++ // A discovery failure must not abort the metalake load (which loads catalogs), and must+ // leave the discovered URI at its previous value rather than throwing out of loadMetalake.+ assertDoesNotThrow(manager::loadMetalakeSync);+ assertEquals("", config.getDiscoveredIcebergRestUri("test"));+ }++ @Test+ public void testConfigRejectsInvalidIcebergRestRoutingEnabledAtStartup() throws Exception {+ GravitinoAdminClient client = mock(GravitinoAdminClient.class);+ CatalogRegister catalogRegister = mock(CatalogRegister.class);++ CatalogConnectorManager manager =+ new CatalogConnectorManager(catalogRegister, createCatalogConnectorFactory(), null);+ GravitinoConfig config =+ new GravitinoConfig(+ ImmutableMap.of(+ "gravitino.uri", "http://127.0.0.1:8090",+ "gravitino.metalake", "test",+ "gravitino.use-single-metalake", "true",+ "gravitino.iceberg.rest-routing-enabled", "yes"));++ assertThrows(TrinoException.class, () -> manager.config(config, client));+ }++ @Test+ public void testIcebergRestRoutingDisabledSkipsDiscovery() throws Exception {+ GravitinoAdminClient client = mock(GravitinoAdminClient.class);+ CatalogRegister catalogRegister = mock(CatalogRegister.class);+ when(catalogRegister.isTrinoStarted()).thenReturn(true);+ when(client.loadMetalake("test")).thenReturn(mock(GravitinoMetalake.class));++ CatalogConnectorManager manager =+ new CatalogConnectorManager(catalogRegister, createCatalogConnectorFactory(), null);+ GravitinoConfig config =+ new GravitinoConfig(+ ImmutableMap.of(+ "gravitino.uri", "http://127.0.0.1:8090",+ "gravitino.metalake", "test",+ "gravitino.use-single-metalake", "true",+ "gravitino.iceberg.rest-routing-enabled", "false"));+ manager.config(config, client);++ manager.loadMetalakeSync();++ verify(client, never()).icebergRestServiceUri("test");+ }++ @Test+ public void testConfiguredIcebergRestUriSkipsDiscovery() throws Exception {+ GravitinoAdminClient client = mock(GravitinoAdminClient.class);+ CatalogRegister catalogRegister = mock(CatalogRegister.class);+ when(catalogRegister.isTrinoStarted()).thenReturn(true);+ when(client.loadMetalake("test")).thenReturn(mock(GravitinoMetalake.class));++ CatalogConnectorManager manager =+ new CatalogConnectorManager(catalogRegister, createCatalogConnectorFactory(), null);+ GravitinoConfig config =+ new GravitinoConfig(+ ImmutableMap.of(+ "gravitino.uri", "http://127.0.0.1:8090",+ "gravitino.metalake", "test",+ "gravitino.use-single-metalake", "true",+ "gravitino.iceberg.rest-uri", "http://irc-host:9001/iceberg"));+ manager.config(config, client);++ manager.loadMetalakeSync();++ verify(client, never()).icebergRestServiceUri("test");+ }++ @Test+ public void testIcebergRestDiscoveryRetriesAndRecovers() throws Exception {+ GravitinoAdminClient client = mock(GravitinoAdminClient.class);+ CatalogRegister catalogRegister = mock(CatalogRegister.class);+ when(catalogRegister.isTrinoStarted()).thenReturn(true);+ when(client.loadMetalake("test")).thenReturn(mock(GravitinoMetalake.class));+ when(client.icebergRestServiceUri("test"))+ .thenThrow(new RESTException("simulated discovery failure"))+ .thenReturn(Optional.of("http://irc-host:9001/iceberg"));++ CatalogConnectorManager manager =+ new CatalogConnectorManager(catalogRegister, createCatalogConnectorFactory(), null);+ GravitinoConfig config =+ new GravitinoConfig(+ ImmutableMap.of(+ "gravitino.uri", "http://127.0.0.1:8090",+ "gravitino.metalake", "test",+ "gravitino.use-single-metalake", "true"));+ manager.config(config, client);++ manager.loadMetalakeSync();+ manager.loadMetalakeSync();++ verify(client, times(2)).icebergRestServiceUri("test");+ assertEquals("http://irc-host:9001/iceberg", config.getDiscoveredIcebergRestUri("test"));+ }+@Testpublic void testPropsWithSecrets() {Catalog catalog = mock(Catalog.class);diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogRegister.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogRegister.javaindex 2effd98843..b850f587f8 100644--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogRegister.java+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogRegister.java@@ -25,20 +25,36 @@ import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertNull;import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.ArgumentMatchers.startsWith;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;+import com.google.common.collect.ImmutableMap;import io.trino.spi.TrinoException;import java.io.IOException;+import java.lang.reflect.Field;import java.nio.file.Files;import java.nio.file.Path;+import java.sql.Connection;+import java.sql.ResultSet;+import java.sql.SQLException;+import java.sql.Statement;+import java.util.Collections;import java.util.HashMap;import java.util.Map;import java.util.Properties;+import org.apache.gravitino.Catalog;import org.apache.gravitino.trino.connector.GravitinoConfig;+import org.apache.gravitino.trino.connector.metadata.GravitinoCatalog;+import org.apache.gravitino.trino.connector.metadata.TestGravitinoCatalog;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.io.TempDir;public class TestCatalogRegister {+ private static final String DISCOVERED_ICEBERG_REST_URI_PROPERTY = "__gravitino.iceberg.rest-uri";+@TempDir private static Path tempDir;private static GravitinoConfig config(Map<String, String> extraConfig) {@@ -377,4 +393,155 @@ public class TestCatalogRegister {assertTrue(e.getMessage().contains("does not exist"));assertTrue(e.getMessage().contains("trino.jdbc.ssl.truststore.path"));}++ @Test+ public void testGenerateCreateCatalogCommandEmbedsDiscoveredUriForIcebergCatalog()+ throws Exception {+ GravitinoConfig config =+ new GravitinoConfig(+ ImmutableMap.of(+ "gravitino.uri", "http://127.0.0.1:8090", "gravitino.metalake", "test"));+ config.setDiscoveredIcebergRestUri("test", "http://irc-host:9001/iceberg");+ CatalogRegister catalogRegister = new CatalogRegister();+ catalogRegister.setConfigForTesting(config);+ Catalog mockCatalog =+ TestGravitinoCatalog.mockCatalog(+ "iceberg_catalog",+ "lakehouse-iceberg",+ "test catalog",+ Catalog.Type.RELATIONAL,+ Collections.emptyMap());++ String command =+ catalogRegister.generateCreateCatalogCommand(+ "iceberg_catalog", new GravitinoCatalog("test", mockCatalog));++ assertTrue(+ command.contains(+ "\"" + DISCOVERED_ICEBERG_REST_URI_PROPERTY + "\":\"http://irc-host:9001/iceberg\""));+ }++ @Test+ public void testGenerateCreateCatalogCommandDoesNotEmbedUriForNonIcebergCatalog()+ throws Exception {+ GravitinoConfig config =+ new GravitinoConfig(+ ImmutableMap.of(+ "gravitino.uri", "http://127.0.0.1:8090", "gravitino.metalake", "test"));+ config.setDiscoveredIcebergRestUri("test", "http://irc-host:9001/iceberg");+ CatalogRegister catalogRegister = new CatalogRegister();+ catalogRegister.setConfigForTesting(config);+ Catalog mockCatalog =+ TestGravitinoCatalog.mockCatalog(+ "hive_catalog",+ "hive",+ "test catalog",+ Catalog.Type.RELATIONAL,+ Collections.emptyMap());++ String command =+ catalogRegister.generateCreateCatalogCommand(+ "hive_catalog", new GravitinoCatalog("test", mockCatalog));++ assertFalse(command.contains(DISCOVERED_ICEBERG_REST_URI_PROPERTY));+ }++ @Test+ public void testRedactSecretsMasksSecretBearingProperties() {+ String command =+ "CREATE CATALOG c USING gravitino WITH ( "+ + "\"gravitino.iceberg.rest-catalog.oauth2.credential\"='client:secretvalue', "+ + "\"gravitino.iceberg.rest-catalog.uri\"='http://irc-host:9001/iceberg', "+ + "\"some.token\"='abc123', "+ + "\"trino.bypass.password\"='hunter2', "+ + "\"trino.bypass.passcode\"='letmein', "+ + "\"trino.bypass.passphrase\"='opensesame')";++ String redacted = CatalogRegister.redactSecrets(command);++ assertFalse(redacted.contains("secretvalue"));+ assertFalse(redacted.contains("abc123"));+ assertFalse(redacted.contains("hunter2"));+ assertFalse(redacted.contains("letmein"));+ assertFalse(redacted.contains("opensesame"));+ assertTrue(redacted.contains("\"gravitino.iceberg.rest-catalog.oauth2.credential\"='***'"));+ assertTrue(redacted.contains("\"some.token\"='***'"));+ assertTrue(redacted.contains("\"trino.bypass.password\"='***'"));+ assertTrue(redacted.contains("\"trino.bypass.passcode\"='***'"));+ assertTrue(redacted.contains("\"trino.bypass.passphrase\"='***'"));+ assertTrue(+ redacted.contains("\"gravitino.iceberg.rest-catalog.uri\"='http://irc-host:9001/iceberg'"));+ }++ @Test+ public void testRedactSecretsMasksJsonEmbeddedSecrets() {+ String command =+ "CREATE CATALOG c USING gravitino WITH ( "+ + "\"__gravitino.dynamic.connector.catalog.config\"="+ + "'{\"name\":\"hive_catalog\",\"properties\":"+ + "{\"jdbc-password\":\"hunter2\",\"s3-secret-key\":\"abc123\",\"jdbc-user\":\"admin\"}}')";++ String redacted = CatalogRegister.redactSecrets(command);++ assertFalse(redacted.contains("hunter2"));+ assertFalse(redacted.contains("abc123"));+ assertTrue(redacted.contains("\"jdbc-password\":\"***\""));+ assertTrue(redacted.contains("\"s3-secret-key\":\"***\""));+ // Non-secret properties must survive redaction unchanged.+ assertTrue(redacted.contains("\"jdbc-user\":\"admin\""));+ }++ @Test+ public void testRegisterCatalogRedactsSecretsFromSqlExceptionMessage() throws Exception {+ // Regression test: some JDBC drivers echo the failing statement back in a SQLException+ // message. registerCatalog must redact that message the same way it redacts its own success+ // log, so a failed CREATE CATALOG never surfaces the embedded credential to the caller.+ String secretValue = "hunter2";+ Statement statement = mock(Statement.class);+ when(statement.execute(eq("SHOW CATALOGS"))).thenReturn(true);+ ResultSet resultSet = mock(ResultSet.class);+ when(statement.getResultSet()).thenReturn(resultSet);+ when(resultSet.next()).thenReturn(false);+ when(statement.execute(startsWith("CREATE CATALOG")))+ .thenThrow(+ new SQLException(+ "Query failed: \"gravitino.iceberg.rest-catalog.oauth2.credential\"='"+ + secretValue+ + "'"));++ Connection connection = mock(Connection.class);+ when(connection.createStatement()).thenReturn(statement);++ CatalogRegister catalogRegister = new CatalogRegister();+ catalogRegister.setConfigForTesting(+ new GravitinoConfig(+ ImmutableMap.of(+ "gravitino.uri", "http://127.0.0.1:8090", "gravitino.metalake", "test")));+ setPrivateField(catalogRegister, "connection", connection);+ setPrivateField(catalogRegister, "catalogStoreDirectory", tempDir.toString());++ Catalog mockCatalog =+ TestGravitinoCatalog.mockCatalog(+ "hive_catalog", "hive", "test catalog", Catalog.Type.RELATIONAL, Map.of());+ GravitinoCatalog catalog = new GravitinoCatalog("test", mockCatalog);++ TrinoException e =+ assertThrows(+ TrinoException.class, () -> catalogRegister.registerCatalog("hive_catalog", catalog));++ // The original driver SQLException carrying the credential is two levels down the cause+ // chain: registerCatalog's generic wrapper -> executeSql's generic wrapper -> the redacted+ // SQLException. No exception in that chain may still carry the raw secret.+ for (Throwable t = e; t != null; t = t.getCause()) {+ assertFalse(String.valueOf(t.getMessage()).contains(secretValue));+ }+ assertTrue(e.getCause().getCause().getMessage().contains("***"));+ }++ private static void setPrivateField(Object target, String fieldName, Object value)+ throws Exception {+ Field field = CatalogRegister.class.getDeclaredField(fieldName);+ field.setAccessible(true);+ field.set(target, value);+ }}diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergCatalogPropertyConverter.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergCatalogPropertyConverter.javaindex 9ef2d72d40..5b00e4d23e 100644--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergCatalogPropertyConverter.java+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergCatalogPropertyConverter.java@@ -27,6 +27,8 @@ import org.apache.gravitino.Catalog;import org.apache.gravitino.catalog.property.PropertyConverter;import org.apache.gravitino.credential.Credential;import org.apache.gravitino.credential.JdbcCredential;+import org.apache.gravitino.credential.S3SecretKeyCredential;+import org.apache.gravitino.trino.connector.GravitinoConfig;import org.apache.gravitino.trino.connector.metadata.GravitinoCatalog;import org.apache.gravitino.trino.connector.metadata.TestGravitinoCatalog;import org.junit.jupiter.api.Assertions;@@ -136,7 +138,7 @@ public class TestIcebergCatalogPropertyConverter {Catalog mockCatalog =TestGravitinoCatalog.mockCatalog(name, "lakehouse-iceberg", "test catalog", Catalog.Type.RELATIONAL, properties);- IcebergConnectorAdapter adapter = new IcebergConnectorAdapter();+ IcebergConnectorAdapter adapter = new IcebergConnectorAdapter(icebergRestUnavailableConfig());Map<String, String> config =adapter.buildInternalConnectorConfig(@@ -177,7 +179,7 @@ public class TestIcebergCatalogPropertyConverter {Catalog mockCatalog =TestGravitinoCatalog.mockCatalog(name, "lakehouse-iceberg", "test catalog", Catalog.Type.RELATIONAL, properties);- IcebergConnectorAdapter adapter = new IcebergConnectorAdapter();+ IcebergConnectorAdapter adapter = new IcebergConnectorAdapter(icebergRestUnavailableConfig());Map<String, String> config =adapter.buildInternalConnectorConfig(@@ -215,7 +217,7 @@ public class TestIcebergCatalogPropertyConverter {Catalog mockCatalog =TestGravitinoCatalog.mockCatalog(name, "lakehouse-iceberg", "test catalog", Catalog.Type.RELATIONAL, properties);- IcebergConnectorAdapter adapter = new IcebergConnectorAdapter();+ IcebergConnectorAdapter adapter = new IcebergConnectorAdapter(icebergRestUnavailableConfig());Map<String, String> config =adapter.buildInternalConnectorConfig(@@ -226,4 +228,578 @@ public class TestIcebergCatalogPropertyConverter {Assertions.assertEquals(config.get("iceberg.jdbc-catalog.connection-user"), "root");Assertions.assertEquals(config.get("iceberg.jdbc-catalog.connection-password"), "ds123");}++ @Test+ public void testBuildConnectorPropertiesRoutesJdbcBackendThroughIcebergRest() throws Exception {+ Map<String, String> properties =+ ImmutableMap.<String, String>builder()+ .put("uri", "jdbc:postgresql://localhost:5432/iceberg")+ .put("catalog-backend", "jdbc")+ .put("jdbc-driver", "org.postgresql.Driver")+ .put("jdbc-user", "iceberg")+ .put("jdbc-password", "secret")+ .put("warehouse", "s3://bucket/warehouse/")+ .put("s3-region", "us-east-1")+ .put("credential-providers", "s3-token")+ .build();++ Map<String, String> config =+ buildConnectorConfig(+ "catalog1", properties, icebergRestConfiguredConfig(ImmutableMap.of()));++ Assertions.assertEquals("rest", config.get("iceberg.catalog.type"));+ Assertions.assertEquals(+ "http://localhost:9001/iceberg", config.get("iceberg.rest-catalog.uri"));+ Assertions.assertEquals("catalog1", config.get("iceberg.rest-catalog.prefix"));+ // The initial GET /v1/config selects the catalog by `warehouse`, not by `prefix`.+ Assertions.assertEquals("catalog1", config.get("iceberg.rest-catalog.warehouse"));+ Assertions.assertEquals("true", config.get("iceberg.rest-catalog.vended-credentials-enabled"));++ // The JDBC backend is how Gravitino stores the metadata; it must not reach Trino.+ Assertions.assertNull(config.get("iceberg.jdbc-catalog.connection-url"));+ Assertions.assertNull(config.get("iceberg.jdbc-catalog.connection-user"));+ Assertions.assertNull(config.get("iceberg.jdbc-catalog.connection-password"));+ }++ @Test+ public void testBuildConnectorPropertiesRoutesHiveBackendThroughIcebergRest() throws Exception {+ Map<String, String> properties =+ ImmutableMap.<String, String>builder()+ .put("uri", "thrift://localhost:9083")+ .put("catalog-backend", "hive")+ .put("warehouse", "s3://bucket/warehouse/")+ .build();++ Map<String, String> config =+ buildConnectorConfig(+ "catalog1", properties, icebergRestConfiguredConfig(ImmutableMap.of()));++ Assertions.assertEquals("rest", config.get("iceberg.catalog.type"));+ Assertions.assertEquals("catalog1", config.get("iceberg.rest-catalog.prefix"));+ Assertions.assertNull(config.get("hive.metastore.uri"));+ }++ @Test+ public void testBuildConnectorPropertiesKeepsRestBackendEndpoint() throws Exception {+ Map<String, String> properties =+ ImmutableMap.<String, String>builder()+ .put("uri", "http://other-irc:9001/iceberg")+ .put("catalog-backend", "rest")+ .put("warehouse", "gt_iceberg_rest")+ .build();++ Map<String, String> config =+ buildConnectorConfig(+ "catalog1", properties, icebergRestConfiguredConfig(ImmutableMap.of()));++ Assertions.assertEquals("rest", config.get("iceberg.catalog.type"));+ Assertions.assertEquals(+ "http://other-irc:9001/iceberg", config.get("iceberg.rest-catalog.uri"));+ Assertions.assertEquals("gt_iceberg_rest", config.get("iceberg.rest-catalog.warehouse"));+ Assertions.assertNull(config.get("iceberg.rest-catalog.prefix"));+ }++ @Test+ public void testBuildConnectorPropertiesWithIcebergRestDisabled() throws Exception {+ Map<String, String> properties =+ ImmutableMap.<String, String>builder()+ .put("uri", "jdbc:postgresql://localhost:5432/iceberg")+ .put("catalog-backend", "jdbc")+ .put("jdbc-driver", "org.postgresql.Driver")+ .put("warehouse", "s3://bucket/warehouse/")+ .build();++ Map<String, String> config =+ buildConnectorConfig("catalog1", properties, icebergRestUnavailableConfig());++ Assertions.assertEquals("jdbc", config.get("iceberg.catalog.type"));+ Assertions.assertEquals(+ "jdbc:postgresql://localhost:5432/iceberg",+ config.get("iceberg.jdbc-catalog.connection-url"));+ Assertions.assertNull(config.get("iceberg.rest-catalog.uri"));+ }++ @Test+ public void testBuildConnectorPropertiesFailsWhenNoIcebergRestUriIsAvailable() {+ Map<String, String> properties =+ ImmutableMap.<String, String>builder()+ .put("uri", "jdbc:postgresql://localhost:5432/iceberg")+ .put("catalog-backend", "jdbc")+ .put("jdbc-driver", "org.postgresql.Driver")+ .build();++ GravitinoConfig config = new GravitinoConfig(ImmutableMap.of("gravitino.metalake", "test"));++ TrinoException exception =+ Assertions.assertThrows(+ TrinoException.class, () -> buildConnectorConfig("catalog1", properties, config));+ Assertions.assertTrue(exception.getMessage().contains("no Iceberg REST endpoint is available"));+ }++ @Test+ public void testBuildIcebergRestPropertiesThrowsOnBlankUri() {+ // buildIcebergRestProperties keeps its own defensive check even though+ // IcebergConnectorAdapter's routing gate means callers can no longer reach it with a blank+ // URI under normal operation.+ Catalog mockCatalog =+ TestGravitinoCatalog.mockCatalog(+ "catalog1",+ "lakehouse-iceberg",+ "test catalog",+ Catalog.Type.RELATIONAL,+ ImmutableMap.of("catalog-backend", "jdbc"));+ GravitinoCatalog catalog = new GravitinoCatalog("test", mockCatalog);+ IcebergCatalogPropertyConverter converter = new IcebergCatalogPropertyConverter();++ Assertions.assertThrows(+ TrinoException.class,+ () -> converter.buildIcebergRestProperties(catalog, icebergRestUnavailableConfig(), ""));+ }++ @Test+ public void testBuildConnectorPropertiesRoutesThroughDiscoveredIcebergRestUri() throws Exception {+ Map<String, String> properties =+ ImmutableMap.<String, String>builder()+ .put("catalog-backend", "jdbc")+ .put("uri", "jdbc:postgresql://localhost:5432/iceberg")+ .put("jdbc-driver", "org.postgresql.Driver")+ .build();++ // No manual gravitino.iceberg.rest-uri: only a per-metalake value discovered from the+ // Gravitino server, embedded onto the catalog exactly as CatalogRegister does before+ // registering it — this is the only way a worker (which never runs discovery itself) can see+ // the same routing decision as the coordinator.+ Map<String, String> config =+ buildConnectorConfig(+ "catalog1",+ properties,+ icebergRestDiscoveredConfig("test", "http://discovered:9001/iceberg"),+ /* embedDiscovery= */ true);++ Assertions.assertEquals("rest", config.get("iceberg.catalog.type"));+ Assertions.assertEquals(+ "http://discovered:9001/iceberg", config.get("iceberg.rest-catalog.uri"));+ }++ @Test+ public void testBuildConnectorPropertiesRejectsDiscoveryForOtherMetalakes() {+ Map<String, String> properties =+ ImmutableMap.<String, String>builder()+ .put("catalog-backend", "jdbc")+ .put("uri", "jdbc:postgresql://localhost:5432/iceberg")+ .put("jdbc-driver", "org.postgresql.Driver")+ .build();++ // Discovery reported an endpoint for a different metalake than the one this catalog belongs+ // to (the mock catalog's metalake is "test"); embedDiscoveredIcebergRestUri must not embed it.+ Assertions.assertThrows(+ TrinoException.class,+ () ->+ buildConnectorConfig(+ "catalog1",+ properties,+ icebergRestDiscoveredConfig("other_metalake", "http://other:9001/iceberg"),+ /* embedDiscovery= */ true));+ }++ @Test+ public void testDiscoveredUriUnusedWithoutEmbedding() {+ // A worker never runs discovery, so its own GravitinoConfig never has a discovered value+ // populated — this asserts that IcebergConnectorAdapter really does read the routing signal+ // from the catalog, not from GravitinoConfig's discovered map directly.+ Map<String, String> properties =+ ImmutableMap.<String, String>builder()+ .put("catalog-backend", "jdbc")+ .put("uri", "jdbc:postgresql://localhost:5432/iceberg")+ .put("jdbc-driver", "org.postgresql.Driver")+ .build();++ Assertions.assertThrows(+ TrinoException.class,+ () ->+ buildConnectorConfig(+ "catalog1",+ properties,+ icebergRestDiscoveredConfig("test", "http://discovered:9001/iceberg"),+ /* embedDiscovery= */ false));+ }++ @Test+ public void testManualUriWinsOverDiscoveredUri() throws Exception {+ // Both a manual gravitino.iceberg.rest-uri and a discovered per-metalake URI are set; the+ // manual override must win, matching IcebergConnectorAdapter.buildInternalConnectorConfig's+ // documented precedence.+ Map<String, String> properties =+ ImmutableMap.<String, String>builder()+ .put("catalog-backend", "jdbc")+ .put("uri", "jdbc:postgresql://localhost:5432/iceberg")+ .put("jdbc-driver", "org.postgresql.Driver")+ .build();++ GravitinoConfig config = icebergRestConfiguredConfig(ImmutableMap.of());+ config.setDiscoveredIcebergRestUri("test", "http://discovered:9001/iceberg");++ Map<String, String> connectorConfig =+ buildConnectorConfig("catalog1", properties, config, /* embedDiscovery= */ true);++ Assertions.assertEquals("rest", connectorConfig.get("iceberg.catalog.type"));+ Assertions.assertEquals(+ "http://localhost:9001/iceberg", connectorConfig.get("iceberg.rest-catalog.uri"));+ }++ @Test+ public void testEmbedDiscoveredIcebergRestUriDoesNotAffectNonIcebergCatalog() {+ // CatalogRegister calls embedDiscoveredIcebergRestUri unconditionally for every catalog being+ // registered, not just Iceberg ones, so this guard is load-bearing: a Hive/MySQL/etc. catalog+ // must never end up carrying the synthetic discovered-URI property.+ GravitinoConfig config = icebergRestDiscoveredConfig("test", "http://discovered:9001/iceberg");+ Catalog mockHiveCatalog =+ TestGravitinoCatalog.mockCatalog(+ "hive_catalog", "hive", "test catalog", Catalog.Type.RELATIONAL, ImmutableMap.of());+ GravitinoCatalog hiveCatalog = new GravitinoCatalog("test", mockHiveCatalog);++ GravitinoCatalog result =+ IcebergConnectorAdapter.embedDiscoveredIcebergRestUri(hiveCatalog, config);++ Assertions.assertEquals(hiveCatalog.getProperties(), result.getProperties());+ }++ @Test+ public void testBuildConnectorPropertiesWithIcebergRestAuthentication() throws Exception {+ Map<String, String> properties =+ ImmutableMap.<String, String>builder()+ .put("catalog-backend", "jdbc")+ .put("uri", "jdbc:postgresql://localhost:5432/iceberg")+ .put("jdbc-driver", "org.postgresql.Driver")+ .put("warehouse", "s3://bucket/warehouse/")+ .build();+ GravitinoConfig gravitinoConfig =+ icebergRestConfiguredConfig(+ ImmutableMap.of(+ "gravitino.iceberg.rest-catalog.security", "OAUTH2",+ "gravitino.iceberg.rest-catalog.oauth2.credential", "client_id:client_secret",+ "gravitino.iceberg.rest-catalog.uri", "http://ignored:9001/iceberg"));++ Map<String, String> config = buildConnectorConfig("catalog1", properties, gravitinoConfig);++ Assertions.assertEquals("OAUTH2", config.get("iceberg.rest-catalog.security"));+ Assertions.assertEquals(+ "client_id:client_secret", config.get("iceberg.rest-catalog.oauth2.credential"));+ // The endpoint the connector routes to cannot be overridden by the pass-through prefix.+ Assertions.assertEquals(+ "http://localhost:9001/iceberg", config.get("iceberg.rest-catalog.uri"));+ }++ @Test+ public void testBuildConnectorPropertiesForwardsSessionUser() throws Exception {+ Map<String, String> properties =+ ImmutableMap.<String, String>builder()+ .put("catalog-backend", "jdbc")+ .put("uri", "jdbc:postgresql://localhost:5432/iceberg")+ .put("jdbc-driver", "org.postgresql.Driver")+ .build();++ Map<String, String> config =+ buildConnectorConfig(+ "catalog1",+ properties,+ icebergRestConfiguredConfig(+ ImmutableMap.of("gravitino.client.session.forwardUser", "true")));+ Assertions.assertEquals("USER", config.get("iceberg.rest-catalog.session"));++ Map<String, String> explicitConfig =+ buildConnectorConfig(+ "catalog1",+ properties,+ icebergRestConfiguredConfig(+ ImmutableMap.of(+ "gravitino.client.session.forwardUser", "true",+ "gravitino.iceberg.rest-catalog.session", "NONE")));+ Assertions.assertEquals("NONE", explicitConfig.get("iceberg.rest-catalog.session"));++ Map<String, String> defaultConfig =+ buildConnectorConfig(+ "catalog1", properties, icebergRestConfiguredConfig(ImmutableMap.of()));+ Assertions.assertNull(defaultConfig.get("iceberg.rest-catalog.session"));+ }++ @Test+ public void testBuildConnectorPropertiesStorageDetection() throws Exception {+ Map<String, String> s3Config =+ buildConnectorConfig(+ "catalog1",+ ImmutableMap.of(+ "catalog-backend", "jdbc",+ "warehouse", "s3://bucket/warehouse/",+ "s3-region", "us-east-1",+ "s3-endpoint", "http://minio:9000"),+ icebergRestConfiguredConfig(ImmutableMap.of()));+ Assertions.assertEquals("true", s3Config.get("fs.native-s3.enabled"));+ Assertions.assertEquals("us-east-1", s3Config.get("s3.region"));+ Assertions.assertEquals("http://minio:9000", s3Config.get("s3.endpoint"));+ Assertions.assertEquals("true", s3Config.get("fs.hadoop.enabled"));++ Map<String, String> gcsConfig =+ buildConnectorConfig(+ "catalog1",+ ImmutableMap.of("catalog-backend", "jdbc", "warehouse", "gs://bucket/warehouse/"),+ icebergRestConfiguredConfig(ImmutableMap.of()));+ Assertions.assertEquals("true", gcsConfig.get("fs.native-gcs.enabled"));+ Assertions.assertNull(gcsConfig.get("fs.native-s3.enabled"));++ Map<String, String> azureConfig =+ buildConnectorConfig(+ "catalog1",+ ImmutableMap.of(+ "catalog-backend", "jdbc", "warehouse", "abfss://container@account/warehouse/"),+ icebergRestConfiguredConfig(ImmutableMap.of()));+ Assertions.assertEquals("true", azureConfig.get("fs.native-azure.enabled"));++ Map<String, String> hdfsConfig =+ buildConnectorConfig(+ "catalog1",+ ImmutableMap.of("catalog-backend", "jdbc", "warehouse", "hdfs://namenode:9000/wh"),+ icebergRestConfiguredConfig(ImmutableMap.of()));+ Assertions.assertEquals("true", hdfsConfig.get("fs.hadoop.enabled"));+ Assertions.assertNull(hdfsConfig.get("fs.native-s3.enabled"));+ Assertions.assertNull(hdfsConfig.get("fs.native-gcs.enabled"));+ Assertions.assertNull(hdfsConfig.get("fs.native-azure.enabled"));+ }++ @Test+ public void testBuildConnectorPropertiesIcebergRestKeepsCatalogBypass() throws Exception {+ Map<String, String> properties =+ ImmutableMap.<String, String>builder()+ .put("catalog-backend", "jdbc")+ .put("warehouse", "s3://bucket/warehouse/")+ .put("trino.bypass.iceberg.table-statistics-enabled", "true")+ .put("trino.bypass.fs.native-s3.enabled", "false")+ .build();++ Map<String, String> config =+ buildConnectorConfig(+ "catalog1", properties, icebergRestConfiguredConfig(ImmutableMap.of()));++ Assertions.assertEquals("true", config.get("iceberg.table-statistics-enabled"));+ // A catalog can override a derived default, so a Trino release renaming it is not a blocker.+ Assertions.assertEquals("false", config.get("fs.native-s3.enabled"));+ }++ @SuppressWarnings("unchecked")+ private static Map<String, String> buildConnectorConfig(+ String catalogName, Map<String, String> properties, GravitinoConfig gravitinoConfig)+ throws Exception {+ return buildConnectorConfig(catalogName, properties, gravitinoConfig, new Credential[0]);+ }++ @Test+ public void testIcebergRestPathIgnoresCatalogLevelCredentials() throws Exception {+ Map<String, String> properties =+ ImmutableMap.<String, String>builder()+ .put("catalog-backend", "jdbc")+ .put("uri", "jdbc:postgresql://localhost:5432/iceberg")+ .put("jdbc-driver", "org.postgresql.Driver")+ .put("warehouse", "s3://bucket/warehouse/")+ .build();+ Credential[] credentials = {+ new JdbcCredential("root", "ds123"), new S3SecretKeyCredential("AKIAEXAMPLE", "secret")+ };++ Map<String, String> config =+ buildConnectorConfig(+ "catalog1", properties, icebergRestConfiguredConfig(ImmutableMap.of()), credentials);++ // The REST protocol vends a fresh credential per table access, so the catalog-level snapshot+ // must not be pinned into the connector config.+ Assertions.assertNull(config.get("iceberg.jdbc-catalog.connection-user"));+ Assertions.assertNull(config.get("iceberg.jdbc-catalog.connection-password"));+ Assertions.assertNull(config.get("hive.s3.aws-access-key"));+ Assertions.assertNull(config.get("hive.s3.aws-secret-key"));+ Assertions.assertEquals("true", config.get("iceberg.rest-catalog.vended-credentials-enabled"));++ // The backend path still applies them.+ Map<String, String> legacyConfig =+ buildConnectorConfig("catalog1", properties, icebergRestUnavailableConfig(), credentials);+ Assertions.assertEquals("root", legacyConfig.get("iceberg.jdbc-catalog.connection-user"));+ Assertions.assertEquals("AKIAEXAMPLE", legacyConfig.get("hive.s3.aws-access-key"));+ }++ @Test+ public void testIcebergRestReservedPropertiesResistCatalogOverride() throws Exception {+ Map<String, String> properties =+ ImmutableMap.<String, String>builder()+ .put("catalog-backend", "jdbc")+ .put("warehouse", "s3://bucket/warehouse/")+ .put("trino.bypass.iceberg.catalog.type", "jdbc")+ .put("trino.bypass.iceberg.rest-catalog.uri", "http://elsewhere:9001/iceberg")+ .put("trino.bypass.iceberg.rest-catalog.prefix", "other_catalog")+ .put("trino.bypass.iceberg.rest-catalog.warehouse", "other_catalog")+ .build();++ Map<String, String> config =+ buildConnectorConfig(+ "catalog1", properties, icebergRestConfiguredConfig(ImmutableMap.of()));++ // A catalog property must never redirect the connector at another endpoint or catalog.+ Assertions.assertEquals("rest", config.get("iceberg.catalog.type"));+ Assertions.assertEquals(+ "http://localhost:9001/iceberg", config.get("iceberg.rest-catalog.uri"));+ Assertions.assertEquals("catalog1", config.get("iceberg.rest-catalog.prefix"));+ Assertions.assertEquals("catalog1", config.get("iceberg.rest-catalog.warehouse"));+ }++ @Test+ public void testConnectorRestCatalogConfigOverridesCatalogBypass() throws Exception {+ Map<String, String> properties =+ ImmutableMap.<String, String>builder()+ .put("catalog-backend", "jdbc")+ .put("warehouse", "s3://bucket/warehouse/")+ .put("trino.bypass.iceberg.rest-catalog.security", "NONE")+ .build();++ Map<String, String> config =+ buildConnectorConfig(+ "catalog1",+ properties,+ icebergRestConfiguredConfig(+ ImmutableMap.of("gravitino.iceberg.rest-catalog.security", "OAUTH2")));++ // Cluster-level operational settings outrank per-catalog properties.+ Assertions.assertEquals("OAUTH2", config.get("iceberg.rest-catalog.security"));+ }++ @Test+ public void testBuildConnectorPropertiesStorageDetectionEdgeCases() throws Exception {+ // s3a/s3n aliases and an uppercase scheme all resolve to the native S3 file system.+ for (String warehouse : new String[] {"s3a://bucket/wh", "s3n://bucket/wh", "S3://bucket/wh"}) {+ Map<String, String> config =+ buildConnectorConfig(+ "catalog1",+ ImmutableMap.of("catalog-backend", "jdbc", "warehouse", warehouse),+ icebergRestConfiguredConfig(ImmutableMap.of()));+ Assertions.assertEquals(+ "true", config.get("fs.native-s3.enabled"), "warehouse: " + warehouse);+ }++ // A warehouse without a scheme is a plain path and stays on the Hadoop file system.+ Map<String, String> schemeless =+ buildConnectorConfig(+ "catalog1",+ ImmutableMap.of("catalog-backend", "jdbc", "warehouse", "gt_iceberg_rest"),+ icebergRestConfiguredConfig(ImmutableMap.of()));+ Assertions.assertEquals("true", schemeless.get("fs.hadoop.enabled"));+ Assertions.assertNull(schemeless.get("fs.native-s3.enabled"));++ // No warehouse at all.+ Map<String, String> noWarehouse =+ buildConnectorConfig(+ "catalog1",+ ImmutableMap.of("catalog-backend", "jdbc"),+ icebergRestConfiguredConfig(ImmutableMap.of()));+ Assertions.assertEquals("true", noWarehouse.get("fs.hadoop.enabled"));+ Assertions.assertNull(noWarehouse.get("fs.native-s3.enabled"));+ Assertions.assertNull(noWarehouse.get("fs.native-gcs.enabled"));+ Assertions.assertNull(noWarehouse.get("fs.native-azure.enabled"));++ // oss:// has no Trino native file system, so nothing is enabled beyond Hadoop.+ Map<String, String> oss =+ buildConnectorConfig(+ "catalog1",+ ImmutableMap.of(+ "catalog-backend", "jdbc",+ "warehouse", "oss://bucket/wh",+ "credential-providers", "oss-token"),+ icebergRestConfiguredConfig(ImmutableMap.of()));+ Assertions.assertEquals("true", oss.get("fs.hadoop.enabled"));+ Assertions.assertNull(oss.get("fs.native-s3.enabled"));+ }++ @Test+ public void testBuildConnectorPropertiesCopiesS3PathStyleAccess() throws Exception {+ Map<String, String> config =+ buildConnectorConfig(+ "catalog1",+ ImmutableMap.of(+ "catalog-backend", "jdbc",+ "warehouse", "s3://bucket/wh",+ "s3-endpoint", "http://minio:9000",+ "s3-path-style-access", "true"),+ icebergRestConfiguredConfig(ImmutableMap.of()));++ // S3-compatible stores such as MinIO need path-style addressing to resolve the bucket.+ Assertions.assertEquals("true", config.get("s3.path-style-access"));+ Assertions.assertEquals("http://minio:9000", config.get("s3.endpoint"));+ }++ @Test+ public void testRestBackendIsNotReRoutedRegardlessOfCase() throws Exception {+ Map<String, String> config =+ buildConnectorConfig(+ "catalog1",+ ImmutableMap.of("catalog-backend", "REST", "uri", "http://other-irc:9001/iceberg"),+ icebergRestConfiguredConfig(ImmutableMap.of()));++ Assertions.assertEquals(+ "http://other-irc:9001/iceberg", config.get("iceberg.rest-catalog.uri"));+ Assertions.assertNull(config.get("iceberg.rest-catalog.prefix"));+ }++ private static Map<String, String> buildConnectorConfig(+ String catalogName,+ Map<String, String> properties,+ GravitinoConfig gravitinoConfig,+ Credential[] credentials)+ throws Exception {+ Catalog mockCatalog =+ TestGravitinoCatalog.mockCatalog(+ catalogName, "lakehouse-iceberg", "test catalog", Catalog.Type.RELATIONAL, properties);+ return new IcebergConnectorAdapter(gravitinoConfig)+ .buildInternalConnectorConfig(new GravitinoCatalog("test", mockCatalog), credentials);+ }++ /**+ * Like {@link #buildConnectorConfig(String, Map, GravitinoConfig, Credential[])}, but for+ * discovered-endpoint scenarios: {@code embedDiscovery} mirrors what {@code CatalogRegister} does+ * before registering a catalog, so a discovered value only reaches the adapter the same way it+ * would on a real node — through the catalog, never by reading {@code GravitinoConfig}'s+ * discovered map directly.+ */+ private static Map<String, String> buildConnectorConfig(+ String catalogName,+ Map<String, String> properties,+ GravitinoConfig gravitinoConfig,+ boolean embedDiscovery)+ throws Exception {+ Catalog mockCatalog =+ TestGravitinoCatalog.mockCatalog(+ catalogName, "lakehouse-iceberg", "test catalog", Catalog.Type.RELATIONAL, properties);+ GravitinoCatalog catalog = new GravitinoCatalog("test", mockCatalog);+ if (embedDiscovery) {+ catalog = IcebergConnectorAdapter.embedDiscoveredIcebergRestUri(catalog, gravitinoConfig);+ }+ return new IcebergConnectorAdapter(gravitinoConfig)+ .buildInternalConnectorConfig(catalog, new Credential[0]);+ }++ private static GravitinoConfig icebergRestUnavailableConfig() {+ return new GravitinoConfig(+ ImmutableMap.of(+ "gravitino.metalake", "test",+ "gravitino.iceberg.rest-routing-enabled", "false"));+ }++ private static GravitinoConfig icebergRestConfiguredConfig(Map<String, String> extraConfig) {+ return new GravitinoConfig(+ ImmutableMap.<String, String>builder()+ .put("gravitino.metalake", "test")+ .put("gravitino.iceberg.rest-uri", "http://localhost:9001/iceberg")+ .putAll(extraConfig)+ .build());+ }++ private static GravitinoConfig icebergRestDiscoveredConfig(String metalake, String uri) {+ GravitinoConfig config = new GravitinoConfig(ImmutableMap.of("gravitino.metalake", metalake));+ config.setDiscoveredIcebergRestUri(metalake, uri);+ return config;+ }}diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergConnectorAdapterReload.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergConnectorAdapterReload.javanew file mode 100644index 0000000000..d90057f24d--- /dev/null+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergConnectorAdapterReload.java@@ -0,0 +1,95 @@+/*+ * 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.trino.connector.catalog.iceberg;++import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertTrue;++import com.google.common.collect.ImmutableMap;+import org.apache.gravitino.trino.connector.GravitinoConfig;+import org.apache.gravitino.trino.connector.metadata.GravitinoCatalog;+import org.junit.jupiter.api.Test;++public class TestIcebergConnectorAdapterReload {++ private static GravitinoConfig configFor(String metalake, String discoveredUri) {+ GravitinoConfig config =+ new GravitinoConfig(+ ImmutableMap.of(+ "gravitino.uri", "http://127.0.0.1:8090", "gravitino.metalake", metalake));+ if (discoveredUri != null) {+ config.setDiscoveredIcebergRestUri(metalake, discoveredUri);+ }+ return config;+ }++ private static GravitinoCatalog icebergCatalog(String embeddedUri) {+ ImmutableMap<String, String> properties =+ embeddedUri == null+ ? ImmutableMap.of()+ : ImmutableMap.of("__gravitino.iceberg.rest-uri", embeddedUri);+ return new GravitinoCatalog("test", "lakehouse-iceberg", "iceberg_catalog", properties, 5L);+ }++ @Test+ public void testUnchangedWhenDiscoveredUriMatchesEmbeddedUri() {+ GravitinoConfig config = configFor("test", "http://irc-host:9001/iceberg");+ GravitinoCatalog freshCatalog = icebergCatalog(null);+ GravitinoCatalog registeredCatalog = icebergCatalog("http://irc-host:9001/iceberg");++ assertFalse(+ IcebergConnectorAdapter.hasDiscoveredIcebergRestUriChanged(+ freshCatalog, registeredCatalog, config));+ }++ @Test+ public void testChangedWhenIcebergRestBecomesAvailable() {+ GravitinoConfig config = configFor("test", "http://irc-host:9001/iceberg");+ GravitinoCatalog freshCatalog = icebergCatalog(null);+ GravitinoCatalog registeredCatalog = icebergCatalog(null);++ assertTrue(+ IcebergConnectorAdapter.hasDiscoveredIcebergRestUriChanged(+ freshCatalog, registeredCatalog, config));+ }++ @Test+ public void testChangedWhenIcebergRestBecomesUnavailable() {+ GravitinoConfig config = configFor("test", null);+ GravitinoCatalog freshCatalog = icebergCatalog(null);+ GravitinoCatalog registeredCatalog = icebergCatalog("http://irc-host:9001/iceberg");++ assertTrue(+ IcebergConnectorAdapter.hasDiscoveredIcebergRestUriChanged(+ freshCatalog, registeredCatalog, config));+ }++ @Test+ public void testNonIcebergCatalogNeverReportsChanged() {+ GravitinoConfig config = configFor("test", "http://irc-host:9001/iceberg");+ GravitinoCatalog freshCatalog =+ new GravitinoCatalog("test", "hive", "hive_catalog", ImmutableMap.of(), 5L);+ GravitinoCatalog registeredCatalog =+ new GravitinoCatalog("test", "hive", "hive_catalog", ImmutableMap.of(), 5L);++ assertFalse(+ IcebergConnectorAdapter.hasDiscoveredIcebergRestUriChanged(+ freshCatalog, registeredCatalog, config));+ }+}