LuciferYang commented on code in PR #14407:
URL: https://github.com/apache/gravitino/pull/14407#discussion_r4666953022


##########
catalogs/hadoop-common/src/main/java/org/apache/gravitino/catalog/hadoop/fs/HDFSFileSystemProxy.java:
##########
@@ -182,6 +341,107 @@ private synchronized void close() {
       }
       kerberosClient = null;
     }
+    if (keytabFile != null) {
+      try {
+        Files.deleteIfExists(keytabFile.toPath());
+        LIVE_KEYTAB_FILES.remove(keytabFile);
+        releaseKeytabSlot();
+      } catch (IOException | RuntimeException e) {
+        LOG.warn("Failed to delete the keytab file {}", keytabFile, e);
+        // Deleted at exit instead. The shutdown hook would hand it over too, 
but a catalog class
+        // loader removes that hook when it is closed. Only failed deletes get 
here.
+        deleteOnExit(keytabFile);
+        // Its name stays taken while the file may still be there.
+        keytabSlotPrefix = null;
+      }
+      keytabFile = null;
+    }
+  }
+
+  private synchronized void recordKeytabFile(File file) {
+    File previous = keytabFile;
+    keytabFile = file;
+    if (KEYTAB_CLEANER.get() == null) {
+      Thread cleaner =
+          new Thread(HDFSFileSystemProxy::deleteLiveKeytabFilesOnExit, 
"gravitino-keytab-cleaner");
+      // A catalog class loader removes, when it is closed, the hooks whose 
context class loader is
+      // its own.
+      
cleaner.setContextClassLoader(HDFSFileSystemProxy.class.getClassLoader());
+      if (KEYTAB_CLEANER.compareAndSet(null, cleaner)) {
+        try {
+          Runtime.getRuntime().addShutdownHook(cleaner);
+        } catch (IllegalStateException e) {
+          // The JVM is shutting down, so no hook will hand the files over.
+          deleteLiveKeytabFilesOnExit();
+        }
+      }
+    }
+    // The hook sets the flag and goes through the set under the same 
LIVE_KEYTAB_FILES lock, so
+    // either the hook sees the file or this method sees the flag.
+    synchronized (LIVE_KEYTAB_FILES) {
+      if (previous != null) {
+        LIVE_KEYTAB_FILES.remove(previous);
+      }
+      LIVE_KEYTAB_FILES.add(file);
+      if (keytabFilesHandedOver) {
+        deleteOnExit(file);
+      }
+    }
+  }
+
+  // Takes the lowest free name for the identifier and keytab URI. A name is 
only reused for the
+  // same keytab URI, as the JDK may return the keys it cached for the path 
when the file it reads
+  // there has the same modification time.
+  private synchronized File reserveKeytabFile(String identifier, String 
keytabUri) {
+    String prefix =
+        identifier
+            + "-"
+            + JVM_KEYTAB_TOKEN
+            + "-"
+            + 
UUID.nameUUIDFromBytes(keytabUri.getBytes(StandardCharsets.UTF_8));

Review Comment:
   Done. A proxy now fetches the keytab into a staging file with a unique name, 
then moves it to `keytabs/gravitino-<id>-<token>-<hash>-<n>`, where the hash is 
a keyed hash of the keytab URI and the fetched content. A name is reused only 
for the same URI and identical content, so a replaced keytab, valid or not, 
gets a new path. A `file://` keytab stays a symlink, so an open proxy's 
renewals still read it through the JDK's cache, as before; a downloaded keytab 
stays the copy its proxy fetched. `testLoginReadsTheKeysOfAReplacedKeytab` 
writes real keytabs and reads them through 
`javax.security.auth.kerberos.KeyTab` at login. It reads KVNO 1, then KVNO 2 at 
the same URI and mtime, then no keys from an invalid file. With names per URI 
it read 1, 1, 1.
   



##########
catalogs/catalog-fileset/src/main/java/org/apache/gravitino/catalog/fileset/FilesetCatalogOperations.java:
##########
@@ -1481,17 +1572,179 @@ FileSystem getFileSystemWithCache(Path path, 
Map<String, String> conf) {
     FileSystemProvider provider = fileSystemProvidersMap.get(scheme);
     String authority =
         provider != null ? provider.getFullAuthority(path, conf) : 
path.toUri().getAuthority();
+    // Only an HDFS file system logs in with the settings of the 
configuration, see
+    // createFileSystem.
+    String fsScheme = scheme != null ? scheme : 
defaultFileSystemProvider.scheme();
+    if (!SCHEME_HDFS.equals(fsScheme)) {
+      return fileSystemCache.get(
+          new FileSystemCacheKey(scheme, authority, Collections.emptyMap()),
+          cacheKey -> newFileSystem(path, conf, cacheKey, null));
+    }
+
+    Map<String, String> hdfsConf = Collections.unmodifiableMap(new 
HashMap<>(conf));
+    // Resolving the settings and creating the file system share one 
connection timeout.
+    long deadlineNanos =
+        System.nanoTime() + 
TimeUnit.SECONDS.toNanos(connectionTimeoutSeconds(hdfsConf));
+    FileSystem fs = getHdfsFileSystemWithCache(path, hdfsConf, scheme, 
authority, deadlineNanos);
+    if (fs == null) {
+      // The config.resources files changed after their login settings were 
cached.
+      sharedHdfsLoginSettingsCache.invalidate(withoutIdentifier(hdfsConf));
+      hdfsLoginSettingsCache.invalidate(hdfsConf);
+      fs = getHdfsFileSystemWithCache(path, hdfsConf, scheme, authority, 
deadlineNanos);
+    }
+    if (fs == null) {
+      throw new GravitinoRuntimeException(
+          "The login settings in config.resources changed while getting 
FileSystem for fileset:"
+              + " path: %s",
+          path);
+    }
+    return fs;
+  }
+
+  // Returns null if the config.resources files no longer resolve to the 
cached login settings: a
+  // file system is cached only under the settings of the configuration it is 
created with.
+  @Nullable
+  private FileSystem getHdfsFileSystemWithCache(
+      Path path,
+      Map<String, String> conf,
+      @Nullable String scheme,
+      @Nullable String authority,
+      long deadlineNanos) {
+    Map<String, String> settings = hdfsLoginSettings(path, conf, 
deadlineNanos);
+    // A null result caches nothing; the cache statistics count it as a failed 
load.
     return fileSystemCache.get(
-        new FileSystemCacheKey(scheme, authority),
-        cacheKey -> {
-          try {
-            // 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);
-          }
-        });
+        new FileSystemCacheKey(scheme, authority, settings),
+        cacheKey ->
+            newFileSystem(
+                path, conf, cacheKey, new 
ExpectedLogin(cacheKey.loginSettings, deadlineNanos)));
+  }
+
+  private Map<String, String> hdfsLoginSettings(
+      Path path, Map<String, String> conf, long deadlineNanos) {
+    // Settings resolved for the shared entry that expand variables, cached 
for this configuration
+    // after the shared cache's load returns.
+    AtomicReference<Map<String, String>> resolved = new AtomicReference<>();
+    Optional<Map<String, String>> shared =
+        sharedHdfsLoginSettingsCache.get(

Review Comment:
   Done. The three caches are now Caffeine `AsyncCache`s. On a miss, `get()` 
only submits the load to its pool, and each caller waits on the future until 
its own deadline. The load fails at the deadline of the caller that started it, 
which cancels the task and closes a later result. A caller that waited on 
another caller's load tries again itself if that load failed and it has time 
left, and an interrupted caller leaves the load to the others.
   
   In `testFileSystemCacheResolvesLoginSettingsBesideAHangingResolution`, a 
4-second lookup whose configuration shares a settings-cache bucket with a 
hanging resolution returns within its timeout. In 
`testFileSystemCacheWaitsForAFileSystemBeingCreatedUntilItsOwnDeadline`, a 
1-second lookup waiting on a file system being created fails after 1 second. On 
the previous commit, the first failed after 10 seconds and the second after 11.
   



##########
catalogs/hadoop-common/src/main/java/org/apache/gravitino/catalog/hadoop/fs/HDFSFileSystemProxy.java:
##########
@@ -55,8 +68,37 @@ public class HDFSFileSystemProxy implements 
MethodInterceptor {
 
   public static final String GRAVITINO_KEYTAB_FORMAT = "keytabs/gravitino-%s";
   private static final String GRAVITINO_ID_KEY = "gravitino.identifier";
+  // The Hadoop properties the login settings may come from.
+  private static final List<String> LOGIN_HADOOP_KEYS =
+      ImmutableList.of(
+          HADOOP_SECURITY_AUTHENTICATION,
+          Constants.HADOOP_SECURITY_PRINCIPAL,
+          Constants.HADOOP_SECURITY_KEYTAB,
+          Constants.HADOOP_KRB5_CONF);
+  // The source hadoopConfiguration sets the authentication type with when it 
replaces a value
+  // that refers to a variable.
+  private static final String EXPANDED_AUTHENTICATION_SOURCE =
+      "Gravitino, replacing a value with variables";
+
+  // Keytab files not deleted yet, because their proxy is still open or failed 
to delete them on
+  // close. A shutdown hook hands them to File.deleteOnExit, as calling it for 
every proxy would
+  // keep every name ever used until the JVM exits.
+  private static final Set<File> LIVE_KEYTAB_FILES = 
ConcurrentHashMap.newKeySet();
+  private static final AtomicReference<Thread> KEYTAB_CLEANER = new 
AtomicReference<>();
+  // The JDK caches every keytab path it reads until the JVM exits, so a name 
is reused once its
+  // file is deleted. The used slots of each identifier and keytab URI, 
guarded by the map.
+  private static final Map<String, BitSet> KEYTAB_SLOTS = new HashMap<>();
+  // Tells apart the keytab files of each loaded copy of this class: JVMs that 
share a working
+  // directory, and catalog class loaders, each of which keeps its own slots.
+  private static final String JVM_KEYTAB_TOKEN = 
UUID.randomUUID().toString().substring(0, 8);

Review Comment:
   Done. The token, the HMAC key and the slot table moved to 
`org.apache.gravitino.utils.KeytabNames` in the common module. Catalog class 
loaders delegate that package to the server's class loader, and catalog-fileset 
has common only as `compileOnly`, so the server loads the class once for all 
catalog loaders. Once the earlier proxy has closed, a fileset reopened after 
its loader is evicted gets the same keytab name for the same keytab URI and 
content. The staging file still gets a new name each time, but the JDK only 
reads the name it is moved to. GVFS has no catalog reloads and loads the class 
with the rest of the client runtime.
   
   `testKeytabFileNamesAreReusedAfterACatalogReload` holds a slot, as an open 
proxy of an earlier loader would, and checks that a proxy takes the next slot 
and then the freed one. `testCatalogLoadersShareKeytabNames` checks that a 
catalog loader gets the server's class.
   



##########
catalogs/catalog-fileset/src/main/java/org/apache/gravitino/catalog/fileset/FilesetCatalogOperations.java:
##########
@@ -198,6 +224,26 @@ public class FilesetCatalogOperations extends 
ManagedSchemaOperations
         }
       };
 
+  // A pool of its own, so that resolving login settings, which only reads 
files, does not wait
+  // behind file system creations and logins that may hang.
+  @VisibleForTesting
+  final ThreadPoolExecutor loginSettingsExecutor =
+      new ThreadPoolExecutor(
+          Math.max(2, Math.min(Runtime.getRuntime().availableProcessors(), 4)),
+          Math.max(2, Math.min(Runtime.getRuntime().availableProcessors(), 4)),
+          5L,
+          TimeUnit.SECONDS,
+          new ArrayBlockingQueue<>(100),

Review Comment:
   Done. The login-settings pool now queues up to 1000 tasks, like the file 
system pool, and a queued resolution leaves the queue once the lookup that 
started it times out. I kept the resolution on the pool: run by the caller, it 
would run inside `submit`, before the timeout is armed, so a hung 
`config.resources` read would keep the caller past its deadline. Concurrent 
lookups of one configuration share one resolution, and filesets differing only 
in identifier share one entry unless their settings expand Hadoop variables, so 
a burst queues about one task per distinct configuration.
   
   `testFileSystemCacheQueuesABurstOfLoginSettingsResolutions` holds every pool 
thread, checks that a timed-out resolution leaves the queue, then runs 120 cold 
lookups of different settings and checks that all succeed. With a queue of 100, 
20 of them were rejected.
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to