World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#14415] fix(fileset): Create HDFS file systems for the request user (#14416)
YangJie21220d631e9e
diff --git a/catalogs/catalog-fileset/src/main/java/org/apache/gravitino/catalog/fileset/FilesetCatalogOperations.java b/catalogs/catalog-fileset/src/main/java/org/apache/gravitino/catalog/fileset/FilesetCatalogOperations.javaindex 7da3a90b99..1c7120f5ba 100644--- a/catalogs/catalog-fileset/src/main/java/org/apache/gravitino/catalog/fileset/FilesetCatalogOperations.java+++ b/catalogs/catalog-fileset/src/main/java/org/apache/gravitino/catalog/fileset/FilesetCatalogOperations.java@@ -180,7 +180,8 @@ public class FilesetCatalogOperations extends ManagedSchemaOperations// BaseGVFSOperations@VisibleForTesting Cache<FileSystemCacheKey, FileSystem> fileSystemCache;- private final ThreadPoolExecutor fileSystemExecutor =+ @VisibleForTesting+ final ThreadPoolExecutor fileSystemExecutor =new ThreadPoolExecutor(Math.max(2, Math.min(Runtime.getRuntime().availableProcessors() * 2, 16)),Math.max(2, Math.min(Runtime.getRuntime().availableProcessors() * 2, 32)),@@ -1475,7 +1476,8 @@ public class FilesetCatalogOperations extends ManagedSchemaOperationsnew FileSystemCacheKey(scheme, authority),cacheKey -> {try {- return getFileSystem(path, conf);+ // Create the file system for the user it is cached under.+ return getFileSystem(path, conf, cacheKey.currentUser);} catch (IOException e) {throw new GravitinoRuntimeException(e, "Failed to get FileSystem for fileset: path: %s", path);@@ -1492,6 +1494,11 @@ public class FilesetCatalogOperations extends ManagedSchemaOperations}FileSystem getFileSystem(Path path, Map<String, String> config) throws IOException {+ // Read the user here: a pool thread keeps the Subject of the request that started it.+ return getFileSystem(path, config, PrincipalUtils.getCurrentUserName());+ }++ FileSystem getFileSystem(Path path, Map<String, String> config, String user) throws IOException {if (path == null) {throw new IllegalArgumentException("Path should not be null");}@@ -1518,7 +1525,7 @@ public class FilesetCatalogOperations extends ManagedSchemaOperationstry {return executeFileSystemTask(- () -> createFileSystem(path, config, scheme, provider), timeoutSeconds);+ () -> createFileSystem(path, config, scheme, provider, user), timeoutSeconds);} catch (TimeoutException e) {LOG.warn("Timeout when getting FileSystem for path: {}, scheme: {}, provider: {} within {} seconds",@@ -1622,6 +1629,8 @@ public class FilesetCatalogOperations extends ManagedSchemaOperationsString.format("Fileset connection testing does not support scheme %s", scheme));}+ // Read the user here: a pool thread keeps the Subject of the request that started it.+ String user = PrincipalUtils.getCurrentUserName();String credentialHandle = null;try {credentialHandle = addVendedCredential(path, scheme, fileSystemProvider, probeConf);@@ -1635,7 +1644,7 @@ public class FilesetCatalogOperations extends ManagedSchemaOperationsexecuteFileSystemTask(() -> {try (FileSystem fileSystem =- createProbeFileSystem(path, probeConf, scheme, fileSystemProvider)) {+ createProbeFileSystem(path, probeConf, scheme, fileSystemProvider, user)) {Path qualifiedPath =path.makeQualified(fileSystem.getUri(), fileSystem.getWorkingDirectory());try {@@ -1738,21 +1747,29 @@ public class FilesetCatalogOperations extends ManagedSchemaOperationscredentialManagerSupplier.get(), "Catalog credential manager must not be null");}- private FileSystem createFileSystem(- Path path, Map<String, String> config, String scheme, FileSystemProvider provider)+ @VisibleForTesting+ FileSystem createFileSystem(+ Path path,+ Map<String, String> config,+ String scheme,+ FileSystemProvider provider,+ String user)throws IOException {if (scheme.equals(SCHEME_HDFS)) {- return new ImpersonationHDFSFileSystemProxy(path, config, PrincipalUtils::getCurrentUserName)- .getProxy();+ return new ImpersonationHDFSFileSystemProxy(path, config, () -> user).getProxy();}return provider.getFileSystem(path, config);}private FileSystem createProbeFileSystem(- Path path, Map<String, String> config, String scheme, FileSystemProvider provider)+ Path path,+ Map<String, String> config,+ String scheme,+ FileSystemProvider provider,+ String user)throws IOException {try {- return createFileSystem(path, config, scheme, provider);+ return createFileSystem(path, config, scheme, provider, user);} catch (Exception e) {throw new ProbeInitializationException(e);}diff --git a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.java b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.javaindex dca9a991f4..5a51246bde 100644--- a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.java+++ b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.java@@ -79,6 +79,7 @@ import java.util.Map;import java.util.Properties;import java.util.Set;import java.util.UUID;+import java.util.concurrent.CopyOnWriteArrayList;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;@@ -182,6 +183,7 @@ import org.junit.jupiter.params.provider.CsvSource;import org.junit.jupiter.params.provider.EnumSource;import org.junit.jupiter.params.provider.MethodSource;import org.junit.jupiter.params.provider.ValueSource;+import org.mockito.MockedConstruction;import org.mockito.MockedStatic;import org.mockito.Mockito;@@ -2616,7 +2618,9 @@ public class TestFilesetCatalogOperations {try (FilesetCatalogOperations ops =Mockito.spy(new FilesetCatalogOperations(store, secretManager))) {- doReturn(fileSystem).when(ops).getFileSystem(Mockito.eq(path), Mockito.anyMap());+ doReturn(fileSystem)+ .when(ops)+ .getFileSystem(Mockito.eq(path), Mockito.anyMap(), Mockito.anyString());ConnectionFailedException failure =Assertions.assertThrows(ConnectionFailedException.class,@@ -2655,6 +2659,103 @@ public class TestFilesetCatalogOperations {}}+ @ParameterizedTest+ @ValueSource(booleans = {true, false})+ public void testGetFileSystemUsesRequestUserOnPoolThread(boolean cached) throws Exception {+ try (FilesetCatalogOperations ops =+ Mockito.spy(new FilesetCatalogOperations(store, secretManager))) {+ ops.initialize(ImmutableMap.of(), randomCatalogInfo("m1", "c1"), FILESET_PROPERTIES_METADATA);+ List<String> users = recordFileSystemUsers(ops);+ startPoolThreadsAs(ops, "alice");++ Path path = new Path(TEST_ROOT_PATH, "pool_thread_user");+ PrincipalUtils.doAs(+ new UserPrincipal("bob"),+ () -> {+ if (cached) {+ // ops.close() closes the cached file system.+ ops.getFileSystemWithCache(path, ImmutableMap.of());+ } else {+ ops.getFileSystem(path, ImmutableMap.of()).close();+ }+ return null;+ });++ Assertions.assertEquals(Collections.singletonList("bob on alice"), users);+ }+ }++ @Test+ public void testTestConnectionUsesRequestUserOnPoolThread() throws Exception {+ File location = new File(UNFORMALIZED_TEST_ROOT_PATH, "connection/pool-thread-user");+ FileUtils.forceMkdir(location);++ try (FilesetCatalogOperations ops =+ Mockito.spy(new FilesetCatalogOperations(store, secretManager))) {+ ops.initialize(+ ImmutableMap.of(LOCATION, location.toURI().toString()),+ randomCatalogInfo("metalake", "catalog"),+ FILESET_PROPERTIES_METADATA);+ List<String> users = recordFileSystemUsers(ops);+ startPoolThreadsAs(ops, "alice");++ PrincipalUtils.doAs(+ new UserPrincipal("bob"),+ () -> {+ ops.testConnection(NameIdentifier.of("metalake", "catalog"));+ return null;+ });++ Assertions.assertEquals(Collections.singletonList("bob on alice"), users);+ }+ }++ @Test+ public void testHdfsFileSystemProxyUsesGivenUser() throws Exception {+ List<ImpersonationHDFSFileSystemProxy.ProxyUserHandler> handlers = new ArrayList<>();+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager);+ MockedConstruction<ImpersonationHDFSFileSystemProxy> ignored =+ Mockito.mockConstruction(+ ImpersonationHDFSFileSystemProxy.class,+ (proxy, context) ->+ handlers.add(+ (ImpersonationHDFSFileSystemProxy.ProxyUserHandler)+ context.arguments().get(2)))) {+ ops.initialize(ImmutableMap.of(), randomCatalogInfo("m1", "c1"), FILESET_PROPERTIES_METADATA);+ // Called directly: construction mocks only intercept on the current thread.+ ops.createFileSystem(+ new Path("hdfs://localhost:8020/proxy_user"), ImmutableMap.of(), "hdfs", null, "bob");++ Assertions.assertEquals(1, handlers.size());+ Assertions.assertEquals(+ "bob", PrincipalUtils.doAs(new UserPrincipal("alice"), handlers.get(0)::getProxyUser));+ }+ }++ private static List<String> recordFileSystemUsers(FilesetCatalogOperations ops)+ throws IOException {+ List<String> users = new CopyOnWriteArrayList<>();+ Mockito.doAnswer(+ invocation -> {+ // The requested user, and the user whose Subject the pool thread carries.+ users.add(invocation.getArgument(4) + " on " + PrincipalUtils.getCurrentUserName());+ return invocation.callRealMethod();+ })+ .when(ops)+ .createFileSystem(any(), any(), any(), any(), any());+ return users;+ }++ // The tests rely on a thread started inside Subject.doAs keeping that Subject, as it does up to+ // JDK 22. Revisit them when PrincipalUtils moves off Subject.getSubject, which later JDKs no+ // longer support. Keep the threads alive so that bob's request does not start new ones.+ private static void startPoolThreadsAs(FilesetCatalogOperations ops, String user)+ throws Exception {+ ops.fileSystemExecutor.allowCoreThreadTimeOut(false);+ PrincipalUtils.doAs(+ new UserPrincipal(user), () -> ops.fileSystemExecutor.prestartAllCoreThreads());+ }+@Testpublic void testTestConnectionWithoutCatalogLocation() throws IOException {try (FilesetCatalogOperations catalogOperations =@@ -3408,7 +3509,7 @@ public class TestFilesetCatalogOperations {String subPath = "/test/test.parquet";when(mockOps.getFileLocation(filesetIdent, subPath)).thenCallRealMethod();when(mockOps.getFileLocation(filesetIdent, subPath, null)).thenCallRealMethod();- when(mockOps.getFileSystem(any(), any()))+ when(mockOps.getFileSystem(any(), any(), any())).thenReturn(FileSystem.getLocal(new Configuration()));when(mockOps.getFileSystemWithCache(any(), any())).thenCallRealMethod();String fileLocation = mockOps.getFileLocation(filesetIdent, subPath);@@ -3421,6 +3522,7 @@ public class TestFilesetCatalogOperations {FileSystem fs2 =mockOps.getFileSystemWithCache(new Path("file:///dir1/subdir/file2"), mockOps.getConf());+ Assertions.assertNotNull(fs1);Assertions.assertSame(fs1, fs2);} catch (Exception e) {throw new RuntimeException(e);@@ -3952,7 +4054,9 @@ public class TestFilesetCatalogOperations {randomCatalogInfo("m1", "c1"),FILESET_PROPERTIES_METADATA);ops.fileSystemCache.invalidateAll();- Mockito.doThrow(cause).when(ops).getFileSystem(Mockito.eq(path), Mockito.eq(conf));+ Mockito.doThrow(cause)+ .when(ops)+ .getFileSystem(Mockito.eq(path), Mockito.eq(conf), Mockito.anyString());GravitinoRuntimeException e =Assertions.assertThrows(