This is an automated email from the ASF dual-hosted git repository.

jerryshao pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gravitino.git


The following commit(s) were added to refs/heads/main by this push:
     new 0e6e4f6130 [#13454] fix(gvfs): collect delegation tokens for 
configured filesets (#13455)
0e6e4f6130 is described below

commit 0e6e4f61309af44d4516bcbbfd0d42ea2cf567f9
Author: Honggeun Ji <[email protected]>
AuthorDate: Fri Nov 13 01:44:22 2026 -0500

    [#13454] fix(gvfs): collect delegation tokens for configured filesets 
(#13455)
    
    ### What changes were proposed in this pull request?
    
    Token requests carry no path, and all `gvfs://fileset/...` paths share
    one GVFS instance, so GVFS cannot tell which filesets a job needs.
    Executors then get no token for a fileset outside `fs.defaultFS`, and
    with filesets on several HDFS clusters, at most one cluster gets a
    token.
    
    - Add `fs.gravitino.kerberos.access.filesets`. GVFS resolves each listed
    fileset and collects a token for its cluster.
    - Hand out only tokens owned by the current user, so a catalog's service
    keytab is never shipped to executors.
    - Token collection does not create a missing fileset location.
    
    ### Why are the changes needed?
    
    Fix: #13454
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. New GVFS config `fs.gravitino.kerberos.access.filesets`. It is
    needed to read filesets outside `fs.defaultFS` on Kerberized YARN, e.g.
    with Spark:
    
    ```
    spark.kerberos.access.hadoopFileSystems=gvfs://fileset
    
spark.hadoop.fs.gravitino.kerberos.access.filesets=gvfs://fileset/catalog1/schema1/fileset1,gvfs://fileset/catalog2/schema2/fileset2
    ```
    
    Existing usage, where filesets resolve to `fs.defaultFS`, is unchanged.
    
    ### How was this patch tested?
    
    - UT: `TestPrepareDelegationTokens`
    - E2E: Spark on YARN with Kerberos, reading filesets on two extra
    Kerberized HDFS clusters. See the results in [this
    
comment](https://github.com/apache/gravitino/pull/13455#discussion_r4218846314)
    (posted before the option was renamed).
---
 .../filesystem/hadoop/BaseGVFSOperations.java      | 105 ++++-
 .../GravitinoVirtualFileSystemConfiguration.java   |   8 +
 .../hadoop/TestPrepareDelegationTokens.java        | 439 +++++++++++++++++++++
 docs/how-to-use-gvfs.md                            |  22 ++
 4 files changed, 566 insertions(+), 8 deletions(-)

diff --git 
a/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/BaseGVFSOperations.java
 
b/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/BaseGVFSOperations.java
index 833b4caeb5..ee5cf96378 100644
--- 
a/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/BaseGVFSOperations.java
+++ 
b/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/BaseGVFSOperations.java
@@ -43,7 +43,6 @@ import java.io.Closeable;
 import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.net.URI;
-import java.util.Arrays;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
@@ -97,9 +96,12 @@ import org.apache.hadoop.fs.FileStatus;
 import org.apache.hadoop.fs.FileSystem;
 import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.fs.permission.FsPermission;
+import org.apache.hadoop.io.Text;
 import org.apache.hadoop.security.Credentials;
 import org.apache.hadoop.security.UserGroupInformation;
 import org.apache.hadoop.security.token.Token;
+import org.apache.hadoop.security.token.TokenIdentifier;
+import 
org.apache.hadoop.security.token.delegation.AbstractDelegationTokenIdentifier;
 import org.apache.hadoop.util.Progressable;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -455,22 +457,54 @@ public abstract class BaseGVFSOperations implements 
Closeable {
   public abstract Token<?>[] addDelegationTokens(String renewer, Credentials 
credentials);
 
   /**
-   * Add delegation tokens for all file systems in the cache.
+   * Add delegation tokens for all file systems in the cache and for the 
filesets listed in {@link
+   * 
GravitinoVirtualFileSystemConfiguration#FS_GRAVITINO_KERBEROS_ACCESS_FILESETS}. 
Token requests
+   * carry no path, so filesets outside {@code fs.defaultFS} must be listed 
there.
+   *
+   * <p>Only tokens owned by the current user are added. A fileset configured 
with its own Kerberos
+   * principal is accessed as that principal, and its token must not be handed 
to the caller's job.
    *
    * @param renewer the renewer.
    * @param credentials the credentials.
    * @return the array of tokens.
    */
-  protected Token<?>[] addDelegationTokensForAllFS(String renewer, Credentials 
credentials) {
+  protected Token<?>[] addDelegationTokensForAllFS(
+      String renewer, @Nullable Credentials credentials) {
+    // Hadoop accepts null credentials and returns the new tokens only.
+    if (credentials == null) {
+      credentials = new Credentials();
+    }
+
+    String currentUser;
+    try {
+      currentUser = UserGroupInformation.getCurrentUser().getShortUserName();
+    } catch (IOException e) {
+      LOG.warn("Failed to get the current user, skipping delegation tokens", 
e);
+      return new Token<?>[0];
+    }
+
     List<Token<?>> tokenList = Lists.newArrayList();
     for (FileSystem fileSystem : fileSystemCache.asMap().values()) {
+      addDelegationTokens(fileSystem, renewer, credentials, currentUser, 
tokenList);
+    }
+    for (String path :
+        conf.getTrimmedStrings(
+            
GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_KERBEROS_ACCESS_FILESETS)) 
{
+      FileSystem fileSystem;
       try {
-        tokenList.addAll(Arrays.asList(fileSystem.addDelegationTokens(renewer, 
credentials)));
-      } catch (IOException e) {
-        LOG.warn("Failed to add delegation tokens for filesystem: {}", 
fileSystem.getUri(), e);
+        // Token collection must not write, so the fileset location is never 
created here.
+        fileSystem =
+            getActualFileSystemByLocationName(
+                extractIdentifier(metalakeName, path), currentLocationName(), 
false);
+      } catch (Exception e) {
+        // Never fail token collection: an unresolvable fileset simply yields 
no token.
+        LOG.warn("Failed to resolve {} while collecting delegation tokens", 
path, e);
+        continue;
       }
+      // Collect right after resolving, as the bounded cache may already have 
evicted it.
+      addDelegationTokens(fileSystem, renewer, credentials, currentUser, 
tokenList);
     }
-    return tokenList.stream().distinct().toArray(Token[]::new);
+    return tokenList.toArray(new Token<?>[0]);
   }
 
   /**
@@ -717,6 +751,12 @@ public abstract class BaseGVFSOperations implements 
Closeable {
    */
   protected FileSystem getActualFileSystemByLocationName(
       NameIdentifier filesetIdent, String locationName) throws 
FileNotFoundException {
+    return getActualFileSystemByLocationName(filesetIdent, locationName, true);
+  }
+
+  private FileSystem getActualFileSystemByLocationName(
+      NameIdentifier filesetIdent, String locationName, boolean createLocation)
+      throws FileNotFoundException {
     NameIdentifier catalogIdent =
         NameIdentifier.of(filesetIdent.namespace().level(0), 
filesetIdent.namespace().level(1));
     try {
@@ -747,7 +787,9 @@ public abstract class BaseGVFSOperations implements 
Closeable {
       }
 
       FileSystem actualFileSystem = getActualFileSystemByPath(targetLocation, 
allProperties);
-      createFilesetLocationIfNeed(filesetIdent, actualFileSystem, 
targetLocation);
+      if (createLocation) {
+        createFilesetLocationIfNeed(filesetIdent, actualFileSystem, 
targetLocation);
+      }
       return actualFileSystem;
     } catch (RuntimeException e) {
       Throwable cause = e.getCause();
@@ -1140,4 +1182,51 @@ public abstract class BaseGVFSOperations implements 
Closeable {
     return 
Optional.ofNullable(configuration.get(FS_GRAVITINO_CURRENT_LOCATION_NAME))
         .orElse(System.getenv(currentLocationEnvVar));
   }
+
+  private void addDelegationTokens(
+      FileSystem fileSystem,
+      String renewer,
+      Credentials credentials,
+      String currentUser,
+      List<Token<?>> tokenList) {
+    // Collect into a copy, so a token owned by another user never reaches the 
caller.
+    Credentials fetched = new Credentials(credentials);
+    try {
+      fileSystem.addDelegationTokens(renewer, fetched);
+    } catch (IOException e) {
+      LOG.warn("Failed to add delegation tokens for filesystem: {}", 
fileSystem.getUri(), e);
+      return;
+    }
+    for (Map.Entry<Text, Token<? extends TokenIdentifier>> entry :
+        fetched.getTokenMap().entrySet()) {
+      Token<?> token = entry.getValue();
+      if (credentials.getToken(entry.getKey()) != null) {
+        continue;
+      }
+      if (!isOwnedBy(token, currentUser)) {
+        LOG.warn(
+            "Skipping delegation token for {} owned by another user than {}",
+            entry.getKey(),
+            currentUser);
+        continue;
+      }
+      credentials.addToken(entry.getKey(), token);
+      tokenList.add(token);
+    }
+  }
+
+  private static boolean isOwnedBy(Token<?> token, String user) {
+    TokenIdentifier identifier;
+    try {
+      identifier = token.decodeIdentifier();
+    } catch (IOException e) {
+      return false;
+    }
+    // Tokens without an owner, such as those of some object stores, are not 
tied to a user.
+    if (!(identifier instanceof AbstractDelegationTokenIdentifier)) {
+      return true;
+    }
+    return user.equals(
+        ((AbstractDelegationTokenIdentifier) 
identifier).getUser().getShortUserName());
+  }
 }
diff --git 
a/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/GravitinoVirtualFileSystemConfiguration.java
 
b/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/GravitinoVirtualFileSystemConfiguration.java
index 7be8dd0ad1..5748d791ba 100644
--- 
a/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/GravitinoVirtualFileSystemConfiguration.java
+++ 
b/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/GravitinoVirtualFileSystemConfiguration.java
@@ -238,6 +238,14 @@ public class GravitinoVirtualFileSystemConfiguration {
   /** The default value for whether to enable auto-creation of fileset 
location. */
   public static final boolean FS_GRAVITINO_AUTO_CREATE_LOCATION_DEFAULT = true;
 
+  /**
+   * The configuration key for the comma-separated fileset paths to collect 
delegation tokens for,
+   * e.g. {@code gvfs://fileset/catalog/schema/fileset}. Needed when a job 
reads filesets outside
+   * {@code fs.defaultFS}, because token requests carry no path for GVFS to 
resolve.
+   */
+  public static final String FS_GRAVITINO_KERBEROS_ACCESS_FILESETS =
+      "fs.gravitino.kerberos.access.filesets";
+
   /**
    * The prefix for user-defined location configs: {@code
    * fs.path.config.<locationName>.<property_name>=<property_value>}.
diff --git 
a/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestPrepareDelegationTokens.java
 
b/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestPrepareDelegationTokens.java
new file mode 100644
index 0000000000..3beb89562f
--- /dev/null
+++ 
b/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestPrepareDelegationTokens.java
@@ -0,0 +1,439 @@
+/*
+ * 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.filesystem.hadoop;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.withSettings;
+
+import com.google.common.collect.ImmutableMap;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.security.PrivilegedExceptionAction;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.Catalog;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Schema;
+import org.apache.gravitino.SupportsSchemas;
+import org.apache.gravitino.client.GravitinoClient;
+import org.apache.gravitino.exceptions.NoSuchFilesetException;
+import org.apache.gravitino.file.Fileset;
+import org.apache.gravitino.file.FilesetCatalog;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FSDataInputStream;
+import org.apache.hadoop.fs.FSDataOutputStream;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.permission.FsPermission;
+import org.apache.hadoop.io.Text;
+import org.apache.hadoop.security.Credentials;
+import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.hadoop.security.token.Token;
+import 
org.apache.hadoop.security.token.delegation.AbstractDelegationTokenIdentifier;
+import org.apache.hadoop.util.Progressable;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Tests that delegation token collection resolves the configured filesets 
first, and that only
+ * tokens owned by the current user are handed out.
+ */
+public class TestPrepareDelegationTokens {
+
+  private static final String METALAKE = "ml";
+  private static final Path GVFS_PATH = new 
Path("gvfs://fileset/catalog/schema/fs");
+  private static final Path OTHER_PATH = new 
Path("gvfs://fileset/catalog/schema/other");
+  private static final Text SERVICE = new Text("nn:8020");
+
+  @Test
+  public void testResolvesConfiguredFilesets() throws Exception {
+    Catalog catalog = newCatalog();
+    Fileset fileset = newFileset();
+    Fileset other = newFileset();
+    TestOps ops = newOps(withFilesets(GVFS_PATH + ", " + OTHER_PATH), catalog, 
fileset);
+    when(catalog.asFilesetCatalog().loadFileset(NameIdentifier.of("schema", 
"other")))
+        .thenReturn(other);
+
+    ops.addDelegationTokens("renewer", new Credentials());
+
+    assertEquals(
+        List.of(location(fileset), location(other)).toString(), 
ops.resolvedPaths.toString());
+  }
+
+  @Test
+  public void testDoesNotCreateMissingLocation() throws Exception {
+    java.nio.file.Path missing = 
Files.createTempDirectory("gvfs-token-missing").resolve("fs");
+    String location = missing.toUri().toString();
+    Fileset fileset = mock(Fileset.class);
+    when(fileset.properties())
+        .thenReturn(ImmutableMap.of(Fileset.PROPERTY_DEFAULT_LOCATION_NAME, 
"unknown"));
+    when(fileset.storageLocations()).thenReturn(ImmutableMap.of("unknown", 
location));
+    Catalog catalog = newCatalog();
+    
when(catalog.properties()).thenReturn(ImmutableMap.of("disable-filesystem-ops", 
"true"));
+    TestOps ops = newOps(withFilesets(GVFS_PATH.toString()), catalog, fileset);
+
+    ops.addDelegationTokens("renewer", new Credentials());
+
+    assertEquals(List.of(new Path(location)), ops.resolvedPaths);
+    assertFalse(Files.exists(missing));
+  }
+
+  @Test
+  public void testResolvesNothingWithoutConfiguredFilesets() throws Exception {
+    TestOps ops = newOps(newConf(), newCatalog(), newFileset());
+
+    ops.addDelegationTokens("renewer", new Credentials());
+
+    assertTrue(ops.resolvedPaths.isEmpty());
+  }
+
+  @Test
+  public void testResolvesTheCurrentLocation() throws Exception {
+    String defaultLocation = 
Files.createTempDirectory("gvfs-token-default").toUri().toString();
+    String currentLocation = 
Files.createTempDirectory("gvfs-token-current").toUri().toString();
+    Fileset fileset = mock(Fileset.class);
+    when(fileset.properties())
+        .thenReturn(ImmutableMap.of(Fileset.PROPERTY_DEFAULT_LOCATION_NAME, 
"unknown"));
+    when(fileset.storageLocations())
+        .thenReturn(ImmutableMap.of("unknown", defaultLocation, "current", 
currentLocation));
+
+    Configuration conf = withFilesets(GVFS_PATH.toString());
+    
conf.set(GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_CURRENT_LOCATION_NAME,
 "current");
+    TestOps ops = newOps(conf, newCatalog(), fileset);
+
+    ops.addDelegationTokens("renewer", new Credentials());
+
+    assertEquals(List.of(new Path(currentLocation)), ops.resolvedPaths);
+  }
+
+  @Test
+  public void testUnresolvableFilesetDoesNotStopOthers() throws Exception {
+    Catalog catalog = newCatalog();
+    Fileset other = newFileset();
+    when(catalog.asFilesetCatalog().loadFileset(NameIdentifier.of("schema", 
"fs")))
+        .thenThrow(new NoSuchFilesetException("gone"));
+    when(catalog.asFilesetCatalog().loadFileset(NameIdentifier.of("schema", 
"other")))
+        .thenReturn(other);
+    TestOps ops = newOps(withFilesets(GVFS_PATH + "," + OTHER_PATH), catalog, 
null);
+
+    assertDoesNotThrow(() -> ops.addDelegationTokens("renewer", new 
Credentials()));
+    assertEquals(List.of(location(other)).toString(), 
ops.resolvedPaths.toString());
+  }
+
+  @Test
+  public void testCollectsTokensForFilesetsEvictedFromCache() throws Exception 
{
+    Catalog catalog = newCatalog();
+    Fileset fileset = newFileset();
+    Fileset other = newFileset();
+    Configuration conf = withFilesets(GVFS_PATH + "," + OTHER_PATH);
+    conf.setInt(
+        
GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_FILESET_CACHE_MAX_CAPACITY_KEY,
 1);
+    TestOps ops = newOps(conf, catalog, fileset);
+    when(catalog.asFilesetCatalog().loadFileset(NameIdentifier.of("schema", 
"other")))
+        .thenReturn(other);
+    // Each fileset lives on its own cluster, so the second one evicts the 
first from the cache.
+    ops.fakeFileSystems = true;
+
+    UserGroupInformation ugi = UserGroupInformation.createRemoteUser("alice");
+    Credentials credentials = new Credentials();
+    ugi.doAs(
+        (PrivilegedExceptionAction<Token<?>[]>)
+            () -> ops.addDelegationTokens("renewer", credentials));
+
+    assertEquals(1, ops.internalFileSystemCache().estimatedSize());
+    assertEquals(2, credentials.numberOfTokens());
+  }
+
+  @Test
+  public void testAddsTokenOwnedByCurrentUser() throws Exception {
+    Token<?> token = newToken(UserGroupInformation.createRemoteUser("alice"));
+    Credentials credentials = collectAs("alice", token);
+
+    assertSame(token, credentials.getToken(SERVICE));
+  }
+
+  @Test
+  public void testSkipsTokenOwnedByAnotherUser() throws Exception {
+    // A fileset with its own Kerberos principal is accessed as that principal.
+    Token<?> token = newToken(UserGroupInformation.createRemoteUser("svc"));
+    Credentials credentials = collectAs("alice", token);
+
+    assertNull(credentials.getToken(SERVICE));
+  }
+
+  @Test
+  public void testAddsImpersonatedToken() throws Exception {
+    UserGroupInformation proxy =
+        UserGroupInformation.createProxyUser("alice", 
UserGroupInformation.createRemoteUser("svc"));
+    Token<?> token = newToken(proxy);
+    Credentials credentials = collectAs("alice", token);
+
+    assertSame(token, credentials.getToken(SERVICE));
+  }
+
+  @Test
+  public void testAcceptsNullCredentials() throws Exception {
+    Token<?> token = newToken(UserGroupInformation.createRemoteUser("alice"));
+
+    assertArrayEquals(new Token<?>[] {token}, addTokensAs("alice", token, 
null));
+  }
+
+  @Test
+  public void testDoesNotReplaceExistingToken() throws Exception {
+    Token<?> existing = 
newToken(UserGroupInformation.createRemoteUser("alice"));
+    Credentials credentials = new Credentials();
+    credentials.addToken(SERVICE, existing);
+
+    collectAs("alice", 
newToken(UserGroupInformation.createRemoteUser("alice")), credentials);
+
+    assertSame(existing, credentials.getToken(SERVICE));
+  }
+
+  private Credentials collectAs(String user, Token<?> token) throws Exception {
+    return collectAs(user, token, new Credentials());
+  }
+
+  private Credentials collectAs(String user, Token<?> token, Credentials 
credentials)
+      throws Exception {
+    addTokensAs(user, token, credentials);
+    return credentials;
+  }
+
+  private Token<?>[] addTokensAs(String user, Token<?> token, Credentials 
credentials)
+      throws Exception {
+    FileSystem fs = mock(FileSystem.class);
+    when(fs.addDelegationTokens(any(), any()))
+        .thenAnswer(
+            invocation -> {
+              Credentials target = invocation.getArgument(1);
+              if (target.getToken(SERVICE) == null) {
+                target.addToken(SERVICE, token);
+              }
+              return new Token<?>[] {token};
+            });
+
+    TestOps ops = newOps(newConf(), newCatalog(), null);
+    UserGroupInformation ugi = UserGroupInformation.createRemoteUser(user);
+    ops.internalFileSystemCache()
+        .put(new BaseGVFSOperations.FileSystemCacheKey("hdfs", "nn:8020", 
ugi), fs);
+    return ugi.doAs(
+        (PrivilegedExceptionAction<Token<?>[]>)
+            () -> ops.addDelegationTokens("renewer", credentials));
+  }
+
+  private static FileSystem newTokenIssuingFileSystem(Text service) {
+    FileSystem fs = mock(FileSystem.class);
+    try {
+      Token<?> token = newToken(UserGroupInformation.getCurrentUser());
+      when(fs.addDelegationTokens(any(), any()))
+          .thenAnswer(
+              invocation -> {
+                Credentials target = invocation.getArgument(1);
+                target.addToken(service, token);
+                return new Token<?>[] {token};
+              });
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    }
+    return fs;
+  }
+
+  @SuppressWarnings("unchecked")
+  private static Token<?> newToken(UserGroupInformation owner) throws 
IOException {
+    AbstractDelegationTokenIdentifier identifier = 
mock(AbstractDelegationTokenIdentifier.class);
+    when(identifier.getUser()).thenReturn(owner);
+    Token<AbstractDelegationTokenIdentifier> token = mock(Token.class);
+    when(token.decodeIdentifier()).thenReturn(identifier);
+    return token;
+  }
+
+  private Path location(Fileset fileset) {
+    return new Path(fileset.storageLocations().get("unknown"));
+  }
+
+  private Fileset newFileset() throws IOException {
+    String location = 
Files.createTempDirectory("gvfs-token-test").toUri().toString();
+    Fileset fileset = mock(Fileset.class);
+    when(fileset.properties())
+        .thenReturn(ImmutableMap.of(Fileset.PROPERTY_DEFAULT_LOCATION_NAME, 
"unknown"));
+    when(fileset.storageLocations()).thenReturn(ImmutableMap.of("unknown", 
location));
+    return fileset;
+  }
+
+  /** The catalog is both a {@link Catalog} and a {@link FilesetCatalog}, as 
it is on the server. */
+  private Catalog newCatalog() {
+    Catalog catalog = mock(Catalog.class, 
withSettings().extraInterfaces(FilesetCatalog.class));
+    Schema schema = mock(Schema.class);
+    SupportsSchemas schemas = mock(SupportsSchemas.class);
+
+    when(catalog.properties()).thenReturn(ImmutableMap.of());
+    when(catalog.asSchemas()).thenReturn(schemas);
+    when(catalog.asFilesetCatalog()).thenReturn((FilesetCatalog) catalog);
+    when(schemas.loadSchema("schema")).thenReturn(schema);
+    when(schema.properties()).thenReturn(ImmutableMap.of());
+    return catalog;
+  }
+
+  private Configuration withFilesets(String filesets) {
+    Configuration conf = newConf();
+    conf.set(
+        
GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_KERBEROS_ACCESS_FILESETS, 
filesets);
+    return conf;
+  }
+
+  private Configuration newConf() {
+    Configuration conf = new Configuration();
+    
conf.set(GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_CLIENT_METALAKE_KEY,
 METALAKE);
+    conf.set(
+        GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_SERVER_URI_KEY,
+        "http://localhost:8090";);
+    return conf;
+  }
+
+  private TestOps newOps(Configuration conf, Catalog catalog, Fileset fileset) 
throws Exception {
+    if (fileset != null) {
+      when(catalog.asFilesetCatalog().loadFileset(NameIdentifier.of("schema", 
"fs")))
+          .thenReturn(fileset);
+    }
+
+    GravitinoClient client = mock(GravitinoClient.class);
+    when(client.loadCatalog("catalog")).thenReturn(catalog);
+
+    return new TestOps(conf, client);
+  }
+
+  private static final class TestOps extends BaseGVFSOperations {
+    private final GravitinoClient client;
+    private final List<Path> resolvedPaths = new ArrayList<>();
+    private boolean fakeFileSystems;
+
+    private TestOps(Configuration configuration, GravitinoClient client) {
+      super(configuration);
+      this.client = client;
+    }
+
+    @Override
+    GravitinoClient getGravitinoClient() {
+      return client;
+    }
+
+    @Override
+    protected FileSystem getActualFileSystemByPath(
+        Path actualFilePath, Map<String, String> allProperties) {
+      resolvedPaths.add(actualFilePath);
+      if (!fakeFileSystems) {
+        return super.getActualFileSystemByPath(actualFilePath, allProperties);
+      }
+      FileSystem fs = newTokenIssuingFileSystem(new 
Text(actualFilePath.toString()));
+      try {
+        internalFileSystemCache()
+            .put(
+                new FileSystemCacheKey(
+                    "hdfs", actualFilePath.toString(), 
UserGroupInformation.getCurrentUser()),
+                fs);
+      } catch (IOException e) {
+        throw new RuntimeException(e);
+      }
+      internalFileSystemCache().cleanUp();
+      return fs;
+    }
+
+    @Override
+    protected Schema getSchema(NameIdentifier schemaIdent) {
+      Schema schema = mock(Schema.class);
+      when(schema.properties()).thenReturn(ImmutableMap.of());
+      return schema;
+    }
+
+    @Override
+    public FSDataInputStream open(Path gvfsPath, int bufferSize) {
+      throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public void setWorkingDirectory(Path gvfsDir) {}
+
+    @Override
+    public FSDataOutputStream create(
+        Path gvfsPath,
+        FsPermission permission,
+        boolean overwrite,
+        int bufferSize,
+        short replication,
+        long blockSize,
+        Progressable progress) {
+      throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public FSDataOutputStream append(Path gvfsPath, int bufferSize, 
Progressable progress) {
+      throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public boolean rename(Path srcGvfsPath, Path dstGvfsPath) {
+      throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public boolean delete(Path gvfsPath, boolean recursive) {
+      throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public FileStatus[] listStatus(Path gvfsPath) {
+      throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public FileStatus getFileStatus(Path gvfsPath) {
+      throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public boolean mkdirs(Path gvfsPath, FsPermission permission) {
+      throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public short getDefaultReplication(Path gvfsPath) {
+      throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public long getDefaultBlockSize(Path gvfsPath) {
+      throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public Token<?>[] addDelegationTokens(String renewer, Credentials 
credentials) {
+      return addDelegationTokensForAllFS(renewer, credentials);
+    }
+  }
+}
diff --git a/docs/how-to-use-gvfs.md b/docs/how-to-use-gvfs.md
index 1b080cad1f..988e1053c8 100644
--- a/docs/how-to-use-gvfs.md
+++ b/docs/how-to-use-gvfs.md
@@ -74,6 +74,7 @@ the path mapping and convert automatically.
 | `fs.gravitino.client.`                                | The configuration 
key prefix for the Gravitino client config.                                     
                                                                                
                                                                                
                                                                                
                     | (none)                                                   
      | No       [...]
 | `fs.gravitino.filesetMetadataCache.enable`            | Whether to cache the 
fileset, fileset schema or fileset catalog metadata in the Gravitino Virtual 
File System. Note that this cache causes a side effect: if you modify the 
fileset or fileset catalog metadata, the client cannot see the latest changes.  
                                                                                
                           | `false`                                            
            | No       [...]
 | `fs.gravitino.autoCreateLocation`                     | The configuration 
key for whether to enable auto-creation of fileset location when the 
server-side filesystem ops are disabled and the location does not exist.        
                                                                                
                                                                                
                                | `true`                                        
                 | No       [...]
+| `fs.gravitino.kerberos.access.filesets`               | Comma-separated 
fileset paths, such as `gvfs://fileset/catalog/schema/fileset`, to collect 
Hadoop delegation tokens for. Needed on Kerberized HDFS when a job reads 
filesets stored outside `fs.defaultFS`. See [Via Apache 
Spark](#via-apache-spark).                                                      
                                                           | (none)             
                                            | No       [...]
 | `fs.path.config.<name>`                               | Defines a logical 
location entry. Set `fs.path.config.<name>` to the real base URI (for example, 
`hdfs://cluster1/`). Any key that starts with the same prefix (such as 
`fs.path.config.<name>.config.resource`) is treated as a location-scoped 
property and will be forwarded to the underlying filesystem client. Note: 
location names must not contain (`.`, `_`). | (none)                            
                             | No       [...]
 
 To configure the Gravitino client, use properties prefixed with 
`fs.gravitino.client.`. These properties will be passed to the Gravitino client 
after removing the `fs.` prefix.
@@ -280,6 +281,27 @@ fs.getFileStatus(filesetPath);
     rdd.foreach(println)
     ```
 
+4. Collect delegation tokens for filesets on Kerberized HDFS (if necessary).
+
+   On YARN with Kerberized HDFS, executors authenticate to HDFS with 
delegation tokens that Spark
+   collects when the application starts. Spark gets a token for `fs.defaultFS` 
by itself. If a
+   fileset is stored on another HDFS cluster, list it so that GVFS collects a 
token for that
+   cluster too:
+
+    ```shell
+    --conf spark.kerberos.access.hadoopFileSystems=gvfs://fileset
+    --conf 
spark.hadoop.fs.gravitino.kerberos.access.filesets=gvfs://fileset/test_catalog/test_schema/test_fileset_1,gvfs://fileset/test_catalog/test_schema/test_fileset_2
+    ```
+
+   `gvfs://fileset` makes Spark ask GVFS for tokens, and GVFS then collects 
one for each fileset
+   listed in `fs.gravitino.kerberos.access.filesets`. Listing the filesets in
+   `spark.kerberos.access.hadoopFileSystems` instead doesn't work: Spark asks 
GVFS for tokens
+   without passing the path, so GVFS never sees which filesets were listed 
there.
+
+   GVFS only returns tokens owned by the current user. A fileset that 
authenticates with its own
+   Kerberos principal and keytab (`authentication.kerberos.*`) without 
impersonation gets no token,
+   since its executors log in with that keytab instead.
+
 #### Via TensorFlow
 
 For Tensorflow to support GVFS, you need to recompile the 
[tensorflow-io](https://github.com/tensorflow/io) module.

Reply via email to