World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#11486] refactor(catalog): Add shared Hadoop Kerberos auth module (#11765)
Qi Yu1729e33b2753
diff --git a/build.gradle.kts b/build.gradle.ktsindex 26fd64bd1e..3a2b96e1f9 100644--- a/build.gradle.kts+++ b/build.gradle.kts@@ -357,6 +357,7 @@ subprojects {":api",":common",":catalogs:catalog-common",+ ":catalogs:hadoop-auth",":catalogs:hadoop-common",":maintenance:jobs",":maintenance:optimizer-api",@@ -1180,6 +1181,7 @@ tasks {!it.name.startsWith("optimizer") &&it.name != "hive-metastore-common" &&it.name != "docs" &&+ it.name != "hadoop-auth" &&it.name != "hadoop-common" &&it.name != "web" &&it.name != "web-v2" &&diff --git a/catalogs/catalog-fileset/build.gradle.kts b/catalogs/catalog-fileset/build.gradle.ktsindex 6e048200dc..0ed158f61a 100644--- a/catalogs/catalog-fileset/build.gradle.kts+++ b/catalogs/catalog-fileset/build.gradle.kts@@ -37,6 +37,11 @@ dependencies {implementation(project(":catalogs:hadoop-common")) {exclude(group = "*")}+ // hadoop-common's Kerberos path lives in :catalogs:hadoop-auth; bundle it into the+ // catalog runtime libs (the hadoop-common dependency above is non-transitive).+ implementation(project(":catalogs:hadoop-auth")) {+ exclude(group = "*")+ }implementation(libs.caffeine)implementation(libs.cglib)diff --git a/catalogs/catalog-lakehouse-paimon/build.gradle.kts b/catalogs/catalog-lakehouse-paimon/build.gradle.ktsindex 1d2df30a3a..0ba959ba90 100644--- a/catalogs/catalog-lakehouse-paimon/build.gradle.kts+++ b/catalogs/catalog-lakehouse-paimon/build.gradle.kts@@ -39,6 +39,9 @@ dependencies {implementation(project(":catalogs:catalog-common")) {exclude("*")}+ implementation(project(":catalogs:hadoop-auth")) {+ exclude("*")+ }implementation(libs.bundles.log4j)implementation(libs.bundles.paimon) {diff --git a/catalogs/catalog-lakehouse-paimon/src/main/java/org/apache/gravitino/catalog/lakehouse/paimon/authentication/kerberos/KerberosClient.java b/catalogs/catalog-lakehouse-paimon/src/main/java/org/apache/gravitino/catalog/lakehouse/paimon/authentication/kerberos/KerberosClient.javadeleted file mode 100644index 6e4737d9bb..0000000000--- a/catalogs/catalog-lakehouse-paimon/src/main/java/org/apache/gravitino/catalog/lakehouse/paimon/authentication/kerberos/KerberosClient.java+++ /dev/null@@ -1,124 +0,0 @@-/*- * 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.lakehouse.paimon.authentication.kerberos;--import com.google.common.util.concurrent.ThreadFactoryBuilder;-import java.io.Closeable;-import java.io.File;-import java.io.IOException;-import java.util.Map;-import java.util.concurrent.ScheduledThreadPoolExecutor;-import java.util.concurrent.ThreadFactory;-import java.util.concurrent.TimeUnit;-import org.apache.gravitino.utils.FileFetcher;-import org.apache.hadoop.conf.Configuration;-import org.apache.hadoop.security.UserGroupInformation;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;--public class KerberosClient implements Closeable {- private static final Logger LOG = LoggerFactory.getLogger(KerberosClient.class);-- public static final String GRAVITINO_KEYTAB_FORMAT =- "keytabs/gravitino-lakehouse-paimon-%s-keytab";-- private final ScheduledThreadPoolExecutor checkTgtExecutor;- private final Map<String, String> conf;- private final Configuration hadoopConf;-- public KerberosClient(Map<String, String> conf, Configuration hadoopConf) {- this.conf = conf;- this.hadoopConf = hadoopConf;- this.checkTgtExecutor = new ScheduledThreadPoolExecutor(1, getThreadFactory("check-tgt"));- }-- /**- * performing kerberos authentication based on the keytab file.- *- * @param keytabFilePath local keytab file path- * @throws IOException if Kerberos authentication fails- */- public void login(String keytabFilePath) throws IOException {- KerberosConfig kerberosConfig = new KerberosConfig(conf);-- // Check the principal and keytab file- String catalogPrincipal = kerberosConfig.getPrincipalName();-- // Login- UserGroupInformation.setConfiguration(hadoopConf);- UserGroupInformation.loginUserFromKeytab(catalogPrincipal, keytabFilePath);- UserGroupInformation kerberosLoginUgi = UserGroupInformation.getCurrentUser();-- // Refresh the cache if it's out of date.- int checkInterval = kerberosConfig.getCheckIntervalSec();- checkTgtExecutor.scheduleAtFixedRate(- () -> {- try {- kerberosLoginUgi.checkTGTAndReloginFromKeytab();- } catch (Exception e) {- LOG.error("Fail to refresh ugi token: ", e);- }- },- checkInterval,- checkInterval,- TimeUnit.SECONDS);- }-- public File saveKeyTabFileFromUri(String catalogId) throws IOException {-- KerberosConfig kerberosConfig = new KerberosConfig(conf);-- String keyTabUri = kerberosConfig.getKeytab();-- File keytabsDir = new File("keytabs");- if (!keytabsDir.exists()) {- // Ignore the return value, because there exists many Paimon catalog operations making- // this directory.- keytabsDir.mkdir();- }-- File keytabFile = new File(String.format(GRAVITINO_KEYTAB_FORMAT, catalogId));- keytabFile.deleteOnExit();- if (keytabFile.exists() && !keytabFile.delete()) {- throw new IllegalStateException(- String.format("Fail to delete keytab file %s", keytabFile.getAbsolutePath()));- }-- int fetchKeytabFileTimeout = kerberosConfig.getFetchTimeoutSec();- FileFetcher.get()- .fetchFileFromUri(- keyTabUri,- keytabFile,- fetchKeytabFileTimeout * 1000,- null /* hadoopConf: Paimon keytab URIs never use the hdfs scheme */);-- return keytabFile;- }-- private static ThreadFactory getThreadFactory(String factoryName) {- return new ThreadFactoryBuilder().setDaemon(true).setNameFormat(factoryName + "-%d").build();- }-- @Override- public void close() {- if (checkTgtExecutor != null) {- checkTgtExecutor.shutdown();- }- }-}diff --git a/catalogs/catalog-lakehouse-paimon/src/main/java/org/apache/gravitino/catalog/lakehouse/paimon/utils/CatalogUtils.java b/catalogs/catalog-lakehouse-paimon/src/main/java/org/apache/gravitino/catalog/lakehouse/paimon/utils/CatalogUtils.javaindex d479dfa43d..1c44cb498e 100644--- a/catalogs/catalog-lakehouse-paimon/src/main/java/org/apache/gravitino/catalog/lakehouse/paimon/utils/CatalogUtils.java+++ b/catalogs/catalog-lakehouse-paimon/src/main/java/org/apache/gravitino/catalog/lakehouse/paimon/utils/CatalogUtils.java@@ -35,10 +35,12 @@ import java.util.HashMap;import java.util.Map;import java.util.UUID;import org.apache.commons.lang3.StringUtils;+import org.apache.gravitino.catalog.hadoop.auth.KerberosAuthUtils;+import org.apache.gravitino.catalog.hadoop.auth.KerberosClient;import org.apache.gravitino.catalog.lakehouse.paimon.PaimonCatalogBackend;import org.apache.gravitino.catalog.lakehouse.paimon.PaimonConfig;import org.apache.gravitino.catalog.lakehouse.paimon.authentication.AuthenticationConfig;-import org.apache.gravitino.catalog.lakehouse.paimon.authentication.kerberos.KerberosClient;+import org.apache.gravitino.catalog.lakehouse.paimon.authentication.kerberos.KerberosConfig;import org.apache.gravitino.catalog.lakehouse.paimon.ops.PaimonBackendCatalogWrapper;import org.apache.gravitino.exceptions.ConnectionFailedException;import org.apache.hadoop.conf.Configuration;@@ -64,9 +66,24 @@ public class CatalogUtils {configuration.set(HADOOP_SECURITY_AUTHENTICATION, "kerberos");try {- KerberosClient kerberosClient = new KerberosClient(allConfig, configuration);+ KerberosConfig kerberosConfig = new KerberosConfig(allConfig);+ KerberosClient kerberosClient =+ KerberosClient.builder(kerberosConfig.getPrincipalName(), configuration)+ .loginMode(KerberosAuthUtils.LoginMode.CURRENT_USER)+ .checkIntervalSec(kerberosConfig.getCheckIntervalSec())+ .build();File keytabFile =- kerberosClient.saveKeyTabFileFromUri(UUID.randomUUID().toString().replace("-", ""));+ new File(+ String.format(+ "keytabs/gravitino-lakehouse-paimon-%s-keytab",+ UUID.randomUUID().toString().replace("-", "")));+ KerberosAuthUtils.saveKeytabFromUri(+ kerberosConfig.getKeytab(),+ keytabFile,+ kerberosConfig.getFetchTimeoutSec(),+ false,+ // Paimon keytab URIs never use the hdfs scheme.+ null);kerberosClient.login(keytabFile.getAbsolutePath());Catalog catalog = loadCatalogBackendWithKerberosAuth(paimonConfig, configuration);return new PaimonBackendCatalogWrapper(catalog, kerberosClient);diff --git a/catalogs/hadoop-auth/build.gradle.kts b/catalogs/hadoop-auth/build.gradle.ktsnew file mode 100644index 0000000000..7fb39e288a--- /dev/null+++ b/catalogs/hadoop-auth/build.gradle.kts@@ -0,0 +1,46 @@+/*+ * 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.+ */++description = "hadoop-auth"++plugins {+ id("java")+}++dependencies {+ compileOnly(project(":api"))+ compileOnly(project(":common"))++ compileOnly(libs.hadoop3.client.api)+ compileOnly(libs.guava)+ compileOnly(libs.slf4j.api)++ testImplementation(project(":api"))+ testImplementation(project(":common"))++ testImplementation(libs.hadoop3.client.api)+ testImplementation(libs.hadoop3.client.runtime)+ testImplementation(libs.guava)+ testImplementation(libs.junit.jupiter.api)+ testImplementation(libs.junit.jupiter.params)+ testImplementation(libs.mockito.core)+ testImplementation(libs.slf4j.api)++ testRuntimeOnly(libs.junit.jupiter.engine)+}diff --git a/catalogs/hadoop-auth/src/main/java/org/apache/gravitino/catalog/hadoop/auth/KerberosAuthUtils.java b/catalogs/hadoop-auth/src/main/java/org/apache/gravitino/catalog/hadoop/auth/KerberosAuthUtils.javanew file mode 100644index 0000000000..c29b43a0d0--- /dev/null+++ b/catalogs/hadoop-auth/src/main/java/org/apache/gravitino/catalog/hadoop/auth/KerberosAuthUtils.java@@ -0,0 +1,249 @@+/*+ * 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.auth;++import com.google.common.base.Preconditions;+import java.io.File;+import java.io.IOException;+import java.net.URI;+import java.net.URISyntaxException;+import java.util.concurrent.Executors;+import java.util.concurrent.ScheduledExecutorService;+import java.util.concurrent.ThreadFactory;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.atomic.AtomicInteger;+import javax.annotation.Nullable;+import org.apache.gravitino.utils.FileFetcher;+import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.security.UserGroupInformation;+import org.slf4j.Logger;++/** Shared Kerberos helpers for Hadoop-aware Gravitino modules. */+public final class KerberosAuthUtils {++ private static final String TICKET_REFRESH_THREAD_NAME_PREFIX = "kerberos-ticket-refresh-";+ private static final AtomicInteger TICKET_REFRESH_THREAD_ID = new AtomicInteger(0);++ private KerberosAuthUtils() {}++ /** Login behavior used by Hadoop-backed Kerberos clients. */+ public enum LoginMode {+ /** Log in as the process login user and return {@link UserGroupInformation#getLoginUser()}. */+ LOGIN_USER,++ /**+ * Log in as the process login user and return {@link UserGroupInformation#getCurrentUser()}.+ */+ CURRENT_USER,++ /** Return an isolated UGI from {@link UserGroupInformation#loginUserFromKeytabAndReturnUGI}. */+ RETURN_UGI+ }++ /**+ * Validates a Kerberos principal and returns its realm.+ *+ * @param principal Kerberos principal in {@code name@REALM} format+ * @return the realm portion of the principal+ */+ public static String checkPrincipalAndGetRealm(String principal) {+ Preconditions.checkArgument(principal != null, "The principal can't be blank");++ String normalizedPrincipal = principal.trim();+ Preconditions.checkArgument(!normalizedPrincipal.isEmpty(), "The principal can't be blank");++ String[] principalComponents = normalizedPrincipal.split("@", -1);+ Preconditions.checkArgument(+ principalComponents.length == 2+ && !principalComponents[0].isEmpty()+ && !principalComponents[1].isEmpty(),+ "The principal has the wrong format");++ return principalComponents[1];+ }++ /**+ * Fetches a Kerberos keytab URI to a local file.+ *+ * @param keytabUri source keytab URI+ * @param keytabFile local destination file+ * @param timeoutSec fetch timeout in seconds+ * @param allowHdfsKeytabUri whether {@code hdfs://} keytab URIs are allowed+ * @param hadoopConf Hadoop configuration, required only when fetching an HDFS URI+ * @return the fetched local keytab file+ * @throws IOException if the file cannot be fetched+ */+ public static File fetchKeytabFromUri(+ String keytabUri,+ File keytabFile,+ int timeoutSec,+ boolean allowHdfsKeytabUri,+ @Nullable Configuration hadoopConf)+ throws IOException {+ Preconditions.checkArgument(+ keytabUri != null && !keytabUri.trim().isEmpty(), "Keytab uri can't be blank");+ Preconditions.checkArgument(+ allowHdfsKeytabUri || !isHdfsUri(keytabUri),+ "HDFS URIs are not supported for keytab files");++ File parentFile = keytabFile.getParentFile();+ if (parentFile != null && !parentFile.exists() && !parentFile.mkdirs()) {+ throw new IOException(+ String.format("Failed to create keytab directory %s", parentFile.getAbsolutePath()));+ }++ FileFetcher.get().fetchFileFromUri(keytabUri, keytabFile, timeoutSec * 1000, hadoopConf);+ return keytabFile;+ }++ /**+ * Fetches a keytab URI into {@code keytabFile}, replacing any stale file first.+ *+ * <p>Deletes a pre-existing destination, marks the new file for deletion on JVM exit, and then+ * fetches the keytab. The parent directory is created if needed.+ *+ * @param keytabUri source keytab URI+ * @param keytabFile local destination file+ * @param timeoutSec fetch timeout in seconds+ * @param allowHdfsKeytabUri whether {@code hdfs://} keytab URIs are allowed+ * @param hadoopConf Hadoop configuration, required only when fetching an HDFS URI+ * @return the fetched local keytab file+ * @throws IOException if the file cannot be fetched+ */+ public static File saveKeytabFromUri(+ String keytabUri,+ File keytabFile,+ int timeoutSec,+ boolean allowHdfsKeytabUri,+ @Nullable Configuration hadoopConf)+ throws IOException {+ keytabFile.deleteOnExit();+ if (keytabFile.exists() && !keytabFile.delete()) {+ throw new IllegalStateException(+ String.format("Fail to delete keytab file %s", keytabFile.getAbsolutePath()));+ }+ return fetchKeytabFromUri(keytabUri, keytabFile, timeoutSec, allowHdfsKeytabUri, hadoopConf);+ }++ /**+ * Configures the JVM Kerberos configuration path from a Hadoop configuration key.+ *+ * @param hadoopConf Hadoop configuration+ * @param hadoopKrb5ConfKey Hadoop configuration key that stores the krb5.conf path+ * @param systemKrb5ConfKey JVM system property key for the krb5.conf path+ */+ public static void configureKrb5Conf(+ Configuration hadoopConf, String hadoopKrb5ConfKey, String systemKrb5ConfKey) {+ Preconditions.checkArgument(hadoopConf != null, "Hadoop configuration can't be null");+ Preconditions.checkArgument(+ hadoopKrb5ConfKey != null && !hadoopKrb5ConfKey.trim().isEmpty(),+ "Hadoop krb5.conf key can't be blank");+ Preconditions.checkArgument(+ systemKrb5ConfKey != null && !systemKrb5ConfKey.trim().isEmpty(),+ "System krb5.conf key can't be blank");++ String krb5Config = hadoopConf.get(hadoopKrb5ConfKey);+ if (krb5Config != null) {+ System.setProperty(systemKrb5ConfKey, krb5Config);+ }+ }++ /**+ * Logs in with a Kerberos keytab.+ *+ * @param principal Kerberos principal+ * @param keytabFilePath local keytab file path+ * @param hadoopConf Hadoop configuration+ * @param loginMode login behavior to use+ * @return the login UGI+ * @throws IOException if login fails+ */+ public static UserGroupInformation login(+ String principal, String keytabFilePath, Configuration hadoopConf, LoginMode loginMode)+ throws IOException {+ checkPrincipalAndGetRealm(principal);+ Preconditions.checkArgument(loginMode != null, "loginMode can't be null");+ UserGroupInformation.setConfiguration(hadoopConf);++ switch (loginMode) {+ case RETURN_UGI:+ return UserGroupInformation.loginUserFromKeytabAndReturnUGI(principal, keytabFilePath);+ case CURRENT_USER:+ UserGroupInformation.loginUserFromKeytab(principal, keytabFilePath);+ return UserGroupInformation.getCurrentUser();+ case LOGIN_USER:+ UserGroupInformation.loginUserFromKeytab(principal, keytabFilePath);+ return UserGroupInformation.getLoginUser();+ default:+ throw new IllegalArgumentException(String.format("Unsupported loginMode: %s", loginMode));+ }+ }++ /**+ * Starts a dedicated single-thread daemon scheduler that periodically refreshes a keytab-backed+ * TGT.+ *+ * <p>Each caller gets its own executor so a slow or unreachable KDC only blocks that caller's+ * refresh. The caller owns the returned executor and must shut it down (via {@link+ * ScheduledExecutorService#shutdown()}) when it is no longer needed.+ *+ * @param loginUgi login user to refresh+ * @param checkIntervalSec refresh interval in seconds+ * @param log logger used for refresh failures+ * @return the scheduler running the refresh task, owned by the caller+ */+ public static ScheduledExecutorService startTicketRefresh(+ UserGroupInformation loginUgi, int checkIntervalSec, Logger log) {+ Preconditions.checkArgument(checkIntervalSec > 0, "The check interval must be positive");++ ScheduledExecutorService executor =+ Executors.newSingleThreadScheduledExecutor(+ daemonThreadFactory(TICKET_REFRESH_THREAD_NAME_PREFIX));+ executor.scheduleAtFixedRate(+ () -> refreshTicket(loginUgi, log), checkIntervalSec, checkIntervalSec, TimeUnit.SECONDS);+ return executor;+ }++ private static boolean isHdfsUri(String keytabUri) {+ try {+ URI uri = new URI(keytabUri.trim());+ return "hdfs".equalsIgnoreCase(uri.getScheme());+ } catch (URISyntaxException e) {+ return keytabUri.trim().startsWith("hdfs");+ }+ }++ private static void refreshTicket(UserGroupInformation loginUgi, Logger log) {+ try {+ loginUgi.checkTGTAndReloginFromKeytab();+ } catch (Exception e) {+ log.error("Fail to refresh ugi token: ", e);+ }+ }++ private static ThreadFactory daemonThreadFactory(String threadNamePrefix) {+ return runnable -> {+ Thread thread = new Thread(runnable);+ thread.setDaemon(true);+ thread.setName(threadNamePrefix + TICKET_REFRESH_THREAD_ID.getAndIncrement());+ return thread;+ };+ }+}diff --git a/catalogs/hadoop-auth/src/main/java/org/apache/gravitino/catalog/hadoop/auth/KerberosClient.java b/catalogs/hadoop-auth/src/main/java/org/apache/gravitino/catalog/hadoop/auth/KerberosClient.javanew file mode 100644index 0000000000..8576e35c99--- /dev/null+++ b/catalogs/hadoop-auth/src/main/java/org/apache/gravitino/catalog/hadoop/auth/KerberosClient.java@@ -0,0 +1,187 @@+/*+ * 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.auth;++import com.google.common.base.Preconditions;+import java.io.Closeable;+import java.io.IOException;+import java.util.concurrent.ScheduledExecutorService;+import javax.annotation.Nullable;+import org.apache.gravitino.catalog.hadoop.auth.KerberosAuthUtils.LoginMode;+import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.security.UserGroupInformation;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++/**+ * Shared keytab-based Kerberos login client for Hadoop-aware Gravitino modules.+ *+ * <p>Handles the common orchestration — validate principal, optionally point the JVM at a+ * krb5.conf, log in from a keytab, and (optionally) schedule a background TGT refresh. Per-module+ * differences (login mode, refresh on/off, thread name, krb5.conf wiring) are supplied through+ * {@link Builder}.+ */+public class KerberosClient implements Closeable {++ private static final Logger LOG = LoggerFactory.getLogger(KerberosClient.class);++ private final String principal;+ private final Configuration hadoopConf;+ private final LoginMode loginMode;+ private final boolean refreshCredentials;+ private final int checkIntervalSec;+ @Nullable private final String hadoopKrb5ConfKey;+ @Nullable private final String systemKrb5ConfKey;++ private ScheduledExecutorService checkTgtRefreshExecutor;+ private UserGroupInformation loginUser;+ private String realm;++ private KerberosClient(Builder builder) {+ this.principal = builder.principal;+ this.hadoopConf = builder.hadoopConf;+ this.loginMode = builder.loginMode;+ this.refreshCredentials = builder.refreshCredentials;+ this.checkIntervalSec = builder.checkIntervalSec;+ this.hadoopKrb5ConfKey = builder.hadoopKrb5ConfKey;+ this.systemKrb5ConfKey = builder.systemKrb5ConfKey;+ }++ /**+ * Logs in from the given keytab and, when configured, starts a background TGT refresh.+ *+ * @param keytabFilePath local keytab file path+ * @return the resulting login UGI (also available via {@link #getLoginUser()})+ * @throws IOException if login fails+ */+ public UserGroupInformation login(String keytabFilePath) throws IOException {+ this.realm = KerberosAuthUtils.checkPrincipalAndGetRealm(principal);+ if (hadoopKrb5ConfKey != null) {+ KerberosAuthUtils.configureKrb5Conf(hadoopConf, hadoopKrb5ConfKey, systemKrb5ConfKey);+ }+ this.loginUser = KerberosAuthUtils.login(principal, keytabFilePath, hadoopConf, loginMode);+ if (refreshCredentials) {+ shutdownTicketRefresh();+ this.checkTgtRefreshExecutor =+ KerberosAuthUtils.startTicketRefresh(loginUser, checkIntervalSec, LOG);+ }+ return loginUser;+ }++ /** Returns the realm parsed from the principal, available after {@link #login(String)}. */+ public String getRealm() {+ Preconditions.checkState(realm != null, "login() has not been called");+ return realm;+ }++ /** Returns the login UGI, available after {@link #login(String)}. */+ public UserGroupInformation getLoginUser() {+ Preconditions.checkState(loginUser != null, "login() has not been called");+ return loginUser;+ }++ @Override+ public void close() {+ shutdownTicketRefresh();+ }++ private void shutdownTicketRefresh() {+ if (checkTgtRefreshExecutor != null) {+ // Graceful shutdown: let any in-flight relogin finish before the thread is torn down.+ checkTgtRefreshExecutor.shutdown();+ checkTgtRefreshExecutor = null;+ }+ }++ /**+ * Creates a builder for a client logging in as {@code principal}.+ *+ * @param principal Kerberos principal in {@code name@REALM} format+ * @param hadoopConf Hadoop configuration+ * @return a new builder+ */+ public static Builder builder(String principal, Configuration hadoopConf) {+ return new Builder(principal, hadoopConf);+ }++ /** Builder for {@link KerberosClient}. */+ public static final class Builder {+ private final String principal;+ private final Configuration hadoopConf;+ private LoginMode loginMode = LoginMode.CURRENT_USER;+ private boolean refreshCredentials = true;+ private int checkIntervalSec = 60;+ private String hadoopKrb5ConfKey;+ private String systemKrb5ConfKey;++ private Builder(String principal, Configuration hadoopConf) {+ this.principal = principal;+ this.hadoopConf = hadoopConf;+ }++ /** Sets the login mode (defaults to {@link LoginMode#CURRENT_USER}). */+ public Builder loginMode(LoginMode mode) {+ this.loginMode = mode;+ return this;+ }++ /** Enables or disables the background TGT refresh (defaults to enabled). */+ public Builder refreshCredentials(boolean refresh) {+ this.refreshCredentials = refresh;+ return this;+ }++ /** Sets the TGT refresh interval in seconds (used only when refresh is enabled). */+ public Builder checkIntervalSec(int seconds) {+ this.checkIntervalSec = seconds;+ return this;+ }++ /**+ * Points the JVM krb5.conf system property at the path stored under {@code hadoopKrb5ConfKey}+ * in the Hadoop configuration before login. When not set, the JVM krb5.conf is left untouched.+ */+ public Builder krb5Conf(String hadoopKrb5ConfKey, String systemKrb5ConfKey) {+ this.hadoopKrb5ConfKey = hadoopKrb5ConfKey;+ this.systemKrb5ConfKey = systemKrb5ConfKey;+ return this;+ }++ /** Builds the client. */+ public KerberosClient build() {+ Preconditions.checkArgument(+ principal != null && !principal.trim().isEmpty(), "principal can't be blank");+ Preconditions.checkArgument(hadoopConf != null, "hadoopConf can't be null");+ Preconditions.checkArgument(loginMode != null, "loginMode can't be null");+ if (refreshCredentials) {+ Preconditions.checkArgument(checkIntervalSec > 0, "checkIntervalSec must be positive");+ }+ if (hadoopKrb5ConfKey != null || systemKrb5ConfKey != null) {+ Preconditions.checkArgument(+ hadoopKrb5ConfKey != null && !hadoopKrb5ConfKey.trim().isEmpty(),+ "hadoopKrb5ConfKey can't be blank");+ Preconditions.checkArgument(+ systemKrb5ConfKey != null && !systemKrb5ConfKey.trim().isEmpty(),+ "systemKrb5ConfKey can't be blank");+ }+ return new KerberosClient(this);+ }+ }+}diff --git a/catalogs/hadoop-auth/src/test/java/org/apache/gravitino/catalog/hadoop/auth/TestKerberosAuthUtils.java b/catalogs/hadoop-auth/src/test/java/org/apache/gravitino/catalog/hadoop/auth/TestKerberosAuthUtils.javanew file mode 100644index 0000000000..a6759daa32--- /dev/null+++ b/catalogs/hadoop-auth/src/test/java/org/apache/gravitino/catalog/hadoop/auth/TestKerberosAuthUtils.java@@ -0,0 +1,175 @@+/*+ * 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.auth;++import java.io.File;+import java.nio.file.Files;+import java.util.concurrent.ScheduledExecutorService;+import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.security.UserGroupInformation;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.io.TempDir;+import org.mockito.Mockito;+import org.slf4j.LoggerFactory;++public class TestKerberosAuthUtils {++ @TempDir private File tempDir;++ @Test+ public void testCheckPrincipalAndGetRealm() {+ Assertions.assertEquals(+ "EXAMPLE.COM", KerberosAuthUtils.checkPrincipalAndGetRealm("service/[email protected]"));+ Assertions.assertEquals(+ "EXAMPLE.COM", KerberosAuthUtils.checkPrincipalAndGetRealm(" service/[email protected] "));++ Assertions.assertThrows(+ IllegalArgumentException.class, () -> KerberosAuthUtils.checkPrincipalAndGetRealm(""));+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> KerberosAuthUtils.checkPrincipalAndGetRealm("service/host"));+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> KerberosAuthUtils.checkPrincipalAndGetRealm("service/host@REALM@EXTRA"));+ }++ @Test+ public void testFetchKeytabFromLocalUri() throws Exception {+ File source = new File(tempDir, "source.keytab");+ File destination = new File(tempDir, "destination.keytab");+ Files.writeString(source.toPath(), "keytab-content");++ File fetched =+ KerberosAuthUtils.fetchKeytabFromUri(+ source.toURI().toString(),+ destination,+ 1,+ false /* allowHdfsKeytabUri */,+ null /* hadoopConf */);++ Assertions.assertEquals(destination.getAbsolutePath(), fetched.getAbsolutePath());+ Assertions.assertTrue(Files.isSymbolicLink(destination.toPath()));+ Assertions.assertEquals(source.toPath(), Files.readSymbolicLink(destination.toPath()));+ }++ @Test+ public void testFetchKeytabRejectsHdfsWhenDisabled() {+ File destination = new File(tempDir, "destination.keytab");++ IllegalArgumentException exception =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ KerberosAuthUtils.fetchKeytabFromUri(+ "hdfs://namenode/keytab",+ destination,+ 1,+ false /* allowHdfsKeytabUri */,+ null /* hadoopConf */));++ Assertions.assertTrue(exception.getMessage().contains("HDFS"));+ }++ @Test+ public void testConfigureKrb5ConfSetsSystemProperty() {+ String hadoopKrb5ConfKey = "gravitino.test.krb5.conf";+ String systemKrb5ConfKey = "java.security.krb5.conf.test";+ String krb5ConfPath = new File(tempDir, "krb5.conf").getAbsolutePath();+ Configuration configuration = new Configuration(false);+ configuration.set(hadoopKrb5ConfKey, krb5ConfPath);++ String originalValue = System.getProperty(systemKrb5ConfKey);+ try {+ KerberosAuthUtils.configureKrb5Conf(configuration, hadoopKrb5ConfKey, systemKrb5ConfKey);+ Assertions.assertEquals(krb5ConfPath, System.getProperty(systemKrb5ConfKey));+ } finally {+ if (originalValue == null) {+ System.clearProperty(systemKrb5ConfKey);+ } else {+ System.setProperty(systemKrb5ConfKey, originalValue);+ }+ }+ }++ @Test+ public void testConfigureKrb5ConfRejectsInvalidKeys() {+ Configuration configuration = new Configuration(false);++ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> KerberosAuthUtils.configureKrb5Conf(configuration, " ", "java.security.krb5.conf"));+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ KerberosAuthUtils.configureKrb5Conf(configuration, "hadoop.security.krb5.conf", null));+ }++ @Test+ public void testStartTicketRefreshRejectsInvalidArguments() {+ UserGroupInformation ugi = Mockito.mock(UserGroupInformation.class);++ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> KerberosAuthUtils.startTicketRefresh(ugi, 0, LoggerFactory.getLogger(getClass())));+ }++ @Test+ public void testLoginRejectsNullLoginMode() {+ IllegalArgumentException exception =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ KerberosAuthUtils.login(+ "service/[email protected]",+ new File(tempDir, "missing.keytab").getAbsolutePath(),+ new Configuration(false),+ null));++ Assertions.assertTrue(exception.getMessage().contains("loginMode"));+ }++ @Test+ public void testStartTicketRefreshReturnsDedicatedExecutorPerCall() {+ UserGroupInformation ugi = Mockito.mock(UserGroupInformation.class);+ ScheduledExecutorService firstRefresh =+ KerberosAuthUtils.startTicketRefresh(ugi, 60, LoggerFactory.getLogger(getClass()));+ ScheduledExecutorService secondRefresh =+ KerberosAuthUtils.startTicketRefresh(ugi, 60, LoggerFactory.getLogger(getClass()));++ try {+ Assertions.assertNotSame(firstRefresh, secondRefresh);+ Assertions.assertFalse(firstRefresh.isShutdown());+ Assertions.assertFalse(secondRefresh.isShutdown());+ Assertions.assertTrue(+ Thread.getAllStackTraces().keySet().stream()+ .anyMatch(+ candidate ->+ candidate.isDaemon()+ && candidate.getName().startsWith("kerberos-ticket-refresh-")));+ } finally {+ firstRefresh.shutdownNow();+ secondRefresh.shutdownNow();+ }++ Assertions.assertTrue(firstRefresh.isShutdown());+ Assertions.assertTrue(secondRefresh.isShutdown());+ }+}diff --git a/catalogs/hadoop-auth/src/test/java/org/apache/gravitino/catalog/hadoop/auth/TestKerberosClient.java b/catalogs/hadoop-auth/src/test/java/org/apache/gravitino/catalog/hadoop/auth/TestKerberosClient.javanew file mode 100644index 0000000000..486c933cc1--- /dev/null+++ b/catalogs/hadoop-auth/src/test/java/org/apache/gravitino/catalog/hadoop/auth/TestKerberosClient.java@@ -0,0 +1,91 @@+/*+ * 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.auth;++import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertThrows;++import org.apache.hadoop.conf.Configuration;+import org.junit.jupiter.api.Test;++public class TestKerberosClient {++ @Test+ public void testBuilderRejectsBlankPrincipal() {+ assertThrows(+ IllegalArgumentException.class,+ () -> KerberosClient.builder(" ", new Configuration()).build());+ }++ @Test+ public void testBuilderRejectsNullHadoopConf() {+ assertThrows(+ IllegalArgumentException.class,+ () -> KerberosClient.builder("hdfs/[email protected]", null).build());+ }++ @Test+ public void testBuilderRejectsInvalidRefreshConfiguration() {+ assertThrows(+ IllegalArgumentException.class,+ () ->+ KerberosClient.builder("hdfs/[email protected]", new Configuration())+ .checkIntervalSec(0)+ .build());+ }++ @Test+ public void testBuilderAllowsInvalidRefreshConfigurationWhenRefreshDisabled() {+ KerberosClient client =+ KerberosClient.builder("hdfs/[email protected]", new Configuration())+ .refreshCredentials(false)+ .checkIntervalSec(0)+ .build();+ assertNotNull(client);+ }++ @Test+ public void testBuilderRejectsInvalidKrb5ConfKeys() {+ assertThrows(+ IllegalArgumentException.class,+ () ->+ KerberosClient.builder("hdfs/[email protected]", new Configuration())+ .krb5Conf(" ", "java.security.krb5.conf")+ .build());++ assertThrows(+ IllegalArgumentException.class,+ () ->+ KerberosClient.builder("hdfs/[email protected]", new Configuration())+ .krb5Conf("hadoop.security.krb5.conf", null)+ .build());+ }++ @Test+ public void testBuilderBuildsWithDefaults() {+ KerberosClient client =+ KerberosClient.builder("hdfs/[email protected]", new Configuration())+ .loginMode(KerberosAuthUtils.LoginMode.RETURN_UGI)+ .refreshCredentials(false)+ .checkIntervalSec(30)+ .build();+ assertNotNull(client);+ }+}diff --git a/catalogs/hadoop-common/build.gradle.kts b/catalogs/hadoop-common/build.gradle.ktsindex 4394bd3c26..9fe27c2b76 100644--- a/catalogs/hadoop-common/build.gradle.kts+++ b/catalogs/hadoop-common/build.gradle.kts@@ -29,6 +29,9 @@ dependencies {implementation(libs.cglib)implementation(libs.commons.io)implementation(libs.commons.lang3)+ implementation(project(":catalogs:hadoop-auth")) {+ exclude("*")+ }implementation(libs.guava)implementation(libs.hadoop3.client.api)implementation(libs.hadoop3.client.runtime)diff --git a/catalogs/hadoop-common/src/main/java/org/apache/gravitino/catalog/hadoop/fs/HDFSFileSystemProxy.java b/catalogs/hadoop-common/src/main/java/org/apache/gravitino/catalog/hadoop/fs/HDFSFileSystemProxy.javaindex cf27d04903..a4ac6f3b21 100644--- a/catalogs/hadoop-common/src/main/java/org/apache/gravitino/catalog/hadoop/fs/HDFSFileSystemProxy.java+++ b/catalogs/hadoop-common/src/main/java/org/apache/gravitino/catalog/hadoop/fs/HDFSFileSystemProxy.java@@ -34,8 +34,10 @@ import java.util.Map;import net.sf.cglib.proxy.Enhancer;import net.sf.cglib.proxy.MethodInterceptor;import net.sf.cglib.proxy.MethodProxy;+import org.apache.gravitino.catalog.hadoop.auth.KerberosAuthUtils;+import org.apache.gravitino.catalog.hadoop.auth.KerberosClient;import org.apache.gravitino.catalog.hadoop.fs.kerberos.AuthenticationConfig;-import org.apache.gravitino.catalog.hadoop.fs.kerberos.KerberosClient;+import org.apache.gravitino.catalog.hadoop.fs.kerberos.KerberosConfig;import org.apache.gravitino.exceptions.GravitinoRuntimeException;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.FileSystem;@@ -167,12 +169,25 @@ public class HDFSFileSystemProxy implements MethodInterceptor {private UserGroupInformation initKerberosUgi(Map<String, String> properties, Configuration configuration) {try {- KerberosClient client = new KerberosClient(properties, configuration, true);+ KerberosConfig kerberosConfig = new KerberosConfig(properties, configuration);+ KerberosClient client =+ KerberosClient.builder(kerberosConfig.getPrincipalName(), configuration)+ .loginMode(KerberosAuthUtils.LoginMode.RETURN_UGI)+ .refreshCredentials(true)+ .checkIntervalSec(kerberosConfig.getCheckIntervalSec())+ .krb5Conf(Constants.HADOOP_KRB5_CONF, Constants.SECURITY_KRB5_ENV)+ .build();String keytabPath =String.format(GRAVITINO_KEYTAB_FORMAT, properties.getOrDefault(GRAVITINO_ID_KEY, ""));- File keytabFile = client.saveKeyTabFileFromUri(keytabPath);+ File keytabFile =+ KerberosAuthUtils.saveKeytabFromUri(+ kerberosConfig.getKeytab(),+ new File(keytabPath),+ kerberosConfig.getFetchTimeoutSec(),+ false,+ configuration);UserGroupInformation ugi = client.login(keytabFile.getAbsolutePath());- this.kerberosRealm = client.getKerberosRealm();+ this.kerberosRealm = client.getRealm();return ugi;} catch (IOException e) {throw new RuntimeException("Failed to login with Kerberos", e);diff --git a/catalogs/hadoop-common/src/main/java/org/apache/gravitino/catalog/hadoop/fs/kerberos/KerberosClient.java b/catalogs/hadoop-common/src/main/java/org/apache/gravitino/catalog/hadoop/fs/kerberos/KerberosClient.javadeleted file mode 100644index b3d3799f73..0000000000--- a/catalogs/hadoop-common/src/main/java/org/apache/gravitino/catalog/hadoop/fs/kerberos/KerberosClient.java+++ /dev/null@@ -1,146 +0,0 @@-/*- * 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.kerberos;--import static org.apache.gravitino.catalog.hadoop.fs.Constants.HADOOP_KRB5_CONF;-import static org.apache.gravitino.catalog.hadoop.fs.Constants.SECURITY_KRB5_ENV;--import com.google.common.base.Preconditions;-import com.google.common.base.Splitter;-import com.google.common.util.concurrent.ThreadFactoryBuilder;-import java.io.Closeable;-import java.io.File;-import java.io.IOException;-import java.util.List;-import java.util.Map;-import java.util.concurrent.ScheduledThreadPoolExecutor;-import java.util.concurrent.ThreadFactory;-import java.util.concurrent.TimeUnit;-import org.apache.commons.lang3.StringUtils;-import org.apache.gravitino.utils.FileFetcher;-import org.apache.hadoop.conf.Configuration;-import org.apache.hadoop.security.UserGroupInformation;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;--public class KerberosClient implements Closeable {- private static final Logger LOG = LoggerFactory.getLogger(KerberosClient.class);-- private ScheduledThreadPoolExecutor checkTgtExecutor;- private final Map<String, String> conf;- private final Configuration hadoopConf;- private final boolean refreshCredentials;- private String kerberosRealm;-- public KerberosClient(- Map<String, String> conf, Configuration hadoopConf, boolean refreshCredentials) {- this.conf = conf;- this.hadoopConf = hadoopConf;- this.refreshCredentials = refreshCredentials;- }-- public UserGroupInformation login(String keytabFilePath) throws IOException {- KerberosConfig kerberosConfig = new KerberosConfig(conf, hadoopConf);-- // Check the principal and keytab file- String catalogPrincipal = kerberosConfig.getPrincipalName();- Preconditions.checkArgument(- StringUtils.isNotBlank(catalogPrincipal), "The principal can't be blank");- @SuppressWarnings("null")- List<String> principalComponents = Splitter.on('@').splitToList(catalogPrincipal);- Preconditions.checkArgument(- principalComponents.size() == 2, "The principal has the wrong format");- kerberosRealm = principalComponents.get(1);-- String krb5Config = hadoopConf.get(HADOOP_KRB5_CONF);- if (krb5Config != null) {- System.setProperty(SECURITY_KRB5_ENV, krb5Config);- }-- // Login- UserGroupInformation.setConfiguration(hadoopConf);- UserGroupInformation kerberosLoginUgi =- UserGroupInformation.loginUserFromKeytabAndReturnUGI(catalogPrincipal, keytabFilePath);-- // Refresh the cache if it's out of date.- if (refreshCredentials) {- this.checkTgtExecutor = new ScheduledThreadPoolExecutor(1, getThreadFactory("check-tgt"));- int checkInterval = kerberosConfig.getCheckIntervalSec();- checkTgtExecutor.scheduleAtFixedRate(- () -> {- try {- kerberosLoginUgi.checkTGTAndReloginFromKeytab();- } catch (Exception e) {- LOG.error("Fail to refresh ugi token: ", e);- }- },- checkInterval,- checkInterval,- TimeUnit.SECONDS);- }-- return kerberosLoginUgi;- }-- public File saveKeyTabFileFromUri(String keytabPath) throws IOException {- KerberosConfig kerberosConfig = new KerberosConfig(conf, hadoopConf);-- String keyTabUri = kerberosConfig.getKeytab();- Preconditions.checkArgument(StringUtils.isNotBlank(keyTabUri), "Keytab uri can't be blank");- // TODO: Support to download the file from Kerberos HDFS- Preconditions.checkArgument(- !keyTabUri.trim().startsWith("hdfs"), "Keytab uri doesn't support to use HDFS");-- java.io.File keytabsDir = new File("keytabs");- if (!keytabsDir.exists()) {- // Ignore the return value, because there exists many Fileset catalog operations making- // this directory.- keytabsDir.mkdir();- }-- File keytabFile = new File(keytabPath);- keytabFile.deleteOnExit();- if (keytabFile.exists() && !keytabFile.delete()) {- throw new IllegalStateException(- String.format("Fail to delete keytab file %s", keytabFile.getAbsolutePath()));- }-- int fetchKeytabFileTimeout = kerberosConfig.getFetchTimeoutSec();- FileFetcher.get()- .fetchFileFromUri(keyTabUri, keytabFile, fetchKeytabFileTimeout * 1000, hadoopConf);-- return keytabFile;- }-- private static ThreadFactory getThreadFactory(String factoryName) {- return new ThreadFactoryBuilder().setDaemon(true).setNameFormat(factoryName + "-%d").build();- }-- @Override- public void close() throws IOException {- if (checkTgtExecutor != null) {- checkTgtExecutor.shutdown();- }- }-- public String getKerberosRealm() {- return kerberosRealm;- }-}diff --git a/catalogs/hive-metastore-common/build.gradle.kts b/catalogs/hive-metastore-common/build.gradle.ktsindex 1479f18e96..7b7203b454 100644--- a/catalogs/hive-metastore-common/build.gradle.kts+++ b/catalogs/hive-metastore-common/build.gradle.kts@@ -47,6 +47,9 @@ dependencies {implementation(project(":catalogs:catalog-common")) {exclude("*")}+ implementation(project(":catalogs:hadoop-auth")) {+ exclude("*")+ }annotationProcessor(libs.immutables.value)annotationProcessor(libs.lombok)diff --git a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClientFactory.java b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClientFactory.javaindex 3a2a80898d..54e8977601 100644--- a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClientFactory.java+++ b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClientFactory.java@@ -32,7 +32,7 @@ import java.util.Properties;import org.apache.commons.lang3.reflect.MethodUtils;import org.apache.gravitino.exceptions.GravitinoRuntimeException;import org.apache.gravitino.hive.kerberos.AuthenticationConfig;-import org.apache.gravitino.hive.kerberos.KerberosClient;+import org.apache.gravitino.hive.kerberos.HmsKerberosClient;import org.apache.gravitino.utils.PrincipalUtils;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.security.UserGroupInformation;@@ -50,7 +50,7 @@ public final class HiveClientFactory {private boolean enableKerberos;private boolean enableImpersonation = false;- private KerberosClient kerberosClient;+ private HmsKerberosClient kerberosClient;private final Configuration hadoopConf;private final Properties properties;@@ -242,7 +242,7 @@ public final class HiveClientFactory {return;}- kerberosClient = new KerberosClient(properties, hadoopConf, true, keytabPath);+ kerberosClient = new HmsKerberosClient(properties, hadoopConf, true, keytabPath);kerberosClient.login();} catch (Exception e) {diff --git a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/kerberos/KerberosClient.java b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/kerberos/HmsKerberosClient.javasimilarity index 66%rename from catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/kerberos/KerberosClient.javarename to catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/kerberos/HmsKerberosClient.javaindex 57ed6949e1..ccd255ecc8 100644--- a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/kerberos/KerberosClient.java+++ b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/kerberos/HmsKerberosClient.java@@ -23,20 +23,15 @@ import static org.apache.gravitino.catalog.hive.HiveConstants.HIVE_METASTORE_TOKimport static org.apache.gravitino.hive.kerberos.KerberosConfig.PRINCIPAL_KEY;import com.google.common.base.Preconditions;-import com.google.common.base.Splitter;-import com.google.common.util.concurrent.ThreadFactoryBuilder;+import java.io.Closeable;import java.io.File;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Paths;-import java.util.List;import java.util.Properties;-import java.util.concurrent.ScheduledThreadPoolExecutor;-import java.util.concurrent.ThreadFactory;-import java.util.concurrent.TimeUnit;-import org.apache.commons.lang3.StringUtils;+import java.util.concurrent.ScheduledExecutorService;+import org.apache.gravitino.catalog.hadoop.auth.KerberosAuthUtils;import org.apache.gravitino.hive.client.HiveClient;-import org.apache.gravitino.utils.FileFetcher;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.hive.thrift.DelegationTokenIdentifier;import org.apache.hadoop.io.Text;@@ -45,11 +40,16 @@ import org.apache.hadoop.security.token.Token;import org.slf4j.Logger;import org.slf4j.LoggerFactory;-/** Kerberos client for Hive Metastore. */-public class KerberosClient implements java.io.Closeable {- private static final Logger LOG = LoggerFactory.getLogger(KerberosClient.class);+/**+ * Kerberos client for Hive Metastore.+ *+ * <p>This class keeps HMS-specific behavior on top of the shared Hadoop Kerberos helpers, including+ * proxy user creation, delegation-token retrieval, Hive client wiring, and local keytab lifecycle.+ */+public class HmsKerberosClient implements Closeable {+ private static final Logger LOG = LoggerFactory.getLogger(HmsKerberosClient.class);- private ScheduledThreadPoolExecutor checkTgtExecutor;+ private ScheduledExecutorService checkTgtRefreshExecutor;private final Properties conf;private final Configuration hadoopConf;private final boolean refreshCredentials;@@ -57,7 +57,7 @@ public class KerberosClient implements java.io.Closeable {private final String keytabFilePath;private HiveClient hiveClient = null;- public KerberosClient(+ public HmsKerberosClient(Properties properties,Configuration hadoopConf,boolean refreshCredentials,@@ -85,10 +85,7 @@ public class KerberosClient implements java.io.Closeable {String tokenSignature = conf.getProperty(HIVE_METASTORE_TOKEN_SIGNATURE, "");String principal = conf.getProperty(PRINCIPAL_KEY, "");- List<String> principalComponents = Splitter.on('@').splitToList(principal);- Preconditions.checkArgument(- principalComponents.size() == 2, "The principal has the wrong format");- String kerberosRealm = principalComponents.get(1);+ String kerberosRealm = KerberosAuthUtils.checkPrincipalAndGetRealm(principal);UserGroupInformation proxyUser;final String finalPrincipalName;@@ -124,37 +121,19 @@ public class KerberosClient implements java.io.Closeable {public UserGroupInformation login() throws Exception {KerberosConfig kerberosConfig = new KerberosConfig(conf, hadoopConf);- // Check the principal and keytab fileString catalogPrincipal = kerberosConfig.getPrincipalName();- Preconditions.checkArgument(- StringUtils.isNotBlank(catalogPrincipal), "The principal can't be blank");- List<String> principalComponents = Splitter.on('@').splitToList(catalogPrincipal);- Preconditions.checkArgument(- principalComponents.size() == 2, "The principal has the wrong format");// Login- UserGroupInformation.setConfiguration(hadoopConf);- UserGroupInformation.loginUserFromKeytab(catalogPrincipal, keytabFilePath);- UserGroupInformation loginUgi = UserGroupInformation.getLoginUser();+ UserGroupInformation loginUgi =+ KerberosAuthUtils.login(+ catalogPrincipal, keytabFilePath, hadoopConf, KerberosAuthUtils.LoginMode.LOGIN_USER);realLoginUgi = loginUgi;// Refresh the cache if it's out of date.if (refreshCredentials) {- if (checkTgtExecutor == null) {- checkTgtExecutor = new ScheduledThreadPoolExecutor(1, getThreadFactory("check-tgt"));- }+ shutdownTicketRefresh();int checkInterval = kerberosConfig.getCheckIntervalSec();- checkTgtExecutor.scheduleAtFixedRate(- () -> {- try {- loginUgi.checkTGTAndReloginFromKeytab();- } catch (Exception e) {- LOG.error("Fail to refresh ugi token: ", e);- }- },- checkInterval,- checkInterval,- TimeUnit.SECONDS);+ checkTgtRefreshExecutor = KerberosAuthUtils.startTicketRefresh(loginUgi, checkInterval, LOG);}return loginUgi;@@ -164,31 +143,18 @@ public class KerberosClient implements java.io.Closeable {KerberosConfig kerberosConfig = new KerberosConfig(conf, hadoopConf);String keyTabUri = kerberosConfig.getKeytab();- Preconditions.checkArgument(StringUtils.isNotBlank(keyTabUri), "Keytab uri can't be blank");- Preconditions.checkArgument(- !keyTabUri.trim().startsWith("hdfs"), "HDFS URIs are not supported for keytab files");- File keytabsDir = new File("keytabs");- if (!keytabsDir.exists()) {- keytabsDir.mkdir();- }File keytabFile = new File(path);int fetchKeytabFileTimeout = kerberosConfig.getFetchTimeoutSec();- FileFetcher.get()- .fetchFileFromUri(keyTabUri, keytabFile, fetchKeytabFileTimeout * 1000, hadoopConf);+ KerberosAuthUtils.fetchKeytabFromUri(+ keyTabUri, keytabFile, fetchKeytabFileTimeout, false /* allowHdfsKeytabUri */, hadoopConf);return keytabFile;}- private static ThreadFactory getThreadFactory(String factoryName) {- return new ThreadFactoryBuilder().setDaemon(true).setNameFormat(factoryName + "-%d").build();- }-@Overridepublic void close() {try {- if (checkTgtExecutor != null) {- checkTgtExecutor.shutdown();- }+ shutdownTicketRefresh();Files.deleteIfExists(Paths.get(keytabFilePath));} catch (IOException e) {@@ -196,6 +162,14 @@ public class KerberosClient implements java.io.Closeable {}}+ private void shutdownTicketRefresh() {+ if (checkTgtRefreshExecutor != null) {+ // Graceful shutdown: let any in-flight relogin finish before the thread is torn down.+ checkTgtRefreshExecutor.shutdown();+ checkTgtRefreshExecutor = null;+ }+ }+public void setHiveClient(HiveClient client) {this.hiveClient = client;}@@ -209,7 +183,7 @@ public class KerberosClient implements java.io.Closeable {* @throws IllegalStateException if {@link #login()} has not been called yet.*/public UserGroupInformation getRealLoginUgi() {- Preconditions.checkState(realLoginUgi != null, "KerberosClient.login() has not been called");+ Preconditions.checkState(realLoginUgi != null, "HmsKerberosClient.login() has not been called");return realLoginUgi;}}diff --git a/iceberg/iceberg-common/build.gradle.kts b/iceberg/iceberg-common/build.gradle.ktsindex bd0bd45f92..427df238ea 100644--- a/iceberg/iceberg-common/build.gradle.kts+++ b/iceberg/iceberg-common/build.gradle.kts@@ -32,6 +32,9 @@ dependencies {implementation(project(":api"))implementation(project(":catalogs:catalog-common"))+ implementation(project(":catalogs:hadoop-auth")) {+ exclude("*")+ }implementation(project(":catalogs:hadoop-common")) {exclude("*")}diff --git a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/ClosableHiveCatalog.java b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/ClosableHiveCatalog.javaindex 9b708acc68..6fd8dcd7d3 100644--- a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/ClosableHiveCatalog.java+++ b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/ClosableHiveCatalog.java@@ -31,9 +31,11 @@ import java.util.Map;import java.util.concurrent.ScheduledExecutorService;import lombok.Getter;import org.apache.commons.lang3.reflect.FieldUtils;+import org.apache.gravitino.catalog.hadoop.auth.KerberosAuthUtils;+import org.apache.gravitino.catalog.hadoop.auth.KerberosClient;import org.apache.gravitino.iceberg.common.authentication.AuthenticationConfig;import org.apache.gravitino.iceberg.common.authentication.SupportsKerberos;-import org.apache.gravitino.iceberg.common.authentication.kerberos.KerberosClient;+import org.apache.gravitino.iceberg.common.authentication.kerberos.KerberosConfig;import org.apache.gravitino.iceberg.common.utils.CaffeineSchedulerExtractorUtils;import org.apache.gravitino.iceberg.common.utils.IcebergHiveCachedClientPool;import org.apache.gravitino.utils.PrincipalUtils;@@ -273,10 +275,22 @@ public class ClosableHiveCatalog extends HiveCatalog implements Closeable, Suppoprivate KerberosClient initKerberosClient() {try {- KerberosClient kerberosClient = new KerberosClient(this.properties(), this.getConf());+ KerberosConfig kerberosConfig = new KerberosConfig(this.properties());+ KerberosClient kerberosClient =+ KerberosClient.builder(kerberosConfig.getPrincipalName(), this.getConf())+ .loginMode(KerberosAuthUtils.LoginMode.CURRENT_USER)+ .checkIntervalSec(kerberosConfig.getCheckIntervalSec())+ .build();// catalog_uuid always exists for Gravitino managed catalogs, `0` is just a fallback value.String catalogUUID = properties().getOrDefault("catalog_uuid", "0");- File keytabFile = kerberosClient.saveKeyTabFileFromUri(Long.parseLong(catalogUUID));+ File keytabFile =+ new File(String.format(KerberosConfig.GRAVITINO_KEYTAB_FORMAT, catalogUUID));+ KerberosAuthUtils.saveKeytabFromUri(+ kerberosConfig.getKeytab(),+ keytabFile,+ kerberosConfig.getFetchTimeoutSec(),+ false,+ this.getConf());kerberosClient.login(keytabFile.getAbsolutePath());return kerberosClient;} catch (IOException e) {diff --git a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/authentication/kerberos/KerberosClient.java b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/authentication/kerberos/KerberosClient.javadeleted file mode 100644index be4536e03e..0000000000--- a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/authentication/kerberos/KerberosClient.java+++ /dev/null@@ -1,136 +0,0 @@-/*- * 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.iceberg.common.authentication.kerberos;--import com.google.common.base.Preconditions;-import com.google.common.base.Splitter;-import com.google.common.util.concurrent.ThreadFactoryBuilder;-import java.io.Closeable;-import java.io.File;-import java.io.IOException;-import java.util.List;-import java.util.Map;-import java.util.concurrent.ScheduledThreadPoolExecutor;-import java.util.concurrent.TimeUnit;-import lombok.Getter;-import org.apache.commons.lang3.StringUtils;-import org.apache.gravitino.utils.FileFetcher;-import org.apache.hadoop.conf.Configuration;-import org.apache.hadoop.security.UserGroupInformation;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;--public class KerberosClient implements Closeable {- private static final Logger LOG = LoggerFactory.getLogger(KerberosClient.class);-- private final ScheduledThreadPoolExecutor checkTgtExecutor;- private final Map<String, String> conf;- private final Configuration hadoopConf;- @Getter private UserGroupInformation loginUser;- private String realm;-- public KerberosClient(Map<String, String> conf, Configuration hadoopConf) {- this.conf = conf;- this.hadoopConf = hadoopConf;- this.checkTgtExecutor =- new ScheduledThreadPoolExecutor(- 1,- new ThreadFactoryBuilder()- .setDaemon(true)- .setNameFormat("check-Iceberg-Hive-tgt-%d")- .build());- }-- public String getRealm() {- return realm;- }-- public void login(String keytabFilePath) throws IOException {- KerberosConfig kerberosConfig = new KerberosConfig(conf);-- // Check the principal and keytab file- String catalogPrincipal = kerberosConfig.getPrincipalName();- Preconditions.checkArgument(- StringUtils.isNotBlank(catalogPrincipal), "The principal can't be blank");- @SuppressWarnings("null")- List<String> principalComponents = Splitter.on('@').splitToList(catalogPrincipal);- Preconditions.checkArgument(- principalComponents.size() == 2, "The principal has the wrong format");-- // Login- UserGroupInformation.setConfiguration(hadoopConf);- UserGroupInformation.loginUserFromKeytab(catalogPrincipal, keytabFilePath);- loginUser = UserGroupInformation.getCurrentUser();-- // Refresh the cache if it's out of date.- int checkInterval = kerberosConfig.getCheckIntervalSec();- checkTgtExecutor.scheduleAtFixedRate(- () -> {- try {- loginUser.checkTGTAndReloginFromKeytab();- } catch (Exception e) {- LOG.error("Fail to refresh ugi token: ", e);- }- },- checkInterval,- checkInterval,- TimeUnit.SECONDS);-- this.realm = principalComponents.get(1);- }-- public File saveKeyTabFileFromUri(Long catalogId) throws IOException {-- KerberosConfig kerberosConfig = new KerberosConfig(conf);-- String keyTabUri = kerberosConfig.getKeytab();- Preconditions.checkArgument(StringUtils.isNotBlank(keyTabUri), "Keytab uri can't be blank");- // TODO: Support to download the file from Kerberos HDFS- Preconditions.checkArgument(- !keyTabUri.trim().startsWith("hdfs"), "Keytab uri doesn't support to use HDFS");-- File keytabsDir = new File("keytabs");- if (!keytabsDir.exists()) {- // Ignore the return value, because there exists many Hive catalog operations making- // this directory.- keytabsDir.mkdir();- }-- File keytabFile = new File(String.format(KerberosConfig.GRAVITINO_KEYTAB_FORMAT, catalogId));- keytabFile.deleteOnExit();- if (keytabFile.exists() && !keytabFile.delete()) {- throw new IllegalStateException(- String.format("Fail to delete keytab file %s", keytabFile.getAbsolutePath()));- }-- // TODO: Make the configuration- int fetchKeytabFileTimeout = kerberosConfig.getFetchTimeoutSec();- FileFetcher.get()- .fetchFileFromUri(keyTabUri, keytabFile, fetchKeytabFileTimeout * 1000, hadoopConf);-- return keytabFile;- }-- @Override- public void close() throws IOException {- if (checkTgtExecutor != null) {- checkTgtExecutor.shutdownNow();- }- }-}diff --git a/settings.gradle.kts b/settings.gradle.ktsindex e49a0e4d11..c8a705ab7a 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -125,6 +125,7 @@ include(":bundles:gcp", ":bundles:gcp-bundle", ":bundles:iceberg-gcp-bundle")include(":bundles:aliyun", ":bundles:aliyun-bundle", ":bundles:iceberg-aliyun-bundle")include(":bundles:azure", ":bundles:azure-bundle", ":bundles:iceberg-azure-bundle")include(":catalogs:hadoop-common")+include(":catalogs:hadoop-auth")include(":lineage")include(":mcp-server")include(":plugins:idp-basic")