Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#12552] feat(catalog): support testing existing catalog connections (#12553)

mchadesb5a28dfa772c
diff --git a/api/src/main/java/org/apache/gravitino/SupportsCatalogs.java b/api/src/main/java/org/apache/gravitino/SupportsCatalogs.java
index 088279b69f..650d60fdbb 100644
--- a/api/src/main/java/org/apache/gravitino/SupportsCatalogs.java
+++ b/api/src/main/java/org/apache/gravitino/SupportsCatalogs.java
@@ -214,4 +214,16 @@ public interface SupportsCatalogs {
String comment,
Map<String, String> properties)
throws Exception;
+
+ /**
+ * Test the connection of an existing catalog using its stored configuration.
+ *
+ * @param catalogName the name of the existing catalog.
+ * @throws NoSuchCatalogException if the catalog does not exist.
+ * @throws Exception if the test failed.
+ */
+ default void testConnection(String catalogName) throws Exception {
+ throw new UnsupportedOperationException(
+ String.format("Catalog %s does not support connection testing", catalogName));
+ }
}
diff --git a/bundles/aliyun/build.gradle.kts b/bundles/aliyun/build.gradle.kts
index 44f1d11351..78e061708f 100644
--- a/bundles/aliyun/build.gradle.kts
+++ b/bundles/aliyun/build.gradle.kts
@@ -45,6 +45,10 @@ dependencies {
compileOnly(libs.hadoop3.oss)
compileOnly(libs.lombok)
+ testImplementation(libs.aliyun.credentials.sdk)
+ testImplementation(libs.hadoop3.client.api)
+ testImplementation(libs.hadoop3.client.runtime)
+ testImplementation(libs.hadoop3.oss)
testImplementation(libs.junit.jupiter.api)
testImplementation(libs.junit.jupiter.params)
testRuntimeOnly(libs.junit.jupiter.engine)
diff --git a/bundles/aliyun/src/test/java/org/apache/gravitino/oss/fs/TestOSSCredentialVending.java b/bundles/aliyun/src/test/java/org/apache/gravitino/oss/fs/TestOSSCredentialVending.java
new file mode 100644
index 0000000000..ce66ac104c
--- /dev/null
+++ b/bundles/aliyun/src/test/java/org/apache/gravitino/oss/fs/TestOSSCredentialVending.java
@@ -0,0 +1,86 @@
+/*
+ * 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.oss.fs;
+
+import com.aliyun.oss.common.auth.Credentials;
+import java.net.URI;
+import java.util.Map;
+import org.apache.gravitino.catalog.hadoop.fs.GravitinoFileSystemCredentialsProvider;
+import org.apache.gravitino.catalog.hadoop.fs.InMemoryFileSystemCredentialsProvider;
+import org.apache.gravitino.credential.Credential;
+import org.apache.gravitino.credential.OSSSecretKeyCredential;
+import org.apache.gravitino.credential.OSSTokenCredential;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.aliyun.oss.Constants;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+/** Tests the complete in-memory credential vending path for OSS credentials. */
+public class TestOSSCredentialVending {
+
+ private static final URI OSS_URI = URI.create("oss://test-bucket/");
+
+ @Test
+ void testSecretKeyCredential() {
+ OSSSecretKeyCredential credential = new OSSSecretKeyCredential("access-key", "secret-key");
+
+ Credentials actual = readCredential(credential);
+
+ Assertions.assertEquals("access-key", actual.getAccessKeyId());
+ Assertions.assertEquals("secret-key", actual.getSecretAccessKey());
+ Assertions.assertFalse(actual.useSecurityToken());
+ }
+
+ @Test
+ void testTokenCredential() {
+ OSSTokenCredential credential =
+ new OSSTokenCredential(
+ "access-key", "secret-key", "security-token", System.currentTimeMillis() + 60_000L);
+
+ Credentials actual = readCredential(credential);
+
+ Assertions.assertEquals("access-key", actual.getAccessKeyId());
+ Assertions.assertEquals("secret-key", actual.getSecretAccessKey());
+ Assertions.assertEquals("security-token", actual.getSecurityToken());
+ Assertions.assertTrue(actual.useSecurityToken());
+ }
+
+ private Credentials readCredential(Credential credential) {
+ Credential[] credentials = new Credential[] {credential};
+ String handle = InMemoryFileSystemCredentialsProvider.register(credentials);
+ try {
+ Configuration conf = new Configuration(false);
+ Map<String, String> credentialConf =
+ new OSSFileSystemProvider().getFileSystemCredentialConf(credentials);
+ credentialConf.forEach(conf::set);
+ conf.set(
+ GravitinoFileSystemCredentialsProvider.GVFS_CREDENTIAL_PROVIDER,
+ InMemoryFileSystemCredentialsProvider.class.getCanonicalName());
+ conf.set(InMemoryFileSystemCredentialsProvider.CREDENTIAL_HANDLE, handle);
+ Assertions.assertEquals(
+ OSSCredentialsProvider.class.getCanonicalName(),
+ conf.get(Constants.CREDENTIALS_PROVIDER_KEY));
+
+ return new OSSCredentialsProvider(OSS_URI, conf).getCredentials();
+ } finally {
+ InMemoryFileSystemCredentialsProvider.unregister(handle);
+ }
+ }
+}
diff --git a/bundles/aws/build.gradle.kts b/bundles/aws/build.gradle.kts
index 7b6d4f1ec1..8b9fe82abc 100644
--- a/bundles/aws/build.gradle.kts
+++ b/bundles/aws/build.gradle.kts
@@ -48,6 +48,9 @@ dependencies {
testImplementation(libs.aws.iam)
testImplementation(libs.aws.policy)
testImplementation(libs.aws.sts)
+ testImplementation(libs.hadoop3.aws)
+ testImplementation(libs.hadoop3.client.api)
+ testImplementation(libs.hadoop3.client.runtime)
testImplementation(libs.junit.jupiter.api)
testImplementation(libs.junit.jupiter.params)
testRuntimeOnly(libs.junit.jupiter.engine)
diff --git a/bundles/aws/src/test/java/org/apache/gravitino/s3/fs/TestS3CredentialVending.java b/bundles/aws/src/test/java/org/apache/gravitino/s3/fs/TestS3CredentialVending.java
new file mode 100644
index 0000000000..2d1adab78b
--- /dev/null
+++ b/bundles/aws/src/test/java/org/apache/gravitino/s3/fs/TestS3CredentialVending.java
@@ -0,0 +1,101 @@
+/*
+ * 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.s3.fs;
+
+import com.amazonaws.auth.AWSCredentials;
+import com.amazonaws.auth.AWSSessionCredentials;
+import java.net.URI;
+import java.util.Map;
+import org.apache.gravitino.catalog.hadoop.fs.GravitinoFileSystemCredentialsProvider;
+import org.apache.gravitino.catalog.hadoop.fs.InMemoryFileSystemCredentialsProvider;
+import org.apache.gravitino.credential.AwsIrsaCredential;
+import org.apache.gravitino.credential.Credential;
+import org.apache.gravitino.credential.S3SecretKeyCredential;
+import org.apache.gravitino.credential.S3TokenCredential;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.s3a.Constants;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+/** Tests the complete in-memory credential vending path for S3 credentials. */
+public class TestS3CredentialVending {
+
+ private static final URI S3_URI = URI.create("s3a://test-bucket/");
+ private static final long EXPIRATION_TIME = System.currentTimeMillis() + 60_000L;
+
+ @Test
+ void testSecretKeyCredential() {
+ S3SecretKeyCredential credential = new S3SecretKeyCredential("access-key", "secret-key");
+
+ AWSCredentials actual = readCredential(credential);
+
+ Assertions.assertEquals("access-key", actual.getAWSAccessKeyId());
+ Assertions.assertEquals("secret-key", actual.getAWSSecretKey());
+ Assertions.assertFalse(actual instanceof AWSSessionCredentials);
+ }
+
+ @Test
+ void testTokenCredential() {
+ S3TokenCredential credential =
+ new S3TokenCredential("access-key", "secret-key", "session-token", EXPIRATION_TIME);
+
+ AWSCredentials actual = readCredential(credential);
+
+ Assertions.assertTrue(actual instanceof AWSSessionCredentials);
+ Assertions.assertEquals("access-key", actual.getAWSAccessKeyId());
+ Assertions.assertEquals("secret-key", actual.getAWSSecretKey());
+ Assertions.assertEquals("session-token", ((AWSSessionCredentials) actual).getSessionToken());
+ }
+
+ @Test
+ void testIrsaCredential() {
+ AwsIrsaCredential credential =
+ new AwsIrsaCredential("access-key", "secret-key", "session-token", EXPIRATION_TIME);
+
+ AWSCredentials actual = readCredential(credential);
+
+ Assertions.assertTrue(actual instanceof AWSSessionCredentials);
+ Assertions.assertEquals("access-key", actual.getAWSAccessKeyId());
+ Assertions.assertEquals("secret-key", actual.getAWSSecretKey());
+ Assertions.assertEquals("session-token", ((AWSSessionCredentials) actual).getSessionToken());
+ }
+
+ private AWSCredentials readCredential(Credential credential) {
+ Credential[] credentials = new Credential[] {credential};
+ String handle = InMemoryFileSystemCredentialsProvider.register(credentials);
+ try {
+ Configuration conf = new Configuration(false);
+ Map<String, String> credentialConf =
+ new S3FileSystemProvider().getFileSystemCredentialConf(credentials);
+ credentialConf.forEach(conf::set);
+ conf.set(
+ GravitinoFileSystemCredentialsProvider.GVFS_CREDENTIAL_PROVIDER,
+ InMemoryFileSystemCredentialsProvider.class.getCanonicalName());
+ conf.set(InMemoryFileSystemCredentialsProvider.CREDENTIAL_HANDLE, handle);
+ Assertions.assertEquals(
+ S3CredentialsProvider.class.getCanonicalName(),
+ conf.get(Constants.AWS_CREDENTIALS_PROVIDER));
+
+ return new S3CredentialsProvider(S3_URI, conf).getCredentials();
+ } finally {
+ InMemoryFileSystemCredentialsProvider.unregister(handle);
+ }
+ }
+}
diff --git a/bundles/azure/build.gradle.kts b/bundles/azure/build.gradle.kts
index 031c7c5e8c..6c38c51764 100644
--- a/bundles/azure/build.gradle.kts
+++ b/bundles/azure/build.gradle.kts
@@ -45,6 +45,10 @@ dependencies {
compileOnly(libs.hadoop3.client.api)
testImplementation(libs.azure.identity)
+ testImplementation(libs.azure.storage.file.datalake)
+ testImplementation(libs.hadoop3.abs)
+ testImplementation(libs.hadoop3.client.api)
+ testImplementation(libs.hadoop3.client.runtime)
testImplementation(libs.junit.jupiter.api)
testImplementation(libs.junit.jupiter.params)
testRuntimeOnly(libs.junit.jupiter.engine)
diff --git a/bundles/azure/src/test/java/org/apache/gravitino/abs/fs/TestAzureCredentialVending.java b/bundles/azure/src/test/java/org/apache/gravitino/abs/fs/TestAzureCredentialVending.java
new file mode 100644
index 0000000000..e295c89ca7
--- /dev/null
+++ b/bundles/azure/src/test/java/org/apache/gravitino/abs/fs/TestAzureCredentialVending.java
@@ -0,0 +1,86 @@
+/*
+ * 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.abs.fs;
+
+import static org.apache.hadoop.fs.azurebfs.constants.ConfigurationKeys.FS_AZURE_ACCOUNT_AUTH_TYPE_PROPERTY_NAME;
+import static org.apache.hadoop.fs.azurebfs.constants.ConfigurationKeys.FS_AZURE_SAS_TOKEN_PROVIDER_TYPE;
+
+import java.io.IOException;
+import java.util.Map;
+import org.apache.gravitino.catalog.hadoop.fs.GravitinoFileSystemCredentialsProvider;
+import org.apache.gravitino.catalog.hadoop.fs.InMemoryFileSystemCredentialsProvider;
+import org.apache.gravitino.credential.ADLSTokenCredential;
+import org.apache.gravitino.credential.AzureAccountKeyCredential;
+import org.apache.gravitino.credential.Credential;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.azurebfs.services.AuthType;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+/** Tests the credential configuration and in-memory vending paths for Azure credentials. */
+public class TestAzureCredentialVending {
+
+ private static final String ACCOUNT_NAME = "testaccount";
+ private static final String ACCOUNT_HOST = ACCOUNT_NAME + ".dfs.core.windows.net";
+
+ @Test
+ void testAccountKeyCredential() {
+ AzureAccountKeyCredential credential =
+ new AzureAccountKeyCredential(ACCOUNT_NAME, "account-key");
+
+ Map<String, String> credentialConf =
+ new AzureFileSystemProvider().getFileSystemCredentialConf(new Credential[] {credential});
+
+ Assertions.assertEquals(
+ "account-key", credentialConf.get("fs.azure.account.key." + ACCOUNT_HOST));
+ }
+
+ @Test
+ void testAdlsTokenCredential() throws IOException {
+ ADLSTokenCredential credential =
+ new ADLSTokenCredential(ACCOUNT_NAME, "sas-token", System.currentTimeMillis() + 60_000L);
+ Credential[] credentials = new Credential[] {credential};
+ String handle = InMemoryFileSystemCredentialsProvider.register(credentials);
+ try {
+ Configuration conf = new Configuration(false);
+ Map<String, String> credentialConf =
+ new AzureFileSystemProvider().getFileSystemCredentialConf(credentials);
+ credentialConf.forEach(conf::set);
+ conf.set(
+ GravitinoFileSystemCredentialsProvider.GVFS_CREDENTIAL_PROVIDER,
+ InMemoryFileSystemCredentialsProvider.class.getCanonicalName());
+ conf.set(InMemoryFileSystemCredentialsProvider.CREDENTIAL_HANDLE, handle);
+
+ Assertions.assertEquals(
+ AuthType.SAS.name(),
+ conf.get(FS_AZURE_ACCOUNT_AUTH_TYPE_PROPERTY_NAME + "." + ACCOUNT_HOST));
+ Assertions.assertEquals(
+ AzureSasCredentialsProvider.class.getName(),
+ conf.get(FS_AZURE_SAS_TOKEN_PROVIDER_TYPE + "." + ACCOUNT_HOST));
+
+ AzureSasCredentialsProvider provider = new AzureSasCredentialsProvider();
+ provider.initialize(conf, ACCOUNT_HOST);
+ Assertions.assertEquals(
+ "sas-token", provider.getSASToken(ACCOUNT_HOST, "container", "path", "list"));
+ } finally {
+ InMemoryFileSystemCredentialsProvider.unregister(handle);
+ }
+ }
+}
diff --git a/bundles/gcp/build.gradle.kts b/bundles/gcp/build.gradle.kts
index 80658d352a..bf99bbfda9 100644
--- a/bundles/gcp/build.gradle.kts
+++ b/bundles/gcp/build.gradle.kts
@@ -43,6 +43,10 @@ dependencies {
compileOnly(libs.hadoop3.gcs)
compileOnly(libs.google.auth.http)
+ testImplementation(libs.google.auth.http)
+ testImplementation(libs.hadoop3.client.api)
+ testImplementation(libs.hadoop3.client.runtime)
+ testImplementation(libs.hadoop3.gcs)
testImplementation(libs.junit.jupiter.api)
testImplementation(libs.junit.jupiter.params)
testRuntimeOnly(libs.junit.jupiter.engine)
diff --git a/bundles/gcp/src/test/java/org/apache/gravitino/gcs/fs/TestGCSCredentialVending.java b/bundles/gcp/src/test/java/org/apache/gravitino/gcs/fs/TestGCSCredentialVending.java
new file mode 100644
index 0000000000..75e878817a
--- /dev/null
+++ b/bundles/gcp/src/test/java/org/apache/gravitino/gcs/fs/TestGCSCredentialVending.java
@@ -0,0 +1,64 @@
+/*
+ * 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.gcs.fs;
+
+import com.google.cloud.hadoop.util.AccessTokenProvider.AccessToken;
+import java.util.Map;
+import org.apache.gravitino.catalog.hadoop.fs.GravitinoFileSystemCredentialsProvider;
+import org.apache.gravitino.catalog.hadoop.fs.InMemoryFileSystemCredentialsProvider;
+import org.apache.gravitino.credential.Credential;
+import org.apache.gravitino.credential.GCSTokenCredential;
+import org.apache.hadoop.conf.Configuration;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+/** Tests the complete in-memory credential vending path for GCS access tokens. */
+public class TestGCSCredentialVending {
+
+ @Test
+ void testTokenCredential() {
+ long expirationTime = System.currentTimeMillis() + 60_000L;
+ GCSTokenCredential credential = new GCSTokenCredential("access-token", expirationTime);
+ Credential[] credentials = new Credential[] {credential};
+ String handle = InMemoryFileSystemCredentialsProvider.register(credentials);
+ try {
+ Configuration conf = new Configuration(false);
+ Map<String, String> credentialConf =
+ new GCSFileSystemProvider().getFileSystemCredentialConf(credentials);
+ credentialConf.forEach(conf::set);
+ conf.set(
+ GravitinoFileSystemCredentialsProvider.GVFS_CREDENTIAL_PROVIDER,
+ InMemoryFileSystemCredentialsProvider.class.getCanonicalName());
+ conf.set(InMemoryFileSystemCredentialsProvider.CREDENTIAL_HANDLE, handle);
+ Assertions.assertEquals(
+ GCSCredentialsProvider.class.getName(),
+ conf.get("fs.gs.auth.access.token.provider.impl"));
+
+ GCSCredentialsProvider provider = new GCSCredentialsProvider();
+ provider.setConf(conf);
+ AccessToken actual = provider.getAccessToken();
+
+ Assertions.assertEquals("access-token", actual.getToken());
+ Assertions.assertEquals(expirationTime, actual.getExpirationTimeMilliSeconds());
+ } finally {
+ InMemoryFileSystemCredentialsProvider.unregister(handle);
+ }
+ }
+}
diff --git a/bundles/tencent/src/test/java/org/apache/gravitino/cos/fs/TestCOSCredentialsProvider.java b/bundles/tencent/src/test/java/org/apache/gravitino/cos/fs/TestCOSCredentialsProvider.java
index f1b1244bec..76ff4d1d11 100644
--- a/bundles/tencent/src/test/java/org/apache/gravitino/cos/fs/TestCOSCredentialsProvider.java
+++ b/bundles/tencent/src/test/java/org/apache/gravitino/cos/fs/TestCOSCredentialsProvider.java
@@ -24,9 +24,11 @@ import com.qcloud.cos.auth.COSCredentials;
import java.net.URI;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.gravitino.catalog.hadoop.fs.GravitinoFileSystemCredentialsProvider;
+import org.apache.gravitino.catalog.hadoop.fs.InMemoryFileSystemCredentialsProvider;
import org.apache.gravitino.credential.COSSecretKeyCredential;
import org.apache.gravitino.credential.Credential;
import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.CosNConfigKeys;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
@@ -68,6 +70,30 @@ public class TestCOSCredentialsProvider {
Assertions.assertEquals("test-sk", credentials.getCOSSecretKey());
}
+ @Test
+ void testRefreshWithInMemoryCredentialProvider() {
+ Credential[] credentials = new Credential[] {new COSSecretKeyCredential("test-ak", "test-sk")};
+ String handle = InMemoryFileSystemCredentialsProvider.register(credentials);
+ try {
+ Configuration conf = new Configuration(false);
+ conf.set(
+ GravitinoFileSystemCredentialsProvider.GVFS_CREDENTIAL_PROVIDER,
+ InMemoryFileSystemCredentialsProvider.class.getCanonicalName());
+ conf.set(InMemoryFileSystemCredentialsProvider.CREDENTIAL_HANDLE, handle);
+ new COSFileSystemProvider().getFileSystemCredentialConf(credentials).forEach(conf::set);
+ Assertions.assertEquals(
+ COSCredentialsProvider.class.getCanonicalName(),
+ conf.get(CosNConfigKeys.COSN_CREDENTIALS_PROVIDER));
+
+ COSCredentials actual = new COSCredentialsProvider(COS_URI, conf).getCredentials();
+
+ Assertions.assertEquals("test-ak", actual.getCOSAccessKeyId());
+ Assertions.assertEquals("test-sk", actual.getCOSSecretKey());
+ } finally {
+ InMemoryFileSystemCredentialsProvider.unregister(handle);
+ }
+ }
+
@Test
void testRefreshThrowsWhenNoSuitableCredential() {
// No COSSecretKeyCredential in the array -> COSUtils#getSuitableCredential returns null
diff --git a/catalogs/catalog-fileset/src/main/java/org/apache/gravitino/catalog/fileset/FilesetCatalogImpl.java b/catalogs/catalog-fileset/src/main/java/org/apache/gravitino/catalog/fileset/FilesetCatalogImpl.java
index 4402e45127..c264a29787 100644
--- a/catalogs/catalog-fileset/src/main/java/org/apache/gravitino/catalog/fileset/FilesetCatalogImpl.java
+++ b/catalogs/catalog-fileset/src/main/java/org/apache/gravitino/catalog/fileset/FilesetCatalogImpl.java
@@ -48,7 +48,7 @@ public class FilesetCatalogImpl extends BaseCatalog<FilesetCatalogImpl> {
@Override
protected CatalogOperations newOps(Map<String, String> config) {
- return new FilesetCatalogOperations();
+ return new FilesetCatalogOperations(this::catalogCredentialManager);
}
@Override
diff --git a/catalogs/catalog-fileset/src/main/java/org/apache/gravitino/catalog/fileset/FilesetCatalogOperations.java b/catalogs/catalog-fileset/src/main/java/org/apache/gravitino/catalog/fileset/FilesetCatalogOperations.java
index ea5b32edde..95f037cf96 100644
--- a/catalogs/catalog-fileset/src/main/java/org/apache/gravitino/catalog/fileset/FilesetCatalogOperations.java
+++ b/catalogs/catalog-fileset/src/main/java/org/apache/gravitino/catalog/fileset/FilesetCatalogOperations.java
@@ -37,18 +37,22 @@ import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
+import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.Instant;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledThreadPoolExecutor;
@@ -56,12 +60,12 @@ import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
-import org.apache.gravitino.Catalog;
import org.apache.gravitino.Entity;
import org.apache.gravitino.EntityStore;
import org.apache.gravitino.GravitinoEnv;
@@ -77,15 +81,22 @@ import org.apache.gravitino.catalog.FilesetFileOps;
import org.apache.gravitino.catalog.ManagedSchemaOperations;
import org.apache.gravitino.catalog.hadoop.fs.FileSystemProvider;
import org.apache.gravitino.catalog.hadoop.fs.FileSystemUtils;
+import org.apache.gravitino.catalog.hadoop.fs.GravitinoFileSystemCredentialsProvider;
+import org.apache.gravitino.catalog.hadoop.fs.InMemoryFileSystemCredentialsProvider;
+import org.apache.gravitino.catalog.hadoop.fs.SupportsCredentialVending;
import org.apache.gravitino.connector.CatalogInfo;
import org.apache.gravitino.connector.CatalogOperations;
import org.apache.gravitino.connector.HasPropertyMetadata;
import org.apache.gravitino.connector.credential.PathContext;
import org.apache.gravitino.connector.credential.SupportsPathBasedCredentials;
+import org.apache.gravitino.credential.CatalogCredentialManager;
+import org.apache.gravitino.credential.Credential;
import org.apache.gravitino.credential.CredentialConstants;
import org.apache.gravitino.credential.CredentialUtils;
+import org.apache.gravitino.credential.PathBasedCredentialContext;
import org.apache.gravitino.dto.file.FileInfoDTO;
import org.apache.gravitino.exceptions.AlreadyExistsException;
+import org.apache.gravitino.exceptions.ConnectionFailedException;
import org.apache.gravitino.exceptions.FilesetAlreadyExistsException;
import org.apache.gravitino.exceptions.GravitinoRuntimeException;
import org.apache.gravitino.exceptions.NoSuchCatalogException;
@@ -113,6 +124,7 @@ import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.RemoteIterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -121,6 +133,9 @@ public class FilesetCatalogOperations extends ManagedSchemaOperations
private static final String SCHEMA_DOES_NOT_EXIST_MSG = "Schema %s does not exist";
private static final String FILESET_DOES_NOT_EXIST_MSG = "Fileset %s does not exist";
private static final String SLASH = "/";
+ private static final String CATALOG_PLACEHOLDER = "{{catalog}}";
+ private static final String PROBE_UNSUPPORTED = "probe unsupported";
+ private static final String PROBE_UNSUPPORTED_DETAIL_PREFIX = PROBE_UNSUPPORTED + ":";
// location placeholder pattern format: {{placeholder}}
private static final Pattern LOCATION_PLACEHOLDER_PATTERN = Pattern.compile("\\{\\{(.*?)\\}\\}");
@@ -130,6 +145,8 @@ public class FilesetCatalogOperations extends ManagedSchemaOperations
private final SecretManager secretManager;
+ @Nullable private final Supplier<CatalogCredentialManager> credentialManagerSupplier;
+
private HasPropertyMetadata propertiesMetadata;
@VisibleForTesting Configuration hadoopConf;
@@ -172,8 +189,23 @@ public class FilesetCatalogOperations extends ManagedSchemaOperations
};
FilesetCatalogOperations(EntityStore store, SecretManager secretManager) {
+ this(store, secretManager, null);
+ }
+
+ FilesetCatalogOperations(
+ EntityStore store,
+ SecretManager secretManager,
+ @Nullable Supplier<CatalogCredentialManager> credentialManagerSupplier) {
this.store = store;
this.secretManager = secretManager;
+ this.credentialManagerSupplier = credentialManagerSupplier;
+ }
+
+ FilesetCatalogOperations(Supplier<CatalogCredentialManager> credentialManagerSupplier) {
+ this(
+ GravitinoEnv.getInstance().entityStore(),
+ GravitinoEnv.getInstance().secretManager(),
+ credentialManagerSupplier);
}
static class FileSystemCacheKey {
@@ -219,7 +251,8 @@ public class FilesetCatalogOperations extends ManagedSchemaOperations
}
public FilesetCatalogOperations() {
- this(GravitinoEnv.getInstance().entityStore(), GravitinoEnv.getInstance().secretManager());
+ this(
+ GravitinoEnv.getInstance().entityStore(), GravitinoEnv.getInstance().secretManager(), null);
}
@Override
@@ -951,24 +984,39 @@ public class FilesetCatalogOperations extends ManagedSchemaOperations
}
}
- /**
- * Since the Fileset catalog was completely managed by Gravitino, we don't need to test the
- * connection
- *
- * @param catalogIdent the name of the catalog.
- * @param type the type of the catalog.
- * @param provider the provider of the catalog.
- * @param comment the comment of the catalog.
- * @param properties the properties of the catalog.
- */
@Override
- public void testConnection(
- NameIdentifier catalogIdent,
- Catalog.Type type,
- String provider,
- String comment,
- Map<String, String> properties) {
- // Do nothing
+ public void testConnection(NameIdentifier catalogIdent) {
+ if (disableFSOps) {
+ throw new UnsupportedOperationException(
+ "Fileset connection testing requires filesystem operations to be enabled");
+ }
+ if (catalogStorageLocations.isEmpty()) {
+ throw new IllegalArgumentException("Fileset catalog has no catalog-level location to test");
+ }
+
+ List<String> failures = new ArrayList<>();
+ catalogStorageLocations.forEach(
+ (locationName, location) -> {
+ try {
+ Path path = resolveProbeLocation(location.toString(), catalogIdent);
+ probeLocation(path);
+ } catch (Exception e) {
+ String displayName = displayLocationName(locationName);
+ String failure = failureDescription(e);
+ LOG.warn(
+ "Fileset catalog connection probe failed for catalog {} at {} ({})",
+ catalogIdent,
+ displayName,
+ failure,
+ e);
+ failures.add(displayName + " (" + failure + ")");
+ }
+ });
+
+ if (!failures.isEmpty()) {
+ throw new ConnectionFailedException(
+ "Failed to test Fileset catalog connection: %s", String.join("; ", failures));
+ }
}
@Override
@@ -1073,7 +1121,7 @@ public class FilesetCatalogOperations extends ManagedSchemaOperations
if (!disableFSOps && !containsPlaceholder(v)) {
Path path = new Path(v);
// At catalog initialization, only merge catalog config and user-defined location
- // configs
+ // configs.
Map<String, String> fsConf = new HashMap<>(conf);
fsConf.putAll(
FilesetUtil.getUserDefinedFileSystemConfigs(
@@ -1394,23 +1442,10 @@ public class FilesetCatalogOperations extends ManagedSchemaOperations
.getOrDefault(
config, FilesetCatalogPropertiesMetadata.FILESYSTEM_CONNECTION_TIMEOUT_SECONDS);
- Future<FileSystem> fileSystemFuture =
- fileSystemExecutor.submit(
- () -> {
- if (scheme.equals(SCHEME_HDFS)) {
- return new ImpersonationHDFSFileSystemProxy(
- path, config, PrincipalUtils::getCurrentUserName)
- .getProxy();
- } else {
- return provider.getFileSystem(path, config);
- }
- });
-
try {
- return fileSystemFuture.get(timeoutSeconds, TimeUnit.SECONDS);
+ return executeFileSystemTask(
+ () -> createFileSystem(path, config, scheme, provider), timeoutSeconds);
} catch (TimeoutException e) {
- fileSystemFuture.cancel(true);
-
LOG.warn(
"Timeout when getting FileSystem for path: {}, scheme: {}, provider: {} within {} seconds",
path,
@@ -1431,7 +1466,6 @@ public class FilesetCatalogOperations extends ManagedSchemaOperations
FilesetCatalogPropertiesMetadata.FILESYSTEM_CONNECTION_TIMEOUT_SECONDS),
e);
} catch (InterruptedException e) {
- Thread.currentThread().interrupt();
LOG.warn(
"Interrupted when getting FileSystem for path: {}, possibly the server is"
+ " shutting down or catalog is been dropped",
@@ -1446,6 +1480,250 @@ public class FilesetCatalogOperations extends ManagedSchemaOperations
}
}
+ private <T> T executeFileSystemTask(Callable<T> task, int timeoutSeconds)
+ throws InterruptedException, ExecutionException, TimeoutException {
+ Future<T> future = fileSystemExecutor.submit(task);
+ try {
+ return future.get(timeoutSeconds, TimeUnit.SECONDS);
+ } catch (TimeoutException e) {
+ future.cancel(true);
+ throw e;
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw e;
+ }
+ }
+
+ @VisibleForTesting
+ Path resolveProbeLocation(String location, NameIdentifier catalogIdent) {
+ String resolved = location.replace(CATALOG_PLACEHOLDER, catalogIdent.name());
+ Matcher matcher = LOCATION_PLACEHOLDER_PATTERN.matcher(resolved);
+ List<String> unresolvedPlaceholders = new ArrayList<>();
+ while (matcher.find()) {
+ unresolvedPlaceholders.add(matcher.group());
+ }
+ if (!unresolvedPlaceholders.isEmpty()) {
+ String placeholderLabel =
+ unresolvedPlaceholders.size() == 1
+ ? "unresolved placeholder "
+ : "unresolved placeholders ";
+ throw new ProbeUnsupportedException(
+ PROBE_UNSUPPORTED_DETAIL_PREFIX
+ + " "
+ + placeholderLabel
+ + String.join(", ", unresolvedPlaceholders)
+ + " in "
+ + resolved
+ + "; no filesystem path was tested");
+ }
+
+ if (StringUtils.isBlank(resolved)) {
+ throw new InvalidProbeLocationException(
+ "Fileset catalog location has no valid concrete target that can be tested");
+ }
+
+ try {
+ return new Path(resolved);
+ } catch (IllegalArgumentException e) {
+ throw new InvalidProbeLocationException(
+ "Fileset catalog location has no valid concrete target that can be tested", e);
+ }
+ }
+
+ private void probeLocation(Path path) throws Exception {
+ Map<String, String> probeConf = new HashMap<>(conf);
+ probeConf.putAll(
+ FilesetUtil.getUserDefinedFileSystemConfigs(
+ path.toUri(),
+ probeConf,
+ FilesetCatalogPropertiesMetadata.FS_GRAVITINO_PATH_CONFIG_PREFIX));
+
+ String scheme =
+ path.toUri().getScheme() != null
+ ? path.toUri().getScheme()
+ : defaultFileSystemProvider.scheme();
+ FileSystemProvider fileSystemProvider = fileSystemProvidersMap.get(scheme);
+ if (fileSystemProvider == null) {
+ throw new UnsupportedOperationException(
+ String.format("Fileset connection testing does not support scheme %s", scheme));
+ }
+
+ String credentialHandle = null;
+ try {
+ credentialHandle = addVendedCredential(path, scheme, fileSystemProvider, probeConf);
+ int timeoutSeconds =
+ (int)
+ propertiesMetadata
+ .catalogPropertiesMetadata()
+ .getOrDefault(
+ probeConf,
+ FilesetCatalogPropertiesMetadata.FILESYSTEM_CONNECTION_TIMEOUT_SECONDS);
+ executeFileSystemTask(
+ () -> {
+ try (FileSystem fileSystem =
+ createFileSystem(path, probeConf, scheme, fileSystemProvider)) {
+ Path qualifiedPath =
+ path.makeQualified(fileSystem.getUri(), fileSystem.getWorkingDirectory());
+ try {
+ RemoteIterator<FileStatus> iterator = fileSystem.listStatusIterator(qualifiedPath);
+ if (iterator.hasNext()) {
+ FileStatus first = iterator.next();
+ if (first.isFile() && first.getPath().equals(qualifiedPath)) {
+ throw new ProbeLocationNotDirectoryException(
+ "Fileset catalog location must be a directory");
+ }
+ }
+ } catch (FileNotFoundException ignored) {
+ // A catalog location may be created later by schema or fileset operations.
+ }
+ return null;
+ }
+ },
+ timeoutSeconds);
+ } catch (TimeoutException e) {
+ throw new IOException("Filesystem connection probe timed out", e);
+ } catch (InterruptedException e) {
+ throw new IOException("Filesystem connection probe was interrupted", e);
+ } catch (ExecutionException e) {
+ Throwable cause = e.getCause();
+ if (cause instanceof Exception) {
+ throw (Exception) cause;
+ }
+ throw new IOException("Filesystem connection probe failed", cause);
+ } finally {
+ InMemoryFileSystemCredentialsProvider.unregister(credentialHandle);
+ }
+ }
+
+ @Nullable
+ private String addVendedCredential(
+ Path path,
+ String scheme,
+ FileSystemProvider fileSystemProvider,
+ Map<String, String> probeConf) {
+ Set<String> credentialTypes = CredentialUtils.getCredentialProvidersByOrder(() -> conf);
+ if (credentialTypes.isEmpty()) {
+ return null;
+ }
+
+ CatalogCredentialManager manager = catalogCredentialManager();
+ List<String> matchingTypes =
+ credentialTypes.stream()
+ .filter(
+ type ->
+ manager
+ .getCredentialProvider(type)
+ .map(provider -> provider.supportsScheme(scheme))
+ .orElse(false))
+ .collect(Collectors.toList());
+ if (matchingTypes.isEmpty()) {
+ return null;
+ }
+ if (!(fileSystemProvider instanceof SupportsCredentialVending)) {
+ throw new UnsupportedOperationException(
+ String.format("Filesystem provider for scheme %s cannot use vended credentials", scheme));
+ }
+
+ PathBasedCredentialContext context =
+ new PathBasedCredentialContext(
+ PrincipalUtils.getCurrentUserName(),
+ Collections.emptySet(),
+ Collections.singleton(path.toString()));
+ Credential[] credentials =
+ matchingTypes.stream()
+ .map(type -> manager.getCredential(type, context))
+ .filter(Optional::isPresent)
+ .map(Optional::get)
+ .toArray(Credential[]::new);
+ if (credentials.length == 0) {
+ throw new ConnectionFailedException(
+ "Credential providers returned no credential for Fileset connection test");
+ }
+ String handle = InMemoryFileSystemCredentialsProvider.register(credentials);
+ try {
+ probeConf.put(
+ GravitinoFileSystemCredentialsProvider.GVFS_CREDENTIAL_PROVIDER,
+ InMemoryFileSystemCredentialsProvider.class.getCanonicalName());
+ probeConf.put(InMemoryFileSystemCredentialsProvider.CREDENTIAL_HANDLE, handle);
+ probeConf.putAll(
+ ((SupportsCredentialVending) fileSystemProvider)
+ .getFileSystemCredentialConf(credentials));
+ return handle;
+ } catch (RuntimeException e) {
+ InMemoryFileSystemCredentialsProvider.unregister(handle);
+ throw e;
+ }
+ }
+
+ @VisibleForTesting
+ CatalogCredentialManager catalogCredentialManager() {
+ Preconditions.checkState(
+ credentialManagerSupplier != null,
+ "Catalog credential manager is not available for Fileset connection testing");
+ return Objects.requireNonNull(
+ credentialManagerSupplier.get(), "Catalog credential manager must not be null");
+ }
+
+ private FileSystem createFileSystem(
+ Path path, Map<String, String> config, String scheme, FileSystemProvider provider)
+ throws IOException {
+ if (scheme.equals(SCHEME_HDFS)) {
+ return new ImpersonationHDFSFileSystemProxy(path, config, PrincipalUtils::getCurrentUserName)
+ .getProxy();
+ }
+ return provider.getFileSystem(path, config);
+ }
+
+ private String displayLocationName(String locationName) {
+ return LOCATION_NAME_UNKNOWN.equals(locationName) ? "location" : "location-" + locationName;
+ }
+
+ private String failureDescription(Throwable throwable) {
+ Throwable current = throwable;
+ while (current != null) {
+ if (current instanceof ProbeUnsupportedException) {
+ return current.getMessage();
+ }
+ current = current.getCause();
+ }
+ return failureCategory(throwable);
+ }
+
+ private String failureCategory(Throwable throwable) {
+ Throwable current = throwable;
+ while (current != null) {
+ String simpleName = current.getClass().getSimpleName().toLowerCase(Locale.ROOT);
+ String message =
+ Optional.ofNullable(current.getMessage()).orElse("").toLowerCase(Locale.ROOT);
+ if (current instanceof ProbeLocationNotDirectoryException) {
+ return "location is not a directory";
+ }
+ if (current instanceof InvalidProbeLocationException) {
+ return "invalid location configuration";
+ }
+ if (current instanceof TimeoutException || message.contains("timed out")) {
+ return "timeout";
+ }
+ if (simpleName.contains("accessdenied")
+ || simpleName.contains("forbidden")
+ || message.contains("permission denied")
+ || message.contains("access denied")) {
+ return "access denied";
+ }
+ if (simpleName.contains("filenotfound") || simpleName.contains("notfound")) {
+ return "location not found";
+ }
+ if (current instanceof ConnectionFailedException) {
+ return "credential generation failed";
+ }
+ if (current instanceof UnsupportedOperationException) {
+ return PROBE_UNSUPPORTED;
+ }
+ current = current.getCause();
+ }
+ return "probe failed";
+ }
+
private String getFileLocation(Fileset fileset, String subPath, String locationName) {
Preconditions.checkArgument(subPath != null, "subPath must not be null");
String processedSubPath;
@@ -1618,4 +1896,29 @@ public class FilesetCatalogOperations extends ManagedSchemaOperations
fileset.name());
return targetLocation;
}
+
+ private static final class InvalidProbeLocationException extends IllegalArgumentException {
+
+ private InvalidProbeLocationException(String message) {
+ super(message);
+ }
+
+ private InvalidProbeLocationException(String message, Throwable cause) {
+ super(message, cause);
+ }
+ }
+
+ private static final class ProbeLocationNotDirectoryException extends IllegalArgumentException {
+
+ private ProbeLocationNotDirectoryException(String message) {
+ super(message);
+ }
+ }
+
+ private static final class ProbeUnsupportedException extends UnsupportedOperationException {
+
+ private ProbeUnsupportedException(String message) {
+ super(message);
+ }
+ }
}
diff --git a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.java b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.java
index 07416f2def..f96f7fb9bd 100644
--- a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.java
+++ b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.java
@@ -68,6 +68,7 @@ import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.io.FileUtils;
@@ -90,11 +91,15 @@ import org.apache.gravitino.audit.FilesetDataOperation;
import org.apache.gravitino.catalog.hadoop.fs.FileSystemProvider;
import org.apache.gravitino.catalog.hadoop.fs.FileSystemUtils;
import org.apache.gravitino.catalog.hadoop.fs.LocalFileSystemProvider;
+import org.apache.gravitino.catalog.hadoop.fs.SupportsCredentialVending;
import org.apache.gravitino.connector.CatalogInfo;
import org.apache.gravitino.connector.HasPropertyMetadata;
import org.apache.gravitino.connector.PropertiesMetadata;
import org.apache.gravitino.connector.PropertyEntry;
+import org.apache.gravitino.credential.CatalogCredentialManager;
+import org.apache.gravitino.credential.Credential;
import org.apache.gravitino.credential.CredentialConstants;
+import org.apache.gravitino.exceptions.ConnectionFailedException;
import org.apache.gravitino.exceptions.GravitinoRuntimeException;
import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.exceptions.NoSuchFilesetException;
@@ -1380,16 +1385,380 @@ public class TestFilesetCatalogOperations {
}
@Test
- public void testTestConnection() {
- FilesetCatalogOperations catalogOperations = new FilesetCatalogOperations(store, secretManager);
- Assertions.assertDoesNotThrow(
- () ->
- catalogOperations.testConnection(
- NameIdentifier.of("metalake", "catalog"),
- Catalog.Type.FILESET,
- "fileset",
- "comment",
- ImmutableMap.of()));
+ public void testTestConnection() throws IOException {
+ File firstLocation = new File(UNFORMALIZED_TEST_ROOT_PATH, "connection/first");
+ File secondLocation = new File(UNFORMALIZED_TEST_ROOT_PATH, "connection/second");
+ FileUtils.forceMkdir(firstLocation);
+ FileUtils.forceMkdir(secondLocation);
+
+ Map<String, String> properties = new HashMap<>();
+ properties.put(LOCATION, firstLocation.toURI().toString());
+ properties.put(
+ PROPERTY_MULTIPLE_LOCATIONS_PREFIX + "archive", secondLocation.toURI().toString());
+
+ try (FilesetCatalogOperations catalogOperations =
+ new FilesetCatalogOperations(store, secretManager)) {
+ catalogOperations.initialize(
+ properties, randomCatalogInfo("metalake", "catalog"), FILESET_PROPERTIES_METADATA);
+ Assertions.assertDoesNotThrow(
+ () -> catalogOperations.testConnection(NameIdentifier.of("metalake", "catalog")));
+ }
+ }
+
+ @Test
+ public void testResolveProbeLocationAllowsSchemeWithoutAuthority() throws IOException {
+ try (FilesetCatalogOperations catalogOperations =
+ new FilesetCatalogOperations(store, secretManager)) {
+ Path path =
+ catalogOperations.resolveProbeLocation(
+ "hdfs:///warehouse", NameIdentifier.of("metalake", "catalog"));
+
+ Assertions.assertEquals("hdfs", path.toUri().getScheme());
+ Assertions.assertNull(path.toUri().getAuthority());
+ Assertions.assertEquals("/warehouse", path.toUri().getPath());
+ }
+ }
+
+ @Test
+ public void testResolveProbeLocationReportsUnresolvedPlaceholderInAuthority() throws IOException {
+ try (FilesetCatalogOperations catalogOperations =
+ new FilesetCatalogOperations(store, secretManager)) {
+ UnsupportedOperationException exception =
+ Assertions.assertThrows(
+ UnsupportedOperationException.class,
+ () ->
+ catalogOperations.resolveProbeLocation(
+ "s3a://bucket{{schema}}", NameIdentifier.of("metalake", "catalog")));
+
+ Assertions.assertEquals(
+ "probe unsupported: unresolved placeholder {{schema}} in s3a://bucket{{schema}}; no "
+ + "filesystem path was tested",
+ exception.getMessage());
+ }
+ }
+
+ @Test
+ public void testInitializeRejectsNamedCatalogLocationThatIsAFile() throws IOException {
+ File fileLocation = new File(UNFORMALIZED_TEST_ROOT_PATH, "connection/file-location");
+ FileUtils.forceMkdir(fileLocation.getParentFile());
+ FileUtils.touch(fileLocation);
+
+ Map<String, String> properties =
+ ImmutableMap.of(
+ PROPERTY_MULTIPLE_LOCATIONS_PREFIX + "archive", fileLocation.toURI().toString());
+
+ try (FilesetCatalogOperations catalogOperations =
+ new FilesetCatalogOperations(store, secretManager)) {
+ IllegalArgumentException exception =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ catalogOperations.initialize(
+ properties,
+ randomCatalogInfo("metalake", "catalog"),
+ FILESET_PROPERTIES_METADATA));
+ Assertions.assertTrue(
+ exception.getMessage().contains("Fileset catalog location cannot be a file"));
+ Assertions.assertTrue(exception.getMessage().contains("location name: archive"));
+ }
+ }
+
+ @Test
+ public void testTestConnectionRejectsDefaultCatalogLocationThatIsAFile() throws IOException {
+ File fileLocation = new File(UNFORMALIZED_TEST_ROOT_PATH, "connection/default-file-location");
+ FileUtils.forceMkdir(fileLocation.getParentFile());
+ FileUtils.touch(fileLocation);
+
+ Map<String, String> properties = ImmutableMap.of(LOCATION, fileLocation.toURI().toString());
+
+ try (FilesetCatalogOperations catalogOperations =
+ new FilesetCatalogOperations(store, secretManager)) {
+ catalogOperations.initialize(
+ properties, randomCatalogInfo("metalake", "catalog"), FILESET_PROPERTIES_METADATA);
+ ConnectionFailedException exception =
+ Assertions.assertThrows(
+ ConnectionFailedException.class,
+ () -> catalogOperations.testConnection(NameIdentifier.of("metalake", "catalog")));
+ Assertions.assertTrue(
+ exception.getMessage().contains("location (location is not a directory)"));
+ Assertions.assertFalse(exception.getMessage().contains(fileLocation.toURI().toString()));
+ }
+ }
+
+ @Test
+ public void testTestConnectionWithoutCatalogLocation() throws IOException {
+ try (FilesetCatalogOperations catalogOperations =
+ new FilesetCatalogOperations(store, secretManager)) {
+ catalogOperations.initialize(
+ ImmutableMap.of(), randomCatalogInfo("metalake", "catalog"), FILESET_PROPERTIES_METADATA);
+ IllegalArgumentException exception =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> catalogOperations.testConnection(NameIdentifier.of("metalake", "catalog")));
+ Assertions.assertTrue(exception.getMessage().contains("no catalog-level location"));
+ }
+ }
+
+ @Test
+ public void testTestConnectionWithFilesystemOperationsDisabled() throws IOException {
+ File fileLocation = new File(UNFORMALIZED_TEST_ROOT_PATH, "connection/disabled-file-location");
+ FileUtils.forceMkdir(fileLocation.getParentFile());
+ FileUtils.touch(fileLocation);
+
+ Map<String, String> properties =
+ ImmutableMap.of(
+ PROPERTY_MULTIPLE_LOCATIONS_PREFIX + "archive",
+ fileLocation.toURI().toString(),
+ DISABLE_FILESYSTEM_OPS,
+ "true");
+
+ try (FilesetCatalogOperations catalogOperations =
+ new FilesetCatalogOperations(store, secretManager)) {
+ Assertions.assertDoesNotThrow(
+ () ->
+ catalogOperations.initialize(
+ properties,
+ randomCatalogInfo("metalake", "catalog"),
+ FILESET_PROPERTIES_METADATA));
+ Assertions.assertThrows(
+ UnsupportedOperationException.class,
+ () -> catalogOperations.testConnection(NameIdentifier.of("metalake", "catalog")));
+ }
+ }
+
+ @Test
+ public void testTestConnectionResolvesCatalogPlaceholder() throws IOException {
+ File catalogLocation = new File(UNFORMALIZED_TEST_ROOT_PATH, "placeholder/catalog");
+ FileUtils.forceMkdir(catalogLocation);
+ String location =
+ new File(UNFORMALIZED_TEST_ROOT_PATH, "placeholder").toURI().toString() + "{{catalog}}";
+
+ try (FilesetCatalogOperations catalogOperations =
+ new FilesetCatalogOperations(store, secretManager)) {
+ catalogOperations.initialize(
+ ImmutableMap.of(LOCATION, location),
+ randomCatalogInfo("metalake", "catalog"),
+ FILESET_PROPERTIES_METADATA);
+ Assertions.assertDoesNotThrow(
+ () -> catalogOperations.testConnection(NameIdentifier.of("metalake", "catalog")));
+ }
+ }
+
+ @Test
+ public void testTestConnectionReportsUnresolvedPlaceholderWithoutProbingStaticParent()
+ throws IOException {
+ String location =
+ new File(UNFORMALIZED_TEST_ROOT_PATH, "placeholder").toURI().toString()
+ + "{{catalog}}/{{schema}}";
+ String resolvedLocation = location.replace("{{catalog}}", "catalog");
+
+ try (FilesetCatalogOperations catalogOperations =
+ new FilesetCatalogOperations(store, secretManager)) {
+ catalogOperations.initialize(
+ ImmutableMap.of(LOCATION, location),
+ randomCatalogInfo("metalake", "catalog"),
+ FILESET_PROPERTIES_METADATA);
+ ConnectionFailedException exception =
+ Assertions.assertThrows(
+ ConnectionFailedException.class,
+ () -> catalogOperations.testConnection(NameIdentifier.of("metalake", "catalog")));
+ Assertions.assertTrue(
+ exception
+ .getMessage()
+ .contains(
+ "location (probe unsupported: unresolved placeholder {{schema}} in "
+ + resolvedLocation
+ + "; no filesystem path was tested)"));
+ }
+ }
+
+ @Test
+ public void testTestConnectionAggregatesLocationFailures() throws IOException {
+ Map<String, String> properties =
+ ImmutableMap.of(
+ PROPERTY_MULTIPLE_LOCATIONS_PREFIX + "primary",
+ "unsupported://primary/{{catalog}}",
+ PROPERTY_MULTIPLE_LOCATIONS_PREFIX + "archive",
+ "unsupported://archive/{{catalog}}");
+
+ try (FilesetCatalogOperations catalogOperations =
+ new FilesetCatalogOperations(store, secretManager)) {
+ catalogOperations.initialize(
+ properties, randomCatalogInfo("metalake", "catalog"), FILESET_PROPERTIES_METADATA);
+ ConnectionFailedException exception =
+ Assertions.assertThrows(
+ ConnectionFailedException.class,
+ () -> catalogOperations.testConnection(NameIdentifier.of("metalake", "catalog")));
+ Assertions.assertTrue(
+ exception.getMessage().contains("location-primary (probe unsupported)"));
+ Assertions.assertTrue(
+ exception.getMessage().contains("location-archive (probe unsupported)"));
+ Assertions.assertFalse(exception.getMessage().contains("unsupported://"));
+ }
+ }
+
+ @Test
+ public void testTestConnectionAllowsMissingCatalogLocations() throws IOException {
+ String missingBase =
+ new File(UNFORMALIZED_TEST_ROOT_PATH, "missing-" + UUID.randomUUID()).toURI().toString();
+ Map<String, String> properties =
+ ImmutableMap.of(
+ LOCATION,
+ missingBase + "/default",
+ PROPERTY_MULTIPLE_LOCATIONS_PREFIX + "archive",
+ missingBase + "/archive");
+
+ try (FilesetCatalogOperations catalogOperations =
+ new FilesetCatalogOperations(store, secretManager)) {
+ catalogOperations.initialize(
+ properties, randomCatalogInfo("metalake", "catalog"), FILESET_PROPERTIES_METADATA);
+ Assertions.assertDoesNotThrow(
+ () -> catalogOperations.testConnection(NameIdentifier.of("metalake", "catalog")));
+ }
+ }
+
+ @Test
+ public void testTestConnectionAggregatesLocationResolutionAndProbeFailures() throws IOException {
+ String unsupportedLocation = "unsupported://archive/{{catalog}}";
+ Map<String, String> properties =
+ ImmutableMap.of(
+ PROPERTY_MULTIPLE_LOCATIONS_PREFIX + "primary",
+ "{{schema}}",
+ PROPERTY_MULTIPLE_LOCATIONS_PREFIX + "archive",
+ unsupportedLocation);
+
+ try (FilesetCatalogOperations catalogOperations =
+ new FilesetCatalogOperations(store, secretManager)) {
+ catalogOperations.initialize(
+ properties, randomCatalogInfo("metalake", "catalog"), FILESET_PROPERTIES_METADATA);
+ ConnectionFailedException exception =
+ Assertions.assertThrows(
+ ConnectionFailedException.class,
+ () -> catalogOperations.testConnection(NameIdentifier.of("metalake", "catalog")));
+ Assertions.assertTrue(
+ exception
+ .getMessage()
+ .contains(
+ "location-primary (probe unsupported: unresolved placeholder {{schema}} in "
+ + "{{schema}}; no filesystem path was tested)"));
+ Assertions.assertTrue(
+ exception.getMessage().contains("location-archive (probe unsupported)"));
+ Assertions.assertFalse(exception.getMessage().contains(unsupportedLocation));
+ }
+ }
+
+ @Test
+ public void testTestConnectionUsesVendedCredential() throws Exception {
+ File location = new File(UNFORMALIZED_TEST_ROOT_PATH, "credential-vending");
+ FileUtils.forceMkdir(location);
+ Map<String, String> properties =
+ ImmutableMap.of(
+ LOCATION,
+ location.toURI().toString(),
+ CredentialConstants.CREDENTIAL_PROVIDERS,
+ TestFilesetCredentialProvider.TYPE);
+ AtomicBoolean credentialObserved = new AtomicBoolean(false);
+
+ class CredentialAwareProvider extends LocalFileSystemProvider
+ implements SupportsCredentialVending {
+ @Override
+ public FileSystem getFileSystem(Path path, Map<String, String> config) throws IOException {
+ Configuration hadoopConfiguration = FileSystemUtils.createCompatibleConfiguration(config);
+ Credential[] credentials =
+ FileSystemUtils.getGvfsCredentialProvider(hadoopConfiguration).getCredentials();
+ Assertions.assertEquals(1, credentials.length);
+ Assertions.assertEquals(
+ TestFilesetCredentialProvider.TYPE, credentials[0].credentialType());
+ credentialObserved.set(true);
+ return super.getFileSystem(path, config);
+ }
+ }
+ FileSystemProvider provider = new CredentialAwareProvider();
+
+ try (CatalogCredentialManager credentialManager =
+ new CatalogCredentialManager("catalog", properties);
+ FilesetCatalogOperations catalogOperations =
+ new FilesetCatalogOperations(store, secretManager, () -> credentialManager)) {
+ catalogOperations.initialize(
+ properties, randomCatalogInfo("metalake", "catalog"), FILESET_PROPERTIES_METADATA);
+ FieldUtils.writeField(
+ catalogOperations, "fileSystemProvidersMap", ImmutableMap.of("file", provider), true);
+ catalogOperations.testConnection(NameIdentifier.of("metalake", "catalog"));
+ Assertions.assertTrue(credentialObserved.get());
+ }
+ }
+
+ @Test
+ public void testTestConnectionUsesMultipleMatchingCredentialProviders() throws Exception {
+ File location = new File(UNFORMALIZED_TEST_ROOT_PATH, "multiple-credential-providers");
+ FileUtils.forceMkdir(location);
+ Map<String, String> properties =
+ ImmutableMap.of(
+ LOCATION,
+ location.toURI().toString(),
+ CredentialConstants.CREDENTIAL_PROVIDERS,
+ TestFilesetCredentialProvider.TYPE + "," + TestFilesetSecondCredentialProvider.TYPE);
+ AtomicBoolean credentialsObserved = new AtomicBoolean(false);
+
+ class CredentialAwareProvider extends LocalFileSystemProvider
+ implements SupportsCredentialVending {
+ @Override
+ public FileSystem getFileSystem(Path path, Map<String, String> config) throws IOException {
+ Configuration hadoopConfiguration = FileSystemUtils.createCompatibleConfiguration(config);
+ Credential[] credentials =
+ FileSystemUtils.getGvfsCredentialProvider(hadoopConfiguration).getCredentials();
+ Assertions.assertEquals(2, credentials.length);
+ Assertions.assertEquals(
+ Set.of(TestFilesetCredentialProvider.TYPE, TestFilesetSecondCredentialProvider.TYPE),
+ Arrays.stream(credentials).map(Credential::credentialType).collect(Collectors.toSet()));
+ credentialsObserved.set(true);
+ return super.getFileSystem(path, config);
+ }
+ }
+ FileSystemProvider provider = new CredentialAwareProvider();
+
+ try (CatalogCredentialManager credentialManager =
+ new CatalogCredentialManager("catalog", properties);
+ FilesetCatalogOperations catalogOperations =
+ new FilesetCatalogOperations(store, secretManager, () -> credentialManager)) {
+ catalogOperations.initialize(
+ properties, randomCatalogInfo("metalake", "catalog"), FILESET_PROPERTIES_METADATA);
+ FieldUtils.writeField(
+ catalogOperations, "fileSystemProvidersMap", ImmutableMap.of("file", provider), true);
+ catalogOperations.testConnection(NameIdentifier.of("metalake", "catalog"));
+ Assertions.assertTrue(credentialsObserved.get());
+ }
+ }
+
+ @Test
+ public void testTestConnectionReportsUnsupportedLocationProbe() throws IOException {
+ String location = "unsupported://host/path";
+
+ try (FilesetCatalogOperations catalogOperations =
+ new FilesetCatalogOperations(store, secretManager)) {
+ catalogOperations.initialize(
+ ImmutableMap.of(LOCATION, location),
+ randomCatalogInfo("metalake", "catalog"),
+ FILESET_PROPERTIES_METADATA);
+ ConnectionFailedException exception =
+ Assertions.assertThrows(
+ ConnectionFailedException.class,
+ () -> catalogOperations.testConnection(NameIdentifier.of("metalake", "catalog")));
+ Assertions.assertTrue(exception.getMessage().contains("location (probe unsupported)"));
+ Assertions.assertFalse(exception.getMessage().contains(location));
+ }
+ }
+
+ @Test
+ void testCloseDoesNotCloseSharedCredentialManager() throws IOException {
+ CatalogCredentialManager credentialManager = Mockito.mock(CatalogCredentialManager.class);
+
+ try (FilesetCatalogOperations catalogOperations =
+ new FilesetCatalogOperations(store, secretManager, () -> credentialManager)) {
+ Assertions.assertSame(credentialManager, catalogOperations.catalogCredentialManager());
+ }
+
+ Mockito.verify(credentialManager, Mockito.never()).close();
}
@Test
diff --git a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCredentialProvider.java b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCredentialProvider.java
new file mode 100644
index 0000000000..2d21aaf2a5
--- /dev/null
+++ b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCredentialProvider.java
@@ -0,0 +1,79 @@
+/*
+ * 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.catalog.fileset;
+
+import java.util.Collections;
+import java.util.Map;
+import org.apache.gravitino.credential.Credential;
+import org.apache.gravitino.credential.CredentialContext;
+import org.apache.gravitino.credential.CredentialProvider;
+
+/** Credential provider used to verify Fileset connection-test credential vending. */
+public class TestFilesetCredentialProvider implements CredentialProvider {
+
+ static final String TYPE = "fileset-test";
+
+ @Override
+ public void initialize(Map<String, String> properties) {}
+
+ @Override
+ public String credentialType() {
+ return TYPE;
+ }
+
+ @Override
+ public boolean supportsScheme(String scheme) {
+ return "file".equals(scheme);
+ }
+
+ @Override
+ public Credential getCredential(CredentialContext context) {
+ return new TestCredential(credentialType());
+ }
+
+ @Override
+ public void close() {}
+
+ private static class TestCredential implements Credential {
+
+ private final String credentialType;
+
+ private TestCredential(String credentialType) {
+ this.credentialType = credentialType;
+ }
+
+ @Override
+ public String credentialType() {
+ return credentialType;
+ }
+
+ @Override
+ public long expireTimeInMs() {
+ return 0;
+ }
+
+ @Override
+ public Map<String, String> credentialInfo() {
+ return Collections.emptyMap();
+ }
+
+ @Override
+ public void initialize(Map<String, String> credentialInfo, long expireTimeInMs) {}
+ }
+}
diff --git a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetSecondCredentialProvider.java b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetSecondCredentialProvider.java
new file mode 100644
index 0000000000..4f3a91df86
--- /dev/null
+++ b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetSecondCredentialProvider.java
@@ -0,0 +1,30 @@
+/*
+ * 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.catalog.fileset;
+
+/** Second matching credential provider used to verify multi-provider credential vending. */
+public class TestFilesetSecondCredentialProvider extends TestFilesetCredentialProvider {
+
+ static final String TYPE = "fileset-test-second";
+
+ @Override
+ public String credentialType() {
+ return TYPE;
+ }
+}
diff --git a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/integration/test/FilesetABSCatalogIT.java b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/integration/test/FilesetABSCatalogIT.java
index 7651432cfe..209f66bce7 100644
--- a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/integration/test/FilesetABSCatalogIT.java
+++ b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/integration/test/FilesetABSCatalogIT.java
@@ -164,6 +164,7 @@ public class FilesetABSCatalogIT extends FilesetCatalogIT {
ImmutableMap.of("k1", "v1"));
Assertions.assertEquals(
ossLocation + "/local_schema/local_fileset", localFileset.storageLocation());
+ Assertions.assertDoesNotThrow(() -> metalake.testConnection(localCatalogName));
// Delete schema
localCatalog.asSchemas().dropSchema(localSchema.name(), true);
diff --git a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/integration/test/FilesetCOSCatalogIT.java b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/integration/test/FilesetCOSCatalogIT.java
index 813d8cd441..232fd63864 100644
--- a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/integration/test/FilesetCOSCatalogIT.java
+++ b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/integration/test/FilesetCOSCatalogIT.java
@@ -170,6 +170,7 @@ public class FilesetCOSCatalogIT extends FilesetCatalogIT {
ImmutableMap.of("k1", "v1"));
Assertions.assertEquals(
cosLocation + "/local_schema/local_fileset", localFileset.storageLocation());
+ Assertions.assertDoesNotThrow(() -> metalake.testConnection(localCatalogName));
// Delete schema
localCatalog.asSchemas().dropSchema(localSchema.name(), true);
diff --git a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/integration/test/FilesetCatalogIT.java b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/integration/test/FilesetCatalogIT.java
index 9712e6cfa0..ed741b1520 100644
--- a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/integration/test/FilesetCatalogIT.java
+++ b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/integration/test/FilesetCatalogIT.java
@@ -1252,6 +1252,7 @@ public class FilesetCatalogIT extends BaseIT {
ImmutableMap.of("k1", "v1"));
Assertions.assertEquals(
hdfsLocation + "/local_schema/local_fileset", localFileset.storageLocation());
+ Assertions.assertDoesNotThrow(() -> metalake.testConnection(localCatalogName));
// Delete schema
localCatalog.asSchemas().dropSchema(localSchema.name(), true);
diff --git a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/integration/test/FilesetGCSCatalogIT.java b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/integration/test/FilesetGCSCatalogIT.java
index cccff6021c..2f19d7d166 100644
--- a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/integration/test/FilesetGCSCatalogIT.java
+++ b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/integration/test/FilesetGCSCatalogIT.java
@@ -142,6 +142,7 @@ public class FilesetGCSCatalogIT extends FilesetCatalogIT {
ImmutableMap.of("k1", "v1"));
Assertions.assertEquals(
ossLocation + "/local_schema/local_fileset", localFileset.storageLocation());
+ Assertions.assertDoesNotThrow(() -> metalake.testConnection(localCatalogName));
// Delete schema
localCatalog.asSchemas().dropSchema(localSchema.name(), true);
diff --git a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/integration/test/FilesetOSSCatalogIT.java b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/integration/test/FilesetOSSCatalogIT.java
index fc18eba99f..4ffd93f1b0 100644
--- a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/integration/test/FilesetOSSCatalogIT.java
+++ b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/integration/test/FilesetOSSCatalogIT.java
@@ -168,6 +168,7 @@ public class FilesetOSSCatalogIT extends FilesetCatalogIT {
ImmutableMap.of("k1", "v1"));
Assertions.assertEquals(
ossLocation + "/local_schema/local_fileset", localFileset.storageLocation());
+ Assertions.assertDoesNotThrow(() -> metalake.testConnection(localCatalogName));
// Delete schema
localCatalog.asSchemas().dropSchema(localSchema.name(), true);
diff --git a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/integration/test/FilesetS3CatalogIT.java b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/integration/test/FilesetS3CatalogIT.java
index 21cb1739c7..2714321d6e 100644
--- a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/integration/test/FilesetS3CatalogIT.java
+++ b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/integration/test/FilesetS3CatalogIT.java
@@ -228,6 +228,7 @@ public class FilesetS3CatalogIT extends FilesetCatalogIT {
ImmutableMap.of("k1", "v1"));
Assertions.assertEquals(
s3Location + "/local_schema/local_fileset", localFileset.storageLocation());
+ Assertions.assertDoesNotThrow(() -> metalake.testConnection(localCatalogName));
// Delete schema
localCatalog.asSchemas().dropSchema(localSchema.name(), true);
diff --git a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/integration/test/FilesetS3TokenConnectionIT.java b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/integration/test/FilesetS3TokenConnectionIT.java
new file mode 100644
index 0000000000..86403dbd14
--- /dev/null
+++ b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/integration/test/FilesetS3TokenConnectionIT.java
@@ -0,0 +1,97 @@
+/*
+ * 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.catalog.fileset.integration.test;
+
+import static org.apache.gravitino.catalog.fileset.FilesetCatalogPropertiesMetadata.FILESYSTEM_PROVIDERS;
+import static org.apache.gravitino.catalog.fileset.FilesetCatalogPropertiesMetadata.LOCATION;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+import org.apache.gravitino.Catalog;
+import org.apache.gravitino.client.GravitinoMetalake;
+import org.apache.gravitino.credential.CredentialConstants;
+import org.apache.gravitino.credential.S3TokenCredential;
+import org.apache.gravitino.integration.test.container.MinIOContainer;
+import org.apache.gravitino.integration.test.util.BaseIT;
+import org.apache.gravitino.integration.test.util.GravitinoITUtils;
+import org.apache.gravitino.storage.S3Properties;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+/** Tests an existing Fileset catalog connection with S3 temporary credentials against MinIO. */
+@Tag("gravitino-docker-test")
+public class FilesetS3TokenConnectionIT extends BaseIT {
+
+ private static final String ROLE_ARN = "arn:minio:iam:::role/test";
+ private static final String REGION = "us-east-1";
+
+ private final String bucketName =
+ "fileset-connection-" + UUID.randomUUID().toString().replace("-", "");
+ private final String metalakeName = GravitinoITUtils.genRandomName("fileset_connection_metalake");
+ private final String catalogName = GravitinoITUtils.genRandomName("fileset_connection_catalog");
+
+ private GravitinoMetalake metalake;
+
+ /** {@inheritDoc} */
+ @Override
+ @BeforeAll
+ public void startIntegrationTest() throws Exception {
+ copyBundleJarsToHadoop("aws-bundle");
+ containerSuite.startMinIOContainer();
+ MinIOContainer minIOContainer = containerSuite.getMinIOContainer();
+ minIOContainer.createBucket(bucketName);
+
+ super.startIntegrationTest();
+
+ client.createMetalake(metalakeName, "comment", new HashMap<>());
+ metalake = client.loadMetalake(metalakeName);
+
+ String endpoint = minIOContainer.getS3Endpoint();
+ Map<String, String> properties = new HashMap<>();
+ properties.put(LOCATION, String.format("s3a://%s", bucketName));
+ properties.put(FILESYSTEM_PROVIDERS, "s3");
+ properties.put(
+ CredentialConstants.CREDENTIAL_PROVIDERS, S3TokenCredential.S3_TOKEN_CREDENTIAL_TYPE);
+ properties.put(S3Properties.GRAVITINO_S3_REGION, REGION);
+ properties.put(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID, MinIOContainer.ACCESS_KEY);
+ properties.put(S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY, MinIOContainer.SECRET_KEY);
+ properties.put(S3Properties.GRAVITINO_S3_ROLE_ARN, ROLE_ARN);
+ properties.put(S3Properties.GRAVITINO_S3_ENDPOINT, endpoint);
+ properties.put(S3Properties.GRAVITINO_S3_STS_ENDPOINT, endpoint);
+ properties.put(S3Properties.GRAVITINO_S3_PATH_STYLE_ACCESS, "true");
+
+ metalake.createCatalog(catalogName, Catalog.Type.FILESET, "hadoop", "comment", properties);
+ }
+
+ @AfterAll
+ void cleanup() {
+ if (metalake != null) {
+ client.dropMetalake(metalakeName, true);
+ }
+ }
+
+ @Test
+ void testExistingCatalogConnectionWithS3Token() throws Exception {
+ metalake.testConnection(catalogName);
+ }
+}
diff --git a/catalogs/catalog-fileset/src/test/resources/META-INF/services/org.apache.gravitino.credential.CredentialProvider b/catalogs/catalog-fileset/src/test/resources/META-INF/services/org.apache.gravitino.credential.CredentialProvider
new file mode 100644
index 0000000000..78a74ee940
--- /dev/null
+++ b/catalogs/catalog-fileset/src/test/resources/META-INF/services/org.apache.gravitino.credential.CredentialProvider
@@ -0,0 +1,20 @@
+#
+# 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.
+#
+org.apache.gravitino.catalog.fileset.TestFilesetCredentialProvider
+org.apache.gravitino.catalog.fileset.TestFilesetSecondCredentialProvider
diff --git a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueCatalogOperations.java b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueCatalogOperations.java
index 0e8fa2dc12..e7ce0ea8b0 100644
--- a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueCatalogOperations.java
+++ b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueCatalogOperations.java
@@ -37,7 +37,6 @@ import java.util.function.Consumer;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
-import org.apache.gravitino.Catalog;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.SchemaChange;
@@ -70,6 +69,7 @@ import org.apache.gravitino.utils.PrincipalUtils;
import org.apache.iceberg.catalog.TableIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.services.glue.GlueClient;
import software.amazon.awssdk.services.glue.model.CreateDatabaseRequest;
import software.amazon.awssdk.services.glue.model.CreateTableRequest;
@@ -155,18 +155,12 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemas
}
@Override
- public void testConnection(
- NameIdentifier catalogIdent,
- Catalog.Type type,
- String provider,
- String comment,
- Map<String, String> properties)
- throws Exception {
+ public void testConnection(NameIdentifier catalogIdent) {
try {
GetDatabasesRequest.Builder req = GetDatabasesRequest.builder().maxResults(1);
applyCatalogId(catalogId, req::catalogId);
glueClient.getDatabases(req.build());
- } catch (GlueException e) {
+ } catch (SdkException e) {
throw new ConnectionFailedException(e, "Failed to connect to AWS Glue: %s", e.getMessage());
}
}
diff --git a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogSchemaOperations.java b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogSchemaOperations.java
index 89e0163e55..438a07edc5 100644
--- a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogSchemaOperations.java
+++ b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogSchemaOperations.java
@@ -35,12 +35,14 @@ import java.util.Map;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.SchemaChange;
+import org.apache.gravitino.exceptions.ConnectionFailedException;
import org.apache.gravitino.exceptions.NoSuchSchemaException;
import org.apache.gravitino.exceptions.NonEmptySchemaException;
import org.apache.gravitino.exceptions.SchemaAlreadyExistsException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
+import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.services.glue.GlueClient;
import software.amazon.awssdk.services.glue.model.AlreadyExistsException;
import software.amazon.awssdk.services.glue.model.CreateDatabaseRequest;
@@ -70,6 +72,20 @@ class TestGlueCatalogSchemaOperations {
// catalogId is null by default (caller's AWS account)
}
+ @Test
+ void testConnectionMapsSdkClientException() {
+ SdkClientException cause = SdkClientException.create("connection refused");
+ when(mockClient.getDatabases(any(GetDatabasesRequest.class))).thenThrow(cause);
+
+ ConnectionFailedException exception =
+ assertThrows(
+ ConnectionFailedException.class,
+ () -> ops.testConnection(NameIdentifier.of("metalake", "catalog")));
+
+ assertEquals(cause, exception.getCause());
+ assertTrue(exception.getMessage().contains("connection refused"));
+ }
+
// -------------------------------------------------------------------------
// listSchemas
// -------------------------------------------------------------------------
diff --git a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/integration/test/AbstractGlueCatalogIT.java b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/integration/test/AbstractGlueCatalogIT.java
index 7af5ec6115..946502567a 100644
--- a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/integration/test/AbstractGlueCatalogIT.java
+++ b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/integration/test/AbstractGlueCatalogIT.java
@@ -18,6 +18,7 @@
*/
package org.apache.gravitino.catalog.glue.integration.test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -180,6 +181,11 @@ abstract class AbstractGlueCatalogIT {
Collections.emptyMap());
}
+ @Test
+ void testExistingCatalogConnection() {
+ assertDoesNotThrow(() -> ops.testConnection(NameIdentifier.of("ml", "cat")));
+ }
+
// -------------------------------------------------------------------------
// Schema tests
// -------------------------------------------------------------------------
diff --git a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalogOperations.java b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalogOperations.java
index 7013930a18..b07a1c4468 100644
--- a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalogOperations.java
+++ b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalogOperations.java
@@ -50,7 +50,6 @@ import java.util.Set;
import java.util.concurrent.ThreadFactory;
import java.util.stream.Collectors;
import org.apache.commons.lang3.ArrayUtils;
-import org.apache.gravitino.Catalog;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.SchemaChange;
@@ -1015,18 +1014,9 @@ public class HiveCatalogOperations
* Performs `getAllDatabases` operation in Hive Metastore to test the connection.
*
* @param catalogIdent the name of the catalog.
- * @param type the type of the catalog.
- * @param provider the provider of the catalog.
- * @param comment the comment of the catalog.
- * @param properties the properties of the catalog.
*/
@Override
- public void testConnection(
- NameIdentifier catalogIdent,
- Catalog.Type type,
- String provider,
- String comment,
- Map<String, String> properties) {
+ public void testConnection(NameIdentifier catalogIdent) {
try {
clientPool.run(c -> c.getAllDatabases(catalogName));
} catch (ConnectionFailedException e) {
diff --git a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHive2IT.java b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHive2IT.java
index 121ab3a809..d296b19878 100644
--- a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHive2IT.java
+++ b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHive2IT.java
@@ -306,6 +306,11 @@ public class CatalogHive2IT extends BaseIT {
catalog = metalake.loadCatalog(catalogName);
}
+ @Test
+ void testExistingCatalogConnection() {
+ Assertions.assertDoesNotThrow(() -> metalake.testConnection(catalogName));
+ }
+
private void createSchema() throws TException, InterruptedException {
Map<String, String> schemaProperties = createSchemaProperties();
String comment = "comment";
diff --git a/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/JdbcCatalogOperations.java b/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/JdbcCatalogOperations.java
index 94850f38a3..e8c3feeb60 100644
--- a/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/JdbcCatalogOperations.java
+++ b/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/JdbcCatalogOperations.java
@@ -38,7 +38,6 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.sql.DataSource;
import org.apache.commons.lang3.StringUtils;
-import org.apache.gravitino.Catalog;
import org.apache.gravitino.GravitinoEnv;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
@@ -58,6 +57,8 @@ import org.apache.gravitino.connector.CatalogInfo;
import org.apache.gravitino.connector.CatalogOperations;
import org.apache.gravitino.connector.HasPropertyMetadata;
import org.apache.gravitino.connector.SupportsSchemas;
+import org.apache.gravitino.exceptions.ConnectionFailedException;
+import org.apache.gravitino.exceptions.GravitinoRuntimeException;
import org.apache.gravitino.exceptions.NoSuchCatalogException;
import org.apache.gravitino.exceptions.NoSuchSchemaException;
import org.apache.gravitino.exceptions.NoSuchTableException;
@@ -235,19 +236,20 @@ public class JdbcCatalogOperations implements CatalogOperations, SupportsSchemas
* Performs `show databases` operation to check if the JDBC connection is valid.
*
* @param catalogIdent the name of the catalog.
- * @param type the type of the catalog.
- * @param provider the provider of the catalog.
- * @param comment the comment of the catalog.
- * @param properties the properties of the catalog.
*/
@Override
- public void testConnection(
- NameIdentifier catalogIdent,
- Catalog.Type type,
- String provider,
- String comment,
- Map<String, String> properties) {
- databaseOperation.listDatabases();
+ public void testConnection(NameIdentifier catalogIdent) {
+ try {
+ databaseOperation.listDatabases();
+ } catch (ConnectionFailedException e) {
+ throw e;
+ } catch (GravitinoRuntimeException e) {
+ if (e.getClass() == GravitinoRuntimeException.class && e.getCause() instanceof SQLException) {
+ throw new ConnectionFailedException(
+ e.getCause(), "Failed to connect to JDBC catalog: %s", e.getMessage());
+ }
+ throw e;
+ }
}
/**
@@ -568,7 +570,8 @@ public class JdbcCatalogOperations implements CatalogOperations, SupportsSchemas
metaData.getDriverMajorVersion(),
metaData.getDriverMinorVersion());
} catch (final SQLException se) {
- throw exceptionConverter.toGravitinoException(se);
+ throw new ConnectionFailedException(
+ se, "Failed to connect to JDBC catalog: %s", se.getMessage());
}
}
diff --git a/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/TestJdbcCatalogOperations.java b/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/TestJdbcCatalogOperations.java
index 964e632db2..a070f101c6 100644
--- a/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/TestJdbcCatalogOperations.java
+++ b/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/TestJdbcCatalogOperations.java
@@ -18,13 +18,12 @@
*/
package org.apache.gravitino.catalog.jdbc;
-import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import java.sql.SQLException;
import java.util.HashMap;
+import java.util.List;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
-import org.apache.gravitino.Catalog;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.catalog.jdbc.config.JdbcConfig;
import org.apache.gravitino.catalog.jdbc.converter.SqliteColumnDefaultValueConverter;
@@ -33,6 +32,7 @@ import org.apache.gravitino.catalog.jdbc.converter.SqliteTypeConverter;
import org.apache.gravitino.catalog.jdbc.operation.SqliteDatabaseOperations;
import org.apache.gravitino.catalog.jdbc.operation.SqliteTableOperations;
import org.apache.gravitino.catalog.jdbc.utils.DataSourceUtils;
+import org.apache.gravitino.exceptions.ConnectionFailedException;
import org.apache.gravitino.exceptions.GravitinoRuntimeException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -40,23 +40,28 @@ import org.junit.jupiter.api.Test;
public class TestJdbcCatalogOperations {
@Test
- public void testTestConnection() {
+ public void testExistingCatalogConnectionFailure() {
+ SQLException cause = new SQLException("connection refused");
+ SqliteDatabaseOperations databaseOperations =
+ new SqliteDatabaseOperations("/unused") {
+ @Override
+ public List<String> listDatabases() {
+ throw new GravitinoRuntimeException(cause, cause.getMessage());
+ }
+ };
+
try (JdbcCatalogOperations catalogOperations =
new JdbcCatalogOperations(
new SqliteExceptionConverter(),
new SqliteTypeConverter(),
- new SqliteDatabaseOperations("/illegal/path"),
+ databaseOperations,
new SqliteTableOperations(),
new SqliteColumnDefaultValueConverter())) {
- Assertions.assertThrows(
- GravitinoRuntimeException.class,
- () ->
- catalogOperations.testConnection(
- NameIdentifier.of("metalake", "catalog"),
- Catalog.Type.RELATIONAL,
- "sqlite",
- "comment",
- ImmutableMap.of()));
+ ConnectionFailedException exception =
+ Assertions.assertThrows(
+ ConnectionFailedException.class,
+ () -> catalogOperations.testConnection(NameIdentifier.of("metalake", "catalog")));
+ Assertions.assertSame(cause, exception.getCause());
}
}
diff --git a/catalogs/catalog-jdbc-doris/src/test/java/org/apache/gravitino/catalog/doris/integration/test/CatalogDorisIT.java b/catalogs/catalog-jdbc-doris/src/test/java/org/apache/gravitino/catalog/doris/integration/test/CatalogDorisIT.java
index e5aeebf702..93ba4b09e7 100644
--- a/catalogs/catalog-jdbc-doris/src/test/java/org/apache/gravitino/catalog/doris/integration/test/CatalogDorisIT.java
+++ b/catalogs/catalog-jdbc-doris/src/test/java/org/apache/gravitino/catalog/doris/integration/test/CatalogDorisIT.java
@@ -192,6 +192,11 @@ public class CatalogDorisIT extends BaseIT {
catalog = loadCatalog;
}
+ @Test
+ void testExistingCatalogConnection() {
+ Assertions.assertDoesNotThrow(() -> metalake.testConnection(catalogName));
+ }
+
private void createSchema() {
NameIdentifier ident = NameIdentifier.of(metalakeName, catalogName, schemaName);
String propKey = "key";
diff --git a/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/integration/test/CatalogMysqlIT.java b/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/integration/test/CatalogMysqlIT.java
index db9035d6c3..0aba67f646 100644
--- a/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/integration/test/CatalogMysqlIT.java
+++ b/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/integration/test/CatalogMysqlIT.java
@@ -201,6 +201,36 @@ public class CatalogMysqlIT extends BaseIT {
return loadCatalog;
}
+ @Test
+ void testExistingCatalogConnection() {
+ Assertions.assertDoesNotThrow(() -> metalake.testConnection(catalogName));
+ }
+
+ @Test
+ void testExistingCatalogConnectionWithUnreachableEndpoint() throws SQLException {
+ String unreachableCatalogName = GravitinoITUtils.genRandomName("mysql_unreachable_catalog");
+ Map<String, String> catalogProperties = Maps.newHashMap();
+ catalogProperties.put(
+ JdbcConfig.JDBC_URL.getKey(), "jdbc:mysql://127.0.0.1:1/?useSSL=false&connectTimeout=1000");
+ catalogProperties.put(
+ JdbcConfig.JDBC_DRIVER.getKey(), MYSQL_CONTAINER.getDriverClassName(TEST_DB_NAME));
+ catalogProperties.put(JdbcConfig.USERNAME.getKey(), MYSQL_CONTAINER.getUsername());
+ catalogProperties.put(JdbcConfig.PASSWORD.getKey(), MYSQL_CONTAINER.getPassword());
+
+ metalake.createCatalog(
+ unreachableCatalogName,
+ Catalog.Type.RELATIONAL,
+ provider,
+ "unreachable MySQL catalog",
+ catalogProperties);
+ try {
+ assertThrows(
+ ConnectionFailedException.class, () -> metalake.testConnection(unreachableCatalogName));
+ } finally {
+ metalake.dropCatalog(unreachableCatalogName, true);
+ }
+ }
+
private void createSchema(Catalog catalog, String schemaName) {
Map<String, String> prop = Maps.newHashMap();
diff --git a/catalogs/catalog-jdbc-postgresql/src/test/java/org/apache/gravitino/catalog/postgresql/integration/test/CatalogPostgreSqlIT.java b/catalogs/catalog-jdbc-postgresql/src/test/java/org/apache/gravitino/catalog/postgresql/integration/test/CatalogPostgreSqlIT.java
index 68216e674b..7bea7747eb 100644
--- a/catalogs/catalog-jdbc-postgresql/src/test/java/org/apache/gravitino/catalog/postgresql/integration/test/CatalogPostgreSqlIT.java
+++ b/catalogs/catalog-jdbc-postgresql/src/test/java/org/apache/gravitino/catalog/postgresql/integration/test/CatalogPostgreSqlIT.java
@@ -186,6 +186,11 @@ public class CatalogPostgreSqlIT extends BaseIT {
return loadCatalog;
}
+ @Test
+ void testExistingCatalogConnection() {
+ Assertions.assertDoesNotThrow(() -> metalake.testConnection(catalogName));
+ }
+
private void createSchema(String schemaName) {
Schema createdSchema =
diff --git a/catalogs/catalog-jdbc-starrocks/src/test/java/org/apache/gravitino/catalog/starrocks/integration/test/CatalogStarRocksIT.java b/catalogs/catalog-jdbc-starrocks/src/test/java/org/apache/gravitino/catalog/starrocks/integration/test/CatalogStarRocksIT.java
index a314fb52dd..28369a00c8 100644
--- a/catalogs/catalog-jdbc-starrocks/src/test/java/org/apache/gravitino/catalog/starrocks/integration/test/CatalogStarRocksIT.java
+++ b/catalogs/catalog-jdbc-starrocks/src/test/java/org/apache/gravitino/catalog/starrocks/integration/test/CatalogStarRocksIT.java
@@ -183,6 +183,11 @@ public class CatalogStarRocksIT extends BaseIT {
catalog = loadCatalog;
}
+ @Test
+ void testExistingCatalogConnection() {
+ Assertions.assertDoesNotThrow(() -> metalake.testConnection(catalogName));
+ }
+
private void createSchema() {
NameIdentifier ident = NameIdentifier.of(metalakeName, catalogName, schemaName);
Map<String, String> prop = Maps.newHashMap();
diff --git a/catalogs/catalog-kafka/src/main/java/org/apache/gravitino/catalog/kafka/KafkaCatalogOperations.java b/catalogs/catalog-kafka/src/main/java/org/apache/gravitino/catalog/kafka/KafkaCatalogOperations.java
index 7455679897..980b92b542 100644
--- a/catalogs/catalog-kafka/src/main/java/org/apache/gravitino/catalog/kafka/KafkaCatalogOperations.java
+++ b/catalogs/catalog-kafka/src/main/java/org/apache/gravitino/catalog/kafka/KafkaCatalogOperations.java
@@ -39,7 +39,6 @@ import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
-import org.apache.gravitino.Catalog;
import org.apache.gravitino.Entity;
import org.apache.gravitino.EntityStore;
import org.apache.gravitino.GravitinoEnv;
@@ -185,14 +184,13 @@ public class KafkaCatalogOperations implements CatalogOperations, SupportsSchema
}
@Override
- public void testConnection(
- NameIdentifier catalogIdent,
- Catalog.Type type,
- String provider,
- String comment,
- Map<String, String> properties) {
+ public void testConnection(NameIdentifier catalogIdent) {
try {
adminClient.listTopics().names().get();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new ConnectionFailedException(
+ e, "Failed to run listTopics in Kafka: %s", e.getMessage());
} catch (Exception e) {
throw new ConnectionFailedException(
e, "Failed to run listTopics in Kafka: %s", e.getMessage());
diff --git a/catalogs/catalog-kafka/src/test/java/org/apache/gravitino/catalog/kafka/TestKafkaCatalogOperations.java b/catalogs/catalog-kafka/src/test/java/org/apache/gravitino/catalog/kafka/TestKafkaCatalogOperations.java
index fd21391cb9..0e0d9df1dc 100644
--- a/catalogs/catalog-kafka/src/test/java/org/apache/gravitino/catalog/kafka/TestKafkaCatalogOperations.java
+++ b/catalogs/catalog-kafka/src/test/java/org/apache/gravitino/catalog/kafka/TestKafkaCatalogOperations.java
@@ -51,6 +51,7 @@ import java.io.File;
import java.io.IOException;
import java.time.Instant;
import java.util.Map;
+import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.gravitino.Config;
@@ -65,6 +66,7 @@ import org.apache.gravitino.SchemaChange;
import org.apache.gravitino.catalog.kafka.embedded.KafkaClusterEmbedded;
import org.apache.gravitino.connector.HasPropertyMetadata;
import org.apache.gravitino.connector.PropertiesMetadata;
+import org.apache.gravitino.exceptions.ConnectionFailedException;
import org.apache.gravitino.exceptions.NoSuchSchemaException;
import org.apache.gravitino.exceptions.NoSuchTopicException;
import org.apache.gravitino.exceptions.TopicAlreadyExistsException;
@@ -76,6 +78,9 @@ import org.apache.gravitino.meta.CatalogEntity;
import org.apache.gravitino.meta.SchemaVersion;
import org.apache.gravitino.storage.IdGenerator;
import org.apache.gravitino.storage.RandomIdGenerator;
+import org.apache.kafka.clients.admin.AdminClient;
+import org.apache.kafka.clients.admin.ListTopicsResult;
+import org.apache.kafka.common.KafkaFuture;
import org.apache.kafka.common.config.TopicConfig;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
@@ -573,4 +578,28 @@ public class TestKafkaCatalogOperations extends KafkaClusterEmbedded {
"comment",
ImmutableMap.of()));
}
+
+ @Test
+ public void testConnectionPreservesInterruptStatus() throws Exception {
+ AdminClient adminClient = Mockito.mock(AdminClient.class);
+ ListTopicsResult listTopicsResult = Mockito.mock(ListTopicsResult.class);
+ @SuppressWarnings("unchecked")
+ KafkaFuture<Set<String>> namesFuture = Mockito.mock(KafkaFuture.class);
+ when(adminClient.listTopics()).thenReturn(listTopicsResult);
+ when(listTopicsResult.names()).thenReturn(namesFuture);
+ when(namesFuture.get()).thenThrow(new InterruptedException("interrupted"));
+
+ KafkaCatalogOperations operations = new KafkaCatalogOperations(store, idGenerator);
+ FieldUtils.writeField(operations, "adminClient", adminClient, true);
+
+ Thread.interrupted();
+ try {
+ Assertions.assertThrows(
+ ConnectionFailedException.class,
+ () -> operations.testConnection(NameIdentifier.of("metalake", "catalog")));
+ Assertions.assertTrue(Thread.currentThread().isInterrupted());
+ } finally {
+ Thread.interrupted();
+ }
+ }
}
diff --git a/catalogs/catalog-kafka/src/test/java/org/apache/gravitino/catalog/kafka/integration/test/CatalogKafkaIT.java b/catalogs/catalog-kafka/src/test/java/org/apache/gravitino/catalog/kafka/integration/test/CatalogKafkaIT.java
index 1429e2708b..12c19eab1d 100644
--- a/catalogs/catalog-kafka/src/test/java/org/apache/gravitino/catalog/kafka/integration/test/CatalogKafkaIT.java
+++ b/catalogs/catalog-kafka/src/test/java/org/apache/gravitino/catalog/kafka/integration/test/CatalogKafkaIT.java
@@ -165,6 +165,7 @@ public class CatalogKafkaIT extends BaseIT {
// test load catalog
Catalog loadedCatalog = metalake.loadCatalog(catalogName);
Assertions.assertEquals(createdCatalog, loadedCatalog);
+ Assertions.assertDoesNotThrow(() -> metalake.testConnection(catalogName));
// test alter catalog
Catalog alteredCatalog =
diff --git a/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/GenericCatalogOperations.java b/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/GenericCatalogOperations.java
index 1d5876b6dd..445b87dcc4 100644
--- a/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/GenericCatalogOperations.java
+++ b/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/GenericCatalogOperations.java
@@ -147,13 +147,9 @@ public class GenericCatalogOperations implements CatalogOperations, SupportsSche
}
@Override
- public void testConnection(
- NameIdentifier catalogIdent,
- Catalog.Type type,
- String provider,
- String comment,
- Map<String, String> properties) {
- // No-op for generic catalog.
+ public void testConnection(NameIdentifier catalogIdent) {
+ throw new UnsupportedOperationException(
+ "Generic catalogs do not define a catalog-level connection probe");
}
@Override
diff --git a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/delta/integration/test/CatalogGenericCatalogDeltaIT.java b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/delta/integration/test/CatalogGenericCatalogDeltaIT.java
index 8dffe0c32b..0bdc70c484 100644
--- a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/delta/integration/test/CatalogGenericCatalogDeltaIT.java
+++ b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/delta/integration/test/CatalogGenericCatalogDeltaIT.java
@@ -145,6 +145,12 @@ public class CatalogGenericCatalogDeltaIT extends BaseIT {
createSchema();
}
+ @Test
+ void testExistingCatalogConnectionIsUnsupported() {
+ Assertions.assertThrows(
+ UnsupportedOperationException.class, () -> metalake.testConnection(catalogName));
+ }
+
@Test
public void testCreateDeltaTableAndRegisterToGravitino() throws Exception {
String tableLocation = tempDirectory + "/" + tableName;
diff --git a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestGenericCatalogOperations.java b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestGenericCatalogOperations.java
index fe749a18a3..fc0c0859c1 100644
--- a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestGenericCatalogOperations.java
+++ b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestGenericCatalogOperations.java
@@ -152,6 +152,13 @@ public class TestGenericCatalogOperations {
FileUtils.deleteDirectory(new File(STORE_PATH));
}
+ @Test
+ public void testConnectionNotSupported() {
+ Assertions.assertThrows(
+ UnsupportedOperationException.class,
+ () -> ops.testConnection(NameIdentifier.of(METALAKE_NAME, CATALOG_NAME)));
+ }
+
@Test
public void testSchemaOperations() {
String schemaName = randomSchemaName();
diff --git a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/lance/integration/test/CatalogGenericCatalogLanceIT.java b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/lance/integration/test/CatalogGenericCatalogLanceIT.java
index f2dc40907a..2654bec7a5 100644
--- a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/lance/integration/test/CatalogGenericCatalogLanceIT.java
+++ b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/lance/integration/test/CatalogGenericCatalogLanceIT.java
@@ -153,6 +153,12 @@ public class CatalogGenericCatalogLanceIT extends BaseIT {
createSchema();
}
+ @Test
+ void testExistingCatalogConnectionIsUnsupported() {
+ Assertions.assertThrows(
+ UnsupportedOperationException.class, () -> metalake.testConnection(catalogName));
+ }
+
@Test
public void testPurgeTableWhenLocationMissing() throws IOException {
Column[] columns = createColumns();
diff --git a/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/HudiCatalogOperations.java b/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/HudiCatalogOperations.java
index f471dbbdce..e6f89bbffe 100644
--- a/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/HudiCatalogOperations.java
+++ b/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/HudiCatalogOperations.java
@@ -22,7 +22,6 @@ import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
import java.util.Objects;
-import org.apache.gravitino.Catalog;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.Schema;
@@ -86,20 +85,9 @@ public class HudiCatalogOperations implements CatalogOperations, SupportsSchemas
* Performs `listSchemas` operation on the Hudi Catalog to test the catalog connection.
*
* @param catalogIdent the name of the catalog.
- * @param type the type of the catalog.
- * @param provider the provider of the catalog.
- * @param comment the comment of the catalog.
- * @param properties the properties of the catalog.
- * @throws Exception if failed to run `listSchemas` operation on the Hudi Catalog.
*/
@Override
- public void testConnection(
- NameIdentifier catalogIdent,
- Catalog.Type type,
- String provider,
- String comment,
- Map<String, String> properties)
- throws Exception {
+ public void testConnection(NameIdentifier catalogIdent) {
try {
hudiCatalogBackendOps.listSchemas(
Namespace.of(catalogIdent.namespace().level(0), catalogIdent.name()));
diff --git a/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/integration/test/HudiCatalogHMSIT.java b/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/integration/test/HudiCatalogHMSIT.java
index dca8dbbc40..1bed6959d0 100644
--- a/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/integration/test/HudiCatalogHMSIT.java
+++ b/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/integration/test/HudiCatalogHMSIT.java
@@ -172,6 +172,7 @@ public class HudiCatalogHMSIT extends BaseIT {
Map<String, String> expectedProperties = new HashMap<>(properties);
expectedProperties.put(PROPERTY_IN_USE, "true");
Assertions.assertEquals(expectedProperties, catalog.properties());
+ Assertions.assertDoesNotThrow(() -> metalake.testConnection(catalogName));
// test list
String[] catalogs = metalake.listCatalogs();
diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalogOperations.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalogOperations.java
index 6e7346f636..ea53a7fd0f 100644
--- a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalogOperations.java
+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalogOperations.java
@@ -33,7 +33,6 @@ import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
-import org.apache.gravitino.Catalog;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.SchemaChange;
@@ -658,18 +657,9 @@ public class IcebergCatalogOperations
* Performs `listNamespaces` operation on the Iceberg catalog to test the connection.
*
* @param catalogIdent the name of the catalog.
- * @param type the type of the catalog.
- * @param provider the provider of the catalog.
- * @param comment the comment of the catalog.
- * @param properties the properties of the catalog.
*/
@Override
- public void testConnection(
- NameIdentifier catalogIdent,
- Catalog.Type type,
- String provider,
- String comment,
- Map<String, String> properties) {
+ public void testConnection(NameIdentifier catalogIdent) {
try {
icebergCatalogWrapper.listNamespace(IcebergCatalogWrapperHelper.getIcebergNamespace());
} catch (Exception e) {
diff --git a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/integration/test/CatalogIcebergBaseIT.java b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/integration/test/CatalogIcebergBaseIT.java
index b44bea50c7..9dffcf72c1 100644
--- a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/integration/test/CatalogIcebergBaseIT.java
+++ b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/integration/test/CatalogIcebergBaseIT.java
@@ -261,6 +261,11 @@ public abstract class CatalogIcebergBaseIT extends BaseIT {
catalog = loadCatalog;
}
+ @Test
+ void testExistingCatalogConnection() {
+ Assertions.assertDoesNotThrow(() -> metalake.testConnection(catalogName));
+ }
+
private void createSchema() {
NameIdentifier ident = NameIdentifier.of(schemaName);
Map<String, String> prop = Maps.newHashMap();
diff --git a/catalogs/catalog-lakehouse-paimon/src/main/java/org/apache/gravitino/catalog/lakehouse/paimon/PaimonCatalogOperations.java b/catalogs/catalog-lakehouse-paimon/src/main/java/org/apache/gravitino/catalog/lakehouse/paimon/PaimonCatalogOperations.java
index bcfc07d0c9..515fdd8510 100644
--- a/catalogs/catalog-lakehouse-paimon/src/main/java/org/apache/gravitino/catalog/lakehouse/paimon/PaimonCatalogOperations.java
+++ b/catalogs/catalog-lakehouse-paimon/src/main/java/org/apache/gravitino/catalog/lakehouse/paimon/PaimonCatalogOperations.java
@@ -162,6 +162,11 @@ public class PaimonCatalogOperations
String provider,
String comment,
Map<String, String> properties) {
+ testConnection(catalogIdent);
+ }
+
+ @Override
+ public void testConnection(NameIdentifier catalogIdent) {
try {
paimonCatalogOps.listDatabases();
} catch (Exception e) {
diff --git a/catalogs/catalog-lakehouse-paimon/src/test/java/org/apache/gravitino/catalog/lakehouse/paimon/integration/test/CatalogPaimonBaseIT.java b/catalogs/catalog-lakehouse-paimon/src/test/java/org/apache/gravitino/catalog/lakehouse/paimon/integration/test/CatalogPaimonBaseIT.java
index 1e1a7a20d7..00e97ac304 100644
--- a/catalogs/catalog-lakehouse-paimon/src/test/java/org/apache/gravitino/catalog/lakehouse/paimon/integration/test/CatalogPaimonBaseIT.java
+++ b/catalogs/catalog-lakehouse-paimon/src/test/java/org/apache/gravitino/catalog/lakehouse/paimon/integration/test/CatalogPaimonBaseIT.java
@@ -159,6 +159,11 @@ public abstract class CatalogPaimonBaseIT extends BaseIT {
protected abstract Map<String, String> initPaimonCatalogProperties();
+ @Test
+ void testExistingCatalogConnection() {
+ Assertions.assertDoesNotThrow(() -> metalake.testConnection(catalogName));
+ }
+
@Test
void testPaimonSchemaOperations() throws DatabaseNotExistException {
SupportsSchemas schemas = catalog.asSchemas();
diff --git a/catalogs/catalog-model/src/main/java/org/apache/gravitino/catalog/model/ModelCatalogOperations.java b/catalogs/catalog-model/src/main/java/org/apache/gravitino/catalog/model/ModelCatalogOperations.java
index d89d2d9933..1f2d14c6e0 100644
--- a/catalogs/catalog-model/src/main/java/org/apache/gravitino/catalog/model/ModelCatalogOperations.java
+++ b/catalogs/catalog-model/src/main/java/org/apache/gravitino/catalog/model/ModelCatalogOperations.java
@@ -29,7 +29,6 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
-import org.apache.gravitino.Catalog;
import org.apache.gravitino.Entity;
import org.apache.gravitino.EntityAlreadyExistsException;
import org.apache.gravitino.EntityStore;
@@ -79,13 +78,9 @@ public class ModelCatalogOperations extends ManagedSchemaOperations
public void close() throws IOException {}
@Override
- public void testConnection(
- NameIdentifier catalogIdent,
- Catalog.Type type,
- String provider,
- String comment,
- Map<String, String> properties) {
- // No-op for model catalog.
+ public void testConnection(NameIdentifier catalogIdent) {
+ throw new UnsupportedOperationException(
+ "Model catalogs do not define an external catalog-level connection probe");
}
@Override
diff --git a/catalogs/catalog-model/src/test/java/org/apache/gravtitino/catalog/model/TestModelCatalogOperations.java b/catalogs/catalog-model/src/test/java/org/apache/gravtitino/catalog/model/TestModelCatalogOperations.java
index 3237e96105..34fcc5c900 100644
--- a/catalogs/catalog-model/src/test/java/org/apache/gravtitino/catalog/model/TestModelCatalogOperations.java
+++ b/catalogs/catalog-model/src/test/java/org/apache/gravtitino/catalog/model/TestModelCatalogOperations.java
@@ -182,6 +182,13 @@ public class TestModelCatalogOperations {
FileUtils.deleteDirectory(new File(STORE_PATH));
}
+ @Test
+ public void testConnectionNotSupported() {
+ Assertions.assertThrows(
+ UnsupportedOperationException.class,
+ () -> ops.testConnection(NameIdentifier.of(METALAKE_NAME, CATALOG_NAME)));
+ }
+
@Test
public void testSchemaOperations() {
String schemaName = randomSchemaName();
diff --git a/catalogs/catalog-model/src/test/java/org/apache/gravtitino/catalog/model/integration/test/ModelCatalogOperationsIT.java b/catalogs/catalog-model/src/test/java/org/apache/gravtitino/catalog/model/integration/test/ModelCatalogOperationsIT.java
index 9a53e3cdc8..52bf115c41 100644
--- a/catalogs/catalog-model/src/test/java/org/apache/gravtitino/catalog/model/integration/test/ModelCatalogOperationsIT.java
+++ b/catalogs/catalog-model/src/test/java/org/apache/gravtitino/catalog/model/integration/test/ModelCatalogOperationsIT.java
@@ -81,6 +81,12 @@ public class ModelCatalogOperationsIT extends BaseIT {
dropSchema();
}
+ @Test
+ void testExistingCatalogConnectionIsUnsupported() {
+ Assertions.assertThrows(
+ UnsupportedOperationException.class, () -> gravitinoMetalake.testConnection(catalogName));
+ }
+
@Test
public void testRegisterAndGetModel() {
String modelName = RandomNameUtils.genRandomName("model1");
diff --git a/catalogs/hadoop-common/src/main/java/org/apache/gravitino/catalog/hadoop/fs/InMemoryFileSystemCredentialsProvider.java b/catalogs/hadoop-common/src/main/java/org/apache/gravitino/catalog/hadoop/fs/InMemoryFileSystemCredentialsProvider.java
new file mode 100644
index 0000000000..ddcfbb4b69
--- /dev/null
+++ b/catalogs/hadoop-common/src/main/java/org/apache/gravitino/catalog/hadoop/fs/InMemoryFileSystemCredentialsProvider.java
@@ -0,0 +1,86 @@
+/*
+ * 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.catalog.hadoop.fs;
+
+import com.google.common.base.Preconditions;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import org.apache.gravitino.credential.Credential;
+import org.apache.hadoop.conf.Configuration;
+
+/**
+ * Supplies short-lived credentials to a FileSystem created in the same process.
+ *
+ * <p>The Hadoop configuration contains only an opaque handle. Credential values remain in memory
+ * and are removed after the connection probe completes.
+ */
+public class InMemoryFileSystemCredentialsProvider
+ implements GravitinoFileSystemCredentialsProvider {
+
+ /** Hadoop configuration key containing the opaque credential handle. */
+ public static final String CREDENTIAL_HANDLE = "fs.gvfs.credential.handle";
+
+ private static final ConcurrentMap<String, Credential[]> CREDENTIALS = new ConcurrentHashMap<>();
+
+ private Configuration conf;
+
+ /**
+ * Registers credentials and returns an opaque handle.
+ *
+ * @param credentials credentials used by one FileSystem probe.
+ * @return an opaque handle for the registered credentials.
+ */
+ public static String register(Credential[] credentials) {
+ Preconditions.checkArgument(credentials != null, "Credentials must not be null");
+ String handle = UUID.randomUUID().toString();
+ CREDENTIALS.put(handle, credentials.clone());
+ return handle;
+ }
+
+ /**
+ * Removes credentials associated with an opaque handle.
+ *
+ * @param handle the handle returned by {@link #register(Credential[])}.
+ */
+ public static void unregister(String handle) {
+ if (handle != null) {
+ CREDENTIALS.remove(handle);
+ }
+ }
+
+ @Override
+ public Credential[] getCredentials() {
+ Preconditions.checkState(conf != null, "Configuration has not been set");
+ String handle = conf.get(CREDENTIAL_HANDLE);
+ Credential[] credentials = CREDENTIALS.get(handle);
+ Preconditions.checkState(credentials != null, "Credentials are no longer available");
+ return credentials.clone();
+ }
+
+ @Override
+ public void setConf(Configuration conf) {
+ this.conf = conf;
+ }
+
+ @Override
+ public Configuration getConf() {
+ return conf;
+ }
+}
diff --git a/catalogs/hadoop-common/src/test/java/org/apache/gravitino/catalog/hadoop/fs/TestInMemoryFileSystemCredentialsProvider.java b/catalogs/hadoop-common/src/test/java/org/apache/gravitino/catalog/hadoop/fs/TestInMemoryFileSystemCredentialsProvider.java
new file mode 100644
index 0000000000..d9cc663bf1
--- /dev/null
+++ b/catalogs/hadoop-common/src/test/java/org/apache/gravitino/catalog/hadoop/fs/TestInMemoryFileSystemCredentialsProvider.java
@@ -0,0 +1,44 @@
+/*
+ * 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.catalog.hadoop.fs;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import org.apache.gravitino.credential.Credential;
+import org.apache.hadoop.conf.Configuration;
+import org.junit.jupiter.api.Test;
+
+public class TestInMemoryFileSystemCredentialsProvider {
+
+ @Test
+ void testCredentialRegistrationAndCleanup() {
+ Credential[] credentials = new Credential[0];
+ String handle = InMemoryFileSystemCredentialsProvider.register(credentials);
+ Configuration conf = new Configuration(false);
+ conf.set(InMemoryFileSystemCredentialsProvider.CREDENTIAL_HANDLE, handle);
+
+ InMemoryFileSystemCredentialsProvider provider = new InMemoryFileSystemCredentialsProvider();
+ provider.setConf(conf);
+ assertArrayEquals(credentials, provider.getCredentials());
+
+ InMemoryFileSystemCredentialsProvider.unregister(handle);
+ assertThrows(IllegalStateException.class, provider::getCredentials);
+ }
+}
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.java b/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.java
index 99547936c8..b6d85d5d93 100644
--- a/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.java
+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.java
@@ -571,6 +571,9 @@ public class ErrorHandlers {
case ErrorConstants.CONNECTION_FAILED_CODE:
throw new ConnectionFailedException(errorMessage);
+ case ErrorConstants.UNSUPPORTED_OPERATION_CODE:
+ throw new UnsupportedOperationException(errorMessage);
+
case ErrorConstants.NOT_FOUND_CODE:
if (errorResponse.getType().equals(NoSuchMetalakeException.class.getSimpleName())) {
throw new NoSuchMetalakeException(errorMessage);
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoClient.java b/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoClient.java
index cb8afa01a5..fa0a51757e 100644
--- a/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoClient.java
+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoClient.java
@@ -575,6 +575,11 @@ public class GravitinoClient extends GravitinoClientBase
getMetalake().testConnection(catalogName, type, provider, comment, properties);
}
+ @Override
+ public void testConnection(String catalogName) throws Exception {
+ getMetalake().testConnection(catalogName);
+ }
+
@Override
public String[] listTags() throws NoSuchMetalakeException {
return getMetalake().listTags();
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoMetalake.java b/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoMetalake.java
index eed967128d..92d86bcb26 100644
--- a/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoMetalake.java
+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoMetalake.java
@@ -429,6 +429,26 @@ public class GravitinoMetalake extends MetalakeDTO
ErrorHandlers.catalogErrorHandler().accept(resp);
}
+ @Override
+ public void testConnection(String catalogName) throws Exception {
+ ErrorResponse resp =
+ restClient.post(
+ String.format(
+ API_METALAKES_CATALOGS_PATH + "/testConnection",
+ RESTUtils.encodeString(this.name()),
+ RESTUtils.encodeString(catalogName)),
+ null,
+ ErrorResponse.class,
+ Collections.emptyMap(),
+ ErrorHandlers.catalogErrorHandler());
+
+ if (resp.getCode() == 0) {
+ return;
+ }
+
+ ErrorHandlers.catalogErrorHandler().accept(resp);
+ }
+
@Override
public SupportsRoles supportsRoles() {
return this;
diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/TestGravitinoAdminClient.java b/clients/client-java/src/test/java/org/apache/gravitino/client/TestGravitinoAdminClient.java
index a7b8984386..0bcf28d0d0 100644
--- a/clients/client-java/src/test/java/org/apache/gravitino/client/TestGravitinoAdminClient.java
+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/TestGravitinoAdminClient.java
@@ -315,5 +315,24 @@ public class TestGravitinoAdminClient extends TestBase {
metaLake.testConnection(
"catalog", Catalog.Type.RELATIONAL, "hive", "comment", Collections.emptyMap()));
Assertions.assertTrue(exception.getMessage().contains("connection failed"));
+
+ buildMockResource(
+ Method.POST,
+ "/api/metalakes/mock/catalogs/catalog/testConnection",
+ null,
+ new BaseResponse(),
+ HttpStatus.SC_OK);
+ Assertions.assertDoesNotThrow(() -> metaLake.testConnection("catalog"));
+
+ buildMockResource(
+ Method.POST,
+ "/api/metalakes/mock/catalogs/catalog/testConnection",
+ null,
+ ErrorResponse.unsupportedOperation("unsupported"),
+ HttpStatus.SC_OK);
+ exception =
+ Assertions.assertThrows(
+ UnsupportedOperationException.class, () -> metaLake.testConnection("catalog"));
+ Assertions.assertTrue(exception.getMessage().contains("unsupported"));
}
}
diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/CatalogIT.java b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/CatalogIT.java
index 45e911bdff..f3df2f4c9d 100644
--- a/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/CatalogIT.java
+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/CatalogIT.java
@@ -123,6 +123,7 @@ public class CatalogIT extends BaseIT {
Assertions.assertEquals("hive", catalog.provider());
Assertions.assertEquals("catalog comment", catalog.comment());
Assertions.assertTrue(catalog.properties().containsKey("metastore.uris"));
+ Assertions.assertDoesNotThrow(() -> metalake.testConnection(catalogName));
metalake.dropCatalog(catalogName, true);
}
diff --git a/clients/client-python/gravitino/client/gravitino_client.py b/clients/client-python/gravitino/client/gravitino_client.py
index 3811400987..bdce8131bd 100644
--- a/clients/client-python/gravitino/client/gravitino_client.py
+++ b/clients/client-python/gravitino/client/gravitino_client.py
@@ -120,6 +120,10 @@ class GravitinoClient(GravitinoClientBase, SupportsJobs, TagOperations):
def disable_catalog(self, name: str):
return self.get_metalake().disable_catalog(name)
+ def test_connection(self, name: str) -> None:
+ """Test an existing catalog connection using its stored configuration."""
+ self.get_metalake().test_connection(name)
+
def list_job_templates(self) -> List[JobTemplate]:
"""Lists all job templates in the current metalake.
diff --git a/clients/client-python/gravitino/client/gravitino_metalake.py b/clients/client-python/gravitino/client/gravitino_metalake.py
index 5e279ba629..32ed8656b3 100644
--- a/clients/client-python/gravitino/client/gravitino_metalake.py
+++ b/clients/client-python/gravitino/client/gravitino_metalake.py
@@ -62,10 +62,12 @@ from gravitino.dto.requests.privilege_grant_request import PrivilegeGrantRequest
from gravitino.dto.requests.privilege_revoke_request import PrivilegeRevokeRequest
from gravitino.dto.requests.role_grant_request import RoleGrantRequest
from gravitino.dto.requests.role_revoke_request import RoleRevokeRequest
+from gravitino.dto.responses.base_response import BaseResponse
from gravitino.dto.responses.catalog_list_response import CatalogListResponse
from gravitino.dto.responses.catalog_response import CatalogResponse
from gravitino.dto.responses.drop_response import DropResponse
from gravitino.dto.responses.entity_list_response import EntityListResponse
+from gravitino.dto.responses.error_response import ErrorResponse
from gravitino.dto.responses.job_list_response import JobListResponse
from gravitino.dto.responses.job_response import JobResponse
from gravitino.dto.responses.job_template_list_response import JobTemplateListResponse
@@ -363,6 +365,33 @@ class GravitinoMetalake(
url, json=catalog_disable_request, error_handler=CATALOG_ERROR_HANDLER
)
+ def test_connection(self, name: str) -> None:
+ """Test an existing catalog connection using its stored configuration.
+
+ Args:
+ name: The name of the existing catalog.
+
+ Raises:
+ NoSuchCatalogException: If the catalog does not exist.
+ UnsupportedOperationException: If the catalog does not define a connection probe.
+ ConnectionFailedException: If the catalog cannot reach its external system.
+ """
+ url = (
+ self.API_METALAKES_CATALOGS_PATH.format(
+ encode_string(self.name()), encode_string(name)
+ )
+ + "/testConnection"
+ )
+ response = self.rest_client.post(url, error_handler=CATALOG_ERROR_HANDLER)
+ base_response = BaseResponse.from_json(response.body, infer_missing=True)
+ base_response.validate()
+ if base_response.code() == 0:
+ return
+
+ error_response = ErrorResponse.from_json(response.body, infer_missing=True)
+ error_response.validate()
+ CATALOG_ERROR_HANDLER.handle(error_response)
+
##########
# Job operations
##########
diff --git a/clients/client-python/gravitino/dto/responses/error_response.py b/clients/client-python/gravitino/dto/responses/error_response.py
index edd909877f..6299b58d95 100644
--- a/clients/client-python/gravitino/dto/responses/error_response.py
+++ b/clients/client-python/gravitino/dto/responses/error_response.py
@@ -57,11 +57,9 @@ class ErrorResponse(BaseResponse):
)
def format_error_message(self) -> str:
- return (
- f"{self._message}\n" + "\n".join(self._stack)
- if self._stack is not None
- else ""
- )
+ if self._stack is None:
+ return self._message
+ return f"{self._message}\n" + "\n".join(self._stack)
@classmethod
def generate_error_response(
diff --git a/clients/client-python/tests/unittests/test_metalake.py b/clients/client-python/tests/unittests/test_metalake.py
index 3928199ed2..674539389c 100644
--- a/clients/client-python/tests/unittests/test_metalake.py
+++ b/clients/client-python/tests/unittests/test_metalake.py
@@ -16,11 +16,62 @@
# under the License.
import unittest
+from unittest.mock import MagicMock
+from gravitino.client.gravitino_metalake import GravitinoMetalake
+from gravitino.constants.error import ErrorConstants
+from gravitino.dto.metalake_dto import MetalakeDTO
from gravitino.dto.responses.metalake_response import MetalakeResponse
+from gravitino.exceptions.base import (
+ ConnectionFailedException,
+ UnsupportedOperationException,
+)
+from gravitino.exceptions.handlers.catalog_error_handler import CATALOG_ERROR_HANDLER
class TestMetalake(unittest.TestCase):
+ def test_existing_catalog_connection(self):
+ rest_client = MagicMock()
+ rest_client.post.return_value.body = b'{"code":0}'
+ metalake = GravitinoMetalake(
+ MetalakeDTO("metalake", None, {}, None), rest_client
+ )
+
+ metalake.test_connection("catalog/name")
+
+ rest_client.post.assert_called_once_with(
+ "api/metalakes/metalake/catalogs/catalog%2Fname/testConnection",
+ error_handler=CATALOG_ERROR_HANDLER,
+ )
+
+ def test_existing_catalog_connection_failure(self):
+ rest_client = MagicMock()
+ rest_client.post.return_value.body = (
+ '{"code":%d,"type":"ConnectionFailedException",'
+ '"message":"connection failed","stack":null}'
+ % ErrorConstants.CONNECTION_FAILED_CODE.value
+ ).encode("utf-8")
+ metalake = GravitinoMetalake(
+ MetalakeDTO("metalake", None, {}, None), rest_client
+ )
+
+ with self.assertRaisesRegex(ConnectionFailedException, "connection failed"):
+ metalake.test_connection("catalog")
+
+ def test_existing_catalog_connection_unsupported(self):
+ rest_client = MagicMock()
+ rest_client.post.return_value.body = (
+ '{"code":%d,"type":"UnsupportedOperationException",'
+ '"message":"unsupported","stack":null}'
+ % ErrorConstants.UNSUPPORTED_OPERATION_CODE.value
+ ).encode("utf-8")
+ metalake = GravitinoMetalake(
+ MetalakeDTO("metalake", None, {}, None), rest_client
+ )
+
+ with self.assertRaisesRegex(UnsupportedOperationException, "unsupported"):
+ metalake.test_connection("catalog")
+
def test_from_json_metalake_response(self):
str_json = (
b'{"code":0,"metalake":{"name":"example_name18","comment":"This is a sample comment",'
diff --git a/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java b/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java
index 644cb8a647..3af616040a 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java
@@ -739,7 +739,7 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
} finally {
wrapper.close();
}
- } catch (GravitinoRuntimeException e) {
+ } catch (GravitinoRuntimeException | UnsupportedOperationException e) {
throw e;
} catch (Exception e) {
LOG.warn("Failed to test catalog creation {}", ident, e);
@@ -750,6 +750,38 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
}
}
+ /**
+ * Test the connection of an existing catalog using its stored configuration.
+ *
+ * @param ident The identifier of the existing catalog.
+ */
+ @Override
+ public void testConnection(NameIdentifier ident) {
+ TreeLockUtils.doWithTreeLock(
+ ident,
+ LockType.READ,
+ () -> {
+ CatalogWrapper wrapper = loadCatalogAndWrap(ident);
+ wrapper.catalog().checkMetalakeAndCatalogInUse();
+ try {
+ wrapper.doWithCatalogOps(
+ c -> {
+ c.testConnection(ident);
+ return null;
+ });
+ } catch (UnsupportedOperationException e) {
+ throw e;
+ } catch (Exception e) {
+ LOG.warn("Failed to test existing catalog connection {}", ident, e);
+ if (e instanceof RuntimeException) {
+ throw (RuntimeException) e;
+ }
+ throw new RuntimeException(e);
+ }
+ return null;
+ });
+ }
+
@Override
public void enableCatalog(NameIdentifier ident)
throws NoSuchCatalogException, CatalogNotInUseException {
diff --git a/core/src/main/java/org/apache/gravitino/catalog/CatalogNormalizeDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/CatalogNormalizeDispatcher.java
index 56c75a6318..85ba013ba2 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/CatalogNormalizeDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/CatalogNormalizeDispatcher.java
@@ -124,6 +124,12 @@ public class CatalogNormalizeDispatcher implements CatalogDispatcher {
dispatcher.testConnection(ident, type, provider, comment, properties);
}
+ @Override
+ public void testConnection(NameIdentifier ident) throws Exception {
+ validateCatalogName(ident.name());
+ dispatcher.testConnection(ident);
+ }
+
@Override
public void enableCatalog(NameIdentifier ident) throws NoSuchCatalogException {
dispatcher.enableCatalog(ident);
diff --git a/core/src/main/java/org/apache/gravitino/catalog/SupportsCatalogs.java b/core/src/main/java/org/apache/gravitino/catalog/SupportsCatalogs.java
index c83c70cb82..a6f6ccb11e 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/SupportsCatalogs.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/SupportsCatalogs.java
@@ -176,6 +176,15 @@ public interface SupportsCatalogs {
Map<String, String> properties)
throws Exception;
+ /**
+ * Test the connection of an existing catalog using its stored configuration.
+ *
+ * @param ident The identifier of the existing catalog.
+ * @throws NoSuchCatalogException If the catalog does not exist.
+ * @throws Exception If the connection test fails.
+ */
+ void testConnection(NameIdentifier ident) throws Exception;
+
/**
* Enable a catalog. If the catalog is already enabled, this method does nothing.
*
diff --git a/core/src/main/java/org/apache/gravitino/connector/CatalogOperations.java b/core/src/main/java/org/apache/gravitino/connector/CatalogOperations.java
index e617904da3..d8d9389fa9 100644
--- a/core/src/main/java/org/apache/gravitino/connector/CatalogOperations.java
+++ b/core/src/main/java/org/apache/gravitino/connector/CatalogOperations.java
@@ -60,11 +60,24 @@ public interface CatalogOperations extends Closeable {
* @param properties the properties of the catalog.
* @throws Exception if connection fails.
*/
- void testConnection(
+ default void testConnection(
NameIdentifier catalogIdent,
Catalog.Type type,
String provider,
String comment,
Map<String, String> properties)
- throws Exception;
+ throws Exception {
+ testConnection(catalogIdent);
+ }
+
+ /**
+ * Test the connection of an existing catalog using its stored configuration.
+ *
+ * @param catalogIdent the identifier of the existing catalog.
+ * @throws Exception if the connection test fails.
+ */
+ default void testConnection(NameIdentifier catalogIdent) throws Exception {
+ throw new UnsupportedOperationException(
+ String.format("Catalog %s does not support connection testing", catalogIdent));
+ }
}
diff --git a/core/src/main/java/org/apache/gravitino/hook/CatalogHookDispatcher.java b/core/src/main/java/org/apache/gravitino/hook/CatalogHookDispatcher.java
index 81d324856e..577c71dfd8 100644
--- a/core/src/main/java/org/apache/gravitino/hook/CatalogHookDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/hook/CatalogHookDispatcher.java
@@ -167,6 +167,11 @@ public class CatalogHookDispatcher implements CatalogDispatcher {
dispatcher.testConnection(ident, type, provider, comment, properties);
}
+ @Override
+ public void testConnection(NameIdentifier ident) throws Exception {
+ dispatcher.testConnection(ident);
+ }
+
@Override
public void enableCatalog(NameIdentifier ident)
throws NoSuchCatalogException, CatalogNotInUseException {
diff --git a/core/src/main/java/org/apache/gravitino/listener/CatalogEventDispatcher.java b/core/src/main/java/org/apache/gravitino/listener/CatalogEventDispatcher.java
index ce95aa2b6a..bd738380b7 100644
--- a/core/src/main/java/org/apache/gravitino/listener/CatalogEventDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/listener/CatalogEventDispatcher.java
@@ -199,10 +199,16 @@ public class CatalogEventDispatcher implements CatalogDispatcher {
String comment,
Map<String, String> properties)
throws Exception {
- // TODO: Support event dispatching for testConnection
+ // TODO(#12566): Support event dispatching for testConnection
dispatcher.testConnection(ident, type, provider, comment, properties);
}
+ @Override
+ public void testConnection(NameIdentifier ident) throws Exception {
+ // TODO(#12566): Support event dispatching for testConnection
+ dispatcher.testConnection(ident);
+ }
+
@Override
public void enableCatalog(NameIdentifier ident)
throws NoSuchCatalogException, CatalogNotInUseException {
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestCatalogManager.java b/core/src/test/java/org/apache/gravitino/catalog/TestCatalogManager.java
index b53313f026..e1770ecc7b 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestCatalogManager.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestCatalogManager.java
@@ -38,6 +38,11 @@ import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.lang3.reflect.FieldUtils;
@@ -58,11 +63,14 @@ import org.apache.gravitino.connector.TestCatalogOperations;
import org.apache.gravitino.connector.capability.Capability;
import org.apache.gravitino.connector.capability.CapabilityResult;
import org.apache.gravitino.exceptions.CatalogAlreadyExistsException;
+import org.apache.gravitino.exceptions.CatalogNotInUseException;
import org.apache.gravitino.exceptions.NoSuchCatalogException;
import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.exceptions.NoSuchMetalakeException;
import org.apache.gravitino.exceptions.NoSuchSchemaException;
import org.apache.gravitino.lock.LockManager;
+import org.apache.gravitino.lock.LockType;
+import org.apache.gravitino.lock.TreeLockUtils;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.BaseMetalake;
import org.apache.gravitino.meta.CatalogEntity;
@@ -1363,12 +1371,66 @@ public class TestCatalogManager {
catalogManager.disableCatalog(ident);
CatalogEntity disabled = entityStore.get(ident, EntityType.CATALOG, CatalogEntity.class);
Assertions.assertEquals("false", disabled.getProperties().get(Catalog.PROPERTY_IN_USE));
+ Assertions.assertThrows(
+ CatalogNotInUseException.class, () -> catalogManager.testConnection(ident));
catalogManager.enableCatalog(ident);
CatalogEntity enabled = entityStore.get(ident, EntityType.CATALOG, CatalogEntity.class);
Assertions.assertEquals("true", enabled.getProperties().get(Catalog.PROPERTY_IN_USE));
-
Assertions.assertNull(catalogManager.getCatalogCache().getIfPresent(ident));
+ Assertions.assertThrows(
+ UnsupportedOperationException.class, () -> catalogManager.testConnection(ident));
+ }
+
+ @Test
+ void testExistingCatalogConnectionHoldsCatalogReadLock() throws Exception {
+ NameIdentifier ident = NameIdentifier.of("metalake", "connection_lock_test");
+ CatalogManager.CatalogWrapper wrapper = Mockito.mock(CatalogManager.CatalogWrapper.class);
+ BaseCatalog<?> catalog = Mockito.mock(BaseCatalog.class);
+ CountDownLatch connectionStarted = new CountDownLatch(1);
+ CountDownLatch releaseConnection = new CountDownLatch(1);
+ CountDownLatch writerStarted = new CountDownLatch(1);
+ CountDownLatch writeLockAcquired = new CountDownLatch(1);
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+
+ Mockito.doReturn(wrapper).when(catalogManager).loadCatalogAndWrap(ident);
+ Mockito.doReturn(catalog).when(wrapper).catalog();
+ Mockito.doAnswer(
+ invocation -> {
+ connectionStarted.countDown();
+ Assertions.assertTrue(releaseConnection.await(5, TimeUnit.SECONDS));
+ return null;
+ })
+ .when(wrapper)
+ .doWithCatalogOps(any());
+
+ Future<?> connectionFuture = executor.submit(() -> catalogManager.testConnection(ident));
+ Future<?> writerFuture = null;
+ try {
+ Assertions.assertTrue(connectionStarted.await(5, TimeUnit.SECONDS));
+ writerFuture =
+ executor.submit(
+ () -> {
+ writerStarted.countDown();
+ TreeLockUtils.doWithTreeLock(
+ ident,
+ LockType.WRITE,
+ () -> {
+ writeLockAcquired.countDown();
+ return null;
+ });
+ });
+ Assertions.assertTrue(writerStarted.await(5, TimeUnit.SECONDS));
+ Assertions.assertFalse(writeLockAcquired.await(200, TimeUnit.MILLISECONDS));
+
+ releaseConnection.countDown();
+ connectionFuture.get(5, TimeUnit.SECONDS);
+ writerFuture.get(5, TimeUnit.SECONDS);
+ Assertions.assertEquals(0, writeLockAcquired.getCount());
+ } finally {
+ releaseConnection.countDown();
+ executor.shutdownNow();
+ }
}
@Test
diff --git a/docs/open-api/catalogs.yaml b/docs/open-api/catalogs.yaml
index 00be079033..026b361736 100644
--- a/docs/open-api/catalogs.yaml
+++ b/docs/open-api/catalogs.yaml
@@ -88,6 +88,13 @@ paths:
tags:
- catalog
summary: Test catalog connection
+ description: >-
+ Runs the provider's smallest meaningful, read-only catalog-level operation using the
+ supplied configuration and effective credentials. This fail-fast preflight surfaces
+ configuration and connectivity failures before regular catalog operations, but does not
+ guarantee that every object-level or mutating operation will succeed. Fileset catalogs
+ test all catalog-level `location` and `location-*` targets. Model and Generic catalogs do
+ not support connection testing.
operationId: testConnection
requestBody:
content:
@@ -142,7 +149,76 @@ paths:
"5xx":
$ref: "./openapi.yaml#/components/responses/ServerErrorResponse"
-
+ /metalakes/{metalake}/catalogs/{catalog}/testConnection:
+ parameters:
+ - $ref: "./openapi.yaml#/components/parameters/metalake"
+ - $ref: "./openapi.yaml#/components/parameters/catalog"
+ post:
+ tags:
+ - catalog
+ summary: Test an existing catalog connection
+ description: >-
+ Runs the provider's smallest meaningful, read-only catalog-level operation using the
+ catalog's stored configuration and effective credentials. This fail-fast preflight
+ surfaces configuration and connectivity failures before regular catalog operations, but
+ does not guarantee that every object-level or mutating operation will succeed. Fileset
+ catalogs test all catalog-level `location` and `location-*` targets. Model and Generic
+ catalogs do not support connection testing. Expected test failures are returned as
+ application error codes in an HTTP 200 response.
+ operationId: testExistingCatalogConnection
+ responses:
+ "200":
+ description: Connection test completed, including expected test failures
+ content:
+ application/vnd.gravitino.v1+json:
+ schema:
+ type: object
+ required:
+ - code
+ properties:
+ code:
+ type: integer
+ format: int32
+ description: Application status code; 0 indicates success
+ type:
+ type: string
+ description: Internal exception type when the test fails
+ message:
+ type: string
+ description: Sanitized failure message
+ examples:
+ TestConnectionSuccess:
+ value:
+ code: 0
+ TestConnectionFailed:
+ value:
+ code: 1007
+ type: ConnectionFailedException
+ message: "Failed to test Fileset catalog connection: location (access denied)"
+ InvalidProbeTarget:
+ value:
+ code: 1001
+ type: IllegalArgumentException
+ message: Fileset catalog has no catalog-level location to test
+ TestConnectionNotSupported:
+ value:
+ code: 1006
+ type: UnsupportedOperationException
+ message: Model catalogs do not define an external catalog-level connection probe
+ CatalogNotFound:
+ value:
+ code: 1003
+ type: NoSuchCatalogException
+ message: Catalog my_metalake.my_catalog does not exist
+ CatalogDisabled:
+ value:
+ code: 1009
+ type: CatalogNotInUseException
+ message: Catalog my_metalake.my_catalog is not in use
+ "400":
+ $ref: "./openapi.yaml#/components/responses/BadRequestErrorResponse"
+ "5xx":
+ $ref: "./openapi.yaml#/components/responses/ServerErrorResponse"
/metalakes/{metalake}/catalogs/{catalog}:
parameters:
diff --git a/docs/open-api/openapi.yaml b/docs/open-api/openapi.yaml
index c8007aa52e..2b3643d613 100644
--- a/docs/open-api/openapi.yaml
+++ b/docs/open-api/openapi.yaml
@@ -117,6 +117,9 @@ paths:
/metalakes/{metalake}/catalogs/testConnection:
$ref: "./catalogs.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1catalogs~1testConnection"
+ /metalakes/{metalake}/catalogs/{catalog}/testConnection:
+ $ref: "./catalogs.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1catalogs~1%7Bcatalog%7D~1testConnection"
+
/metalakes/{metalake}/catalogs/{catalog}:
$ref: "./catalogs.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1catalogs~1%7Bcatalog%7D"
diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/CatalogOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/CatalogOperations.java
index 7c66b4a852..41f35ab7fb 100644
--- a/server/src/main/java/org/apache/gravitino/server/web/rest/CatalogOperations.java
+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/CatalogOperations.java
@@ -203,6 +203,38 @@ public class CatalogOperations {
}
}
+ @POST
+ @Path("{catalog}/testConnection")
+ @Produces("application/vnd.gravitino.v1+json")
+ @Timed(name = "test-existing-connection." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @AuthorizationExpression(
+ expression = "ANY(OWNER, METALAKE, CATALOG)",
+ accessMetadataType = MetadataObject.Type.CATALOG)
+ @ResponseMetered(name = "test-existing-connection", absolute = true)
+ public Response testExistingConnection(
+ @PathParam("metalake") @AuthorizationMetadata(type = Entity.EntityType.METALAKE)
+ String metalake,
+ @PathParam("catalog") @AuthorizationMetadata(type = Entity.EntityType.CATALOG)
+ String catalogName) {
+ LOG.info("Received test connection request for existing catalog: {}.{}", metalake, catalogName);
+ try {
+ return Utils.doAs(
+ httpRequest,
+ () -> {
+ NameIdentifier ident = NameIdentifierUtil.ofCatalog(metalake, catalogName);
+ catalogDispatcher.testConnection(ident);
+ LOG.info(
+ "Successfully tested connection for existing catalog: {}.{}",
+ metalake,
+ catalogName);
+ return Utils.ok(new BaseResponse());
+ });
+ } catch (Exception e) {
+ LOG.info("Failed to test connection for existing catalog: {}.{}", metalake, catalogName);
+ return ExceptionHandlers.handleExistingCatalogTestConnectionException(e);
+ }
+ }
+
@PATCH
@Path("{catalog}")
@Produces("application/vnd.gravitino.v1+json")
diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java b/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java
index 2570eac02a..9ceb56f82b 100644
--- a/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java
+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java
@@ -171,30 +171,17 @@ public class ExceptionHandlers {
}
public static Response handleTestConnectionException(Exception e) {
- ErrorResponse response;
- if (e instanceof IllegalArgumentException) {
- response = ErrorResponse.illegalArguments(e.getMessage(), e);
-
- } else if (e instanceof ConnectionFailedException) {
- response = ErrorResponse.connectionFailed(e.getMessage(), e);
-
- } else if (e instanceof NotFoundException) {
- response = ErrorResponse.notFound(e.getClass().getSimpleName(), e.getMessage(), e);
-
- } else if (e instanceof AlreadyExistsException) {
- response = ErrorResponse.alreadyExists(e.getClass().getSimpleName(), e.getMessage(), e);
-
- } else if (e instanceof NotInUseException) {
- response = ErrorResponse.notInUse(e.getClass().getSimpleName(), e.getMessage(), e);
-
- } else {
- return Utils.internalError(e.getMessage(), e);
- }
+ return handleTestConnectionException(e, true);
+ }
- return Response.status(Response.Status.OK)
- .entity(response)
- .type(MediaType.APPLICATION_JSON)
- .build();
+ /**
+ * Handles an existing catalog connection test failure without exposing its stack trace.
+ *
+ * @param e the connection test failure
+ * @return an HTTP 200 response containing the application error
+ */
+ public static Response handleExistingCatalogTestConnectionException(Exception e) {
+ return handleTestConnectionException(e, false);
}
public static Response handleOwnerException(
@@ -217,6 +204,38 @@ public class ExceptionHandlers {
return PartitionStatsExceptionHandler.INSTANCE.handle(type, name, parent, e);
}
+ private static Response handleTestConnectionException(Exception e, boolean includeStack) {
+ Throwable throwable = includeStack ? e : null;
+ ErrorResponse response;
+ if (e instanceof IllegalArgumentException) {
+ response = ErrorResponse.illegalArguments(e.getMessage(), throwable);
+
+ } else if (e instanceof ConnectionFailedException) {
+ response = ErrorResponse.connectionFailed(e.getMessage(), throwable);
+
+ } else if (e instanceof UnsupportedOperationException) {
+ response = ErrorResponse.unsupportedOperation(e.getMessage(), throwable);
+
+ } else if (e instanceof NotFoundException) {
+ response = ErrorResponse.notFound(e.getClass().getSimpleName(), e.getMessage(), throwable);
+
+ } else if (e instanceof AlreadyExistsException) {
+ response =
+ ErrorResponse.alreadyExists(e.getClass().getSimpleName(), e.getMessage(), throwable);
+
+ } else if (e instanceof NotInUseException) {
+ response = ErrorResponse.notInUse(e.getClass().getSimpleName(), e.getMessage(), throwable);
+
+ } else {
+ return Utils.internalError(e.getMessage(), throwable);
+ }
+
+ return Response.status(Response.Status.OK)
+ .entity(response)
+ .type(MediaType.APPLICATION_JSON)
+ .build();
+ }
+
private static class PartitionExceptionHandler extends BaseExceptionHandler {
private static final ExceptionHandler INSTANCE = new PartitionExceptionHandler();
diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestCatalogOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestCatalogOperations.java
index 36fda659ea..4c0da660df 100644
--- a/server/src/test/java/org/apache/gravitino/server/web/rest/TestCatalogOperations.java
+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestCatalogOperations.java
@@ -64,6 +64,8 @@ import org.apache.gravitino.dto.responses.EntityListResponse;
import org.apache.gravitino.dto.responses.ErrorConstants;
import org.apache.gravitino.dto.responses.ErrorResponse;
import org.apache.gravitino.exceptions.CatalogAlreadyExistsException;
+import org.apache.gravitino.exceptions.CatalogNotInUseException;
+import org.apache.gravitino.exceptions.ConnectionFailedException;
import org.apache.gravitino.exceptions.NoSuchCatalogException;
import org.apache.gravitino.exceptions.NoSuchMetalakeException;
import org.apache.gravitino.lock.LockManager;
@@ -340,6 +342,85 @@ public class TestCatalogOperations extends BaseOperationsTest {
ErrorResponse errorResponse = resp1.readEntity(ErrorResponse.class);
Assertions.assertEquals(ErrorConstants.INTERNAL_ERROR_CODE, errorResponse.getCode());
Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResponse.getType());
+
+ ConnectionFailedException legacyFailure =
+ new ConnectionFailedException(
+ new IllegalStateException("database connection detail"), "connection failed");
+ doThrow(legacyFailure).when(manager).testConnection(any(), any(), any(), any(), any());
+ Response failedResponse =
+ target("/metalakes/metalake1/catalogs/testConnection")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .post(Entity.entity(req, MediaType.APPLICATION_JSON_TYPE));
+
+ ErrorResponse connectionError = failedResponse.readEntity(ErrorResponse.class);
+ Assertions.assertEquals(ErrorConstants.CONNECTION_FAILED_CODE, connectionError.getCode());
+ Assertions.assertNotNull(connectionError.getStack());
+ Assertions.assertTrue(
+ String.join("\n", connectionError.getStack()).contains("database connection detail"));
+ }
+
+ @Test
+ public void testExistingCatalogConnection() {
+ doNothing().when(manager).testConnection(any(NameIdentifier.class));
+ Response response =
+ target("/metalakes/metalake1/catalogs/catalog1/testConnection")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .post(null);
+
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
+ Assertions.assertEquals(0, response.readEntity(BaseResponse.class).getCode());
+
+ doThrow(new ConnectionFailedException("sanitized failure"))
+ .when(manager)
+ .testConnection(any(NameIdentifier.class));
+ Response failedResponse =
+ target("/metalakes/metalake1/catalogs/catalog1/testConnection")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .post(null);
+
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), failedResponse.getStatus());
+ ErrorResponse errorResponse = failedResponse.readEntity(ErrorResponse.class);
+ Assertions.assertEquals(ErrorConstants.CONNECTION_FAILED_CODE, errorResponse.getCode());
+ Assertions.assertEquals("sanitized failure", errorResponse.getMessage());
+ Assertions.assertNull(errorResponse.getStack());
+
+ doThrow(new UnsupportedOperationException("unsupported"))
+ .when(manager)
+ .testConnection(any(NameIdentifier.class));
+ Response unsupportedResponse =
+ target("/metalakes/metalake1/catalogs/catalog1/testConnection")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .post(null);
+ ErrorResponse unsupported = unsupportedResponse.readEntity(ErrorResponse.class);
+ Assertions.assertEquals(ErrorConstants.UNSUPPORTED_OPERATION_CODE, unsupported.getCode());
+ Assertions.assertNull(unsupported.getStack());
+
+ assertExistingCatalogConnectionError(
+ new IllegalArgumentException("invalid catalog configuration"),
+ ErrorConstants.ILLEGAL_ARGUMENTS_CODE);
+ assertExistingCatalogConnectionError(
+ new NoSuchCatalogException("catalog does not exist"), ErrorConstants.NOT_FOUND_CODE);
+ assertExistingCatalogConnectionError(
+ new CatalogNotInUseException("catalog is not in use"), ErrorConstants.NOT_IN_USE_CODE);
+
+ doThrow(new RuntimeException("unexpected failure"))
+ .when(manager)
+ .testConnection(any(NameIdentifier.class));
+ Response internalErrorResponse =
+ target("/metalakes/metalake1/catalogs/catalog1/testConnection")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .post(null);
+ Assertions.assertEquals(
+ INTERNAL_SERVER_ERROR.getStatusCode(), internalErrorResponse.getStatus());
+ ErrorResponse internalError = internalErrorResponse.readEntity(ErrorResponse.class);
+ Assertions.assertEquals(ErrorConstants.INTERNAL_ERROR_CODE, internalError.getCode());
+ Assertions.assertEquals("unexpected failure", internalError.getMessage());
+ Assertions.assertNull(internalError.getStack());
}
@Test
@@ -607,6 +688,22 @@ public class TestCatalogOperations extends BaseOperationsTest {
return new TestCatalog().withCatalogConf(Collections.emptyMap()).withCatalogEntity(entity);
}
+ private void assertExistingCatalogConnectionError(RuntimeException exception, int expectedCode) {
+ doThrow(exception).when(manager).testConnection(any(NameIdentifier.class));
+ Response response =
+ target("/metalakes/metalake1/catalogs/catalog1/testConnection")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .post(null);
+
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
+ ErrorResponse errorResponse = response.readEntity(ErrorResponse.class);
+ Assertions.assertEquals(expectedCode, errorResponse.getCode());
+ Assertions.assertEquals(exception.getClass().getSimpleName(), errorResponse.getType());
+ Assertions.assertEquals(exception.getMessage(), errorResponse.getMessage());
+ Assertions.assertNull(errorResponse.getStack());
+ }
+
private static TestCatalog buildCatalog(String metalake, String catalogName) {
CatalogEntity entity =
CatalogEntity.builder()