World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#12856] improvement(gvfs): Load the catalog and fileset once per GVFS operation (#14975)
龙骑士k0e56693285a3
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.javaindex a4894f6ada..a14583a5a2 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@@ -45,6 +45,7 @@ import java.io.IOException;import java.net.URI;import java.util.Collections;import java.util.HashMap;+import java.util.IdentityHashMap;import java.util.List;import java.util.Map;import java.util.Objects;@@ -164,6 +165,12 @@ public abstract class BaseGVFSOperations implements Closeable {private final boolean autoCreateLocation;+ // The operation scope this instance has open on the current thread, if any. Each instance keeps+ // its own, so an instance called inside another instance's operation still shares its loads. The+ // value is removed when the outermost scope closes, so no value outlives an operation.+ @SuppressWarnings("ThreadLocalUsage")+ private final ThreadLocal<OperationScope> currentScope = new ThreadLocal<>();+/** A key class for caching FileSystem instances based on scheme, authority, and configuration. */public static class FileSystemCacheKey {private final String scheme;@@ -599,6 +606,66 @@ public abstract class BaseGVFSOperations implements Closeable {return new Path(fileLocation);}+ /**+ * Shares the catalogs and filesets loaded from the server among the calls made until the scope is+ * closed. Only the outermost scope this instance opens on a thread takes effect, and closing it+ * removes the thread-local value.+ */+ final class OperationScope implements AutoCloseable {+ private final boolean outermost = currentScope.get() == null;+ private final Map<NameIdentifier, Catalog> catalogs = new HashMap<>();+ // Keyed by the catalog object a fileset was loaded from, so that a fileset loaded through an+ // overriding getFilesetCatalog is not reused for a load from another catalog.+ private final IdentityHashMap<FilesetCatalog, Map<NameIdentifier, Fileset>> filesets =+ new IdentityHashMap<>();++ private OperationScope() {+ if (outermost) {+ currentScope.set(this);+ }+ }++ @Override+ public void close() {+ if (outermost) {+ currentScope.remove();+ }+ }+ }++ /**+ * Opens a scope in which each catalog and fileset is loaded from the server at most once. Close+ * it when the operation completes.+ */+ OperationScope openOperationScope() {+ return new OperationScope();+ }++ private Catalog loadCatalog(NameIdentifier catalogIdent) {+ return getFilesetMetadataCache()+ .map(cache -> cache.getCatalog(catalogIdent))+ .orElseGet(+ () -> {+ OperationScope scope = currentScope.get();+ return scope == null+ ? getGravitinoClient().loadCatalog(catalogIdent.name())+ : scope.catalogs.computeIfAbsent(+ catalogIdent, ident -> getGravitinoClient().loadCatalog(ident.name()));+ });+ }++ private Fileset loadFileset(NameIdentifier filesetIdent, FilesetCatalog filesetCatalog) {+ NameIdentifier ident =+ NameIdentifier.of(filesetIdent.namespace().level(2), filesetIdent.name());+ OperationScope scope = currentScope.get();+ return scope == null+ ? filesetCatalog.loadFileset(ident)+ : scope+ .filesets+ .computeIfAbsent(filesetCatalog, key -> new HashMap<>())+ .computeIfAbsent(filesetIdent, key -> filesetCatalog.loadFileset(ident));+ }+private void createFilesetLocationIfNeed(NameIdentifier filesetIdent, FileSystem fs, Path filesetPath) {if (!autoCreateLocation) {@@ -699,7 +766,7 @@ public abstract class BaseGVFSOperations implements Closeable {protected FilesetCatalog getFilesetCatalog(NameIdentifier catalogIdent) {return getFilesetMetadataCache().map(cache -> cache.getFilesetCatalog(catalogIdent))- .orElseGet(() -> getGravitinoClient().loadCatalog(catalogIdent.name()).asFilesetCatalog());+ .orElseGet(() -> loadCatalog(catalogIdent).asFilesetCatalog());}/**@@ -714,11 +781,12 @@ public abstract class BaseGVFSOperations implements Closeable {.map(cache -> cache.getFileset(filesetIdent)).orElseGet(() ->- getFilesetCatalog(+ loadFileset(+ filesetIdent,+ getFilesetCatalog(NameIdentifier.of(- filesetIdent.namespace().level(0), filesetIdent.namespace().level(1)))- .loadFileset(- NameIdentifier.of(filesetIdent.namespace().level(2), filesetIdent.name())));+ filesetIdent.namespace().level(0),+ filesetIdent.namespace().level(1)))));}/**@@ -759,7 +827,7 @@ public abstract class BaseGVFSOperations implements Closeable {throws FileNotFoundException {NameIdentifier catalogIdent =NameIdentifier.of(filesetIdent.namespace().level(0), filesetIdent.namespace().level(1));- try {+ try (OperationScope ignored = openOperationScope()) {Fileset fileset = getFileset(filesetIdent);String targetLocationName =locationName == null@@ -1012,7 +1080,6 @@ public abstract class BaseGVFSOperations implements Closeable {@VisibleForTestingMap<String, String> getAllProperties(NameIdentifier filesetIdent) {- String catalogName = filesetIdent.namespace().level(1);String schemaName = filesetIdent.namespace().level(2);// Go through the metadata cache when it is enabled, so that an operation does not reload the// catalog, schema and fileset. Secrets are not cached and are still fetched on every call.@@ -1023,10 +1090,7 @@ public abstract class BaseGVFSOperations implements Closeable {filesetIdent.namespace().level(0),filesetIdent.namespace().level(1),filesetIdent.namespace().level(2));- Catalog catalog =- getFilesetMetadataCache()- .map(cache -> cache.getCatalog(catalogIdent))- .orElseGet(() -> getGravitinoClient().loadCatalog(catalogName));+ Catalog catalog = loadCatalog(catalogIdent);Schema schema =getFilesetMetadataCache().map(cache -> cache.getSchema(schemaIdent))@@ -1034,11 +1098,7 @@ public abstract class BaseGVFSOperations implements Closeable {Fileset fileset =getFilesetMetadataCache().map(cache -> cache.getFileset(filesetIdent))- .orElseGet(- () ->- catalog- .asFilesetCatalog()- .loadFileset(NameIdentifier.of(schemaName, filesetIdent.name())));+ .orElseGet(() -> loadFileset(filesetIdent, catalog.asFilesetCatalog()));Map<String, String> all = new HashMap<>();putPropsAndSecrets(all, catalog.properties(), catalog.supportsSecrets());diff --git a/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/DefaultGVFSOperations.java b/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/DefaultGVFSOperations.javaindex 5b26b1c2be..e40e485106 100644--- a/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/DefaultGVFSOperations.java+++ b/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/DefaultGVFSOperations.java@@ -61,18 +61,22 @@ public class DefaultGVFSOperations extends BaseGVFSOperations {@Overridepublic FSDataInputStream open(Path gvfsPath, int bufferSize) throws IOException {- FileSystem actualFs = getActualFileSystem(gvfsPath, currentLocationName());- Path actualFilePath =- getActualFilePath(gvfsPath, currentLocationName(), FilesetDataOperation.OPEN);- return actualFs.open(actualFilePath, bufferSize);+ try (OperationScope ignored = openOperationScope()) {+ FileSystem actualFs = getActualFileSystem(gvfsPath, currentLocationName());+ Path actualFilePath =+ getActualFilePath(gvfsPath, currentLocationName(), FilesetDataOperation.OPEN);+ return actualFs.open(actualFilePath, bufferSize);+ }}@Overridepublic synchronized void setWorkingDirectory(Path gvfsDir) throws FileNotFoundException {- FileSystem actualFs = getActualFileSystem(gvfsDir, currentLocationName());- Path actualFilePath =- getActualFilePath(gvfsDir, currentLocationName(), FilesetDataOperation.SET_WORKING_DIR);- actualFs.setWorkingDirectory(actualFilePath);+ try (OperationScope ignored = openOperationScope()) {+ FileSystem actualFs = getActualFileSystem(gvfsDir, currentLocationName());+ Path actualFilePath =+ getActualFilePath(gvfsDir, currentLocationName(), FilesetDataOperation.SET_WORKING_DIR);+ actualFs.setWorkingDirectory(actualFilePath);+ }}@Override@@ -85,146 +89,164 @@ public class DefaultGVFSOperations extends BaseGVFSOperations {long blockSize,Progressable progress)throws IOException {- try {- FileSystem actualFs = getActualFileSystem(gvfsPath, currentLocationName());- Path actualFilePath =- getActualFilePath(gvfsPath, currentLocationName(), FilesetDataOperation.CREATE);- return actualFs.create(- actualFilePath, permission, overwrite, bufferSize, replication, blockSize, progress);- } catch (FileNotFoundException e) {- String message =- "Fileset is not found for path: "- + gvfsPath- + " for operation CREATE. "- + "This may be caused by fileset related metadata not found or not in use in "- + "Gravitino, please check the fileset metadata in Gravitino.";- throw new IOException(message, e);+ try (OperationScope ignored = openOperationScope()) {+ try {+ FileSystem actualFs = getActualFileSystem(gvfsPath, currentLocationName());+ Path actualFilePath =+ getActualFilePath(gvfsPath, currentLocationName(), FilesetDataOperation.CREATE);+ return actualFs.create(+ actualFilePath, permission, overwrite, bufferSize, replication, blockSize, progress);+ } catch (FileNotFoundException e) {+ String message =+ "Fileset is not found for path: "+ + gvfsPath+ + " for operation CREATE. "+ + "This may be caused by fileset related metadata not found or not in use in "+ + "Gravitino, please check the fileset metadata in Gravitino.";+ throw new IOException(message, e);+ }}}@Overridepublic FSDataOutputStream append(Path gvfsPath, int bufferSize, Progressable progress)throws IOException {- FileSystem actualFs = getActualFileSystem(gvfsPath, currentLocationName());- Path actualFilePath =- getActualFilePath(gvfsPath, currentLocationName(), FilesetDataOperation.APPEND);- return actualFs.append(actualFilePath, bufferSize, progress);+ try (OperationScope ignored = openOperationScope()) {+ FileSystem actualFs = getActualFileSystem(gvfsPath, currentLocationName());+ Path actualFilePath =+ getActualFilePath(gvfsPath, currentLocationName(), FilesetDataOperation.APPEND);+ return actualFs.append(actualFilePath, bufferSize, progress);+ }}@Overridepublic boolean rename(Path srcGvfsPath, Path dstGvfsPath) throws IOException {- // Fileset identifier is not allowed to be renamed, only its subdirectories can be renamed- // which not in the storage location of the fileset;- NameIdentifier srcIdentifier = extractIdentifier(metalakeName(), srcGvfsPath.toString());- NameIdentifier dstIdentifier = extractIdentifier(metalakeName(), dstGvfsPath.toString());- Preconditions.checkArgument(- srcIdentifier.equals(dstIdentifier),- "Destination path fileset identifier: %s should be same with src path "- + "fileset identifier: %s.",- srcIdentifier,- dstIdentifier);-- Path srcActualPath =- getActualFilePath(srcGvfsPath, currentLocationName(), FilesetDataOperation.RENAME);- Path dstActualPath =- getActualFilePath(dstGvfsPath, currentLocationName(), FilesetDataOperation.RENAME);- FileSystem actualFs = getActualFileSystem(srcGvfsPath, currentLocationName());- return actualFs.rename(srcActualPath, dstActualPath);+ try (OperationScope ignored = openOperationScope()) {+ // Fileset identifier is not allowed to be renamed, only its subdirectories can be renamed+ // which not in the storage location of the fileset;+ NameIdentifier srcIdentifier = extractIdentifier(metalakeName(), srcGvfsPath.toString());+ NameIdentifier dstIdentifier = extractIdentifier(metalakeName(), dstGvfsPath.toString());+ Preconditions.checkArgument(+ srcIdentifier.equals(dstIdentifier),+ "Destination path fileset identifier: %s should be same with src path "+ + "fileset identifier: %s.",+ srcIdentifier,+ dstIdentifier);++ Path srcActualPath =+ getActualFilePath(srcGvfsPath, currentLocationName(), FilesetDataOperation.RENAME);+ Path dstActualPath =+ getActualFilePath(dstGvfsPath, currentLocationName(), FilesetDataOperation.RENAME);+ FileSystem actualFs = getActualFileSystem(srcGvfsPath, currentLocationName());+ return actualFs.rename(srcActualPath, dstActualPath);+ }}@Overridepublic boolean delete(Path gvfsPath, boolean recursive) throws IOException {- try {- FileSystem actualFs = getActualFileSystem(gvfsPath, currentLocationName());- Path actualFilePath =- getActualFilePath(gvfsPath, currentLocationName(), FilesetDataOperation.DELETE);- return actualFs.delete(actualFilePath, recursive);- } catch (FileNotFoundException e) {- return false;+ try (OperationScope ignored = openOperationScope()) {+ try {+ FileSystem actualFs = getActualFileSystem(gvfsPath, currentLocationName());+ Path actualFilePath =+ getActualFilePath(gvfsPath, currentLocationName(), FilesetDataOperation.DELETE);+ return actualFs.delete(actualFilePath, recursive);+ } catch (FileNotFoundException e) {+ return false;+ }}}@Overridepublic FileStatus getFileStatus(Path gvfsPath) throws IOException {- FileSystem actualFs = getActualFileSystem(gvfsPath, currentLocationName());- Path actualFilePath =- getActualFilePath(gvfsPath, currentLocationName(), FilesetDataOperation.GET_FILE_STATUS);- FileStatus fileStatus = actualFs.getFileStatus(actualFilePath);-- NameIdentifier identifier = extractIdentifier(metalakeName(), gvfsPath.toString());- String subPath = getSubPathFromGvfsPath(identifier, gvfsPath.toString());- String filesetLocation =- actualFilePath- .toString()- .substring(0, actualFilePath.toString().length() - subPath.length());-- return convertFileStatusPathPrefix(- fileStatus, filesetLocation, getVirtualLocation(identifier, true));+ try (OperationScope ignored = openOperationScope()) {+ FileSystem actualFs = getActualFileSystem(gvfsPath, currentLocationName());+ Path actualFilePath =+ getActualFilePath(gvfsPath, currentLocationName(), FilesetDataOperation.GET_FILE_STATUS);+ FileStatus fileStatus = actualFs.getFileStatus(actualFilePath);++ NameIdentifier identifier = extractIdentifier(metalakeName(), gvfsPath.toString());+ String subPath = getSubPathFromGvfsPath(identifier, gvfsPath.toString());+ String filesetLocation =+ actualFilePath+ .toString()+ .substring(0, actualFilePath.toString().length() - subPath.length());++ return convertFileStatusPathPrefix(+ fileStatus, filesetLocation, getVirtualLocation(identifier, true));+ }}@Overridepublic FileStatus[] listStatus(Path gvfsPath) throws IOException {- FileSystem actualFs = getActualFileSystem(gvfsPath, currentLocationName());- Path actualFilePath =- getActualFilePath(gvfsPath, currentLocationName(), FilesetDataOperation.LIST_STATUS);- FileStatus[] fileStatusResults = actualFs.listStatus(actualFilePath);-- NameIdentifier identifier = extractIdentifier(metalakeName(), gvfsPath.toString());- String subPath = getSubPathFromGvfsPath(identifier, gvfsPath.toString());- String filesetLocation =- actualFilePath- .toString()- .substring(0, actualFilePath.toString().length() - subPath.length());-- return Arrays.stream(fileStatusResults)- .map(- fileStatus ->- convertFileStatusPathPrefix(- fileStatus, filesetLocation, getVirtualLocation(identifier, true)))- .toArray(FileStatus[]::new);+ try (OperationScope ignored = openOperationScope()) {+ FileSystem actualFs = getActualFileSystem(gvfsPath, currentLocationName());+ Path actualFilePath =+ getActualFilePath(gvfsPath, currentLocationName(), FilesetDataOperation.LIST_STATUS);+ FileStatus[] fileStatusResults = actualFs.listStatus(actualFilePath);++ NameIdentifier identifier = extractIdentifier(metalakeName(), gvfsPath.toString());+ String subPath = getSubPathFromGvfsPath(identifier, gvfsPath.toString());+ String filesetLocation =+ actualFilePath+ .toString()+ .substring(0, actualFilePath.toString().length() - subPath.length());++ return Arrays.stream(fileStatusResults)+ .map(+ fileStatus ->+ convertFileStatusPathPrefix(+ fileStatus, filesetLocation, getVirtualLocation(identifier, true)))+ .toArray(FileStatus[]::new);+ }}@Overridepublic boolean mkdirs(Path gvfsPath, FsPermission permission) throws IOException {- try {- FileSystem actualFs = getActualFileSystem(gvfsPath, currentLocationName());- Path actualFilePath =- getActualFilePath(gvfsPath, currentLocationName(), FilesetDataOperation.MKDIRS);- return actualFs.mkdirs(actualFilePath, permission);- } catch (FileNotFoundException e) {- String message =- "Fileset is not found for path: "- + gvfsPath- + " for operation MKDIRS. "- + "This may be caused by fileset related metadata not found or not in use in "- + "Gravitino, please check the fileset metadata in Gravitino.";- throw new IOException(message, e);+ try (OperationScope ignored = openOperationScope()) {+ try {+ FileSystem actualFs = getActualFileSystem(gvfsPath, currentLocationName());+ Path actualFilePath =+ getActualFilePath(gvfsPath, currentLocationName(), FilesetDataOperation.MKDIRS);+ return actualFs.mkdirs(actualFilePath, permission);+ } catch (FileNotFoundException e) {+ String message =+ "Fileset is not found for path: "+ + gvfsPath+ + " for operation MKDIRS. "+ + "This may be caused by fileset related metadata not found or not in use in "+ + "Gravitino, please check the fileset metadata in Gravitino.";+ throw new IOException(message, e);+ }}}@Overridepublic short getDefaultReplication(Path gvfsPath) {- try {- FileSystem actualFs = getActualFileSystem(gvfsPath, currentLocationName());- Path actualFilePath =- getActualFilePath(- gvfsPath, currentLocationName(), FilesetDataOperation.GET_DEFAULT_REPLICATION);- return actualFs.getDefaultReplication(actualFilePath);- } catch (FileNotFoundException e) {- return 1;+ try (OperationScope ignored = openOperationScope()) {+ try {+ FileSystem actualFs = getActualFileSystem(gvfsPath, currentLocationName());+ Path actualFilePath =+ getActualFilePath(+ gvfsPath, currentLocationName(), FilesetDataOperation.GET_DEFAULT_REPLICATION);+ return actualFs.getDefaultReplication(actualFilePath);+ } catch (FileNotFoundException e) {+ return 1;+ }}}@Overridepublic long getDefaultBlockSize(Path gvfsPath) {- try {- FileSystem actualFs = getActualFileSystem(gvfsPath, currentLocationName());- Path actualFilePath =- getActualFilePath(- gvfsPath, currentLocationName(), FilesetDataOperation.GET_DEFAULT_BLOCK_SIZE);- return actualFs.getDefaultBlockSize(actualFilePath);- } catch (FileNotFoundException e) {- return defaultBlockSize();+ try (OperationScope ignored = openOperationScope()) {+ try {+ FileSystem actualFs = getActualFileSystem(gvfsPath, currentLocationName());+ Path actualFilePath =+ getActualFilePath(+ gvfsPath, currentLocationName(), FilesetDataOperation.GET_DEFAULT_BLOCK_SIZE);+ return actualFs.getDefaultBlockSize(actualFilePath);+ } catch (FileNotFoundException e) {+ return defaultBlockSize();+ }}}diff --git a/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestBaseGVFSOperationsSecrets.java b/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestBaseGVFSOperationsSecrets.javaindex 715d7b133b..db10e219d2 100644--- a/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestBaseGVFSOperationsSecrets.java+++ b/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestBaseGVFSOperationsSecrets.java@@ -24,6 +24,7 @@ import static org.junit.jupiter.api.Assertions.assertSame;import static org.junit.jupiter.api.Assertions.assertThrows;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.anyMap;+import static org.mockito.Mockito.clearInvocations;import static org.mockito.Mockito.doReturn;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.spy;@@ -32,6 +33,9 @@ import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;import java.io.IOException;+import java.io.UncheckedIOException;+import java.util.ArrayList;+import java.util.List;import java.util.Map;import org.apache.gravitino.Catalog;import org.apache.gravitino.NameIdentifier;@@ -62,6 +66,8 @@ import org.apache.hadoop.util.Progressable;import org.junit.jupiter.api.Test;public class TestBaseGVFSOperationsSecrets {+ private static final NameIdentifier PROBE_IDENT =+ NameIdentifier.of("ml", "catalog", "schema", "fs");@Testpublic void testMergeSecrets() throws Exception {@@ -300,6 +306,36 @@ public class TestBaseGVFSOperationsSecrets {assertSame(denied, failure.getCause());}+ @Test+ void testCredentialVendingReusesLoadedFileset() throws Exception {+ Catalog catalog =+ mockCatalogWithCredentials(Map.of("s3-endpoint", "http://s3.example.com"), null);+ FilesetCatalog filesetCatalog = catalog.asFilesetCatalog();+ Fileset fileset = filesetCatalog.loadFileset(NameIdentifier.of("schema", "fs"));+ when(fileset.storageLocations()).thenReturn(Map.of("default", "s3a://bucket/data"));+ SupportsCredentials filesetCredentials = mock(SupportsCredentials.class);+ when(fileset.supportsCredentials()).thenReturn(filesetCredentials);+ when(filesetCredentials.getCredentials())+ .thenReturn(+ new Credential[] {+ new S3TokenCredential("SCOPED", "scoped-secret", "token", Long.MAX_VALUE)+ });+ TestOps ops = spy(opsFor(catalog));+ NameIdentifier ident = NameIdentifier.of("ml", "catalog", "schema", "fs");+ doReturn(true).when(ops).enableCredentialVending();+ doReturn(mock(FileSystem.class)).when(ops).getActualFileSystemByPath(any(Path.class), anyMap());+ clearInvocations(filesetCatalog);++ ops.getActualFileSystemByLocationName(ident, "default");++ // Expected values: the resolution and credential vending call getFileset as before, while the+ // catalog and the fileset are each loaded once during the resolution.+ verify(ops, times(2)).getFileset(ident);+ verify(ops.getGravitinoClient(), times(1)).loadCatalog("catalog");+ verify(filesetCatalog, times(1)).loadFileset(NameIdentifier.of("schema", "fs"));+ verify(filesetCredentials, times(1)).getCredentials();+ }+@Testpublic void testRestFailureDoesNotCacheEmptyStaticCredentials() throws Exception {SupportsCredentials credentials = mock(SupportsCredentials.class);@@ -344,7 +380,59 @@ public class TestBaseGVFSOperationsSecrets {return opsFor(catalog).getAllProperties(NameIdentifier.of("ml", "catalog", "schema", "fs"));}+ @Test+ void testOverriddenFilesetCatalogDoesNotChangePropertiesSource() throws Exception {+ ScopeProbeOps ops = new ScopeProbeOps(probeCatalog("server"));+ ops.hookCatalog = probeCatalog("hook").asFilesetCatalog();++ ops.getActualFileSystemByLocationName(PROBE_IDENT, "default");++ // Expected value: as before the operation scope, getAllProperties reads the fileset from the+ // catalog loaded through the client, not the one loaded through the overriding hook.+ assertEquals("server", ops.props.get(0).get("probe"));+ }++ @Test+ void testNestedOperationsInstancesDoNotShareScope() throws Exception {+ ScopeProbeOps outer = new ScopeProbeOps(probeCatalog("outer"));+ Catalog innerCatalog = probeCatalog("inner");+ FilesetCatalog innerFilesetCatalog = innerCatalog.asFilesetCatalog();+ ScopeProbeOps inner = new ScopeProbeOps(innerCatalog);+ outer.inner = inner;+ clearInvocations(innerFilesetCatalog);++ outer.getActualFileSystemByLocationName(PROBE_IDENT, "default");++ // Expected values: each instance resolves its own fileset within its own scope, so each loads+ // its catalog and its fileset once.+ assertEquals("outer", outer.props.get(0).get("probe"));+ assertEquals("inner", inner.props.get(0).get("probe"));+ verify(outer.client, times(1)).loadCatalog("catalog");+ verify(inner.client, times(1)).loadCatalog("catalog");+ verify(innerFilesetCatalog, times(1)).loadFileset(NameIdentifier.of("schema", "fs"));++ // A later resolution on the same thread opens a new scope and loads the catalog again.+ outer.inner = null;+ outer.getActualFileSystemByLocationName(PROBE_IDENT, "default");+ verify(outer.client, times(2)).loadCatalog("catalog");+ }++ /** Mocks a catalog whose fileset carries the given marker in its properties. */+ private static Catalog probeCatalog(String marker) {+ Catalog catalog = mockCatalogWithCredentials(Map.of(), null);+ Fileset fileset = catalog.asFilesetCatalog().loadFileset(NameIdentifier.of("schema", "fs"));+ when(fileset.properties()).thenReturn(Map.of("probe", marker));+ when(fileset.storageLocations()).thenReturn(Map.of("default", "s3a://bucket/data"));+ return catalog;+ }+private static TestOps opsFor(Catalog catalog) {+ GravitinoClient client = mock(GravitinoClient.class);+ when(client.loadCatalog("catalog")).thenReturn(catalog);+ return new TestOps(opsConf(), client);+ }++ private static Configuration opsConf() {Configuration conf = new Configuration();conf.setBoolean(GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_AUTO_CREATE_LOCATION, false);@@ -352,9 +440,7 @@ public class TestBaseGVFSOperationsSecrets {conf.set(GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_SERVER_URI_KEY,"http://localhost:8090");- GravitinoClient client = mock(GravitinoClient.class);- when(client.loadCatalog("catalog")).thenReturn(catalog);- return new TestOps(conf, client);+ return conf;}/** Mocks catalog/schema/fileset chain with the given catalog props and credentials. */@@ -520,4 +606,46 @@ public class TestBaseGVFSOperationsSecrets {@Overridepublic void close() {}}++ /** Records the properties of each resolution and can override the scope-related hooks. */+ private static class ScopeProbeOps extends DefaultGVFSOperations {+ private final GravitinoClient client = mock(GravitinoClient.class);+ private final List<Map<String, String>> props = new ArrayList<>();+ private FilesetCatalog hookCatalog;+ private ScopeProbeOps inner;++ private ScopeProbeOps(Catalog catalog) {+ super(opsConf());+ when(client.loadCatalog("catalog")).thenReturn(catalog);+ }++ @Override+ GravitinoClient getGravitinoClient() {+ return client;+ }++ @Override+ protected FilesetCatalog getFilesetCatalog(NameIdentifier catalogIdent) {+ return hookCatalog != null ? hookCatalog : super.getFilesetCatalog(catalogIdent);+ }++ @Override+ protected Fileset getFileset(NameIdentifier filesetIdent) {+ if (inner != null) {+ // A hook that resolves through another operations instance on the same thread.+ try {+ inner.getActualFileSystemByLocationName(filesetIdent, "default");+ } catch (IOException e) {+ throw new UncheckedIOException(e);+ }+ }+ return super.getFileset(filesetIdent);+ }++ @Override+ protected FileSystem getActualFileSystemByPath(Path path, Map<String, String> allProperties) {+ props.add(allProperties);+ return mock(FileSystem.class);+ }+ }}diff --git a/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestGvfsBase.java b/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestGvfsBase.javaindex fb69fafae3..0202d07372 100644--- a/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestGvfsBase.java+++ b/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestGvfsBase.java@@ -50,6 +50,7 @@ import com.github.benmanes.caffeine.cache.Cache;import com.google.common.collect.ImmutableMap;import java.io.FileNotFoundException;import java.io.IOException;+import java.io.UncheckedIOException;import java.lang.reflect.Field;import java.net.SocketTimeoutException;import java.net.URISyntaxException;@@ -57,13 +58,18 @@ import java.nio.charset.StandardCharsets;import java.time.Instant;import java.util.ArrayList;import java.util.Arrays;+import java.util.Collections;import java.util.Comparator;import java.util.HashMap;import java.util.List;import java.util.Map;+import java.util.Optional;import java.util.concurrent.TimeUnit;+import org.apache.gravitino.Catalog;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Version;+import org.apache.gravitino.audit.CallerContext;+import org.apache.gravitino.audit.FilesetDataOperation;import org.apache.gravitino.dto.AuditDTO;import org.apache.gravitino.dto.CatalogDTO;import org.apache.gravitino.dto.SchemaDTO;@@ -81,11 +87,15 @@ import org.apache.gravitino.exceptions.NoSuchFilesetException;import org.apache.gravitino.exceptions.NoSuchLocationNameException;import org.apache.gravitino.exceptions.RESTException;import org.apache.gravitino.file.Fileset;+import org.apache.gravitino.file.FilesetCatalog;import org.apache.gravitino.rest.RESTUtils;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.hc.core5.http.Method;import org.awaitility.Awaitility;import org.junit.jupiter.api.AfterAll;@@ -98,6 +108,7 @@ import org.junit.jupiter.api.Test;import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.CsvSource;import org.junit.jupiter.params.provider.ValueSource;+import org.mockito.AdditionalAnswers;import org.mockito.Mockito;import org.mockserver.matchers.Times;import org.mockserver.model.HttpRequest;@@ -1713,6 +1724,337 @@ public class TestGvfsBase extends GravitinoMockServerBase {}}+ @ParameterizedTest+ @CsvSource({+ "open, , false",+ "create, , false",+ "append, , false",+ "delete, , false",+ "mkdirs, , false",+ "getFileStatus, , false",+ "listStatus, , false",+ "getDefaultBlockSize, , false",+ "getDefaultReplication, , false",+ "setWorkingDirectory, , false",+ "rename, , false",+ "open, location2, false",+ "create, location2, false",+ "append, location2, false",+ "delete, location2, false",+ "mkdirs, location2, false",+ "getFileStatus, location2, false",+ "listStatus, location2, false",+ "getDefaultBlockSize, location2, false",+ "getDefaultReplication, location2, false",+ "setWorkingDirectory, location2, false",+ "rename, location2, false",+ "open, , true",+ "create, , true",+ "append, , true",+ "delete, , true",+ "mkdirs, , true",+ "getFileStatus, , true",+ "listStatus, , true",+ "getDefaultBlockSize, , true",+ "getDefaultReplication, , true",+ "setWorkingDirectory, , true",+ "rename, , true"+ })+ public void testMetadataRestCallsPerOperation(+ String operation, String locationName, boolean metadataCache) throws IOException {+ Assumptions.assumeTrue(getClass() == TestGvfsBase.class);+ String filesetName =+ "testMetadataRestCalls_"+ + operation+ + (locationName == null ? "" : "_" + locationName)+ + (metadataCache ? "_cached" : "");+ Path managedFilesetPath =+ FileSystemTestUtils.createFilesetPath(catalogName, schemaName, filesetName, true);+ Path localPath = FileSystemTestUtils.createLocalDirPrefix(catalogName, schemaName, filesetName);+ String catalogPath = String.format("/api/metalakes/%s/catalogs/%s", metalakeName, catalogName);+ String filesetPath =+ String.format(+ "%s/schemas/%s/filesets/%s",+ catalogPath, schemaName, RESTUtils.encodeString(filesetName));+ String locationPath = filesetPath + "/location";++ // Pin the metadata cache setting so the expected counts do not depend on a default defined+ // elsewhere.+ Configuration opsConf = isolatedConf(conf);+ opsConf.setBoolean(+ GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_FILESET_METADATA_CACHE_ENABLE,+ metadataCache);+ Map<String, String> storageLocations;+ if (locationName == null) {+ storageLocations = ImmutableMap.of("location1", localPath.toString());+ } else {+ // The default location uses a scheme no provider serves, so resolving the file system+ // against the default location instead of the current one fails the operation.+ opsConf.set(+ GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_CURRENT_LOCATION_NAME, locationName);+ storageLocations =+ ImmutableMap.of(+ "location1",+ "unknown-scheme://bucket/" + filesetName,+ locationName,+ localPath.toString());+ }++ try (FileSystem gravitinoFileSystem = managedFilesetPath.getFileSystem(opsConf);+ FileSystem localFileSystem = localPath.getFileSystem(conf)) {+ FileSystemTestUtils.mkdirs(new Path(localPath + "/dir"), localFileSystem);+ localFileSystem.create(new Path(localPath + "/test.txt"), true).close();+ localFileSystem.delete(new Path(localPath + "/renamed.txt"), false);+ mockFilesetDTO(+ metalakeName,+ catalogName,+ schemaName,+ filesetName,+ Fileset.Type.MANAGED,+ storageLocations,+ ImmutableMap.of(PROPERTY_DEFAULT_LOCATION_NAME, "location1"));+ for (String subPath : new String[] {"/test.txt", "/renamed.txt", "/dir"}) {+ // With a current location name, the location lookup only matches when the client sends it.+ Map<String, String> queryParams =+ locationName == null+ ? ImmutableMap.of("sub_path", subPath)+ : ImmutableMap.of("sub_path", subPath, "location_name", locationName);+ buildMockResource(+ Method.GET,+ locationPath,+ queryParams,+ null,+ new FileLocationResponse(localPath + subPath),+ SC_OK);+ }+ buildMockResourceForCredential(filesetName, localPath.toString());++ Path filePath = new Path(managedFilesetPath + "/test.txt");+ Path renamedPath = new Path(managedFilesetPath + "/renamed.txt");+ Path dirPath = new Path(managedFilesetPath + "/dir");+ if (metadataCache) {+ // Warm the metadata cache with another operation on the same fileset.+ assertTrue(gravitinoFileSystem.getFileStatus(filePath).isFile());+ }+ int catalogLoads = recordedGetRequests(catalogPath);+ int filesetLoads = recordedGetRequests(filesetPath);+ int locationLookups = recordedGetRequests(locationPath);+ int srcLocationLookups = recordedGetRequests(locationPath, "/test.txt");+ int dstLocationLookups = recordedGetRequests(locationPath, "/renamed.txt");++ switch (operation) {+ case "open":+ gravitinoFileSystem.open(filePath, 4096).close();+ break;+ case "create":+ gravitinoFileSystem+ .create(filePath, FsPermission.getFileDefault(), true, 4096, (short) 1, 1024L, null)+ .close();+ break;+ case "append":+ // The local file system does not support append, but the metadata is resolved first.+ assertThrows(+ UnsupportedOperationException.class,+ () -> gravitinoFileSystem.append(filePath, 4096, null));+ break;+ case "delete":+ assertTrue(gravitinoFileSystem.delete(filePath, false));+ break;+ case "mkdirs":+ assertTrue(gravitinoFileSystem.mkdirs(dirPath, FsPermission.getDirDefault()));+ break;+ case "getFileStatus":+ assertTrue(gravitinoFileSystem.getFileStatus(filePath).isFile());+ break;+ case "listStatus":+ assertEquals(0, gravitinoFileSystem.listStatus(dirPath).length);+ break;+ case "getDefaultBlockSize":+ gravitinoFileSystem.getDefaultBlockSize(filePath);+ break;+ case "getDefaultReplication":+ gravitinoFileSystem.getDefaultReplication(filePath);+ break;+ case "setWorkingDirectory":+ gravitinoFileSystem.setWorkingDirectory(dirPath);+ break;+ case "rename":+ assertTrue(gravitinoFileSystem.rename(filePath, renamedPath));+ break;+ default:+ throw new IllegalArgumentException("Unknown operation: " + operation);+ }++ catalogLoads = recordedGetRequests(catalogPath) - catalogLoads;+ filesetLoads = recordedGetRequests(filesetPath) - filesetLoads;+ locationLookups = recordedGetRequests(locationPath) - locationLookups;+ // Expected values come from the call tree in issue #12856: one operation needs the catalog,+ // the fileset and the file location once each, and a rename looks up the location of both+ // its source and its destination. With the metadata cache enabled, the warm-up operation has+ // already cached the catalog and the fileset, while file locations are never cached.+ int expectedLoads = metadataCache ? 0 : 1;+ assertEquals(expectedLoads, catalogLoads, operation + " catalog loads");+ assertEquals(expectedLoads, filesetLoads, operation + " fileset loads");+ assertEquals(+ "rename".equals(operation) ? 2 : 1,+ locationLookups,+ operation + " must look up each file location exactly once");+ if ("rename".equals(operation)) {+ // The local file system also renames a path to itself, so only the per-path counts catch a+ // destination resolved from the source path.+ assertEquals(+ 1,+ recordedGetRequests(locationPath, "/test.txt") - srcLocationLookups,+ "rename source location lookups");+ assertEquals(+ 1,+ recordedGetRequests(locationPath, "/renamed.txt") - dstLocationLookups,+ "rename destination location lookups");+ }+ localFileSystem.delete(localPath, true);+ }+ }++ @ParameterizedTest+ @CsvSource({+ "LocationNameHookOperations, fsByName fsByName",+ "PathHookOperations, fs fs",+ "FilePathHookOperations, path:test.txt path:test.txt path:renamed.txt",+ "AllHooksOperations, fs fsByName fileset catalog catalog path:test.txt catalog"+ + " path:test.txt catalog path:renamed.txt catalog fs fsByName fileset catalog catalog"+ })+ public void testCustomOperationsResolutionHooks(String operationsClass, String expectedHookCalls)+ throws IOException {+ Assumptions.assumeTrue(getClass() == TestGvfsBase.class);+ String filesetName = "testCustomOperationsResolutionHooks_" + operationsClass;+ Path managedFilesetPath =+ FileSystemTestUtils.createFilesetPath(catalogName, schemaName, filesetName, true);+ Path localPath = FileSystemTestUtils.createLocalDirPrefix(catalogName, schemaName, filesetName);+ String catalogPath = String.format("/api/metalakes/%s/catalogs/%s", metalakeName, catalogName);+ String locationPath =+ String.format(+ "%s/schemas/%s/filesets/%s/location",+ catalogPath, schemaName, RESTUtils.encodeString(filesetName));+ Configuration opsConf = isolatedConf(conf);+ opsConf.set(+ GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_OPERATIONS_CLASS,+ TestGvfsBase.class.getName() + "$" + operationsClass);+ // Both settings change the expected hook calls and catalog loads, so they are pinned here.+ opsConf.setBoolean(+ GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_FILESET_METADATA_CACHE_ENABLE, false);+ opsConf.setBoolean(+ GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_AUTO_CREATE_LOCATION, true);+ opsConf.set(LocalHooks.LOCAL_DIR_KEY, localPath.toString());+ LocalHooks.CALLS.clear();++ try (FileSystem gravitinoFileSystem = managedFilesetPath.getFileSystem(opsConf);+ FileSystem localFileSystem = localPath.getFileSystem(conf)) {+ try (FSDataOutputStream out =+ localFileSystem.create(new Path(localPath + "/test.txt"), true)) {+ out.writeUTF("hooked");+ }+ // The server resolves the same local paths as the hooks, for the hooks a class leaves as is.+ mockFilesetDTO(+ metalakeName,+ catalogName,+ schemaName,+ filesetName,+ Fileset.Type.MANAGED,+ ImmutableMap.of("location1", localPath.toString()),+ ImmutableMap.of(PROPERTY_DEFAULT_LOCATION_NAME, "location1"));+ for (String subPath : new String[] {"/test.txt", "/renamed.txt"}) {+ buildMockResource(+ Method.GET,+ locationPath,+ ImmutableMap.of("sub_path", subPath),+ null,+ new FileLocationResponse(localPath + subPath),+ SC_OK);+ }+ buildMockResourceForCredential(filesetName, localPath.toString());+ Path filePath = new Path(managedFilesetPath + "/test.txt");+ Path renamedPath = new Path(managedFilesetPath + "/renamed.txt");+ int catalogLoads = recordedGetRequests(catalogPath);++ try (FSDataInputStream in = gravitinoFileSystem.open(filePath, 4096)) {+ assertEquals("hooked", in.readUTF());+ }+ assertTrue(gravitinoFileSystem.rename(filePath, renamedPath));+ assertTrue(localFileSystem.exists(new Path(localPath + "/renamed.txt")));++ // Expected values come from the operations before issue #12856, which call the protected+ // hooks in this order for an open followed by a rename. Each operation still loads the+ // catalog from the server once, for the hooks a class does not override.+ assertEquals(expectedHookCalls, String.join(" ", LocalHooks.CALLS), "hook calls");+ assertEquals(2, recordedGetRequests(catalogPath) - catalogLoads, "catalog loads");+ localFileSystem.delete(localPath, true);+ }+ }++ @Test+ public void testMetadataCacheFilesetCatalogOverride() throws IOException {+ Assumptions.assumeTrue(getClass() == TestGvfsBase.class);+ String filesetName = "testMetadataCacheFilesetCatalogOverride";+ Path managedFilesetPath =+ FileSystemTestUtils.createFilesetPath(catalogName, schemaName, filesetName, true);+ Path localPath = FileSystemTestUtils.createLocalDirPrefix(catalogName, schemaName, filesetName);+ String locationPath =+ String.format(+ "/api/metalakes/%s/catalogs/%s/schemas/%s/filesets/%s/location",+ metalakeName, catalogName, schemaName, RESTUtils.encodeString(filesetName));+ Configuration opsConf = isolatedConf(conf);+ opsConf.set(+ GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_OPERATIONS_CLASS,+ CacheOverrideOperations.class.getName());+ opsConf.set(LocalHooks.LOCAL_DIR_KEY, localPath.toString());++ try (FileSystem gravitinoFileSystem = managedFilesetPath.getFileSystem(opsConf);+ FileSystem localFileSystem = localPath.getFileSystem(conf)) {+ for (String name : new String[] {"test.txt", "override.txt"}) {+ try (FSDataOutputStream out = localFileSystem.create(new Path(localPath, name), true)) {+ out.writeUTF(name);+ }+ }+ mockFilesetDTO(+ metalakeName,+ catalogName,+ schemaName,+ filesetName,+ Fileset.Type.MANAGED,+ ImmutableMap.of("location1", localPath.toString()),+ ImmutableMap.of(PROPERTY_DEFAULT_LOCATION_NAME, "location1"));+ buildMockResource(+ Method.GET,+ locationPath,+ ImmutableMap.of("sub_path", "/test.txt"),+ null,+ new FileLocationResponse(localPath + "/test.txt"),+ SC_OK);+ buildMockResourceForCredential(filesetName, localPath.toString());++ // Expected value: as before the operation scope, the file location comes from the fileset+ // catalog returned by the metadata cache, which the cache subclass redirects.+ try (FSDataInputStream in =+ gravitinoFileSystem.open(new Path(managedFilesetPath + "/test.txt"), 4096)) {+ assertEquals("override.txt", in.readUTF());+ }+ localFileSystem.delete(localPath, true);+ }+ }++ // Copies the configuration into one that loads no default resources, leaves the current location+ // name unset and points its env variable at a name that is never set. This way neither a+ // core-site.xml on the test classpath nor CURRENT_LOCATION_NAME in the environment picks one.+ private static Configuration isolatedConf(Configuration configuration) {+ Configuration copy = new Configuration(false);+ configuration.forEach(entry -> copy.set(entry.getKey(), entry.getValue()));+ copy.unset(GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_CURRENT_LOCATION_NAME);+ copy.set(+ GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_CURRENT_LOCATION_NAME_ENV_VAR,+ "GVFS_TEST_UNSET_LOCATION_NAME");+ return copy;+ }+private void buildMockResourceForCredential(String filesetName, String filesetLocation)throws JsonProcessingException {String schemaPath =@@ -1755,4 +2097,181 @@ public class TestGvfsBase extends GravitinoMockServerBase {private MockGVFSHook getHook(FileSystem gvfs) {return (MockGVFSHook) ((GravitinoVirtualFileSystem) gvfs).getHook();}++ private static int recordedGetRequests(String path) {+ return mockServer()+ .retrieveRecordedRequests(HttpRequest.request(path).withMethod(Method.GET.name()))+ .length;+ }++ private static int recordedGetRequests(String path, String subPath) {+ return mockServer()+ .retrieveRecordedRequests(+ HttpRequest.request(path)+ .withMethod(Method.GET.name())+ .withQueryStringParameter("sub_path", subPath))+ .length;+ }++ /** Records the protected hook calls and resolves paths to a local directory. */+ private static final class LocalHooks {+ static final String LOCAL_DIR_KEY = "test.gvfs.local-hooks.dir";+ static final List<String> CALLS = Collections.synchronizedList(new ArrayList<>());++ static FileSystem fileSystem(Configuration configuration) {+ try {+ return FileSystem.getLocal(configuration);+ } catch (IOException e) {+ throw new UncheckedIOException(e);+ }+ }++ static Path filePath(Configuration configuration, Path gvfsPath) {+ return new Path(configuration.get(LOCAL_DIR_KEY) + "/" + gvfsPath.getName());+ }+ }++ /** Overrides the file system hook that takes a fileset identifier. */+ public static class LocationNameHookOperations extends DefaultGVFSOperations {+ private final Configuration configuration;++ public LocationNameHookOperations(Configuration configuration) {+ super(configuration);+ this.configuration = configuration;+ }++ @Override+ protected FileSystem getActualFileSystemByLocationName(+ NameIdentifier filesetIdent, String locationName) {+ LocalHooks.CALLS.add("fsByName");+ return LocalHooks.fileSystem(configuration);+ }+ }++ /** Overrides the file system hook that takes a virtual path. */+ public static class PathHookOperations extends DefaultGVFSOperations {+ private final Configuration configuration;++ public PathHookOperations(Configuration configuration) {+ super(configuration);+ this.configuration = configuration;+ }++ @Override+ protected FileSystem getActualFileSystem(Path filesetPath, String locationName) {+ LocalHooks.CALLS.add("fs");+ return LocalHooks.fileSystem(configuration);+ }+ }++ /** Overrides the file path hook. */+ public static class FilePathHookOperations extends DefaultGVFSOperations {+ private final Configuration configuration;++ public FilePathHookOperations(Configuration configuration) {+ super(configuration);+ this.configuration = configuration;+ }++ @Override+ protected Path getActualFilePath(+ Path gvfsPath, String locationName, FilesetDataOperation operation) {+ LocalHooks.CALLS.add("path:" + gvfsPath.getName());+ return LocalHooks.filePath(configuration, gvfsPath);+ }+ }++ /** Overrides all five hooks, each delegating to the default implementation. */+ public static class AllHooksOperations extends DefaultGVFSOperations {+ public AllHooksOperations(Configuration configuration) {+ super(configuration);+ }++ @Override+ protected FileSystem getActualFileSystem(Path filesetPath, String locationName)+ throws FileNotFoundException {+ LocalHooks.CALLS.add("fs");+ return super.getActualFileSystem(filesetPath, locationName);+ }++ @Override+ protected FileSystem getActualFileSystemByLocationName(+ NameIdentifier filesetIdent, String locationName) throws FileNotFoundException {+ LocalHooks.CALLS.add("fsByName");+ return super.getActualFileSystemByLocationName(filesetIdent, locationName);+ }++ @Override+ protected Path getActualFilePath(+ Path gvfsPath, String locationName, FilesetDataOperation operation)+ throws FileNotFoundException {+ LocalHooks.CALLS.add("path:" + gvfsPath.getName());+ return super.getActualFilePath(gvfsPath, locationName, operation);+ }++ @Override+ protected Fileset getFileset(NameIdentifier filesetIdent) {+ LocalHooks.CALLS.add("fileset");+ return super.getFileset(filesetIdent);+ }++ @Override+ protected FilesetCatalog getFilesetCatalog(NameIdentifier catalogIdent) {+ LocalHooks.CALLS.add("catalog");+ return super.getFilesetCatalog(catalogIdent);+ }+ }++ /** Supplies a metadata cache whose fileset catalog resolves every file to override.txt. */+ public static class CacheOverrideOperations extends DefaultGVFSOperations {+ private final Configuration configuration;+ private FilesetMetadataCache cache;++ public CacheOverrideOperations(Configuration configuration) {+ super(configuration);+ this.configuration = configuration;+ }++ @Override+ protected synchronized Optional<FilesetMetadataCache> getFilesetMetadataCache() {+ if (cache == null) {+ cache =+ new FilesetMetadataCache(getGravitinoClient()) {+ @Override+ public FilesetCatalog getFilesetCatalog(NameIdentifier catalogIdent) {+ // The base code casts the fileset catalog back to Catalog, so the mock keeps both.+ FilesetCatalog filesetCatalog =+ Mockito.mock(+ FilesetCatalog.class,+ Mockito.withSettings()+ .extraInterfaces(Catalog.class)+ .defaultAnswer(+ AdditionalAnswers.delegatesTo(+ super.getFilesetCatalog(catalogIdent))));+ Mockito.doAnswer(+ invocation -> {+ // Like the real client, clear the caller context set for the lookup.+ CallerContext.CallerContextHolder.remove();+ return configuration.get(LocalHooks.LOCAL_DIR_KEY) + "/override.txt";+ })+ .when(filesetCatalog)+ .getFileLocation(any(), any(), any());+ return filesetCatalog;+ }+ };+ }+ return Optional.of(cache);+ }++ @Override+ public void close() throws IOException {+ try {+ if (cache != null) {+ cache.close();+ }+ } finally {+ super.close();+ }+ }+ }}