World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#3337] improvement(hadoop-catalog): Support user impersonation for Hadoop catalog. (#3352)
Qi Yu783839f82d36
diff --git a/catalogs/catalog-hadoop/build.gradle.kts b/catalogs/catalog-hadoop/build.gradle.ktsindex 8afcf6a23e..42dc19ad26 100644--- a/catalogs/catalog-hadoop/build.gradle.kts+++ b/catalogs/catalog-hadoop/build.gradle.kts@@ -34,6 +34,9 @@ dependencies {testImplementation(project(":server"))testImplementation(project(":server-common"))+ testImplementation(libs.minikdc)+ testImplementation(libs.hadoop3.minicluster)+testImplementation(libs.bundles.log4j)testImplementation(libs.mockito.core)testImplementation(libs.mysql.driver)diff --git a/catalogs/catalog-hadoop/src/main/java/com/datastrato/gravitino/catalog/hadoop/HadoopCatalog.java b/catalogs/catalog-hadoop/src/main/java/com/datastrato/gravitino/catalog/hadoop/HadoopCatalog.javaindex f9ecb37578..174a237d3e 100644--- a/catalogs/catalog-hadoop/src/main/java/com/datastrato/gravitino/catalog/hadoop/HadoopCatalog.java+++ b/catalogs/catalog-hadoop/src/main/java/com/datastrato/gravitino/catalog/hadoop/HadoopCatalog.java@@ -4,10 +4,13 @@*/package com.datastrato.gravitino.catalog.hadoop;+import com.datastrato.gravitino.catalog.hadoop.kerberos.KerberosConfig;import com.datastrato.gravitino.connector.BaseCatalog;import com.datastrato.gravitino.connector.CatalogOperations;+import com.datastrato.gravitino.connector.ProxyPlugin;import com.datastrato.gravitino.connector.capability.Capability;import java.util.Map;+import java.util.Optional;/*** Hadoop catalog is a fileset catalog that can manage filesets on the Hadoop Compatible File@@ -31,4 +34,13 @@ public class HadoopCatalog extends BaseCatalog<HadoopCatalog> {protected Capability newCapability() {return new HadoopCatalogCapability();}++ @Override+ protected Optional<ProxyPlugin> newProxyPlugin(Map<String, String> config) {+ boolean impersonationEnabled = new KerberosConfig(config).isImpersonationEnabled();+ if (!impersonationEnabled) {+ return Optional.empty();+ }+ return Optional.of(new HadoopProxyPlugin());+ }}diff --git a/catalogs/catalog-hadoop/src/main/java/com/datastrato/gravitino/catalog/hadoop/HadoopCatalogOperations.java b/catalogs/catalog-hadoop/src/main/java/com/datastrato/gravitino/catalog/hadoop/HadoopCatalogOperations.javaindex 3f077b9956..9a1dd4d462 100644--- a/catalogs/catalog-hadoop/src/main/java/com/datastrato/gravitino/catalog/hadoop/HadoopCatalogOperations.java+++ b/catalogs/catalog-hadoop/src/main/java/com/datastrato/gravitino/catalog/hadoop/HadoopCatalogOperations.java@@ -5,6 +5,7 @@package com.datastrato.gravitino.catalog.hadoop;import static com.datastrato.gravitino.connector.BaseCatalog.CATALOG_BYPASS_PREFIX;+import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION;import com.datastrato.gravitino.Entity;import com.datastrato.gravitino.EntityStore;@@ -14,9 +15,12 @@ import com.datastrato.gravitino.Namespace;import com.datastrato.gravitino.Schema;import com.datastrato.gravitino.SchemaChange;import com.datastrato.gravitino.StringIdentifier;+import com.datastrato.gravitino.catalog.hadoop.kerberos.AuthenticationConfig;+import com.datastrato.gravitino.catalog.hadoop.kerberos.KerberosClient;import com.datastrato.gravitino.connector.CatalogInfo;import com.datastrato.gravitino.connector.CatalogOperations;import com.datastrato.gravitino.connector.PropertiesMetadata;+import com.datastrato.gravitino.connector.ProxyPlugin;import com.datastrato.gravitino.connector.SupportsSchemas;import com.datastrato.gravitino.exceptions.AlreadyExistsException;import com.datastrato.gravitino.exceptions.FilesetAlreadyExistsException;@@ -36,6 +40,7 @@ import com.datastrato.gravitino.utils.PrincipalUtils;import com.google.common.annotations.VisibleForTesting;import com.google.common.base.Preconditions;import com.google.common.collect.Maps;+import java.io.File;import java.io.IOException;import java.time.Instant;import java.util.Collections;@@ -47,6 +52,7 @@ import org.apache.commons.lang3.StringUtils;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.FileSystem;import org.apache.hadoop.fs.Path;+import org.apache.hadoop.security.UserGroupInformation;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -72,7 +78,15 @@ public class HadoopCatalogOperations implements CatalogOperations, SupportsSchem@VisibleForTesting Optional<Path> catalogStorageLocation;- // For testing only.+ private Map<String, String> conf;++ @SuppressWarnings("unused")+ private ProxyPlugin proxyPlugin;++ private String kerberosRealm;++ private CatalogInfo catalogInfo;+HadoopCatalogOperations(EntityStore store) {this.store = store;}@@ -81,10 +95,16 @@ public class HadoopCatalogOperations implements CatalogOperations, SupportsSchemthis(GravitinoEnv.getInstance().entityStore());}+ public String getKerberosRealm() {+ return kerberosRealm;+ }+@Overridepublic void initialize(Map<String, String> config, CatalogInfo info) throws RuntimeException {// Initialize Hadoop Configuration.+ this.conf = config;this.hadoopConf = new Configuration();+ this.catalogInfo = info;Map<String, String> bypassConfigs =config.entrySet().stream().filter(e -> e.getKey().startsWith(CATALOG_BYPASS_PREFIX))@@ -98,9 +118,31 @@ public class HadoopCatalogOperations implements CatalogOperations, SupportsSchem(String)CATALOG_PROPERTIES_METADATA.getOrDefault(config, HadoopCatalogPropertiesMetadata.LOCATION);+ conf.forEach(hadoopConf::set);++ initAuthentication(conf, hadoopConf);+this.catalogStorageLocation = Optional.ofNullable(catalogLocation).map(Path::new);}+ private void initAuthentication(Map<String, String> conf, Configuration hadoopConf) {+ AuthenticationConfig config = new AuthenticationConfig(conf);+ boolean enableAuth = config.isEnableAuth();+ String authType = config.getAuthType();++ if (enableAuth && StringUtils.equalsIgnoreCase(authType, "kerberos")) {+ hadoopConf.set(HADOOP_SECURITY_AUTHENTICATION, "kerberos");+ UserGroupInformation.setConfiguration(hadoopConf);+ try {+ KerberosClient kerberosClient = new KerberosClient(conf, hadoopConf);+ File keytabFile = kerberosClient.saveKeyTabFileFromUri(catalogInfo.id());+ this.kerberosRealm = kerberosClient.login(keytabFile.getAbsolutePath());+ } catch (IOException e) {+ throw new RuntimeException("Failed to login with kerberos", e);+ }+ }+ }+@Overridepublic NameIdentifier[] listFilesets(Namespace namespace) throws NoSuchSchemaException {try {@@ -609,4 +651,8 @@ public class HadoopCatalogOperations implements CatalogOperations, SupportsSchemFileSystem defaultFs = FileSystem.get(configuration);return path.makeQualified(defaultFs.getUri(), defaultFs.getWorkingDirectory());}++ void setProxyPlugin(HadoopProxyPlugin hadoopProxyPlugin) {+ this.proxyPlugin = hadoopProxyPlugin;+ }}diff --git a/catalogs/catalog-hadoop/src/main/java/com/datastrato/gravitino/catalog/hadoop/HadoopCatalogPropertiesMetadata.java b/catalogs/catalog-hadoop/src/main/java/com/datastrato/gravitino/catalog/hadoop/HadoopCatalogPropertiesMetadata.javaindex 4eb5c87162..37a5700e57 100644--- a/catalogs/catalog-hadoop/src/main/java/com/datastrato/gravitino/catalog/hadoop/HadoopCatalogPropertiesMetadata.java+++ b/catalogs/catalog-hadoop/src/main/java/com/datastrato/gravitino/catalog/hadoop/HadoopCatalogPropertiesMetadata.java@@ -4,6 +4,8 @@*/package com.datastrato.gravitino.catalog.hadoop;+import com.datastrato.gravitino.catalog.hadoop.kerberos.AuthenticationConfig;+import com.datastrato.gravitino.catalog.hadoop.kerberos.KerberosConfig;import com.datastrato.gravitino.connector.BaseCatalogPropertiesMetadata;import com.datastrato.gravitino.connector.PropertyEntry;import com.google.common.collect.ImmutableMap;@@ -29,6 +31,9 @@ public class HadoopCatalogPropertiesMetadata extends BaseCatalogPropertiesMetadanull,false /* hidden */)).putAll(BASIC_CATALOG_PROPERTY_ENTRIES)+ // The following two are about authentication.+ .putAll(KerberosConfig.KERBEROS_PROPERTY_ENTRIES)+ .putAll(AuthenticationConfig.AUTHENTICATION_PROPERTY_ENTRIES).build();@Overridediff --git a/catalogs/catalog-hadoop/src/main/java/com/datastrato/gravitino/catalog/hadoop/HadoopProxyPlugin.java b/catalogs/catalog-hadoop/src/main/java/com/datastrato/gravitino/catalog/hadoop/HadoopProxyPlugin.javanew file mode 100644index 0000000000..471f6a165c--- /dev/null+++ b/catalogs/catalog-hadoop/src/main/java/com/datastrato/gravitino/catalog/hadoop/HadoopProxyPlugin.java@@ -0,0 +1,74 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.catalog.hadoop;++import com.datastrato.gravitino.connector.CatalogOperations;+import com.datastrato.gravitino.connector.ProxyPlugin;+import com.datastrato.gravitino.utils.Executable;+import java.io.IOException;+import java.lang.reflect.InvocationTargetException;+import java.lang.reflect.UndeclaredThrowableException;+import java.security.Principal;+import java.security.PrivilegedActionException;+import java.security.PrivilegedExceptionAction;+import java.util.Map;+import org.apache.hadoop.security.UserGroupInformation;++public class HadoopProxyPlugin implements ProxyPlugin {+ private HadoopCatalogOperations ops;+ private UserGroupInformation realUser;++ public HadoopProxyPlugin() {+ try {+ realUser = UserGroupInformation.getCurrentUser();+ } catch (IOException ioe) {+ throw new IllegalStateException("Fail to init HadoopCatalogProxyPlugin");+ }+ }++ @Override+ public Object doAs(+ Principal principal, Executable<Object, Exception> action, Map<String, String> properties)+ throws Throwable {+ try {+ UserGroupInformation proxyUser;++ if (UserGroupInformation.isSecurityEnabled() && ops != null) {+ // The Gravitino server may use multiple KDC servers.+ // The http authentication use one KDC server, the Hadoop catalog may use another KDC+ // server.+ // The KerberosAuthenticator will remove realm of principal.+ // And then we add the realm of Hadoop catalog to the user.+ String proxyKerberosPrincipalName = principal.getName();+ if (!proxyKerberosPrincipalName.contains("@")) {+ proxyKerberosPrincipalName =+ String.format("%s@%s", proxyKerberosPrincipalName, ops.getKerberosRealm());+ }++ proxyUser = UserGroupInformation.createProxyUser(proxyKerberosPrincipalName, realUser);+ } else {+ proxyUser = UserGroupInformation.createProxyUser(principal.getName(), realUser);+ }++ return proxyUser.doAs((PrivilegedExceptionAction<Object>) action::execute);+ } catch (UndeclaredThrowableException e) {+ Throwable innerException = e.getCause();+ if (innerException instanceof PrivilegedActionException) {+ throw innerException.getCause();+ } else if (innerException instanceof InvocationTargetException) {+ throw innerException.getCause();+ } else {+ throw innerException;+ }+ }+ }++ @Override+ public void bindCatalogOperation(CatalogOperations ops) {+ this.ops = ((HadoopCatalogOperations) ops);+ this.ops.setProxyPlugin(this);+ }+}diff --git a/catalogs/catalog-hadoop/src/main/java/com/datastrato/gravitino/catalog/hadoop/kerberos/AuthenticationConfig.java b/catalogs/catalog-hadoop/src/main/java/com/datastrato/gravitino/catalog/hadoop/kerberos/AuthenticationConfig.javanew file mode 100644index 0000000000..2128231a3f--- /dev/null+++ b/catalogs/catalog-hadoop/src/main/java/com/datastrato/gravitino/catalog/hadoop/kerberos/AuthenticationConfig.java@@ -0,0 +1,69 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.catalog.hadoop.kerberos;++import com.datastrato.gravitino.Config;+import com.datastrato.gravitino.config.ConfigBuilder;+import com.datastrato.gravitino.config.ConfigConstants;+import com.datastrato.gravitino.config.ConfigEntry;+import com.datastrato.gravitino.connector.PropertyEntry;+import com.google.common.collect.ImmutableMap;+import java.util.Map;++public class AuthenticationConfig extends Config {+ public static final String ENABLE_AUTH_KEY = "authentication.enable";+ public static final String AUTH_TYPE_KEY = "authentication.type";++ public AuthenticationConfig(Map<String, String> properties) {+ super(false);+ loadFromMap(properties, k -> true);+ }++ public static final ConfigEntry<Boolean> ENABLE_AUTH_ENTRY =+ new ConfigBuilder(ENABLE_AUTH_KEY)+ .doc("Whether to enable authentication for Hadoop catalog")+ .version(ConfigConstants.VERSION_0_5_1)+ .booleanConf()+ .createWithDefault(false);++ public static final ConfigEntry<String> AUTH_TYPE_ENTRY =+ new ConfigBuilder(AUTH_TYPE_KEY)+ .doc("The type of authentication for Hadoop catalog, currently we only support kerberos")+ .version(ConfigConstants.VERSION_0_5_1)+ .stringConf()+ .create();++ public boolean isEnableAuth() {+ return get(ENABLE_AUTH_ENTRY);+ }++ public String getAuthType() {+ return get(AUTH_TYPE_ENTRY);+ }++ public static final Map<String, PropertyEntry<?>> AUTHENTICATION_PROPERTY_ENTRIES =+ new ImmutableMap.Builder<String, PropertyEntry<?>>()+ .put(+ ENABLE_AUTH_KEY,+ PropertyEntry.booleanPropertyEntry(+ ENABLE_AUTH_KEY,+ "Whether to enable authentication for Hadoop catalog",+ false,+ true,+ false,+ false,+ false))+ .put(+ AUTH_TYPE_KEY,+ PropertyEntry.stringImmutablePropertyEntry(+ AUTH_TYPE_KEY,+ "The type of authentication for Hadoop catalog, currently we only support kerberos",+ false,+ null,+ false,+ false))+ .build();+}diff --git a/catalogs/catalog-hadoop/src/main/java/com/datastrato/gravitino/catalog/hadoop/kerberos/FetchFileUtils.java b/catalogs/catalog-hadoop/src/main/java/com/datastrato/gravitino/catalog/hadoop/kerberos/FetchFileUtils.javanew file mode 100644index 0000000000..30f75687f6--- /dev/null+++ b/catalogs/catalog-hadoop/src/main/java/com/datastrato/gravitino/catalog/hadoop/kerberos/FetchFileUtils.java@@ -0,0 +1,51 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.gravitino.catalog.hadoop.kerberos;++import java.io.File;+import java.io.IOException;+import java.net.URI;+import java.net.URISyntaxException;+import java.nio.file.Files;+import java.util.Optional;+import org.apache.commons.io.FileUtils;+import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.fs.FileSystem;+import org.apache.hadoop.fs.Path;++public class FetchFileUtils {++ private FetchFileUtils() {}++ public static void fetchFileFromUri(+ String fileUri, File destFile, int timeout, Configuration conf) throws IOException {+ try {+ URI uri = new URI(fileUri);+ String scheme = Optional.ofNullable(uri.getScheme()).orElse("file");++ switch (scheme) {+ case "http":+ case "https":+ case "ftp":+ FileUtils.copyURLToFile(uri.toURL(), destFile, timeout * 1000, timeout * 1000);+ break;++ case "file":+ Files.createSymbolicLink(destFile.toPath(), new File(uri.getPath()).toPath());+ break;++ case "hdfs":+ FileSystem.get(conf).copyToLocalFile(new Path(uri), new Path(destFile.toURI()));+ break;++ default:+ throw new IllegalArgumentException(+ String.format("Doesn't support the scheme %s", scheme));+ }+ } catch (URISyntaxException ue) {+ throw new IllegalArgumentException("The uri of file has the wrong format", ue);+ }+ }+}diff --git a/catalogs/catalog-hadoop/src/main/java/com/datastrato/gravitino/catalog/hadoop/kerberos/KerberosClient.java b/catalogs/catalog-hadoop/src/main/java/com/datastrato/gravitino/catalog/hadoop/kerberos/KerberosClient.javanew file mode 100644index 0000000000..67b9f2a86a--- /dev/null+++ b/catalogs/catalog-hadoop/src/main/java/com/datastrato/gravitino/catalog/hadoop/kerberos/KerberosClient.java@@ -0,0 +1,109 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.catalog.hadoop.kerberos;++import com.google.common.base.Preconditions;+import com.google.common.base.Splitter;+import com.google.common.util.concurrent.ThreadFactoryBuilder;+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.hadoop.conf.Configuration;+import org.apache.hadoop.security.UserGroupInformation;+import org.apache.hadoop.security.authentication.util.KerberosName;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++public class KerberosClient {++ public static final String GRAVITINO_KEYTAB_FORMAT = "keytabs/gravitino-%s-keytab";++ private static final Logger LOG = LoggerFactory.getLogger(KerberosClient.class);++ 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"));+ }++ public String 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);+ KerberosName.resetDefaultRealm();+ 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);++ return 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");++ java.io.File keytabsDir = new File("keytabs");+ if (!keytabsDir.exists()) {+ // Ignore the return value, because there exists many Hadoop 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();+ FetchFileUtils.fetchFileFromUri(keyTabUri, keytabFile, fetchKeytabFileTimeout, hadoopConf);++ return keytabFile;+ }++ private static ThreadFactory getThreadFactory(String factoryName) {+ return new ThreadFactoryBuilder().setDaemon(true).setNameFormat(factoryName + "-%d").build();+ }+}diff --git a/catalogs/catalog-hadoop/src/main/java/com/datastrato/gravitino/catalog/hadoop/kerberos/KerberosConfig.java b/catalogs/catalog-hadoop/src/main/java/com/datastrato/gravitino/catalog/hadoop/kerberos/KerberosConfig.javanew file mode 100644index 0000000000..7e2686a47a--- /dev/null+++ b/catalogs/catalog-hadoop/src/main/java/com/datastrato/gravitino/catalog/hadoop/kerberos/KerberosConfig.java@@ -0,0 +1,128 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.catalog.hadoop.kerberos;++import com.datastrato.gravitino.config.ConfigBuilder;+import com.datastrato.gravitino.config.ConfigConstants;+import com.datastrato.gravitino.config.ConfigEntry;+import com.datastrato.gravitino.connector.PropertyEntry;+import com.google.common.collect.ImmutableMap;+import java.util.Map;+import org.apache.commons.lang3.StringUtils;++public class KerberosConfig extends AuthenticationConfig {+ public static final String KEY_TAB_URI_KEY = "authentication.kerberos.keytab-uri";++ public static final String PRINCIPAL_KEY = "authentication.kerberos.principal";++ public static final String CHECK_INTERVAL_SEC_KEY = "authentication.kerberos.check-interval-sec";++ public static final String FETCH_TIMEOUT_SEC_KEY =+ "authentication.kerberos.keytab-fetch-timeout-sec";++ public static final String IMPERSONATION_ENABLE_KEY =+ "authentication.kerberos.impersonation-enable";++ public static final boolean DEFAULT_IMPERSONATION_ENABLE = false;++ public static final ConfigEntry<String> PRINCIPAL_ENTRY =+ new ConfigBuilder(PRINCIPAL_KEY)+ .doc("The principal of the kerberos connection")+ .version(ConfigConstants.VERSION_0_5_1)+ .stringConf()+ .checkValue(StringUtils::isNotBlank, ConfigConstants.NOT_BLANK_ERROR_MSG)+ .create();++ public static final ConfigEntry<String> KEYTAB_ENTRY =+ new ConfigBuilder(KEY_TAB_URI_KEY)+ .doc("The keytab of the kerberos connection")+ .version(ConfigConstants.VERSION_0_5_1)+ .stringConf()+ .checkValue(StringUtils::isNotBlank, ConfigConstants.NOT_BLANK_ERROR_MSG)+ .create();++ public static final ConfigEntry<Integer> CHECK_INTERVAL_SEC_ENTRY =+ new ConfigBuilder(CHECK_INTERVAL_SEC_KEY)+ .doc("The check interval of the kerberos connection for Hadoop catalog")+ .version(ConfigConstants.VERSION_0_5_1)+ .intConf()+ .checkValue(value -> value > 0, ConfigConstants.POSITIVE_NUMBER_ERROR_MSG)+ .createWithDefault(2);++ public static final ConfigEntry<Integer> FETCH_TIMEOUT_SEC_ENTRY =+ new ConfigBuilder(FETCH_TIMEOUT_SEC_KEY)+ .doc("The fetch timeout of the kerberos connection")+ .version(ConfigConstants.VERSION_0_5_1)+ .intConf()+ .checkValue(value -> value > 0, ConfigConstants.POSITIVE_NUMBER_ERROR_MSG)+ .createWithDefault(2);++ public static final ConfigEntry<Boolean> ENABLE_IMPERSONATION_ENTRY =+ new ConfigBuilder(IMPERSONATION_ENABLE_KEY)+ .doc("Whether to enable impersonation for the Hadoop catalog")+ .version(ConfigConstants.VERSION_0_5_1)+ .booleanConf()+ .createWithDefault(DEFAULT_IMPERSONATION_ENABLE);++ public KerberosConfig(Map<String, String> properties) {+ super(properties);+ loadFromMap(properties, k -> true);+ }++ public boolean isImpersonationEnabled() {+ return get(ENABLE_IMPERSONATION_ENTRY);+ }++ public String getPrincipalName() {+ return get(PRINCIPAL_ENTRY);+ }++ public String getKeytab() {+ return get(KEYTAB_ENTRY);+ }++ public int getCheckIntervalSec() {+ return get(CHECK_INTERVAL_SEC_ENTRY);+ }++ public int getFetchTimeoutSec() {+ return get(FETCH_TIMEOUT_SEC_ENTRY);+ }++ public static final Map<String, PropertyEntry<?>> KERBEROS_PROPERTY_ENTRIES =+ new ImmutableMap.Builder<String, PropertyEntry<?>>()+ .put(+ IMPERSONATION_ENABLE_KEY,+ PropertyEntry.booleanPropertyEntry(+ IMPERSONATION_ENABLE_KEY,+ "Whether to enable impersonation for the Hadoop catalog",+ false,+ true,+ DEFAULT_IMPERSONATION_ENABLE,+ false,+ false))+ .put(+ KEY_TAB_URI_KEY,+ PropertyEntry.stringImmutablePropertyEntry(+ KEY_TAB_URI_KEY, "The uri of key tab for the catalog", false, null, false, false))+ .put(+ PRINCIPAL_KEY,+ PropertyEntry.stringImmutablePropertyEntry(+ PRINCIPAL_KEY, "The principal for the catalog", false, null, false, false))+ .put(+ CHECK_INTERVAL_SEC_KEY,+ PropertyEntry.integerOptionalPropertyEntry(+ CHECK_INTERVAL_SEC_KEY,+ "The interval to check validness of the principal",+ true,+ 60,+ false))+ .put(+ FETCH_TIMEOUT_SEC_KEY,+ PropertyEntry.integerOptionalPropertyEntry(+ FETCH_TIMEOUT_SEC_KEY, "The timeout to fetch key tab", true, 60, false))+ .build();+}diff --git a/catalogs/catalog-hadoop/src/test/java/com/datastrato/gravitino/catalog/hadoop/integration/test/HDFSKerberosIT.java b/catalogs/catalog-hadoop/src/test/java/com/datastrato/gravitino/catalog/hadoop/integration/test/HDFSKerberosIT.javaindex a8d3f657f2..a28407b7f0 100644--- a/catalogs/catalog-hadoop/src/test/java/com/datastrato/gravitino/catalog/hadoop/integration/test/HDFSKerberosIT.java+++ b/catalogs/catalog-hadoop/src/test/java/com/datastrato/gravitino/catalog/hadoop/integration/test/HDFSKerberosIT.java@@ -18,6 +18,7 @@ import org.apache.hadoop.fs.FileSystem;import org.apache.hadoop.fs.Path;import org.apache.hadoop.security.AccessControlException;import org.apache.hadoop.security.UserGroupInformation;+import org.apache.hadoop.security.authentication.util.KerberosName;import org.junit.jupiter.api.AfterAll;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.BeforeAll;@@ -68,6 +69,7 @@ public class HDFSKerberosIT {LOG.info("Kerberos kdc config:\n{}", content);System.setProperty("java.security.krb5.conf", krb5Path);+ KerberosName.resetDefaultRealm();System.setProperty("sun.security.krb5.debug", "true");}@@ -88,6 +90,7 @@ public class HDFSKerberosIT {conf.setBoolean("fs.hdfs.impl.disable.cache", true);conf.set("hadoop.security.authentication", "kerberos");+ UserGroupInformation.reset();UserGroupInformation.setConfiguration(conf);clientUGI = UserGroupInformation.loginUserFromKeytabAndReturnUGI(CLIENT_PRINCIPAL, keytabPath);PrivilegedAction<?> action =diff --git a/catalogs/catalog-hadoop/src/test/java/com/datastrato/gravitino/catalog/hadoop/integration/test/HadoopUserImpersonationIT.java b/catalogs/catalog-hadoop/src/test/java/com/datastrato/gravitino/catalog/hadoop/integration/test/HadoopUserImpersonationIT.javanew file mode 100644index 0000000000..b7cd99f809--- /dev/null+++ b/catalogs/catalog-hadoop/src/test/java/com/datastrato/gravitino/catalog/hadoop/integration/test/HadoopUserImpersonationIT.java@@ -0,0 +1,391 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.catalog.hadoop.integration.test;++import static com.datastrato.gravitino.catalog.hadoop.kerberos.AuthenticationConfig.AUTH_TYPE_KEY;+import static com.datastrato.gravitino.catalog.hadoop.kerberos.AuthenticationConfig.ENABLE_AUTH_KEY;+import static com.datastrato.gravitino.catalog.hadoop.kerberos.KerberosConfig.IMPERSONATION_ENABLE_KEY;+import static com.datastrato.gravitino.catalog.hadoop.kerberos.KerberosConfig.KEY_TAB_URI_KEY;+import static com.datastrato.gravitino.catalog.hadoop.kerberos.KerberosConfig.PRINCIPAL_KEY;+import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_DATA_TRANSFER_PROTECTION_KEY;++import com.datastrato.gravitino.Catalog;+import com.datastrato.gravitino.NameIdentifier;+import com.datastrato.gravitino.Schema;+import com.datastrato.gravitino.client.GravitinoMetalake;+import com.datastrato.gravitino.exceptions.FilesetAlreadyExistsException;+import com.datastrato.gravitino.file.Fileset;+import com.datastrato.gravitino.integration.test.util.AbstractIT;+import com.datastrato.gravitino.integration.test.util.GravitinoITUtils;+import com.datastrato.gravitino.integration.test.util.ITUtils;+import com.google.common.collect.ImmutableMap;+import com.google.common.collect.Maps;+import java.io.File;+import java.io.IOException;+import java.lang.reflect.Method;+import java.security.PrivilegedAction;+import java.security.PrivilegedExceptionAction;+import java.util.Collections;+import java.util.Map;+import java.util.Objects;+import java.util.Properties;+import org.apache.commons.lang3.JavaVersion;+import org.apache.commons.lang3.SystemUtils;+import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.fs.FileSystem;+import org.apache.hadoop.fs.Path;+import org.apache.hadoop.fs.permission.FsPermission;+import org.apache.hadoop.hdfs.HdfsConfiguration;+import org.apache.hadoop.hdfs.MiniDFSCluster;+import org.apache.hadoop.minikdc.MiniKdc;+import org.apache.hadoop.security.UserGroupInformation;+import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.condition.EnabledIf;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++public class HadoopUserImpersonationIT extends AbstractIT {+ private static final Logger LOG = LoggerFactory.getLogger(HadoopCatalogIT.class);++ public static final String metalakeName =+ GravitinoITUtils.genRandomName("CatalogFilesetIT_metalake");+ public static final String catalogName =+ GravitinoITUtils.genRandomName("CatalogFilesetIT_catalog");+ public static final String SCHEMA_PREFIX = "CatalogFilesetIT_schema";+ public static final String schemaName = GravitinoITUtils.genRandomName(SCHEMA_PREFIX);+ private static final String provider = "hadoop";+ private static GravitinoMetalake metalake;+ private static Catalog catalog;++ private static MiniKdc kdc;+ private static MiniDFSCluster hdfsCluster;+ private static File kdcWorkDir;++ private static File serverKeytabFile;+ private static File clientKeytabFile;+ private static Configuration conf;++ private static final String HOSTNAME = "localhost";+ private static final String SERVER_PRINCIPAL = "hdfs/_HOST".replace("_HOST", HOSTNAME);+ private static final String CLIENT_PRINCIPAL = "anonymous";++ private static String hdfsUri;+ private static UserGroupInformation clientUGI;++ @BeforeAll+ public static void setup() throws Exception {+ if (!isEmbedded()) {+ return;+ }++ System.setProperty("sun.security.krb5.debug", "true");+ // Start MiniKDC+ kdcWorkDir = new File(System.getProperty("java.io.tmpdir"), "kdc");+ kdcWorkDir.mkdir();+ Properties kdcConf = MiniKdc.createConf();+ kdc = new MiniKdc(kdcConf, kdcWorkDir);+ kdc.start();++ String krb5ConfFile = kdc.getKrb5conf().getAbsolutePath();+ System.setProperty("java.security.krb5.conf", krb5ConfFile);++ // Reload config when krb5 conf is setup+ if (SystemUtils.isJavaVersionAtMost(JavaVersion.JAVA_1_8)) {+ Class<?> classRef;+ if (System.getProperty("java.vendor").contains("IBM")) {+ classRef = Class.forName("com.ibm.security.krb5.internal.Config");+ } else {+ classRef = Class.forName("sun.security.krb5.Config");+ }+ Method method = classRef.getDeclaredMethod("refresh");+ method.invoke(null);+ }++ // Create a keytab file+ serverKeytabFile = new File(kdcWorkDir, "server.keytab");+ kdc.createPrincipal(serverKeytabFile, SERVER_PRINCIPAL);++ clientKeytabFile = new File(kdcWorkDir, "client.keytab");+ kdc.createPrincipal(clientKeytabFile, CLIENT_PRINCIPAL);++ // Start MiniDFSCluster+ conf = new HdfsConfiguration();+ conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, kdcWorkDir.getAbsolutePath());+ conf.setBoolean("dfs.block.access.token.enable", true);+ conf.setBoolean("dfs.webhdfs.enabled", false);+ conf.set("dfs.permissions", "true");+ conf.set("hadoop.security.authentication", "kerberos");+ conf.set("dfs.namenode.kerberos.principal", SERVER_PRINCIPAL + "@" + kdc.getRealm());+ conf.set("dfs.namenode.keytab.file", serverKeytabFile.getAbsolutePath());+ conf.set("dfs.datanode.kerberos.principal", SERVER_PRINCIPAL + "@" + kdc.getRealm());+ conf.set("dfs.datanode.keytab.file", serverKeytabFile.getAbsolutePath());+ conf.set("ignore.secure.ports.for.testing", "true");+ conf.set(DFS_DATA_TRANSFER_PROTECTION_KEY, "authentication");+ conf.set("dfs.web.authentication.kerberos.principal", SERVER_PRINCIPAL);+ conf.set("dfs.namenode.http-address", "hdfs://localhost:64965");+ conf.set("hadoop.proxyuser.hdfs.hosts", "*");+ conf.set("hadoop.proxyuser.hdfs.groups", "*");+ conf.set("hadoop.proxyuser.hdfs.users", "*");+ conf.set(+ "hadoop.security.auth_to_local", "RULE:[2:$1@$0](.*@EXAMPLE.COM)s/.*/hadoop/\nDEFAULT");+ UserGroupInformation.setConfiguration(conf);+ UserGroupInformation.loginUserFromKeytab(+ SERVER_PRINCIPAL.replaceAll("_HOST", HOSTNAME) + "@" + kdc.getRealm(),+ serverKeytabFile.getAbsolutePath());++ MiniDFSCluster.Builder builder = new MiniDFSCluster.Builder(conf);+ hdfsCluster = builder.build();+ hdfsCluster.waitActive();++ // Hadoop user 'anonymous' to '/anonymous' rw permission+ UserGroupInformation ugiSuperUser = UserGroupInformation.getCurrentUser();+ ugiSuperUser.doAs(+ (PrivilegedExceptionAction<Void>)+ () -> {+ try (FileSystem fs = hdfsCluster.getFileSystem()) {+ Path home = new Path("/anonymous");+ fs.mkdirs(home);+ FsPermission newPerm = new FsPermission(FsPermission.createImmutable((short) 0777));+ // Set permission to "/" (root) for user "anonymous"+ fs.setPermission(home, newPerm);+ fs.setOwner(home, "anonymous", null);+ }+ return null;+ });++ hdfsUri = "hdfs://" + HOSTNAME + ":" + hdfsCluster.getNameNodePort() + "/";++ createMetalake();+ createCatalog();+ createSchema();+ }++ @AfterAll+ public static void stop() {+ if (client != null) {+ client.dropMetalake(metalakeName);+ }++ try {+ closer.close();+ } catch (Exception e) {+ LOG.error("Failed to close CloseableGroup", e);+ }++ // Shutdown MiniDFSCluster+ if (hdfsCluster != null) {+ hdfsCluster.shutdown();+ }+ // Stop the MiniKDC+ if (kdc != null) {+ kdc.stop();+ }+ // Delete KDC directory+ if (kdcWorkDir != null) {+ kdcWorkDir.delete();+ }++ System.clearProperty("sun.security.krb5.debug");+ }++ @Test+ @EnabledIf("isEmbedded")+ void testListFileSystem() throws Exception {+ Configuration clientConf = hdfsCluster.getFileSystem().getConf();+ clientConf.set("fs.defaultFS", hdfsUri);+ clientConf.setBoolean("fs.hdfs.impl.disable.cache", true);+ clientConf.set("hadoop.security.authentication", "kerberos");+ UserGroupInformation.loginUserFromKeytab(+ SERVER_PRINCIPAL + "@EXAMPLE.COM", serverKeytabFile.getAbsolutePath());+ clientUGI = UserGroupInformation.getCurrentUser();+ clientUGI.doAs(+ (PrivilegedAction)+ () -> {+ try {+ FileSystem fs = FileSystem.get(clientConf);+ Path path = new Path("/anonymous");+ Assertions.assertTrue(fs.exists(path));+ return null;+ } catch (IOException e) {+ return Assertions.fail("Failed to list file system", e);+ }+ });+ }++ private static void createMetalake() {+ GravitinoMetalake[] gravitinoMetalakes = client.listMetalakes();+ Assertions.assertEquals(0, gravitinoMetalakes.length);++ GravitinoMetalake createdMetalake =+ client.createMetalake(metalakeName, "comment", Collections.emptyMap());+ GravitinoMetalake loadMetalake = client.loadMetalake(metalakeName);+ Assertions.assertEquals(createdMetalake, loadMetalake);++ metalake = loadMetalake;+ }++ private static void createCatalog() {+ ImmutableMap<String, String> catalogProperties =+ new ImmutableMap.Builder<String, String>()+ .put(ENABLE_AUTH_KEY, "true")+ .put(AUTH_TYPE_KEY, "kerberos")+ .put(IMPERSONATION_ENABLE_KEY, "true")+ .put(PRINCIPAL_KEY, SERVER_PRINCIPAL + "@" + kdc.getRealm())+ .put(KEY_TAB_URI_KEY, serverKeytabFile.getAbsolutePath())+ .build();++ metalake.createCatalog(+ catalogName, Catalog.Type.FILESET, provider, "comment", catalogProperties);++ catalog = metalake.loadCatalog(catalogName);+ }++ private static void createSchema() {+ Map<String, String> properties = Maps.newHashMap();+ properties.put("key1", "val1");+ properties.put("key2", "val2");+ String comment = "comment";++ catalog.asSchemas().createSchema(schemaName, comment, properties);+ Schema loadSchema = catalog.asSchemas().loadSchema(schemaName);+ Assertions.assertEquals(schemaName, loadSchema.name());+ Assertions.assertEquals(comment, loadSchema.comment());+ Assertions.assertEquals("val1", loadSchema.properties().get("key1"));+ Assertions.assertEquals("val2", loadSchema.properties().get("key2"));+ }++ private String storageLocation(String filesetName) {+ return new Path(hdfsUri + "anonymous/", filesetName).toString();+ }++ private Fileset createFileset(+ String filesetName,+ String comment,+ Fileset.Type type,+ String storageLocation,+ Map<String, String> properties) {+ return catalog+ .asFilesetCatalog()+ .createFileset(+ NameIdentifier.of(metalakeName, catalogName, schemaName, filesetName),+ comment,+ type,+ storageLocation,+ properties);+ }++ private boolean checkFilePathExists(String pathString) throws Exception {+ Configuration clientConf = new Configuration();+ clientConf.set("fs.defaultFS", hdfsUri);+ clientConf.set("hadoop.security.authentication", "kerberos");+ clientConf.set("dfs.namenode.kerberos.principal", SERVER_PRINCIPAL + "@" + kdc.getRealm());++ UserGroupInformation.loginUserFromKeytab(+ SERVER_PRINCIPAL + "@EXAMPLE.COM", serverKeytabFile.getAbsolutePath());+ clientUGI = UserGroupInformation.getCurrentUser();+ return (Boolean)+ clientUGI.doAs(+ (PrivilegedAction)+ () -> {+ try {+ FileSystem fs = FileSystem.get(clientConf);+ Path path = new Path(pathString);+ return fs.exists(path);+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ });+ }++ private static boolean isEmbedded() {+ String mode =+ System.getProperty(ITUtils.TEST_MODE) == null+ ? ITUtils.EMBEDDED_TEST_MODE+ : System.getProperty(ITUtils.TEST_MODE);++ return Objects.equals(mode, ITUtils.EMBEDDED_TEST_MODE);+ }++ /**+ * Only runs in embedded mode as miniKDC starts after Gravitino server. in the deploy mode,+ * Gravitino server runs in a separate JVM and miniKDC is not accessible as we haven't get the KDC+ * ip && port.+ */+ @Test+ @EnabledIf("isEmbedded")+ public void testCreateFileset() throws Exception {+ // create fileset+ String filesetName = "test_create_fileset";+ String storageLocation = storageLocation(filesetName);+ Fileset fileset =+ createFileset(+ filesetName,+ "comment",+ Fileset.Type.MANAGED,+ storageLocation,+ ImmutableMap.of("k1", "v1"));++ Assertions.assertTrue(+ checkFilePathExists(storageLocation), "storage location should be created");+ Assertions.assertNotNull(fileset, "fileset should be created");+ Assertions.assertEquals("comment", fileset.comment());+ Assertions.assertEquals(Fileset.Type.MANAGED, fileset.type());+ Assertions.assertEquals(storageLocation, fileset.storageLocation());+ Assertions.assertEquals(1, fileset.properties().size());+ Assertions.assertEquals("v1", fileset.properties().get("k1"));++ // test create a fileset that already exist+ Assertions.assertThrows(+ FilesetAlreadyExistsException.class,+ () ->+ createFileset(+ filesetName,+ "comment",+ Fileset.Type.MANAGED,+ storageLocation,+ ImmutableMap.of("k1", "v1")),+ "Should throw FilesetAlreadyExistsException when fileset already exists");++ // create fileset with null storage location+ String filesetName2 = "test_create_fileset_no_storage_location";+ Fileset fileset2 =+ createFileset(+ filesetName2, null, Fileset.Type.MANAGED, storageLocation(filesetName2), null);+ Assertions.assertNotNull(fileset2, "fileset should be created");+ Assertions.assertNull(fileset2.comment(), "comment should be null");+ Assertions.assertEquals(Fileset.Type.MANAGED, fileset2.type(), "type should be MANAGED");+ Assertions.assertEquals(+ storageLocation(filesetName2),+ fileset2.storageLocation(),+ "storage location should be created");+ Assertions.assertEquals(ImmutableMap.of(), fileset2.properties(), "properties should be empty");++ // create fileset with null fileset name+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ createFileset(+ null,+ "comment",+ Fileset.Type.MANAGED,+ storageLocation,+ ImmutableMap.of("k1", "v1")),+ "Should throw IllegalArgumentException when fileset name is null");++ // create fileset with null fileset type+ String filesetName3 = "test_create_fileset_no_type";+ String storageLocation3 = storageLocation(filesetName3);+ Fileset fileset3 =+ createFileset(filesetName3, "comment", null, storageLocation3, ImmutableMap.of("k1", "v1"));+ Assertions.assertTrue(+ checkFilePathExists(storageLocation3), "storage location should be created");+ Assertions.assertEquals(+ Fileset.Type.MANAGED, fileset3.type(), "fileset type should be MANAGED by default");+ }+}diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex f405461646..47e6ddbbf9 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -117,6 +117,7 @@ hadoop3-hdfs = { group = "org.apache.hadoop", name = "hadoop-hdfs", version.refhadoop3-common = { group = "org.apache.hadoop", name = "hadoop-common", version.ref = "hadoop3"}hadoop3-client = { group = "org.apache.hadoop", name = "hadoop-client", version.ref = "hadoop3"}hadoop3-mapreduce-client-core = { group = "org.apache.hadoop", name = "hadoop-mapreduce-client-core", version.ref = "hadoop3"}+hadoop3-minicluster = { group = "org.apache.hadoop", name = "hadoop-minicluster", version.ref = "hadoop-minikdc"}airlift-units = { group = "io.airlift", name = "units", version.ref = "airlift-units"}airlift-log = { group = "io.airlift", name = "log", version.ref = "airlift-log"}httpclient5 = { group = "org.apache.httpcomponents.client5", name = "httpclient5", version.ref = "httpclient5" }