Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#1616] feat(fileset): Add gravitino hadoop file system support (#1700)

xloya11a423e0c4f5
diff --git a/build.gradle.kts b/build.gradle.kts
index c57c34299b..314ac6ee72 100644
--- a/build.gradle.kts
+++ b/build.gradle.kts
@@ -365,7 +365,7 @@ subprojects {
options.locale = "en_US"
val projectName = project.name
- if (projectName == "common" || projectName == "api" || projectName == "client-java") {
+ if (projectName == "common" || projectName == "api" || projectName == "client-java" || projectName == "filesystem-hadoop3") {
options {
(this as CoreJavadocOptions).addStringOption("Xwerror", "-quiet")
isFailOnError = true
@@ -641,7 +641,7 @@ tasks {
register("copySubprojectDependencies", Copy::class) {
subprojects.forEach() {
if (!it.name.startsWith("catalog") &&
- !it.name.startsWith("client") && it.name != "trino-connector" &&
+ !it.name.startsWith("client") && !it.name.startsWith("filesystem") && it.name != "trino-connector" &&
it.name != "integration-test" && it.name != "bundled-catalog" && it.name != "spark-connector"
) {
from(it.configurations.runtimeClasspath)
@@ -654,6 +654,7 @@ tasks {
subprojects.forEach() {
if (!it.name.startsWith("catalog") &&
!it.name.startsWith("client") &&
+ !it.name.startsWith("filesystem") &&
it.name != "trino-connector" &&
it.name != "spark-connector" &&
it.name != "integration-test" &&
diff --git a/clients/filesystem-hadoop3-runtime/build.gradle.kts b/clients/filesystem-hadoop3-runtime/build.gradle.kts
new file mode 100644
index 0000000000..bc086e0271
--- /dev/null
+++ b/clients/filesystem-hadoop3-runtime/build.gradle.kts
@@ -0,0 +1,31 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+
+import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
+
+plugins {
+ `maven-publish`
+ id("java")
+ alias(libs.plugins.shadow)
+}
+
+dependencies {
+ implementation(project(":clients:filesystem-hadoop3"))
+}
+
+tasks.withType<ShadowJar>(ShadowJar::class.java) {
+ isZip64 = true
+ configurations = listOf(project.configurations.runtimeClasspath.get())
+ archiveClassifier.set("")
+
+ // Relocate dependencies to avoid conflicts
+ relocate("com.google", "com.datastrato.gravitino.shaded.com.google")
+ relocate("com.github.benmanes.caffeine", "com.datastrato.gravitino.shaded.com.github.benmanes.caffeine")
+}
+
+tasks.jar {
+ dependsOn(tasks.named("shadowJar"))
+ archiveClassifier.set("empty")
+}
diff --git a/clients/filesystem-hadoop3/build.gradle.kts b/clients/filesystem-hadoop3/build.gradle.kts
new file mode 100644
index 0000000000..a6ad7ad365
--- /dev/null
+++ b/clients/filesystem-hadoop3/build.gradle.kts
@@ -0,0 +1,35 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+
+plugins {
+ `maven-publish`
+ id("java")
+ id("idea")
+}
+
+dependencies {
+ compileOnly(libs.hadoop3.common)
+ implementation(project(":clients:client-java-runtime", configuration = "shadow"))
+ implementation(libs.caffeine)
+
+ testImplementation(libs.hadoop3.common)
+ testImplementation(libs.junit.jupiter.api)
+ testImplementation(libs.junit.jupiter.params)
+ testImplementation(libs.mockito.core)
+ testImplementation(libs.mockserver.netty) {
+ exclude("com.google.guava", "guava")
+ }
+ testRuntimeOnly(libs.junit.jupiter.engine)
+}
+
+tasks.build {
+ dependsOn("javadoc")
+}
+
+tasks.javadoc {
+ dependsOn(":clients:client-java-runtime:javadoc")
+ source = sourceSets["main"].allJava +
+ project(":clients:client-java-runtime").sourceSets["main"].allJava
+}
diff --git a/clients/filesystem-hadoop3/src/main/java/com/datastrato/gravitino/filesystem/hadoop3/FilesetContext.java b/clients/filesystem-hadoop3/src/main/java/com/datastrato/gravitino/filesystem/hadoop3/FilesetContext.java
new file mode 100644
index 0000000000..3ac23dc028
--- /dev/null
+++ b/clients/filesystem-hadoop3/src/main/java/com/datastrato/gravitino/filesystem/hadoop3/FilesetContext.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.filesystem.hadoop3;
+
+import com.datastrato.gravitino.NameIdentifier;
+import com.datastrato.gravitino.file.Fileset;
+import com.datastrato.gravitino.shaded.com.google.common.base.Preconditions;
+import com.google.common.base.Objects;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+
+/**
+ * A context object that holds the information about the fileset and the file system which used in
+ * the {@link GravitinoVirtualFileSystem}'s operations.
+ */
+class FilesetContext {
+ private NameIdentifier identifier;
+ private Fileset fileset;
+ private FileSystem fileSystem;
+ private Path actualPath;
+
+ private FilesetContext() {}
+
+ public NameIdentifier getIdentifier() {
+ return identifier;
+ }
+
+ public Fileset getFileset() {
+ return fileset;
+ }
+
+ public FileSystem getFileSystem() {
+ return fileSystem;
+ }
+
+ public Path getActualPath() {
+ return actualPath;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof FilesetContext)) return false;
+ FilesetContext that = (FilesetContext) o;
+ return Objects.equal(getIdentifier(), that.getIdentifier())
+ && Objects.equal(getFileset(), that.getFileset())
+ && Objects.equal(getFileSystem(), that.getFileSystem())
+ && Objects.equal(getActualPath(), that.getActualPath());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hashCode(getIdentifier(), getFileset(), getFileSystem(), getActualPath());
+ }
+
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ /** A builder class for {@link FilesetContext}. */
+ public static class Builder {
+
+ private final FilesetContext context;
+
+ private Builder() {
+ this.context = new FilesetContext();
+ }
+
+ public Builder withIdentifier(NameIdentifier identifier) {
+ context.identifier = identifier;
+ return this;
+ }
+
+ public Builder withFileSystem(FileSystem fileSystem) {
+ context.fileSystem = fileSystem;
+ return this;
+ }
+
+ public Builder withFileset(Fileset fileset) {
+ context.fileset = fileset;
+ return this;
+ }
+
+ public Builder withActualPath(Path actualPath) {
+ context.actualPath = actualPath;
+ return this;
+ }
+
+ public FilesetContext build() {
+ Preconditions.checkArgument(context.identifier != null, "Identifier is required");
+ Preconditions.checkArgument(context.fileset != null, "Fileset is required");
+ Preconditions.checkArgument(context.fileSystem != null, "FileSystem is required");
+ Preconditions.checkArgument(context.actualPath != null, "ActualPath is required");
+ return context;
+ }
+ }
+}
diff --git a/clients/filesystem-hadoop3/src/main/java/com/datastrato/gravitino/filesystem/hadoop3/GravitinoVirtualFileSystem.java b/clients/filesystem-hadoop3/src/main/java/com/datastrato/gravitino/filesystem/hadoop3/GravitinoVirtualFileSystem.java
new file mode 100644
index 0000000000..578f461693
--- /dev/null
+++ b/clients/filesystem-hadoop3/src/main/java/com/datastrato/gravitino/filesystem/hadoop3/GravitinoVirtualFileSystem.java
@@ -0,0 +1,424 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.filesystem.hadoop3;
+
+import com.datastrato.gravitino.Catalog;
+import com.datastrato.gravitino.NameIdentifier;
+import com.datastrato.gravitino.client.GravitinoClient;
+import com.datastrato.gravitino.file.Fileset;
+import com.datastrato.gravitino.shaded.com.google.common.annotations.VisibleForTesting;
+import com.datastrato.gravitino.shaded.com.google.common.base.Preconditions;
+import com.datastrato.gravitino.shaded.com.google.common.util.concurrent.ThreadFactoryBuilder;
+import com.datastrato.gravitino.shaded.org.apache.commons.lang3.StringUtils;
+import com.datastrato.gravitino.shaded.org.apache.commons.lang3.tuple.Pair;
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import com.github.benmanes.caffeine.cache.Scheduler;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.net.URI;
+import java.util.Arrays;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+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.InvalidPathException;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.permission.FsPermission;
+import org.apache.hadoop.util.Progressable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * {@link GravitinoVirtualFileSystem} is a virtual file system which users can access `fileset` and
+ * other resources. It obtains the actual storage location corresponding to the resource from the
+ * Gravitino server, and creates an independent file system for it to act as an agent for users to
+ * access the underlying storage.
+ */
+public class GravitinoVirtualFileSystem extends FileSystem {
+ private static final Logger Logger = LoggerFactory.getLogger(GravitinoVirtualFileSystem.class);
+ private Path workingDirectory;
+ private URI uri;
+ private GravitinoClient client;
+ private String metalakeName;
+ private Cache<NameIdentifier, Pair<Fileset, FileSystem>> filesetCache;
+ private ScheduledThreadPoolExecutor scheduler;
+
+ @Override
+ public void initialize(URI name, Configuration configuration) throws IOException {
+ if (!name.toString().startsWith(GravitinoVirtualFileSystemConfiguration.GVFS_FILESET_PREFIX)) {
+ throw new IllegalArgumentException(
+ String.format(
+ "Unsupported file system scheme: %s for %s.",
+ name.getScheme(), GravitinoVirtualFileSystemConfiguration.GVFS_SCHEME));
+ }
+
+ int maxCapacity =
+ configuration.getInt(
+ GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_FILESET_CACHE_MAX_CAPACITY_KEY,
+ GravitinoVirtualFileSystemConfiguration
+ .FS_GRAVITINO_FILESET_CACHE_MAX_CAPACITY_DEFAULT);
+ Preconditions.checkArgument(
+ maxCapacity > 0,
+ "'%s' should be greater than 0",
+ GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_FILESET_CACHE_MAX_CAPACITY_KEY);
+
+ long evictionMillsAfterAccess =
+ configuration.getLong(
+ GravitinoVirtualFileSystemConfiguration
+ .FS_GRAVITINO_FILESET_CACHE_EVICTION_MILLS_AFTER_ACCESS_KEY,
+ GravitinoVirtualFileSystemConfiguration
+ .FS_GRAVITINO_FILESET_CACHE_EVICTION_MILLS_AFTER_ACCESS_DEFAULT);
+ Preconditions.checkArgument(
+ evictionMillsAfterAccess > 0,
+ "'%s' should be greater than 0",
+ GravitinoVirtualFileSystemConfiguration
+ .FS_GRAVITINO_FILESET_CACHE_EVICTION_MILLS_AFTER_ACCESS_KEY);
+
+ initializeCache(maxCapacity, evictionMillsAfterAccess);
+
+ // initialize the Gravitino client
+ String serverUri =
+ configuration.get(GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_SERVER_URI_KEY);
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(serverUri),
+ "'%s' is not set in the configuration",
+ GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_SERVER_URI_KEY);
+
+ this.metalakeName =
+ configuration.get(GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_CLIENT_METALAKE_KEY);
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(metalakeName),
+ "'%s' is not set in the configuration",
+ GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_CLIENT_METALAKE_KEY);
+
+ // TODO Need support more authentication types, now we only support simple auth
+ this.client =
+ GravitinoClient.builder(serverUri).withMetalake(metalakeName).withSimpleAuth().build();
+
+ this.workingDirectory = new Path(name);
+ this.uri = URI.create(name.getScheme() + "://" + name.getAuthority());
+
+ setConf(configuration);
+ super.initialize(uri, getConf());
+ }
+
+ @VisibleForTesting
+ Cache<NameIdentifier, Pair<Fileset, FileSystem>> getFilesetCache() {
+ return filesetCache;
+ }
+
+ private void initializeCache(int maxCapacity, long expireAfterAccess) {
+ // Since Caffeine does not ensure that removalListener will be involved after expiration
+ // We use a scheduler with one thread to clean up expired clients.
+ this.scheduler = new ScheduledThreadPoolExecutor(1, newDaemonThreadFactory());
+
+ this.filesetCache =
+ Caffeine.newBuilder()
+ .maximumSize(maxCapacity)
+ .expireAfterAccess(expireAfterAccess, TimeUnit.MILLISECONDS)
+ .scheduler(Scheduler.forScheduledExecutorService(scheduler))
+ .removalListener(
+ (key, value, cause) -> {
+ try {
+ Pair<Fileset, FileSystem> pair = ((Pair<Fileset, FileSystem>) value);
+ if (pair != null && pair.getRight() != null) pair.getRight().close();
+ } catch (IOException e) {
+ Logger.error("Cannot close the file system for fileset: {}", key, e);
+ }
+ })
+ .build();
+ }
+
+ private ThreadFactory newDaemonThreadFactory() {
+ return new ThreadFactoryBuilder()
+ .setDaemon(true)
+ .setNameFormat("gvfs-cache-cleaner" + "-%d")
+ .build();
+ }
+
+ private String concatVirtualPrefix(NameIdentifier identifier) {
+ return GravitinoVirtualFileSystemConfiguration.GVFS_FILESET_PREFIX
+ + identifier.namespace().level(1)
+ + "/"
+ + identifier.namespace().level(2)
+ + "/"
+ + identifier.name();
+ }
+
+ private Path getActualPathByIdentifier(
+ NameIdentifier identifier, Pair<Fileset, FileSystem> filesetPair, Path path) {
+ String virtualPath = path.toString();
+ if (!virtualPath.startsWith(GravitinoVirtualFileSystemConfiguration.GVFS_FILESET_PREFIX)) {
+ throw new InvalidPathException(
+ String.format(
+ "Path %s doesn't start with the scheme \"%s\".",
+ virtualPath, GravitinoVirtualFileSystemConfiguration.GVFS_FILESET_PREFIX));
+ }
+ try {
+ if (checkMountsSingleFile(filesetPair)) {
+ String virtualPrefix = concatVirtualPrefix(identifier);
+ Preconditions.checkArgument(
+ virtualPath.equals(virtualPrefix),
+ "Path: %s should be same with the virtual prefix: %s, because the fileset only mounts a single file.",
+ virtualPath,
+ virtualPrefix);
+
+ return new Path(filesetPair.getLeft().storageLocation());
+ } else {
+ return new Path(
+ virtualPath.replaceFirst(
+ concatVirtualPrefix(identifier),
+ new Path(filesetPair.getLeft().storageLocation()).toString()));
+ }
+ } catch (Exception e) {
+ throw new RuntimeException(
+ String.format("Cannot resolve path: %s to actual storage path, exception:", path), e);
+ }
+ }
+
+ private boolean checkMountsSingleFile(Pair<Fileset, FileSystem> filesetPair) {
+ try {
+ return filesetPair
+ .getRight()
+ .getFileStatus(new Path(filesetPair.getLeft().storageLocation()))
+ .isFile();
+ } catch (FileNotFoundException e) {
+ // We should always return false here, same with the logic in `FileSystem.isFile(Path f)`.
+ return false;
+ } catch (IOException e) {
+ throw new RuntimeException(
+ String.format(
+ "Cannot check whether the fileset: %s mounts a single file, exception: %s",
+ filesetPair.getLeft().name(), e.getMessage()),
+ e);
+ }
+ }
+
+ private FileStatus convertFileStatusPathPrefix(
+ FileStatus fileStatus, String actualPrefix, String virtualPrefix) {
+ String filePath = fileStatus.getPath().toString();
+ if (!filePath.startsWith(actualPrefix)) {
+ throw new InvalidPathException(
+ String.format("Path %s doesn't start with prefix \"%s\".", filePath, actualPrefix));
+ }
+ Path path = new Path(filePath.replaceFirst(actualPrefix, virtualPrefix));
+ fileStatus.setPath(path);
+
+ return fileStatus;
+ }
+
+ private NameIdentifier extractIdentifier(URI virtualUri) {
+ Preconditions.checkArgument(
+ virtualUri
+ .toString()
+ .startsWith(GravitinoVirtualFileSystemConfiguration.GVFS_FILESET_PREFIX),
+ "Path %s doesn't start with scheme \"%s\".");
+
+ if (StringUtils.isBlank(virtualUri.toString())) {
+ throw new InvalidPathException("Uri which need be extracted cannot be null or empty.");
+ }
+
+ // remove first '/' symbol with empty string
+ String[] reservedDirs =
+ Arrays.stream(virtualUri.getPath().replaceFirst("/", "").split("/")).toArray(String[]::new);
+ Preconditions.checkArgument(
+ reservedDirs.length >= 3, "URI %s doesn't contains valid identifier", virtualUri);
+
+ return NameIdentifier.ofFileset(
+ metalakeName, reservedDirs[0], reservedDirs[1], reservedDirs[2]);
+ }
+
+ private FilesetContext getFilesetContext(Path virtualPath) {
+ NameIdentifier identifier = extractIdentifier(virtualPath.toUri());
+ Pair<Fileset, FileSystem> pair = filesetCache.get(identifier, this::constructNewFilesetPair);
+ Preconditions.checkState(
+ pair != null,
+ "Cannot get the pair of fileset instance and actual file system for %s",
+ identifier);
+ Path actualPath = getActualPathByIdentifier(identifier, pair, virtualPath);
+ return FilesetContext.builder()
+ .withIdentifier(identifier)
+ .withFileset(pair.getLeft())
+ .withFileSystem(pair.getRight())
+ .withActualPath(actualPath)
+ .build();
+ }
+
+ private Pair<Fileset, FileSystem> constructNewFilesetPair(NameIdentifier identifier) {
+ // Always create a new file system instance for the fileset.
+ // Therefore, users cannot bypass gvfs and use `FileSystem.get()` to directly obtain the
+ // FileSystem
+ try {
+ Fileset fileset = loadFileset(identifier);
+ URI storageUri = URI.create(fileset.storageLocation());
+ FileSystem actualFileSystem = FileSystem.newInstance(storageUri, getConf());
+ Preconditions.checkState(actualFileSystem != null, "Cannot get the actual file system");
+ return Pair.of(fileset, actualFileSystem);
+ } catch (IOException e) {
+ throw new RuntimeException(
+ String.format(
+ "Cannot create file system for fileset: %s, exception: %s",
+ identifier, e.getMessage()),
+ e);
+ } catch (RuntimeException e) {
+ throw new RuntimeException(
+ String.format(
+ "Cannot load fileset: %s from the server. exception: %s",
+ identifier, e.getMessage()));
+ }
+ }
+
+ private Fileset loadFileset(NameIdentifier identifier) {
+ Catalog catalog =
+ client.loadCatalog(NameIdentifier.ofCatalog(metalakeName, identifier.namespace().level(1)));
+ return catalog.asFilesetCatalog().loadFileset(identifier);
+ }
+
+ @Override
+ public URI getUri() {
+ return this.uri;
+ }
+
+ @Override
+ public Path getWorkingDirectory() {
+ return this.workingDirectory;
+ }
+
+ @Override
+ public synchronized void setWorkingDirectory(Path newDir) {
+ FilesetContext context = getFilesetContext(newDir);
+ context.getFileSystem().setWorkingDirectory(context.getActualPath());
+ this.workingDirectory = newDir;
+ }
+
+ @Override
+ public FSDataInputStream open(Path path, int bufferSize) throws IOException {
+ FilesetContext context = getFilesetContext(path);
+ return context.getFileSystem().open(context.getActualPath(), bufferSize);
+ }
+
+ @Override
+ public FSDataOutputStream create(
+ Path path,
+ FsPermission permission,
+ boolean overwrite,
+ int bufferSize,
+ short replication,
+ long blockSize,
+ Progressable progress)
+ throws IOException {
+ FilesetContext context = getFilesetContext(path);
+ return context
+ .getFileSystem()
+ .create(
+ context.getActualPath(),
+ permission,
+ overwrite,
+ bufferSize,
+ replication,
+ blockSize,
+ progress);
+ }
+
+ @Override
+ public FSDataOutputStream append(Path path, int bufferSize, Progressable progress)
+ throws IOException {
+ FilesetContext context = getFilesetContext(path);
+ return context.getFileSystem().append(context.getActualPath(), bufferSize, progress);
+ }
+
+ @Override
+ public boolean rename(Path src, Path dst) throws IOException {
+ // There are two cases that cannot be renamed:
+ // 1. Fileset identifier is not allowed to be renamed, only its subdirectories can be renamed
+ // which not in the storage location of the fileset;
+ // 2. Fileset only mounts a single file, the storage location of the fileset cannot be renamed;
+ // Otherwise the metadata in the Gravitino server may be inconsistent.
+ NameIdentifier srcIdentifier = extractIdentifier(src.toUri());
+ NameIdentifier dstIdentifier = extractIdentifier(dst.toUri());
+ Preconditions.checkArgument(
+ srcIdentifier.equals(dstIdentifier),
+ "Destination path fileset identifier: %s should be same with src path fileset identifier: %s.",
+ srcIdentifier,
+ dstIdentifier);
+
+ FilesetContext srcFileContext = getFilesetContext(src);
+ if (checkMountsSingleFile(
+ Pair.of(srcFileContext.getFileset(), srcFileContext.getFileSystem()))) {
+ throw new UnsupportedOperationException(
+ String.format(
+ "Cannot rename the fileset: %s which only mounts to a single file.", srcIdentifier));
+ }
+
+ FilesetContext dstFileContext = getFilesetContext(dst);
+ return srcFileContext
+ .getFileSystem()
+ .rename(srcFileContext.getActualPath(), dstFileContext.getActualPath());
+ }
+
+ @Override
+ public boolean delete(Path path, boolean recursive) throws IOException {
+ FilesetContext context = getFilesetContext(path);
+ return context.getFileSystem().delete(context.getActualPath(), recursive);
+ }
+
+ @Override
+ public FileStatus getFileStatus(Path path) throws IOException {
+ FilesetContext context = getFilesetContext(path);
+ FileStatus fileStatus = context.getFileSystem().getFileStatus(context.getActualPath());
+ return convertFileStatusPathPrefix(
+ fileStatus,
+ context.getFileset().storageLocation(),
+ concatVirtualPrefix(context.getIdentifier()));
+ }
+
+ @Override
+ public FileStatus[] listStatus(Path path) throws IOException {
+ FilesetContext context = getFilesetContext(path);
+ FileStatus[] fileStatusResults = context.getFileSystem().listStatus(context.getActualPath());
+ return Arrays.stream(fileStatusResults)
+ .map(
+ fileStatus ->
+ convertFileStatusPathPrefix(
+ fileStatus,
+ new Path(context.getFileset().storageLocation()).toString(),
+ concatVirtualPrefix(context.getIdentifier())))
+ .toArray(FileStatus[]::new);
+ }
+
+ @Override
+ public boolean mkdirs(Path path, FsPermission permission) throws IOException {
+ FilesetContext context = getFilesetContext(path);
+ return context.getFileSystem().mkdirs(context.getActualPath(), permission);
+ }
+
+ @Override
+ public synchronized void close() throws IOException {
+ // close all actual FileSystems
+ for (Pair<Fileset, FileSystem> filesetPair : filesetCache.asMap().values()) {
+ try {
+ filesetPair.getRight().close();
+ } catch (IOException e) {
+ // ignore
+ }
+ }
+ filesetCache.invalidateAll();
+ // close the client
+ try {
+ if (client != null) {
+ client.close();
+ }
+ } catch (Exception e) {
+ // ignore
+ }
+ scheduler.shutdownNow();
+ super.close();
+ }
+}
diff --git a/clients/filesystem-hadoop3/src/main/java/com/datastrato/gravitino/filesystem/hadoop3/GravitinoVirtualFileSystemConfiguration.java b/clients/filesystem-hadoop3/src/main/java/com/datastrato/gravitino/filesystem/hadoop3/GravitinoVirtualFileSystemConfiguration.java
new file mode 100644
index 0000000000..48a1e8c019
--- /dev/null
+++ b/clients/filesystem-hadoop3/src/main/java/com/datastrato/gravitino/filesystem/hadoop3/GravitinoVirtualFileSystemConfiguration.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.filesystem.hadoop3;
+
+/** Configuration class for Gravitino Virtual File System. */
+class GravitinoVirtualFileSystemConfiguration {
+ public static final String GVFS_FILESET_PREFIX = "gvfs://fileset/";
+ public static final String GVFS_SCHEME = "gvfs";
+
+ /** The configuration key for the Gravitino server URI. */
+ public static final String FS_GRAVITINO_SERVER_URI_KEY = "fs.gravitino.server.uri";
+
+ /** The configuration key for the Gravitino client Metalake. */
+ public static final String FS_GRAVITINO_CLIENT_METALAKE_KEY = "fs.gravitino.client.metalake";
+
+ /** The configuration key for the maximum capacity of the Gravitino fileset cache. */
+ public static final String FS_GRAVITINO_FILESET_CACHE_MAX_CAPACITY_KEY =
+ "fs.gravitino.fileset.cache.maxCapacity";
+
+ public static final int FS_GRAVITINO_FILESET_CACHE_MAX_CAPACITY_DEFAULT = 20;
+
+ /**
+ * The configuration key for the eviction time of the Gravitino fileset cache, measured in mills
+ * after access.
+ */
+ public static final String FS_GRAVITINO_FILESET_CACHE_EVICTION_MILLS_AFTER_ACCESS_KEY =
+ "fs.gravitino.fileset.cache.evictionMillsAfterAccess";
+
+ public static final long FS_GRAVITINO_FILESET_CACHE_EVICTION_MILLS_AFTER_ACCESS_DEFAULT =
+ 1000L * 60 * 5;
+
+ private GravitinoVirtualFileSystemConfiguration() {}
+}
diff --git a/clients/filesystem-hadoop3/src/main/java/com/datastrato/gravitino/filesystem/hadoop3/Gvfs.java b/clients/filesystem-hadoop3/src/main/java/com/datastrato/gravitino/filesystem/hadoop3/Gvfs.java
new file mode 100644
index 0000000000..edcb1892c1
--- /dev/null
+++ b/clients/filesystem-hadoop3/src/main/java/com/datastrato/gravitino/filesystem/hadoop3/Gvfs.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.filesystem.hadoop3;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.DelegateToFileSystem;
+
+/**
+ * A {@link DelegateToFileSystem} implementation that delegates all operations to a {@link
+ * GravitinoVirtualFileSystem}.
+ */
+public class Gvfs extends DelegateToFileSystem {
+
+ /**
+ * Creates a new instance of {@link Gvfs}.
+ *
+ * @param uri the URI of the file system
+ * @param conf the configuration
+ * @throws IOException if an I/O error occurs
+ * @throws URISyntaxException if the URI is invalid
+ */
+ protected Gvfs(URI uri, Configuration conf) throws IOException, URISyntaxException {
+ super(
+ uri,
+ new GravitinoVirtualFileSystem(),
+ conf,
+ GravitinoVirtualFileSystemConfiguration.GVFS_SCHEME,
+ false);
+ }
+}
diff --git a/clients/filesystem-hadoop3/src/test/java/com/datastrato/gravitino/filesystem/hadoop3/FileSystemTestUtils.java b/clients/filesystem-hadoop3/src/test/java/com/datastrato/gravitino/filesystem/hadoop3/FileSystemTestUtils.java
new file mode 100644
index 0000000000..00faf5ea98
--- /dev/null
+++ b/clients/filesystem-hadoop3/src/test/java/com/datastrato/gravitino/filesystem/hadoop3/FileSystemTestUtils.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.filesystem.hadoop3;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.util.UUID;
+import org.apache.hadoop.fs.FSDataInputStream;
+import org.apache.hadoop.fs.FSDataOutputStream;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.permission.FsPermission;
+import org.apache.hadoop.util.Progressable;
+
+public class FileSystemTestUtils {
+ private static final String LOCAL_FS_PREFIX =
+ "file:/tmp/gravitino_test_fs_" + UUID.randomUUID().toString().replace("-", "") + "/";
+
+ private static final int BUFFER_SIZE = 3;
+ private static final short REPLICATION = 1;
+ private static final long BLOCK_SIZE = 1048576L;
+ private static final FsPermission MOCK_PERMISSION = FsPermission.createImmutable((short) 0777);
+ private static final Progressable DEFAULT_PROGRESS = () -> {};
+
+ private FileSystemTestUtils() {}
+
+ public static String localRootPrefix() {
+ return LOCAL_FS_PREFIX;
+ }
+
+ public static Path createFilesetPath(String filesetCatalog, String schema, String fileset) {
+ return new Path(
+ GravitinoVirtualFileSystemConfiguration.GVFS_FILESET_PREFIX
+ + "/"
+ + filesetCatalog
+ + "/"
+ + schema
+ + "/"
+ + fileset);
+ }
+
+ public static Path createLocalRootDir(String filesetCatalog) {
+ return new Path(LOCAL_FS_PREFIX + filesetCatalog);
+ }
+
+ public static Path createLocalDirPrefix(String filesetCatalog, String schema, String fileset) {
+ return new Path(LOCAL_FS_PREFIX + filesetCatalog + "/" + schema + "/" + fileset);
+ }
+
+ public static void create(Path path, FileSystem fileSystem) throws IOException {
+ boolean overwrite = true;
+ try (FSDataOutputStream outputStream =
+ fileSystem.create(
+ path,
+ MOCK_PERMISSION,
+ overwrite,
+ BUFFER_SIZE,
+ REPLICATION,
+ BLOCK_SIZE,
+ DEFAULT_PROGRESS)) {}
+ }
+
+ public static void append(Path path, FileSystem fileSystem) throws IOException {
+ try (FSDataOutputStream mockOutputStream = fileSystem.append(path, BUFFER_SIZE)) {
+ // Hello, World!
+ byte[] mockBytes = new byte[] {72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33};
+ mockOutputStream.write(mockBytes);
+ }
+ }
+
+ public static byte[] read(Path path, FileSystem fileSystem) throws IOException {
+ try (FSDataInputStream inputStream = fileSystem.open(path, BUFFER_SIZE)) {
+ int bytesRead;
+ byte[] buffer = new byte[1024];
+ try (ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream()) {
+ while ((bytesRead = inputStream.read(buffer)) != -1) {
+ byteOutputStream.write(buffer, 0, bytesRead);
+ }
+ return byteOutputStream.toByteArray();
+ }
+ }
+ }
+
+ public static void mkdirs(Path path, FileSystem fileSystem) throws IOException {
+ fileSystem.mkdirs(path, MOCK_PERMISSION);
+ }
+}
diff --git a/clients/filesystem-hadoop3/src/test/java/com/datastrato/gravitino/filesystem/hadoop3/MockServerTestBase.java b/clients/filesystem-hadoop3/src/test/java/com/datastrato/gravitino/filesystem/hadoop3/MockServerTestBase.java
new file mode 100644
index 0000000000..967cbadc70
--- /dev/null
+++ b/clients/filesystem-hadoop3/src/test/java/com/datastrato/gravitino/filesystem/hadoop3/MockServerTestBase.java
@@ -0,0 +1,174 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.filesystem.hadoop3;
+
+import static org.apache.hc.core5.http.HttpStatus.SC_OK;
+
+import com.datastrato.gravitino.NameIdentifier;
+import com.datastrato.gravitino.dto.AuditDTO;
+import com.datastrato.gravitino.dto.CatalogDTO;
+import com.datastrato.gravitino.dto.MetalakeDTO;
+import com.datastrato.gravitino.dto.file.FilesetDTO;
+import com.datastrato.gravitino.dto.responses.CatalogResponse;
+import com.datastrato.gravitino.dto.responses.FilesetResponse;
+import com.datastrato.gravitino.dto.responses.MetalakeResponse;
+import com.datastrato.gravitino.file.Fileset;
+import com.datastrato.gravitino.json.JsonUtils;
+import com.datastrato.gravitino.shaded.com.fasterxml.jackson.core.JsonProcessingException;
+import com.datastrato.gravitino.shaded.com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.collect.ImmutableMap;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import org.apache.hc.core5.http.HttpStatus;
+import org.apache.hc.core5.http.Method;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.mockserver.integration.ClientAndServer;
+import org.mockserver.matchers.Times;
+import org.mockserver.model.HttpRequest;
+import org.mockserver.model.HttpResponse;
+import org.mockserver.model.Parameter;
+
+public abstract class MockServerTestBase {
+ private static final ObjectMapper MAPPER = JsonUtils.objectMapper();
+ private static ClientAndServer mockServer;
+ private static final String MOCK_SERVER_HOST = "http://127.0.0.1:";
+ private static int port;
+ protected static final String metalakeName = "metalake_1";
+ protected static final String catalogName = "fileset_catalog_1";
+ protected static final String schemaName = "schema_1";
+ protected static final String managedFilesetName = "managed_fileset";
+ protected static final String externalFilesetName = "external_fileset";
+ protected static final String provider = "test";
+
+ @BeforeAll
+ public static void setup() {
+ mockServer = ClientAndServer.startClientAndServer(0);
+ port = mockServer.getLocalPort();
+ }
+
+ @AfterEach
+ public void reset() {
+ mockServer.reset();
+ }
+
+ @AfterAll
+ public static void tearDown() {
+ mockServer.stop();
+ }
+
+ public static String serverUri() {
+ return String.format("%s%d", MOCK_SERVER_HOST, port);
+ }
+
+ protected static <T, R> void buildMockResource(
+ Method method,
+ String path,
+ Map<String, String> queryParams,
+ T reqBody,
+ R respBody,
+ int statusCode)
+ throws com.datastrato.gravitino.shaded.com.fasterxml.jackson.core.JsonProcessingException {
+ List<Parameter> parameters =
+ queryParams.entrySet().stream()
+ .map(kv -> new Parameter(kv.getKey(), kv.getValue()))
+ .collect(Collectors.toList());
+
+ HttpRequest mockRequest =
+ HttpRequest.request(path).withMethod(method.name()).withQueryStringParameters(parameters);
+ if (reqBody != null) {
+ String reqJson = MAPPER.writeValueAsString(reqBody);
+ mockRequest = mockRequest.withBody(reqJson);
+ }
+
+ HttpResponse mockResponse = HttpResponse.response().withStatusCode(statusCode);
+ if (respBody != null) {
+ String respJson = MAPPER.writeValueAsString(respBody);
+ mockResponse = mockResponse.withBody(respJson);
+ }
+
+ mockServer.when(mockRequest, Times.unlimited()).respond(mockResponse);
+ }
+
+ protected static <T, R> void buildMockResource(
+ Method method, String path, T reqBody, R respBody, int statusCode)
+ throws com.datastrato.gravitino.shaded.com.fasterxml.jackson.core.JsonProcessingException {
+ buildMockResource(method, path, Collections.emptyMap(), reqBody, respBody, statusCode);
+ }
+
+ protected static void mockMetalakeDTO(String name, String comment) {
+ MetalakeDTO mockMetalake =
+ MetalakeDTO.builder()
+ .withName(name)
+ .withComment(comment)
+ .withAudit(
+ AuditDTO.builder().withCreator("creator").withCreateTime(Instant.now()).build())
+ .build();
+ MetalakeResponse resp = new MetalakeResponse(mockMetalake);
+ try {
+ buildMockResource(Method.GET, "/api/metalakes/" + metalakeName, null, resp, HttpStatus.SC_OK);
+ } catch (JsonProcessingException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ protected static void mockCatalogDTO(String catalogName, String provider, String comment) {
+ CatalogDTO mockCatalog =
+ CatalogDTO.builder()
+ .withName(catalogName)
+ .withType(CatalogDTO.Type.FILESET)
+ .withProvider(provider)
+ .withComment(comment)
+ .withProperties(ImmutableMap.of("k1", "k2"))
+ .withAudit(
+ AuditDTO.builder().withCreator("creator").withCreateTime(Instant.now()).build())
+ .build();
+
+ CatalogResponse catalogResponse = new CatalogResponse(mockCatalog);
+ try {
+ buildMockResource(
+ Method.GET,
+ "/api/metalakes/" + metalakeName + "/catalogs/" + catalogName,
+ null,
+ catalogResponse,
+ SC_OK);
+ } catch (JsonProcessingException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ protected static void mockFilesetDTO(
+ String metalakeName,
+ String catalogName,
+ String schemaName,
+ String filesetName,
+ Fileset.Type type,
+ String location) {
+ NameIdentifier fileset = NameIdentifier.of(metalakeName, catalogName, schemaName, filesetName);
+ String filesetPath =
+ String.format(
+ "/api/metalakes/%s/catalogs/%s/schemas/%s/filesets/%s",
+ metalakeName, catalogName, schemaName, filesetName);
+ FilesetDTO mockFileset =
+ FilesetDTO.builder()
+ .name(fileset.name())
+ .type(type)
+ .storageLocation(location)
+ .comment("comment")
+ .properties(ImmutableMap.of("k1", "v1"))
+ .audit(AuditDTO.builder().withCreator("creator").withCreateTime(Instant.now()).build())
+ .build();
+ FilesetResponse filesetResponse = new FilesetResponse(mockFileset);
+ try {
+ buildMockResource(Method.GET, filesetPath, null, filesetResponse, SC_OK);
+ } catch (JsonProcessingException e) {
+ throw new RuntimeException(e);
+ }
+ }
+}
diff --git a/clients/filesystem-hadoop3/src/test/java/com/datastrato/gravitino/filesystem/hadoop3/TestGravitinoVirtualFileSystem.java b/clients/filesystem-hadoop3/src/test/java/com/datastrato/gravitino/filesystem/hadoop3/TestGravitinoVirtualFileSystem.java
new file mode 100644
index 0000000000..6c016f42bf
--- /dev/null
+++ b/clients/filesystem-hadoop3/src/test/java/com/datastrato/gravitino/filesystem/hadoop3/TestGravitinoVirtualFileSystem.java
@@ -0,0 +1,468 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.filesystem.hadoop3;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import com.datastrato.gravitino.NameIdentifier;
+import com.datastrato.gravitino.file.Fileset;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Objects;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+
+public class TestGravitinoVirtualFileSystem extends MockServerTestBase {
+ private static final String GVFS_IMPL_CLASS = GravitinoVirtualFileSystem.class.getName();
+ private static final String GVFS_ABSTRACT_IMPL_CLASS = Gvfs.class.getName();
+
+ private Configuration conf = null;
+ private Path localDirPath = null;
+ private Path localFilePath = null;
+ private Path managedFilesetPath = null;
+ private Path externalFilesetPath = null;
+
+ @BeforeAll
+ public static void setup() {
+ MockServerTestBase.setup();
+ }
+
+ @BeforeEach
+ public void init() throws IOException {
+ mockMetalakeDTO(metalakeName, "comment");
+ mockCatalogDTO(catalogName, provider, "comment");
+
+ localDirPath =
+ FileSystemTestUtils.createLocalDirPrefix(catalogName, schemaName, managedFilesetName);
+ mockFilesetDTO(
+ metalakeName,
+ catalogName,
+ schemaName,
+ managedFilesetName,
+ Fileset.Type.MANAGED,
+ localDirPath.toString());
+ managedFilesetPath =
+ FileSystemTestUtils.createFilesetPath(catalogName, schemaName, managedFilesetName);
+
+ localFilePath =
+ new Path(
+ FileSystemTestUtils.createLocalDirPrefix(catalogName, schemaName, externalFilesetName)
+ + "/test.txt");
+ mockFilesetDTO(
+ metalakeName,
+ catalogName,
+ schemaName,
+ externalFilesetName,
+ Fileset.Type.EXTERNAL,
+ localFilePath.toString());
+ externalFilesetPath =
+ FileSystemTestUtils.createFilesetPath(catalogName, schemaName, externalFilesetName);
+
+ Configuration configuration = new Configuration();
+ configuration.set("fs.gvfs.impl", GVFS_IMPL_CLASS);
+ configuration.set("fs.AbstractFileSystem.gvfs.impl", GVFS_ABSTRACT_IMPL_CLASS);
+ configuration.set(
+ GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_SERVER_URI_KEY,
+ MockServerTestBase.serverUri());
+ configuration.set(
+ GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_CLIENT_METALAKE_KEY, metalakeName);
+ // close the cache
+ configuration.set(
+ String.format(
+ "fs.%s.impl.disable.cache", GravitinoVirtualFileSystemConfiguration.GVFS_SCHEME),
+ "true");
+ conf = configuration;
+ }
+
+ @AfterEach
+ public void destroy() throws IOException {
+ Path localRootPath = FileSystemTestUtils.createLocalRootDir(catalogName);
+ try (FileSystem localFileSystem = localDirPath.getFileSystem(conf)) {
+ if (localFileSystem.exists(localRootPath)) {
+ localFileSystem.delete(localRootPath, true);
+ }
+ }
+ }
+
+ @Test
+ public void testFSCache() throws IOException {
+ try (FileSystem gravitinoFileSystem = managedFilesetPath.getFileSystem(conf);
+ FileSystem localFileSystem = localDirPath.getFileSystem(conf)) {
+ FileSystemTestUtils.mkdirs(managedFilesetPath, gravitinoFileSystem);
+
+ Configuration conf1 = localFileSystem.getConf();
+ assertEquals(
+ "true",
+ conf1.get(
+ String.format(
+ "fs.%s.impl.disable.cache",
+ GravitinoVirtualFileSystemConfiguration.GVFS_SCHEME)));
+
+ Configuration conf2 = gravitinoFileSystem.getConf();
+ assertEquals(
+ "true",
+ conf2.get(
+ String.format(
+ "fs.%s.impl.disable.cache",
+ GravitinoVirtualFileSystemConfiguration.GVFS_SCHEME)));
+
+ // test gvfs, should not get the same fs
+ try (FileSystem externalFs = externalFilesetPath.getFileSystem(conf)) {
+ assertNotEquals(externalFs, gravitinoFileSystem);
+ }
+
+ // test proxyed local fs, should not get the same fs
+ FileSystemTestUtils.mkdirs(managedFilesetPath, gravitinoFileSystem);
+ FileSystem proxyLocalFs =
+ Objects.requireNonNull(
+ ((GravitinoVirtualFileSystem) gravitinoFileSystem)
+ .getFilesetCache()
+ .getIfPresent(
+ NameIdentifier.of(
+ metalakeName, catalogName, schemaName, managedFilesetName)))
+ .getRight();
+
+ String anotherFilesetName = "test_new_fs";
+ Path diffLocalPath =
+ FileSystemTestUtils.createLocalDirPrefix(catalogName, schemaName, anotherFilesetName);
+ try (FileSystem localFs = diffLocalPath.getFileSystem(conf)) {
+ assertNotEquals(localFs, proxyLocalFs);
+ localFs.delete(diffLocalPath, true);
+ }
+ }
+ }
+
+ @Test
+ public void testInternalCache() throws IOException, InterruptedException {
+ Configuration configuration = new Configuration(conf);
+ configuration.set(
+ GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_FILESET_CACHE_MAX_CAPACITY_KEY, "1");
+ configuration.set(
+ GravitinoVirtualFileSystemConfiguration
+ .FS_GRAVITINO_FILESET_CACHE_EVICTION_MILLS_AFTER_ACCESS_KEY,
+ "1000");
+
+ Path filesetPath1 = FileSystemTestUtils.createFilesetPath(catalogName, schemaName, "fileset1");
+ try (FileSystem fs = filesetPath1.getFileSystem(configuration)) {
+ Path localPath1 =
+ FileSystemTestUtils.createLocalDirPrefix(catalogName, schemaName, "fileset1");
+ mockFilesetDTO(
+ metalakeName,
+ catalogName,
+ schemaName,
+ "fileset1",
+ Fileset.Type.MANAGED,
+ localPath1.toString());
+ FileSystemTestUtils.mkdirs(filesetPath1, fs);
+
+ // expired by size
+ Path filesetPath2 =
+ FileSystemTestUtils.createFilesetPath(catalogName, schemaName, "fileset2");
+ Path localPath2 =
+ FileSystemTestUtils.createLocalDirPrefix(catalogName, schemaName, "fileset2");
+ mockFilesetDTO(
+ metalakeName,
+ catalogName,
+ schemaName,
+ "fileset2",
+ Fileset.Type.MANAGED,
+ localPath2.toString());
+ FileSystemTestUtils.mkdirs(filesetPath2, fs);
+
+ Thread.sleep(1000);
+ assertNull(
+ ((GravitinoVirtualFileSystem) fs)
+ .getFilesetCache()
+ .getIfPresent(NameIdentifier.of(metalakeName, catalogName, schemaName, "fileset1")));
+
+ // expired by time
+ Thread.sleep(1000);
+ assertEquals(0, ((GravitinoVirtualFileSystem) fs).getFilesetCache().asMap().size());
+ assertNull(
+ ((GravitinoVirtualFileSystem) fs)
+ .getFilesetCache()
+ .getIfPresent(NameIdentifier.of(metalakeName, catalogName, schemaName, "fileset2")));
+ }
+ }
+
+ @Test
+ public void testCreate() throws IOException {
+ try (FileSystem gravitinoFileSystem = managedFilesetPath.getFileSystem(conf);
+ FileSystem localFileSystem = localDirPath.getFileSystem(conf)) {
+ FileSystemTestUtils.mkdirs(managedFilesetPath, gravitinoFileSystem);
+
+ // test managed fileset create
+ Path filePath = new Path(managedFilesetPath + "/test.txt");
+ FileSystemTestUtils.create(filePath, gravitinoFileSystem);
+ assertTrue(gravitinoFileSystem.exists(filePath));
+ gravitinoFileSystem.delete(filePath, true);
+
+ // mock the invalid fileset not in the server
+ String invalidFilesetName = "invalid_fileset";
+ Path invalidFilesetPath =
+ FileSystemTestUtils.createFilesetPath(catalogName, schemaName, invalidFilesetName);
+ assertThrows(
+ RuntimeException.class,
+ () -> FileSystemTestUtils.create(invalidFilesetPath, gravitinoFileSystem));
+
+ // mock the not correct protocol prefix path
+ Path localPrefixPath =
+ FileSystemTestUtils.createLocalDirPrefix(catalogName, schemaName, "test");
+ assertThrows(
+ RuntimeException.class,
+ () -> FileSystemTestUtils.create(localPrefixPath, gravitinoFileSystem));
+
+ // test external fileset mounts a single file
+ FileSystemTestUtils.create(externalFilesetPath, gravitinoFileSystem);
+ assertTrue(gravitinoFileSystem.exists(externalFilesetPath));
+ assertTrue(gravitinoFileSystem.getFileStatus(externalFilesetPath).isFile());
+ gravitinoFileSystem.delete(externalFilesetPath, true);
+ assertFalse(localFileSystem.exists(localFilePath));
+ }
+ }
+
+ @Test
+ @Disabled("Append operation is not supported in LocalFileSystem. We can't test it now.")
+ public void testAppend() throws IOException {
+ try (FileSystem gravitinoFileSystem = managedFilesetPath.getFileSystem(conf);
+ FileSystem localFileSystem = localDirPath.getFileSystem(conf)) {
+ FileSystemTestUtils.mkdirs(managedFilesetPath, gravitinoFileSystem);
+
+ // test managed fileset append
+ Path appendFile = new Path(managedFilesetPath + "/test.txt");
+ FileSystemTestUtils.create(appendFile, gravitinoFileSystem);
+ FileSystemTestUtils.append(appendFile, gravitinoFileSystem);
+ assertTrue(gravitinoFileSystem.exists(appendFile));
+ assertTrue(gravitinoFileSystem.getFileStatus(appendFile).isFile());
+ assertEquals(
+ "Hello, World!",
+ new String(
+ FileSystemTestUtils.read(appendFile, gravitinoFileSystem), StandardCharsets.UTF_8));
+ gravitinoFileSystem.delete(appendFile, true);
+
+ // mock the invalid fileset not in server
+ String invalidAppendFilesetName = "invalid_fileset";
+ Path invalidAppendFilesetPath =
+ FileSystemTestUtils.createFilesetPath(catalogName, schemaName, invalidAppendFilesetName);
+ assertThrows(
+ RuntimeException.class,
+ () -> FileSystemTestUtils.append(invalidAppendFilesetPath, gravitinoFileSystem));
+
+ // mock the not correct protocol path
+ Path localPrefixPath =
+ FileSystemTestUtils.createLocalDirPrefix(catalogName, schemaName, "test");
+ assertThrows(
+ RuntimeException.class,
+ () -> FileSystemTestUtils.append(localPrefixPath, gravitinoFileSystem));
+
+ // test external fileset mounts the single file
+ FileSystemTestUtils.create(externalFilesetPath, gravitinoFileSystem);
+ FileSystemTestUtils.append(externalFilesetPath, gravitinoFileSystem);
+ assertTrue(gravitinoFileSystem.exists(externalFilesetPath));
+ assertTrue(gravitinoFileSystem.getFileStatus(externalFilesetPath).isFile());
+ gravitinoFileSystem.delete(externalFilesetPath, true);
+ assertFalse(localFileSystem.exists(localFilePath));
+ }
+ }
+
+ @Test
+ public void testRename() throws IOException {
+ try (FileSystem gravitinoFileSystem = managedFilesetPath.getFileSystem(conf);
+ FileSystem localFileSystem = localDirPath.getFileSystem(conf)) {
+ FileSystemTestUtils.mkdirs(managedFilesetPath, gravitinoFileSystem);
+
+ // test managed fileset rename
+ Path srcRenamePath = new Path(managedFilesetPath + "/rename_src");
+ gravitinoFileSystem.mkdirs(srcRenamePath);
+ assertTrue(gravitinoFileSystem.getFileStatus(srcRenamePath).isDirectory());
+ assertTrue(gravitinoFileSystem.exists(srcRenamePath));
+
+ // cannot rename the identifier
+ Path dstRenamePath1 =
+ FileSystemTestUtils.createFilesetPath(catalogName, schemaName, "rename_dst1");
+ assertThrows(
+ RuntimeException.class, () -> gravitinoFileSystem.rename(srcRenamePath, dstRenamePath1));
+
+ Path dstRenamePath2 = new Path(managedFilesetPath + "/rename_dst2");
+ gravitinoFileSystem.rename(srcRenamePath, dstRenamePath2);
+ assertFalse(gravitinoFileSystem.exists(srcRenamePath));
+ assertTrue(gravitinoFileSystem.exists(dstRenamePath2));
+ gravitinoFileSystem.delete(dstRenamePath2, true);
+
+ // test invalid src path
+ Path invalidSrcPath =
+ FileSystemTestUtils.createFilesetPath(catalogName, schemaName, "invalid_src_name");
+ Path validDstPath =
+ FileSystemTestUtils.createFilesetPath(catalogName, schemaName, managedFilesetName);
+ assertThrows(
+ RuntimeException.class, () -> gravitinoFileSystem.rename(invalidSrcPath, validDstPath));
+
+ // test invalid dst path
+ Path invalidDstPath =
+ FileSystemTestUtils.createFilesetPath(catalogName, schemaName, "invalid_dst_name");
+ assertThrows(
+ RuntimeException.class,
+ () -> gravitinoFileSystem.rename(managedFilesetPath, invalidDstPath));
+
+ // test external fileset mount the single file
+ FileSystemTestUtils.create(externalFilesetPath, gravitinoFileSystem);
+ assertTrue(gravitinoFileSystem.exists(externalFilesetPath));
+ assertTrue(gravitinoFileSystem.getFileStatus(externalFilesetPath).isFile());
+
+ Path dstPath = FileSystemTestUtils.createFilesetPath(catalogName, schemaName, "rename_dst");
+ assertThrows(
+ RuntimeException.class, () -> gravitinoFileSystem.rename(externalFilesetPath, dstPath));
+ localFileSystem.delete(localFilePath, true);
+ assertFalse(localFileSystem.exists(localFilePath));
+ }
+ }
+
+ @Test
+ public void testDelete() throws IOException {
+ try (FileSystem gravitinoFileSystem = managedFilesetPath.getFileSystem(conf);
+ FileSystem localFileSystem = localDirPath.getFileSystem(conf)) {
+
+ FileSystemTestUtils.mkdirs(managedFilesetPath, gravitinoFileSystem);
+
+ // test managed fileset delete
+ FileSystemTestUtils.mkdirs(managedFilesetPath, gravitinoFileSystem);
+ gravitinoFileSystem.delete(managedFilesetPath, true);
+ assertFalse(gravitinoFileSystem.exists(managedFilesetPath));
+
+ // mock the invalid fileset not in server
+ String invalidFilesetName = "invalid_fileset";
+ Path invalidFilesetPath =
+ FileSystemTestUtils.createFilesetPath(catalogName, schemaName, invalidFilesetName);
+ assertThrows(
+ RuntimeException.class, () -> gravitinoFileSystem.delete(invalidFilesetPath, true));
+
+ // mock the not correct protocol path
+ Path localPrefixPath =
+ FileSystemTestUtils.createLocalDirPrefix(catalogName, schemaName, "test");
+ assertThrows(RuntimeException.class, () -> gravitinoFileSystem.delete(localPrefixPath, true));
+
+ // test external fileset mounts the single file
+ FileSystemTestUtils.create(externalFilesetPath, gravitinoFileSystem);
+ assertTrue(gravitinoFileSystem.exists(externalFilesetPath));
+ gravitinoFileSystem.delete(externalFilesetPath, true);
+ assertFalse(gravitinoFileSystem.exists(externalFilesetPath));
+ assertFalse(localFileSystem.exists(localFilePath));
+ }
+ }
+
+ @Test
+ public void testGetStatus() throws IOException {
+ try (FileSystem gravitinoFileSystem = managedFilesetPath.getFileSystem(conf);
+ FileSystem localFileSystem = localDirPath.getFileSystem(conf)) {
+ FileSystemTestUtils.mkdirs(managedFilesetPath, gravitinoFileSystem);
+
+ FileSystemTestUtils.mkdirs(managedFilesetPath, gravitinoFileSystem);
+ assertTrue(gravitinoFileSystem.exists(managedFilesetPath));
+ assertTrue(gravitinoFileSystem.getFileStatus(managedFilesetPath).isDirectory());
+ assertTrue(localFileSystem.exists(localDirPath));
+
+ FileStatus gravitinoStatus = gravitinoFileSystem.getFileStatus(managedFilesetPath);
+ FileStatus localStatus = localFileSystem.getFileStatus(localDirPath);
+ gravitinoFileSystem.delete(managedFilesetPath, true);
+
+ assertFalse(gravitinoFileSystem.exists(managedFilesetPath));
+ assertEquals(
+ localStatus.getPath().toString(),
+ gravitinoStatus
+ .getPath()
+ .toString()
+ .replaceFirst(
+ GravitinoVirtualFileSystemConfiguration.GVFS_FILESET_PREFIX,
+ FileSystemTestUtils.localRootPrefix()));
+ }
+ }
+
+ @Test
+ public void testListStatus() throws IOException {
+ try (FileSystem gravitinoFileSystem = managedFilesetPath.getFileSystem(conf);
+ FileSystem localFileSystem = localDirPath.getFileSystem(conf)) {
+
+ FileSystemTestUtils.mkdirs(managedFilesetPath, gravitinoFileSystem);
+
+ FileSystemTestUtils.mkdirs(managedFilesetPath, gravitinoFileSystem);
+ assertTrue(gravitinoFileSystem.exists(managedFilesetPath));
+ assertTrue(gravitinoFileSystem.getFileStatus(managedFilesetPath).isDirectory());
+ assertTrue(localFileSystem.exists(localDirPath));
+
+ for (int i = 0; i < 5; i++) {
+ Path subPath = new Path(managedFilesetPath + "/sub" + i);
+ FileSystemTestUtils.mkdirs(subPath, gravitinoFileSystem);
+ assertTrue(gravitinoFileSystem.exists(subPath));
+ assertTrue(gravitinoFileSystem.getFileStatus(subPath).isDirectory());
+ }
+
+ List<FileStatus> gravitinoStatuses =
+ new ArrayList<>(Arrays.asList(gravitinoFileSystem.listStatus(managedFilesetPath)));
+ gravitinoStatuses.sort(Comparator.comparing(FileStatus::getPath));
+ assertEquals(5, gravitinoStatuses.size());
+
+ List<FileStatus> localStatuses =
+ new ArrayList<>(Arrays.asList(localFileSystem.listStatus(localDirPath)));
+ localStatuses.sort(Comparator.comparing(FileStatus::getPath));
+ assertEquals(5, localStatuses.size());
+
+ for (int i = 0; i < 5; i++) {
+ assertEquals(
+ localStatuses.get(i).getPath().toString(),
+ gravitinoStatuses
+ .get(i)
+ .getPath()
+ .toString()
+ .replaceFirst(
+ GravitinoVirtualFileSystemConfiguration.GVFS_FILESET_PREFIX,
+ FileSystemTestUtils.localRootPrefix()));
+ gravitinoFileSystem.delete(gravitinoStatuses.get(i).getPath(), true);
+ }
+ }
+ }
+
+ @Test
+ public void testMkdirs() throws IOException {
+ try (FileSystem gravitinoFileSystem = managedFilesetPath.getFileSystem(conf);
+ FileSystem localFileSystem = localDirPath.getFileSystem(conf)) {
+
+ FileSystemTestUtils.mkdirs(managedFilesetPath, gravitinoFileSystem);
+
+ FileSystemTestUtils.mkdirs(managedFilesetPath, gravitinoFileSystem);
+ assertTrue(gravitinoFileSystem.exists(managedFilesetPath));
+ assertTrue(gravitinoFileSystem.getFileStatus(managedFilesetPath).isDirectory());
+
+ FileStatus gravitinoStatus = gravitinoFileSystem.getFileStatus(managedFilesetPath);
+ FileStatus localStatus = localFileSystem.getFileStatus(localDirPath);
+ gravitinoFileSystem.delete(managedFilesetPath, true);
+ assertFalse(gravitinoFileSystem.exists(managedFilesetPath));
+
+ assertEquals(
+ localStatus.getPath().toString(),
+ gravitinoStatus
+ .getPath()
+ .toString()
+ .replaceFirst(
+ GravitinoVirtualFileSystemConfiguration.GVFS_FILESET_PREFIX,
+ FileSystemTestUtils.localRootPrefix()));
+ }
+ }
+}
diff --git a/settings.gradle.kts b/settings.gradle.kts
index d41fa3dcef..a98a37c21e 100644
--- a/settings.gradle.kts
+++ b/settings.gradle.kts
@@ -20,7 +20,7 @@ include(
)
include("catalogs:catalog-hadoop")
include("catalogs:catalog-messaging-kafka")
-include("clients:client-java", "clients:client-java-runtime")
+include("clients:client-java", "clients:client-java-runtime", "clients:filesystem-hadoop3", "clients:filesystem-hadoop3-runtime")
include("trino-connector")
include("spark-connector")
include("web")