Skip to content

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

[#6956] feat(GVFS): make Python GVFS operations customizable (#6964)

mchadesdfbc3f375359
diff --git a/clients/client-python/gravitino/filesystem/gvfs.py b/clients/client-python/gravitino/filesystem/gvfs.py
index 8b59739135..9347879e3e 100644
--- a/clients/client-python/gravitino/filesystem/gvfs.py
+++ b/clients/client-python/gravitino/filesystem/gvfs.py
@@ -14,92 +14,33 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
+import functools
import importlib
import logging
-import os
import re
-import sys
+from typing import Dict, Callable
-# Disable C0302: Too many lines in module
-# pylint: disable=C0302
-import time
-from enum import Enum
-from pathlib import PurePosixPath
-from typing import Dict, Tuple, List, Optional
import fsspec
-from cachetools import TTLCache, LRUCache
-from fsspec import AbstractFileSystem
-from fsspec.implementations.arrow import ArrowFSWrapper
-from fsspec.implementations.local import LocalFileSystem
-from fsspec.utils import infer_storage_options
-from readerwriterlock import rwlock
-from gravitino.api.catalog import Catalog
-from gravitino.api.credential.adls_token_credential import ADLSTokenCredential
-from gravitino.api.credential.azure_account_key_credential import (
- AzureAccountKeyCredential,
-)
-from gravitino.api.credential.credential import Credential
-from gravitino.api.credential.gcs_token_credential import GCSTokenCredential
-from gravitino.api.credential.oss_secret_key_credential import OSSSecretKeyCredential
-from gravitino.api.credential.oss_token_credential import OSSTokenCredential
-from gravitino.api.credential.s3_secret_key_credential import S3SecretKeyCredential
-from gravitino.api.credential.s3_token_credential import S3TokenCredential
-from gravitino.audit.caller_context import CallerContext, CallerContextHolder
-from gravitino.audit.fileset_audit_constants import FilesetAuditConstants
from gravitino.audit.fileset_data_operation import FilesetDataOperation
-from gravitino.audit.internal_client_type import InternalClientType
-from gravitino.client.fileset_catalog import FilesetCatalog
-from gravitino.client.generic_fileset import GenericFileset
from gravitino.exceptions.base import (
GravitinoRuntimeException,
NoSuchCatalogException,
CatalogNotInUseException,
NoSuchFilesetException,
+ NoSuchLocationNameException,
)
-from gravitino.filesystem.gvfs_config import GVFSConfig
-from gravitino.filesystem.gvfs_utils import (
- create_client,
- extract_identifier,
- get_sub_path_from_virtual_path,
+from gravitino.filesystem.gvfs_base_operations import (
+ BaseGVFSOperations,
+ FilesetPathNotFoundError,
)
-from gravitino.name_identifier import NameIdentifier
+from gravitino.filesystem.gvfs_config import GVFSConfig
+from gravitino.filesystem.gvfs_default_operations import DefaultGVFSOperations
logger = logging.getLogger(__name__)
PROTOCOL_NAME = "gvfs"
-TIME_WITHOUT_EXPIRATION = sys.maxsize
-
-
-class StorageType(Enum):
- HDFS = "hdfs"
- LOCAL = "file"
- GCS = "gs"
- S3A = "s3a"
- OSS = "oss"
- ABS = "abfss"
-
-
-class FilesetPathNotFoundError(FileNotFoundError):
- """Exception raised when the catalog, schema or fileset is not found in the GVFS path."""
-
-
-class FilesetContextPair:
- """A context object that holds the information about the actual file location and the file system which used in
- the GravitinoVirtualFileSystem's operations.
- """
-
- def __init__(self, actual_file_location: str, filesystem: AbstractFileSystem):
- self._actual_file_location = actual_file_location
- self._filesystem = filesystem
-
- def actual_file_location(self):
- return self._actual_file_location
-
- def filesystem(self):
- return self._filesystem
-
class GravitinoVirtualFileSystem(fsspec.AbstractFileSystem):
"""This is a virtual file system that users can access `fileset` and
@@ -110,14 +51,10 @@ class GravitinoVirtualFileSystem(fsspec.AbstractFileSystem):
access the underlying storage.
"""
- # Disable R0902: Too many instance attributes
- # pylint: disable=R0902
-
# Override the parent variable
protocol = PROTOCOL_NAME
_identifier_pattern = re.compile("^fileset/([^/]+)/([^/]+)/([^/]+)(?:/[^/]+)*/?$")
SLASH = "/"
- ENV_CURRENT_LOCATION_NAME_ENV_VAR_DEFAULT = "CURRENT_LOCATION_NAME"
def __init__(
self,
@@ -132,37 +69,49 @@ class GravitinoVirtualFileSystem(fsspec.AbstractFileSystem):
:param options: Options for the GravitinoVirtualFileSystem
:param kwargs: Extra args for super filesystem
"""
- self._metalake = metalake_name
- self._client = create_client(options, server_uri, metalake_name)
- cache_size = (
- GVFSConfig.DEFAULT_CACHE_SIZE
- if options is None
- else options.get(GVFSConfig.CACHE_SIZE, GVFSConfig.DEFAULT_CACHE_SIZE)
+ self._operations = self._get_gvfs_operations_class(
+ server_uri, metalake_name, options
)
- cache_expired_time = (
- GVFSConfig.DEFAULT_CACHE_EXPIRED_TIME
- if options is None
- else options.get(
- GVFSConfig.CACHE_EXPIRED_TIME, GVFSConfig.DEFAULT_CACHE_EXPIRED_TIME
- )
- )
- self._cache = TTLCache(maxsize=cache_size, ttl=cache_expired_time)
- self._cache_lock = rwlock.RWLockFair()
- self._catalog_cache = LRUCache(maxsize=100)
- self._catalog_cache_lock = rwlock.RWLockFair()
- self._options = options
- self._current_location_name = self._init_current_location_name()
super().__init__(**kwargs)
- @property
- def cache(self):
- return self._cache
-
@property
def fsid(self):
return PROTOCOL_NAME
+ @property
+ def operations(self):
+ return self._operations
+
+ @staticmethod
+ def _with_exception_translation(operation: FilesetDataOperation):
+ """
+ Decorator to translate fileset metadata not found exceptions into FilesetPathNotFoundError.
+ :param operation: The operation being performed.
+ """
+
+ def decorator(func: Callable):
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ try:
+ return func(*args, **kwargs)
+ except (NoSuchCatalogException, CatalogNotInUseException) as e:
+ message = f"Cannot get fileset catalog during {operation}"
+ logger.warning("%s, %s", message, str(e))
+ raise FilesetPathNotFoundError(message) from e
+ except NoSuchFilesetException as e:
+ message = f"Cannot get fileset during {operation}"
+ logger.warning("%s, %s", message, str(e))
+ raise FilesetPathNotFoundError(message) from e
+ except NoSuchLocationNameException as e:
+ message = f"Cannot find location name during {operation}"
+ logger.warning("%s, %s", message, str(e))
+ raise FilesetPathNotFoundError(message) from e
+
+ return wrapper
+
+ return decorator
+
def sign(self, path, expiration=None, **kwargs):
"""We do not support to create a signed URL representing the given path in gvfs."""
raise GravitinoRuntimeException(
@@ -176,46 +125,10 @@ class GravitinoVirtualFileSystem(fsspec.AbstractFileSystem):
:param kwargs: Extra args
:return If details is true, returns a list of file info dicts, else returns a list of file paths
"""
- context_pair: FilesetContextPair = self._get_fileset_context(
- path, FilesetDataOperation.LIST_STATUS
- )
- self._throw_fileset_path_not_found_error_if(
- context_pair is None, path, FilesetDataOperation.LIST_STATUS
- )
-
- actual_path = context_pair.actual_file_location()
- storage_type = self._recognize_storage_type(actual_path)
- pre_process_path: str = self._pre_process_path(path)
- identifier: NameIdentifier = extract_identifier(
- self._metalake, pre_process_path
- )
- sub_path: str = get_sub_path_from_virtual_path(identifier, pre_process_path)
- storage_location: str = actual_path[: len(actual_path) - len(sub_path)]
- # return entries with details
- if detail:
- entries = context_pair.filesystem().ls(
- self._strip_storage_protocol(storage_type, actual_path),
- detail=True,
- )
- virtual_entries = [
- self._convert_actual_info(
- entry, storage_location, self._get_virtual_location(identifier)
- )
- for entry in entries
- ]
- return virtual_entries
- # only returns paths
- entry_paths = context_pair.filesystem().ls(
- self._strip_storage_protocol(storage_type, actual_path),
- detail=False,
- )
- virtual_entry_paths = [
- self._convert_actual_path(
- entry_path, storage_location, self._get_virtual_location(identifier)
- )
- for entry_path in entry_paths
- ]
- return virtual_entry_paths
+ decorated_ls = self._with_exception_translation(
+ FilesetDataOperation.LIST_STATUS
+ )(self._operations.ls)
+ return decorated_ls(path, detail, **kwargs)
def info(self, path, **kwargs):
"""Get file info.
@@ -223,27 +136,10 @@ class GravitinoVirtualFileSystem(fsspec.AbstractFileSystem):
:param kwargs: Extra args
:return A file info dict
"""
- context_pair: FilesetContextPair = self._get_fileset_context(
- path, FilesetDataOperation.GET_FILE_STATUS
- )
- self._throw_fileset_path_not_found_error_if(
- context_pair is None, path, FilesetDataOperation.GET_FILE_STATUS
- )
-
- actual_path = context_pair.actual_file_location()
- storage_type = self._recognize_storage_type(actual_path)
- pre_process_path: str = self._pre_process_path(path)
- identifier: NameIdentifier = extract_identifier(
- self._metalake, pre_process_path
- )
- sub_path: str = get_sub_path_from_virtual_path(identifier, pre_process_path)
- storage_location: str = actual_path[: len(actual_path) - len(sub_path)]
- actual_info: Dict = context_pair.filesystem().info(
- self._strip_storage_protocol(storage_type, actual_path)
- )
- return self._convert_actual_info(
- actual_info, storage_location, self._get_virtual_location(identifier)
- )
+ decorated_info = self._with_exception_translation(
+ FilesetDataOperation.GET_FILE_STATUS
+ )(self._operations.info)
+ return decorated_info(path, **kwargs)
def exists(self, path, **kwargs):
"""Check if a file or a directory exists.
@@ -251,52 +147,24 @@ class GravitinoVirtualFileSystem(fsspec.AbstractFileSystem):
:param kwargs: Extra args
:return If a file or directory exists, it returns True, otherwise False
"""
- context_pair: FilesetContextPair = self._get_fileset_context(
- path, FilesetDataOperation.EXISTS
- )
- if context_pair is None:
+ decorated_exists = self._with_exception_translation(
+ FilesetDataOperation.EXISTS
+ )(self._operations.exists)
+ try:
+ return decorated_exists(path, **kwargs)
+ except FilesetPathNotFoundError:
return False
- actual_path = context_pair.actual_file_location()
- storage_type = self._recognize_storage_type(actual_path)
- return context_pair.filesystem().exists(
- self._strip_storage_protocol(storage_type, actual_path)
- )
-
def cp_file(self, path1, path2, **kwargs):
"""Copy a file.
:param path1: Virtual src fileset path
:param path2: Virtual dst fileset path, should be consistent with the src path fileset identifier
:param kwargs: Extra args
"""
- src_path = self._pre_process_path(path1)
- dst_path = self._pre_process_path(path2)
- src_identifier: NameIdentifier = extract_identifier(self._metalake, src_path)
- dst_identifier: NameIdentifier = extract_identifier(self._metalake, dst_path)
- if src_identifier != dst_identifier:
- raise GravitinoRuntimeException(
- f"Destination file path identifier: `{dst_identifier}` should be same with src file path "
- f"identifier: `{src_identifier}`."
- )
- src_context_pair: FilesetContextPair = self._get_fileset_context(
- src_path, FilesetDataOperation.COPY_FILE
- )
- self._throw_fileset_path_not_found_error_if(
- src_context_pair is None, src_path, FilesetDataOperation.COPY_FILE
- )
-
- src_actual_path = src_context_pair.actual_file_location()
-
- dst_context_pair: FilesetContextPair = self._get_fileset_context(
- dst_path, FilesetDataOperation.COPY_FILE
- )
- dst_actual_path = dst_context_pair.actual_file_location()
-
- storage_type = self._recognize_storage_type(src_actual_path)
- src_context_pair.filesystem().cp_file(
- self._strip_storage_protocol(storage_type, src_actual_path),
- self._strip_storage_protocol(storage_type, dst_actual_path),
- )
+ decorated_cp_file = self._with_exception_translation(
+ FilesetDataOperation.COPY_FILE
+ )(self._operations.cp_file)
+ return decorated_cp_file(path1, path2, **kwargs)
def mv(self, path1, path2, recursive=False, maxdepth=None, **kwargs):
"""Move a file to another directory.
@@ -308,65 +176,16 @@ class GravitinoVirtualFileSystem(fsspec.AbstractFileSystem):
:param maxdepth: Maximum depth of recursive move
:param kwargs: Extra args
"""
- src_path = self._pre_process_path(path1)
- dst_path = self._pre_process_path(path2)
- src_identifier: NameIdentifier = extract_identifier(self._metalake, src_path)
- dst_identifier: NameIdentifier = extract_identifier(self._metalake, dst_path)
- if src_identifier != dst_identifier:
- raise GravitinoRuntimeException(
- f"Destination file path identifier: `{dst_identifier}`"
- f" should be same with src file path identifier: `{src_identifier}`."
- )
-
- src_context_pair: FilesetContextPair = self._get_fileset_context(
- src_path, FilesetDataOperation.RENAME
+ decorated_mv = self._with_exception_translation(FilesetDataOperation.RENAME)(
+ self._operations.mv
)
- self._throw_fileset_path_not_found_error_if(
- src_context_pair is None, src_path, FilesetDataOperation.RENAME
- )
-
- src_actual_path = src_context_pair.actual_file_location()
- storage_type = self._recognize_storage_type(src_actual_path)
-
- dst_context_pair: FilesetContextPair = self._get_fileset_context(
- dst_path, FilesetDataOperation.RENAME
- )
- dst_actual_path = dst_context_pair.actual_file_location()
-
- # convert the following to in
-
- if storage_type in [
- StorageType.HDFS,
- StorageType.GCS,
- StorageType.S3A,
- StorageType.OSS,
- StorageType.ABS,
- ]:
- src_context_pair.filesystem().mv(
- self._strip_storage_protocol(storage_type, src_actual_path),
- self._strip_storage_protocol(storage_type, dst_actual_path),
- )
- elif storage_type == StorageType.LOCAL:
- src_context_pair.filesystem().mv(
- self._strip_storage_protocol(storage_type, src_actual_path),
- self._strip_storage_protocol(storage_type, dst_actual_path),
- recursive,
- maxdepth,
- )
- else:
- raise GravitinoRuntimeException(
- f"Storage type:{storage_type} doesn't support now."
- )
+ decorated_mv(path1, path2, recursive, maxdepth, **kwargs)
def _rm(self, path):
raise GravitinoRuntimeException(
"Deprecated method, use `rm_file` method instead."
)
- def lazy_load_class(self, module_name, class_name):
- module = importlib.import_module(module_name)
- return getattr(module, class_name)
-
def rm(self, path, recursive=False, maxdepth=None):
"""Remove a file or directory.
:param path: Virtual fileset path
@@ -374,43 +193,19 @@ class GravitinoVirtualFileSystem(fsspec.AbstractFileSystem):
When removing a directory, this parameter should be True.
:param maxdepth: The maximum depth to remove the directory recursively.
"""
- context_pair: FilesetContextPair = self._get_fileset_context(
- path, FilesetDataOperation.DELETE
+ decorated_rm = self._with_exception_translation(FilesetDataOperation.DELETE)(
+ self._operations.rm
)
- self._throw_fileset_path_not_found_error_if(
- context_pair is None, path, FilesetDataOperation.DELETE
- )
-
- actual_path = context_pair.actual_file_location()
- storage_type = self._recognize_storage_type(actual_path)
- fs = context_pair.filesystem()
-
- # S3FileSystem doesn't support maxdepth
- if isinstance(fs, self.lazy_load_class("s3fs", "S3FileSystem")):
- fs.rm(self._strip_storage_protocol(storage_type, actual_path), recursive)
- else:
- fs.rm(
- self._strip_storage_protocol(storage_type, actual_path),
- recursive,
- maxdepth,
- )
+ decorated_rm(path, recursive, maxdepth)
def rm_file(self, path):
"""Remove a file.
:param path: Virtual fileset path
"""
- context_pair: FilesetContextPair = self._get_fileset_context(
- path, FilesetDataOperation.DELETE
- )
- self._throw_fileset_path_not_found_error_if(
- context_pair is None, path, FilesetDataOperation.DELETE
- )
-
- actual_path = context_pair.actual_file_location()
- storage_type = self._recognize_storage_type(actual_path)
- context_pair.filesystem().rm_file(
- self._strip_storage_protocol(storage_type, actual_path)
- )
+ decorated_rm_file = self._with_exception_translation(
+ FilesetDataOperation.DELETE
+ )(self._operations.rm_file)
+ decorated_rm_file(path)
def rmdir(self, path):
"""Remove a directory.
@@ -418,18 +213,10 @@ class GravitinoVirtualFileSystem(fsspec.AbstractFileSystem):
And it will throw an exception if delete a directory which is non-empty for LocalFileSystem.
:param path: Virtual fileset path
"""
- context_pair: FilesetContextPair = self._get_fileset_context(
- path, FilesetDataOperation.DELETE
- )
- self._throw_fileset_path_not_found_error_if(
- context_pair is None, path, FilesetDataOperation.DELETE
- )
-
- actual_path = context_pair.actual_file_location()
- storage_type = self._recognize_storage_type(actual_path)
- context_pair.filesystem().rmdir(
- self._strip_storage_protocol(storage_type, actual_path)
+ decorated_rmdir = self._with_exception_translation(FilesetDataOperation.DELETE)(
+ self._operations.rmdir
)
+ decorated_rmdir(path)
def open(
self,
@@ -456,29 +243,26 @@ class GravitinoVirtualFileSystem(fsspec.AbstractFileSystem):
else:
data_operation = FilesetDataOperation.OPEN
- context_pair: FilesetContextPair = self._get_fileset_context(
- path, data_operation
+ decorated_open = self._with_exception_translation(data_operation)(
+ self._operations.open
)
- if context_pair is None:
+ try:
+ return decorated_open(
+ path,
+ mode,
+ block_size,
+ cache_options,
+ compression,
+ **kwargs,
+ )
+ except FilesetPathNotFoundError as e:
if mode in ("w", "wb", "x", "xb", "a", "ab"):
raise OSError(
f"Fileset is not found for path: {path} for operation OPEN. This "
f"may be caused by fileset related metadata not found or not in use "
f"in Gravitino,"
- )
-
- raise FilesetPathNotFoundError(f"Path {path} not found for operation OPEN.")
-
- actual_path = context_pair.actual_file_location()
- storage_type = self._recognize_storage_type(actual_path)
- return context_pair.filesystem().open(
- self._strip_storage_protocol(storage_type, actual_path),
- mode,
- block_size,
- cache_options,
- compression,
- **kwargs,
- )
+ ) from e
+ raise
def mkdir(self, path, create_parents=True, **kwargs):
"""Make a directory.
@@ -488,45 +272,34 @@ class GravitinoVirtualFileSystem(fsspec.AbstractFileSystem):
:param create_parents: Create parent directories if missing when set to True
:param kwargs: Extra args
"""
- context_pair: FilesetContextPair = self._get_fileset_context(
- path, FilesetDataOperation.MKDIRS
+ decorated_mkdir = self._with_exception_translation(FilesetDataOperation.MKDIRS)(
+ self._operations.mkdir
)
- if context_pair is None:
+ try:
+ decorated_mkdir(path, create_parents, **kwargs)
+ except FilesetPathNotFoundError as e:
raise OSError(
f"Fileset is not found for path: {path} for operation MKDIRS. This "
f"may be caused by fileset related metadata not found or not in use "
f"in Gravitino,"
- )
-
- actual_path = context_pair.actual_file_location()
- storage_type = self._recognize_storage_type(actual_path)
- context_pair.filesystem().mkdir(
- self._strip_storage_protocol(storage_type, actual_path),
- create_parents,
- **kwargs,
- )
+ ) from e
def makedirs(self, path, exist_ok=True):
"""Make a directory recursively.
:param path: Virtual fileset path
:param exist_ok: Continue if a directory already exists
"""
- context_pair: FilesetContextPair = self._get_fileset_context(
- path, FilesetDataOperation.MKDIRS
- )
- if context_pair is None:
+ decorated_makedirs = self._with_exception_translation(
+ FilesetDataOperation.MKDIRS
+ )(self._operations.makedirs)
+ try:
+ decorated_makedirs(path, exist_ok)
+ except FilesetPathNotFoundError as e:
raise OSError(
f"Fileset is not found for path: {path} for operation MKDIRS. This "
f"may be caused by fileset related metadata not found or not in use "
f"in Gravitino,"
- )
-
- actual_path = context_pair.actual_file_location()
- storage_type = self._recognize_storage_type(actual_path)
- context_pair.filesystem().makedirs(
- self._strip_storage_protocol(storage_type, actual_path),
- exist_ok,
- )
+ ) from e
def created(self, path):
"""Return the created timestamp of a file as a datetime.datetime
@@ -534,40 +307,20 @@ class GravitinoVirtualFileSystem(fsspec.AbstractFileSystem):
:param path: Virtual fileset path
:return Created time(datetime.datetime)
"""
- context_pair: FilesetContextPair = self._get_fileset_context(
- path, FilesetDataOperation.CREATED_TIME
- )
- self._throw_fileset_path_not_found_error_if(
- context_pair is None, path, FilesetDataOperation.CREATED_TIME
- )
-
- actual_path = context_pair.actual_file_location()
- storage_type = self._recognize_storage_type(actual_path)
- if storage_type == StorageType.LOCAL:
- return context_pair.filesystem().created(
- self._strip_storage_protocol(storage_type, actual_path)
- )
- raise GravitinoRuntimeException(
- f"Storage type:{storage_type} doesn't support now."
- )
+ decorated_created = self._with_exception_translation(
+ FilesetDataOperation.CREATED_TIME
+ )(self._operations.created)
+ return decorated_created(path)
def modified(self, path):
"""Returns the modified time of the path file if it exists.
:param path: Virtual fileset path
:return Modified time(datetime.datetime)
"""
- context_pair: FilesetContextPair = self._get_fileset_context(
- path, FilesetDataOperation.MODIFIED_TIME
- )
- self._throw_fileset_path_not_found_error_if(
- context_pair is None, path, FilesetDataOperation.MODIFIED_TIME
- )
-
- actual_path = context_pair.actual_file_location()
- storage_type = self._recognize_storage_type(actual_path)
- return context_pair.filesystem().modified(
- self._strip_storage_protocol(storage_type, actual_path)
- )
+ decorated_modified = self._with_exception_translation(
+ FilesetDataOperation.MODIFIED_TIME
+ )(self._operations.modified)
+ return decorated_modified(path)
def cat_file(self, path, start=None, end=None, **kwargs):
"""Get the content of a file.
@@ -577,21 +330,10 @@ class GravitinoVirtualFileSystem(fsspec.AbstractFileSystem):
:param kwargs: Extra args
:return File content
"""
- context_pair: FilesetContextPair = self._get_fileset_context(
- path, FilesetDataOperation.CAT_FILE
- )
- self._throw_fileset_path_not_found_error_if(
- context_pair is None, path, FilesetDataOperation.CAT_FILE
- )
-
- actual_path = context_pair.actual_file_location()
- storage_type = self._recognize_storage_type(actual_path)
- return context_pair.filesystem().cat_file(
- self._strip_storage_protocol(storage_type, actual_path),
- start,
- end,
- **kwargs,
- )
+ decorated_cat_file = self._with_exception_translation(
+ FilesetDataOperation.CAT_FILE
+ )(self._operations.cat_file)
+ return decorated_cat_file(path, start, end, **kwargs)
def get_file(self, rpath, lpath, callback=None, outfile=None, **kwargs):
"""Copy single remote file to local.
@@ -601,680 +343,39 @@ class GravitinoVirtualFileSystem(fsspec.AbstractFileSystem):
:param outfile: The output file path
:param kwargs: Extra args
"""
- if not lpath.startswith(f"{StorageType.LOCAL.value}:") and not lpath.startswith(
- "/"
- ):
- raise GravitinoRuntimeException(
- "Doesn't support copy a remote gvfs file to an another remote file."
- )
-
- context_pair: FilesetContextPair = self._get_fileset_context(
- rpath, FilesetDataOperation.GET_FILE
- )
- self._throw_fileset_path_not_found_error_if(
- context_pair is None, rpath, FilesetDataOperation.GET_FILE
- )
-
- actual_path = context_pair.actual_file_location()
- storage_type = self._recognize_storage_type(actual_path)
- context_pair.filesystem().get_file(
- self._strip_storage_protocol(storage_type, actual_path),
+ decorated_get_file = self._with_exception_translation(
+ FilesetDataOperation.GET_FILE_STATUS
+ )(self._operations.get_file)
+ decorated_get_file(
+ rpath,
lpath,
+ callback,
+ outfile,
**kwargs,
)
- def _init_current_location_name(self):
- """Initialize the current location name.
- get from configuration first, otherwise use the env variable
- if both are not set, return null which means use the default location
- :return: The current location name
- """
- current_location_name_env_var = (
- self._options.get(GVFSConfig.GVFS_FILESYSTEM_CURRENT_LOCATION_NAME_ENV_VAR)
- if self._options
- else None
- ) or self.ENV_CURRENT_LOCATION_NAME_ENV_VAR_DEFAULT
-
- return (
- self._options.get(GVFSConfig.GVFS_FILESYSTEM_CURRENT_LOCATION_NAME)
- if self._options
- else None
- ) or os.environ.get(current_location_name_env_var)
-
- def _convert_actual_path(
+ def _get_gvfs_operations_class(
self,
- actual_path: str,
- storage_location: str,
- virtual_location: str,
- ):
- """Convert an actual path to a virtual path.
- The virtual path is like `fileset/{catalog}/{schema}/{fileset}/xxx`.
- :param actual_path: Actual path
- :param storage_location: Storage location
- :param virtual_location: Virtual location
- :return A virtual path
- """
-
- # If the storage path starts with hdfs, gcs, we should use the path as the prefix.
- if (
- storage_location.startswith(f"{StorageType.HDFS.value}://")
- or storage_location.startswith(f"{StorageType.GCS.value}://")
- or storage_location.startswith(f"{StorageType.S3A.value}://")
- ):
- actual_prefix = infer_storage_options(storage_location)["path"]
- elif storage_location.startswith(f"{StorageType.OSS.value}:/"):
- ops = infer_storage_options(storage_location)
- if "host" not in ops or "path" not in ops:
- raise GravitinoRuntimeException(
- f"Storage location:{storage_location} doesn't support now."
- )
-
- actual_prefix = ops["host"] + ops["path"]
- elif storage_location.startswith(f"{StorageType.ABS.value}://"):
- ops = infer_storage_options(storage_location)
- if "username" not in ops or "host" not in ops or "path" not in ops:
- raise GravitinoRuntimeException(
- f"Storage location:{storage_location} doesn't support now, the username,"
- f"host and path are required in the storage location."
- )
- actual_prefix = f"{StorageType.ABS.value}://{ops['username']}@{ops['host']}{ops['path']}"
-
- # the actual path may be '{container}/{path}', we need to add the host and username
- # get the path from {container}/{path}
- if not actual_path.startswith(f"{StorageType.ABS}"):
- path_without_username = actual_path[actual_path.index("/") + 1 :]
- actual_path = f"{StorageType.ABS.value}://{ops['username']}@{ops['host']}/{path_without_username}"
-
- elif storage_location.startswith(f"{StorageType.LOCAL.value}:/"):
- actual_prefix = storage_location[len(f"{StorageType.LOCAL.value}:") :]
- else:
- raise GravitinoRuntimeException(
- f"Storage location:{storage_location} doesn't support now."
- )
-
- if not actual_path.startswith(actual_prefix):
- raise GravitinoRuntimeException(
- f"Path {actual_path} does not start with valid prefix {actual_prefix}."
- )
-
- # if the storage location is end with "/",
- # we should truncate this to avoid replace issues.
- if actual_prefix.endswith(self.SLASH) and not virtual_location.endswith(
- self.SLASH
- ):
- return f"{actual_path.replace(actual_prefix[:-1], virtual_location)}"
- return f"{actual_path.replace(actual_prefix, virtual_location)}"
-
- def _convert_actual_info(
- self,
- entry: Dict,
- storage_location: str,
- virtual_location: str,
- ):
- """Convert a file info from an actual entry to a virtual entry.
- :param entry: A dict of the actual file info
- :param storage_location: Storage location
- :param virtual_location: Virtual location
- :return A dict of the virtual file info
- """
- path = self._convert_actual_path(
- entry["name"], storage_location, virtual_location
- )
-
- last_modified = None
- if "mtime" in entry:
- # HDFS and GCS
- last_modified = entry["mtime"]
- elif "LastModified" in entry:
- # S3 and OSS
- last_modified = entry["LastModified"]
- elif "last_modified" in entry:
- # Azure Blob Storage
- last_modified = entry["last_modified"]
-
- return {
- "name": path,
- "size": entry["size"],
- "type": entry["type"],
- "mtime": last_modified,
- }
-
- def _get_fileset_context(
- self, virtual_path: str, operation: FilesetDataOperation
- ) -> Optional[FilesetContextPair]:
- """Get a fileset context from the cache or the Gravitino server
- :param virtual_path: The virtual path
- :param operation: The data operation
- :return A fileset context pair
- """
- virtual_path: str = self._pre_process_path(virtual_path)
- identifier: NameIdentifier = extract_identifier(self._metalake, virtual_path)
- catalog_ident: NameIdentifier = NameIdentifier.of(
- self._metalake, identifier.namespace().level(1)
- )
-
- try:
- fileset_catalog = self._get_fileset_catalog(catalog_ident)
- except (NoSuchCatalogException, CatalogNotInUseException):
- logger.warning(
- "Cannot get fileset catalog by identifier: %s",
- catalog_ident,
- exc_info=True,
- )
- return None
-
- if fileset_catalog is None:
- raise GravitinoRuntimeException(
- f"Loaded fileset catalog: {catalog_ident} is null."
- )
- sub_path: str = get_sub_path_from_virtual_path(identifier, virtual_path)
- context = {
- FilesetAuditConstants.HTTP_HEADER_FILESET_DATA_OPERATION: operation.name,
- FilesetAuditConstants.HTTP_HEADER_INTERNAL_CLIENT_TYPE: InternalClientType.PYTHON_GVFS.name,
- }
- caller_context: CallerContext = CallerContext(context)
- CallerContextHolder.set(caller_context)
-
- try:
- actual_file_location: (
- str
- ) = fileset_catalog.as_fileset_catalog().get_file_location(
- NameIdentifier.of(identifier.namespace().level(2), identifier.name()),
- sub_path,
- self._current_location_name,
- )
- except NoSuchFilesetException:
- logger.warning(
- "Cannot get file location by identifier: %s, sub_path: %s",
- identifier,
- sub_path,
- exc_info=True,
- )
- return None
-
- return FilesetContextPair(
- actual_file_location,
- self._get_filesystem(
- actual_file_location,
- fileset_catalog,
- identifier,
- self._current_location_name,
- ),
- )
-
- @staticmethod
- def _get_virtual_location(identifier: NameIdentifier):
- """Get the virtual location of the fileset.
- :param identifier: The name identifier of the fileset
- :return The virtual location.
- """
- return (
- f"fileset/{identifier.namespace().level(1)}"
- f"/{identifier.namespace().level(2)}"
- f"/{identifier.name()}"
- )
-
- @staticmethod
- def _pre_process_path(virtual_path):
- """Pre-process the path.
- We will uniformly process `gvfs://fileset/{catalog}/{schema}/{fileset_name}/xxx`
- into the format of `fileset/{catalog}/{schema}/{fileset_name}/xxx`.
- This is because some implementations of `PyArrow` and `fsspec` can only recognize this format.
- :param virtual_path: The virtual path
- :return The pre-processed path
- """
- if isinstance(virtual_path, PurePosixPath):
- pre_processed_path = virtual_path.as_posix()
- else:
- pre_processed_path = virtual_path
- gvfs_prefix = f"{PROTOCOL_NAME}://"
- if pre_processed_path.startswith(gvfs_prefix):
- pre_processed_path = pre_processed_path[len(gvfs_prefix) :]
- if not pre_processed_path.startswith("fileset/"):
- raise GravitinoRuntimeException(
- f"Invalid path:`{pre_processed_path}`. Expected path to start with `fileset/`."
- " Example: fileset/{fileset_catalog}/{schema}/{fileset_name}/{sub_path}."
- )
- return pre_processed_path
-
- @staticmethod
- def _recognize_storage_type(path: str):
- """Recognize the storage type by the path.
- :param path: The path
- :return: The storage type
- """
- if path.startswith(f"{StorageType.HDFS.value}://"):
- return StorageType.HDFS
- if path.startswith(f"{StorageType.LOCAL.value}:/"):
- return StorageType.LOCAL
- if path.startswith(f"{StorageType.GCS.value}://"):
- return StorageType.GCS
- if path.startswith(f"{StorageType.S3A.value}://"):
- return StorageType.S3A
- if path.startswith(f"{StorageType.OSS.value}://"):
- return StorageType.OSS
- if path.startswith(f"{StorageType.ABS.value}://"):
- return StorageType.ABS
- raise GravitinoRuntimeException(
- f"Storage type doesn't support now. Path:{path}"
- )
-
- @staticmethod
- def _strip_storage_protocol(storage_type: StorageType, path: str):
- """Strip the storage protocol from the path.
- Before passing the path to the underlying file system for processing,
- pre-process the protocol information in the path.
- Some file systems require special processing.
- For HDFS, we can pass the path like 'hdfs://{host}:{port}/xxx'.
- For Local, we can pass the path like '/tmp/xxx'.
- :param storage_type: The storage type
- :param path: The path
- :return: The stripped path
-
- We will handle OSS differently from S3 and GCS, because OSS has different behavior than S3 and GCS.
- Please see the following example:
-
- ```
- >> oss = context_pair.filesystem()
- >> oss.ls('oss://bucket-xiaoyu/test_gvfs_catalog678/test_gvfs_schema/test_gvfs_fileset/test_ls')
- DEBUG:ossfs:Get directory listing page for bucket-xiaoyu/test_gvfs_catalog678/
- test_gvfs_schema/test_gvfs_fileset
- DEBUG:ossfs:CALL: ObjectIterator - () - {'prefix': 'test_gvfs_catalog678/test_gvfs_schema
- /test_gvfs_fileset/', 'delimiter': '/'}
- []
- >> oss.ls('bucket-xiaoyu/test_gvfs_catalog678/test_gvfs_schema/test_gvfs_fileset/test_ls')
- DEBUG:ossfs:Get directory listing page for bucket-xiaoyu/test_gvfs_catalog678/test_gvfs_schema
- /test_gvfs_fileset/test_ls
- DEBUG:ossfs:CALL: ObjectIterator - () - {'prefix': 'test_gvfs_catalog678/test_gvfs_schema
- /test_gvfs_fileset/test_ls/', 'delimiter': '/'}
- [{'name': 'bucket-xiaoyu/test_gvfs_catalog678/test_gvfs_schema/test_gvfs_fileset/test_ls
- /test.file', 'type': 'file', 'size': 0, 'LastModified': 1729754793,
- 'Size': 0, 'Key': 'bucket-xiaoyu/test_gvfs_catalog678/test_gvfs_schema/
- test_gvfs_fileset/test_ls/test.file'}]
-
- ```
-
- Please take a look at the above example: if we do not remove the protocol (starts with oss://),
- it will always return an empty array when we call `oss.ls`, however, if we remove the protocol,
- it will produce the correct result as expected.
- """
- if storage_type in (StorageType.HDFS, StorageType.GCS, StorageType.S3A):
- return path
- if storage_type == StorageType.LOCAL:
- return path[len(f"{StorageType.LOCAL.value}:") :]
-
- ## We need to remove the protocol and account from the path, for instance,
- # the path can be converted from 'abfss://container@account/path' to
- # 'container/path'.
- if storage_type == StorageType.ABS:
- ops = infer_storage_options(path)
- return ops["username"] + ops["path"]
-
- # OSS has different behavior than S3 and GCS, if we do not remove the
- # protocol, it will always return an empty array.
- if storage_type == StorageType.OSS:
- if path.startswith(f"{StorageType.OSS.value}://"):
- return path[len(f"{StorageType.OSS.value}://") :]
- return path
-
- raise GravitinoRuntimeException(
- f"Storage type:{storage_type} doesn't support now."
- )
-
- def _get_fileset_catalog(self, catalog_ident: NameIdentifier):
- read_lock = self._catalog_cache_lock.gen_rlock()
- try:
- read_lock.acquire()
- cache_value: Tuple[NameIdentifier, FilesetCatalog] = (
- self._catalog_cache.get(catalog_ident)
- )
- if cache_value is not None:
- return cache_value
- finally:
- read_lock.release()
-
- write_lock = self._catalog_cache_lock.gen_wlock()
- try:
- write_lock.acquire()
- cache_value: Tuple[NameIdentifier, FilesetCatalog] = (
- self._catalog_cache.get(catalog_ident)
- )
- if cache_value is not None:
- return cache_value
- catalog = self._client.load_catalog(catalog_ident.name())
- self._catalog_cache[catalog_ident] = catalog
- return catalog
- finally:
- write_lock.release()
-
- def _file_system_expired(self, expire_time: int):
- return expire_time <= time.time() * 1000
-
- # Disable Too many branches (13/12) (too-many-branches)
- # pylint: disable=R0912
- def _get_filesystem(
- self,
- actual_file_location: str,
- fileset_catalog: Catalog,
- name_identifier: NameIdentifier,
- location_name: str,
- ):
- storage_type = self._recognize_storage_type(actual_file_location)
- read_lock = self._cache_lock.gen_rlock()
- try:
- read_lock.acquire()
- cache_value: Tuple[int, AbstractFileSystem] = self._cache.get(
- (name_identifier, location_name)
- )
- if cache_value is not None:
- if not self._file_system_expired(cache_value[0]):
- return cache_value[1]
- finally:
- read_lock.release()
-
- write_lock = self._cache_lock.gen_wlock()
- try:
- write_lock.acquire()
- cache_value: Tuple[int, AbstractFileSystem] = self._cache.get(
- name_identifier
- )
-
- if cache_value is not None:
- if not self._file_system_expired(cache_value[0]):
- return cache_value[1]
-
- new_cache_value: Tuple[int, AbstractFileSystem]
- if storage_type == StorageType.HDFS:
- fs_class = importlib.import_module("pyarrow.fs").HadoopFileSystem
- new_cache_value = (
- TIME_WITHOUT_EXPIRATION,
- ArrowFSWrapper(fs_class.from_uri(actual_file_location)),
- )
- elif storage_type == StorageType.LOCAL:
- new_cache_value = (TIME_WITHOUT_EXPIRATION, LocalFileSystem())
- elif storage_type == StorageType.GCS:
- new_cache_value = self._get_gcs_filesystem(
- fileset_catalog, name_identifier
- )
- elif storage_type == StorageType.S3A:
- new_cache_value = self._get_s3_filesystem(
- fileset_catalog, name_identifier
- )
- elif storage_type == StorageType.OSS:
- new_cache_value = self._get_oss_filesystem(
- fileset_catalog, name_identifier
- )
- elif storage_type == StorageType.ABS:
- new_cache_value = self._get_abs_filesystem(
- fileset_catalog, name_identifier
- )
- else:
- raise GravitinoRuntimeException(
- f"Storage type: `{storage_type}` doesn't support now."
- )
- self._cache[(name_identifier, location_name)] = new_cache_value
- return new_cache_value[1]
- finally:
- write_lock.release()
-
- def _get_gcs_filesystem(self, fileset_catalog: Catalog, identifier: NameIdentifier):
- fileset: GenericFileset = fileset_catalog.as_fileset_catalog().load_fileset(
- NameIdentifier.of(identifier.namespace().level(2), identifier.name())
- )
- credentials = fileset.support_credentials().get_credentials()
-
- credential = self._get_most_suitable_gcs_credential(credentials)
- if credential is not None:
- expire_time = self._get_expire_time_by_ratio(credential.expire_time_in_ms())
- if isinstance(credential, GCSTokenCredential):
- fs = importlib.import_module("gcsfs").GCSFileSystem(
- token=credential.token()
- )
- return (expire_time, fs)
-
- # get 'service-account-key' from gcs_options, if the key is not found, throw an exception
- service_account_key_path = self._options.get(
- GVFSConfig.GVFS_FILESYSTEM_GCS_SERVICE_KEY_FILE
- )
- if service_account_key_path is None:
- raise GravitinoRuntimeException(
- "Service account key is not found in the options."
- )
- return (
- TIME_WITHOUT_EXPIRATION,
- importlib.import_module("gcsfs").GCSFileSystem(
- token=service_account_key_path
- ),
- )
-
- def _get_s3_filesystem(self, fileset_catalog: Catalog, identifier: NameIdentifier):
- fileset: GenericFileset = fileset_catalog.as_fileset_catalog().load_fileset(
- NameIdentifier.of(identifier.namespace().level(2), identifier.name())
- )
- credentials = fileset.support_credentials().get_credentials()
- credential = self._get_most_suitable_s3_credential(credentials)
-
- # S3 endpoint from gravitino server, Note: the endpoint may not a real S3 endpoint
- # it can be a simulated S3 endpoint, such as minio, so though the endpoint is not a required field
- # for S3FileSystem, we still need to assign the endpoint to the S3FileSystem
- s3_endpoint = fileset_catalog.properties().get("s3-endpoint", None)
- # If the oss endpoint is not found in the fileset catalog, get it from the client options
- if s3_endpoint is None:
- s3_endpoint = self._options.get(GVFSConfig.GVFS_FILESYSTEM_S3_ENDPOINT)
-
- if credential is not None:
- expire_time = self._get_expire_time_by_ratio(credential.expire_time_in_ms())
- if isinstance(credential, S3TokenCredential):
- fs = importlib.import_module("s3fs").S3FileSystem(
- key=credential.access_key_id(),
- secret=credential.secret_access_key(),
- token=credential.session_token(),
- endpoint_url=s3_endpoint,
- )
- return (expire_time, fs)
- if isinstance(credential, S3SecretKeyCredential):
- fs = importlib.import_module("s3fs").S3FileSystem(
- key=credential.access_key_id(),
- secret=credential.secret_access_key(),
- endpoint_url=s3_endpoint,
- )
- return (expire_time, fs)
-
- # this is the old way to get the s3 file system
- # get 'aws_access_key_id' from s3_options, if the key is not found, throw an exception
- aws_access_key_id = self._options.get(GVFSConfig.GVFS_FILESYSTEM_S3_ACCESS_KEY)
- if aws_access_key_id is None:
- raise GravitinoRuntimeException(
- "AWS access key id is not found in the options."
- )
-
- # get 'aws_secret_access_key' from s3_options, if the key is not found, throw an exception
- aws_secret_access_key = self._options.get(
- GVFSConfig.GVFS_FILESYSTEM_S3_SECRET_KEY
- )
- if aws_secret_access_key is None:
- raise GravitinoRuntimeException(
- "AWS secret access key is not found in the options."
- )
-
- return (
- TIME_WITHOUT_EXPIRATION,
- importlib.import_module("s3fs").S3FileSystem(
- key=aws_access_key_id,
- secret=aws_secret_access_key,
- endpoint_url=s3_endpoint,
- ),
- )
-
- def _get_oss_filesystem(self, fileset_catalog: Catalog, identifier: NameIdentifier):
- fileset: GenericFileset = fileset_catalog.as_fileset_catalog().load_fileset(
- NameIdentifier.of(identifier.namespace().level(2), identifier.name())
- )
- credentials = fileset.support_credentials().get_credentials()
-
- # OSS endpoint from gravitino server
- oss_endpoint = fileset_catalog.properties().get("oss-endpoint", None)
- # If the oss endpoint is not found in the fileset catalog, get it from the client options
- if oss_endpoint is None:
- oss_endpoint = self._options.get(GVFSConfig.GVFS_FILESYSTEM_OSS_ENDPOINT)
-
- credential = self._get_most_suitable_oss_credential(credentials)
- if credential is not None:
- expire_time = self._get_expire_time_by_ratio(credential.expire_time_in_ms())
- if isinstance(credential, OSSTokenCredential):
- fs = importlib.import_module("ossfs").OSSFileSystem(
- key=credential.access_key_id(),
- secret=credential.secret_access_key(),
- token=credential.security_token(),
- endpoint=oss_endpoint,
- )
- return (expire_time, fs)
- if isinstance(credential, OSSSecretKeyCredential):
- return (
- expire_time,
- importlib.import_module("ossfs").OSSFileSystem(
- key=credential.access_key_id(),
- secret=credential.secret_access_key(),
- endpoint=oss_endpoint,
- ),
- )
-
- # get 'oss_access_key_id' from oss options, if the key is not found, throw an exception
- oss_access_key_id = self._options.get(GVFSConfig.GVFS_FILESYSTEM_OSS_ACCESS_KEY)
- if oss_access_key_id is None:
- raise GravitinoRuntimeException(
- "OSS access key id is not found in the options."
- )
-
- # get 'oss_secret_access_key' from oss options, if the key is not found, throw an exception
- oss_secret_access_key = self._options.get(
- GVFSConfig.GVFS_FILESYSTEM_OSS_SECRET_KEY
- )
- if oss_secret_access_key is None:
- raise GravitinoRuntimeException(
- "OSS secret access key is not found in the options."
- )
-
- return (
- TIME_WITHOUT_EXPIRATION,
- importlib.import_module("ossfs").OSSFileSystem(
- key=oss_access_key_id,
- secret=oss_secret_access_key,
- endpoint=oss_endpoint,
- ),
- )
-
- def _get_abs_filesystem(self, fileset_catalog: Catalog, identifier: NameIdentifier):
- fileset: GenericFileset = fileset_catalog.as_fileset_catalog().load_fileset(
- NameIdentifier.of(identifier.namespace().level(2), identifier.name())
- )
- credentials = fileset.support_credentials().get_credentials()
-
- credential = self._get_most_suitable_abs_credential(credentials)
- if credential is not None:
- expire_time = self._get_expire_time_by_ratio(credential.expire_time_in_ms())
- if isinstance(credential, ADLSTokenCredential):
- fs = importlib.import_module("adlfs").AzureBlobFileSystem(
- account_name=credential.account_name(),
- sas_token=credential.sas_token(),
- )
- return (expire_time, fs)
-
- if isinstance(credential, AzureAccountKeyCredential):
- fs = importlib.import_module("adlfs").AzureBlobFileSystem(
- account_name=credential.account_name(),
- account_key=credential.account_key(),
- )
- return (expire_time, fs)
-
- # get 'abs_account_name' from abs options, if the key is not found, throw an exception
- abs_account_name = self._options.get(
- GVFSConfig.GVFS_FILESYSTEM_AZURE_ACCOUNT_NAME
- )
- if abs_account_name is None:
- raise GravitinoRuntimeException(
- "ABS account name is not found in the options."
- )
-
- # get 'abs_account_key' from abs options, if the key is not found, throw an exception
- abs_account_key = self._options.get(
- GVFSConfig.GVFS_FILESYSTEM_AZURE_ACCOUNT_KEY
- )
- if abs_account_key is None:
- raise GravitinoRuntimeException(
- "ABS account key is not found in the options."
- )
-
- return (
- TIME_WITHOUT_EXPIRATION,
- importlib.import_module("adlfs").AzureBlobFileSystem(
- account_name=abs_account_name,
- account_key=abs_account_key,
- ),
+ server_uri: str = None,
+ metalake_name: str = None,
+ options: Dict = None,
+ ) -> BaseGVFSOperations:
+ operations_class = (
+ None
+ if options is None
+ else options.get(GVFSConfig.GVFS_FILESYSTEM_OPERATIONS)
)
+ if operations_class is not None:
+ module_name, class_name = operations_class.rsplit(".", 1)
+ module = importlib.import_module(module_name)
+ loaded_class = getattr(module, class_name)
+ return loaded_class(server_uri, metalake_name, options)
- def _get_most_suitable_s3_credential(self, credentials: List[Credential]):
- for credential in credentials:
- # Prefer to use the token credential, if it does not exist, use the
- # secret key credential.
- if isinstance(credential, S3TokenCredential):
- return credential
-
- for credential in credentials:
- if isinstance(credential, S3SecretKeyCredential):
- return credential
- return None
-
- def _get_most_suitable_oss_credential(self, credentials: List[Credential]):
- for credential in credentials:
- # Prefer to use the token credential, if it does not exist, use the
- # secret key credential.
- if isinstance(credential, OSSTokenCredential):
- return credential
-
- for credential in credentials:
- if isinstance(credential, OSSSecretKeyCredential):
- return credential
- return None
-
- def _get_most_suitable_gcs_credential(self, credentials: List[Credential]):
- for credential in credentials:
- # Prefer to use the token credential, if it does not exist, return None.
- if isinstance(credential, GCSTokenCredential):
- return credential
- return None
-
- def _get_most_suitable_abs_credential(self, credentials: List[Credential]):
- for credential in credentials:
- # Prefer to use the token credential, if it does not exist, use the
- # account key credential
- if isinstance(credential, ADLSTokenCredential):
- return credential
-
- for credential in credentials:
- if isinstance(credential, AzureAccountKeyCredential):
- return credential
- return None
-
- def _get_expire_time_by_ratio(self, expire_time: int):
- if expire_time <= 0:
- return TIME_WITHOUT_EXPIRATION
-
- ratio = float(
- self._options.get(
- GVFSConfig.GVFS_FILESYSTEM_CREDENTIAL_EXPIRED_TIME_RATIO,
- GVFSConfig.DEFAULT_CREDENTIAL_EXPIRED_TIME_RATIO,
- )
+ return DefaultGVFSOperations(
+ server_uri=server_uri,
+ metalake_name=metalake_name,
+ options=options,
)
- return time.time() * 1000 + (expire_time - time.time() * 1000) * ratio
-
- def _throw_fileset_path_not_found_error_if(
- self, condition: bool, path: str, op: FilesetDataOperation
- ):
- if condition:
- raise FilesetPathNotFoundError(
- f"Path [{path}] not found for operation [{op}]"
- )
fsspec.register_implementation(PROTOCOL_NAME, GravitinoVirtualFileSystem)
diff --git a/clients/client-python/gravitino/filesystem/gvfs_base_operations.py b/clients/client-python/gravitino/filesystem/gvfs_base_operations.py
new file mode 100644
index 0000000000..b847cccf59
--- /dev/null
+++ b/clients/client-python/gravitino/filesystem/gvfs_base_operations.py
@@ -0,0 +1,474 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+import logging
+import os
+import sys
+import time
+from abc import ABC, abstractmethod
+from pathlib import PurePosixPath
+from typing import Dict, Tuple
+
+from cachetools import TTLCache, LRUCache
+from fsspec import AbstractFileSystem
+from readerwriterlock import rwlock
+
+from gravitino.api.catalog import Catalog
+from gravitino.audit.caller_context import CallerContextHolder, CallerContext
+from gravitino.audit.fileset_audit_constants import FilesetAuditConstants
+from gravitino.audit.fileset_data_operation import FilesetDataOperation
+from gravitino.audit.internal_client_type import InternalClientType
+from gravitino.client.fileset_catalog import FilesetCatalog
+from gravitino.client.generic_fileset import GenericFileset
+from gravitino.exceptions.base import (
+ GravitinoRuntimeException,
+ NoSuchLocationNameException,
+)
+from gravitino.filesystem.gvfs_config import GVFSConfig
+from gravitino.filesystem.gvfs_storage_handler import get_storage_handler_by_path
+from gravitino.filesystem.gvfs_utils import (
+ get_sub_path_from_virtual_path,
+ extract_identifier,
+ create_client,
+)
+from gravitino.name_identifier import NameIdentifier
+
+logger = logging.getLogger(__name__)
+
+PROTOCOL_NAME = "gvfs"
+
+TIME_WITHOUT_EXPIRATION = sys.maxsize
+
+
+class FilesetPathNotFoundError(FileNotFoundError):
+ """Exception raised when the catalog, schema or fileset is not found in the GVFS path."""
+
+
+class BaseGVFSOperations(ABC):
+ """
+ Abstract base class for Gravitino Virtual File System operations.
+
+ This class provides the core functionality for interacting with the Gravitino Virtual File
+ System, including operations for file manipulation, directory management, and credential
+ handling. It handles the mapping between virtual paths in the Gravitino namespace and actual file
+ paths in underlying storage systems.
+
+ Implementations of this class should provide the specific behaviors for each file system
+ operation.
+ """
+
+ # pylint: disable=too-many-instance-attributes
+
+ SLASH = "/"
+
+ ENV_CURRENT_LOCATION_NAME_ENV_VAR_DEFAULT = "CURRENT_LOCATION_NAME"
+
+ def __init__(
+ self,
+ server_uri: str = None,
+ metalake_name: str = None,
+ options: Dict = None,
+ **kwargs,
+ ):
+ self._metalake = metalake_name
+ self._options = options
+
+ self._client = create_client(options, server_uri, metalake_name)
+
+ cache_size = (
+ GVFSConfig.DEFAULT_CACHE_SIZE
+ if options is None
+ else options.get(GVFSConfig.CACHE_SIZE, GVFSConfig.DEFAULT_CACHE_SIZE)
+ )
+ cache_expired_time = (
+ GVFSConfig.DEFAULT_CACHE_EXPIRED_TIME
+ if options is None
+ else options.get(
+ GVFSConfig.CACHE_EXPIRED_TIME, GVFSConfig.DEFAULT_CACHE_EXPIRED_TIME
+ )
+ )
+ self._filesystem_cache = TTLCache(maxsize=cache_size, ttl=cache_expired_time)
+ self._cache_lock = rwlock.RWLockFair()
+
+ self._catalog_cache = LRUCache(maxsize=100)
+ self._catalog_cache_lock = rwlock.RWLockFair()
+
+ self._current_location_name = self._init_current_location_name()
+
+ @property
+ def current_location_name(self):
+ return self._current_location_name
+
+ @abstractmethod
+ def ls(self, path, detail=True, **kwargs):
+ """List the files and directories info of the path.
+ :param path: Virtual fileset path
+ :param detail: Whether to show the details for the files and directories info
+ :param kwargs: Extra args
+ :return If details is true, returns a list of file info dicts, else returns a list of file paths
+ """
+ pass
+
+ @abstractmethod
+ def info(self, path, **kwargs):
+ """Get file info.
+ :param path: Virtual fileset path
+ :param kwargs: Extra args
+ :return A file info dict
+ """
+ pass
+
+ @abstractmethod
+ def exists(self, path, **kwargs):
+ """Check if a file or a directory exists.
+ :param path: Virtual fileset path
+ :param kwargs: Extra args
+ :return If a file or directory exists, it returns True, otherwise False
+ """
+ pass
+
+ @abstractmethod
+ def cp_file(self, path1, path2, **kwargs):
+ """Copy a file.
+ :param path1: Virtual src fileset path
+ :param path2: Virtual dst fileset path, should be consistent with the src path fileset identifier
+ :param kwargs: Extra args
+ """
+ pass
+
+ @abstractmethod
+ def mv(self, path1, path2, recursive=False, maxdepth=None, **kwargs):
+ """Move a file to another directory.
+ This can move a file to another existing directory.
+ If the target path directory does not exist, an exception will be thrown.
+ :param path1: Virtual src fileset path
+ :param path2: Virtual dst fileset path, should be consistent with the src path fileset identifier
+ :param recursive: Whether to move recursively
+ :param maxdepth: Maximum depth of recursive move
+ :param kwargs: Extra args
+ """
+ pass
+
+ @abstractmethod
+ def rm(self, path, recursive=False, maxdepth=None):
+ """Remove a file or directory.
+ :param path: Virtual fileset path
+ :param recursive: Whether to remove the directory recursively.
+ When removing a directory, this parameter should be True.
+ :param maxdepth: The maximum depth to remove the directory recursively.
+ """
+ pass
+
+ @abstractmethod
+ def rm_file(self, path):
+ """Remove a file.
+ :param path: Virtual fileset path
+ """
+ pass
+
+ @abstractmethod
+ def rmdir(self, path):
+ """Remove a directory.
+ It will delete a directory and all its contents recursively for PyArrow.HadoopFileSystem.
+ And it will throw an exception if delete a directory which is non-empty for LocalFileSystem.
+ :param path: Virtual fileset path
+ """
+ pass
+
+ @abstractmethod
+ def open(
+ self,
+ path,
+ mode="rb",
+ block_size=None,
+ cache_options=None,
+ compression=None,
+ **kwargs,
+ ):
+ """Open a file to read/write/append.
+ :param path: Virtual fileset path
+ :param mode: The mode now supports: rb(read), wb(write), ab(append). See builtin ``open()``
+ :param block_size: Some indication of buffering - this is a value in bytes
+ :param cache_options: Extra arguments to pass through to the cache
+ :param compression: If given, open file using compression codec
+ :param kwargs: Extra args
+ :return A file-like object from the filesystem
+ """
+ pass
+
+ @abstractmethod
+ def mkdir(self, path, create_parents=True, **kwargs):
+ """Make a directory.
+ if create_parents=True, this is equivalent to ``makedirs``.
+
+ :param path: Virtual fileset path
+ :param create_parents: Create parent directories if missing when set to True
+ :param kwargs: Extra args
+ """
+ pass
+
+ @abstractmethod
+ def makedirs(self, path, exist_ok=True):
+ """Make a directory recursively.
+ :param path: Virtual fileset path
+ :param exist_ok: Continue if a directory already exists
+ """
+ pass
+
+ @abstractmethod
+ def created(self, path):
+ """Return the created timestamp of a file as a datetime.datetime
+ Only supports for `fsspec.LocalFileSystem` now.
+ :param path: Virtual fileset path
+ :return Created time(datetime.datetime)
+ """
+ pass
+
+ @abstractmethod
+ def modified(self, path):
+ """Returns the modified time of the path file if it exists.
+ :param path: Virtual fileset path
+ :return Modified time(datetime.datetime)
+ """
+ pass
+
+ @abstractmethod
+ def cat_file(self, path, start=None, end=None, **kwargs):
+ """Get the content of a file.
+ :param path: Virtual fileset path
+ :param start: The offset in bytes to start reading from. It can be None.
+ :param end: The offset in bytes to end reading at. It can be None.
+ :param kwargs: Extra args
+ :return File content
+ """
+ pass
+
+ @abstractmethod
+ def get_file(self, rpath, lpath, callback=None, outfile=None, **kwargs):
+ """Copy single remote file to local.
+ :param rpath: Remote file path
+ :param lpath: Local file path
+ :param callback: The callback class
+ :param outfile: The output file path
+ :param kwargs: Extra args
+ """
+ pass
+
+ @staticmethod
+ def _pre_process_path(virtual_path):
+ """Pre-process the path.
+ This method uniformly processes `gvfs://fileset/{catalog}/{schema}/{fileset_name}/xxx`
+ into the format of `fileset/{catalog}/{schema}/{fileset_name}/xxx`.
+ The conversion is necessary because some implementations of `PyArrow` and `fsspec`
+ can only recognize this format.
+ :param virtual_path: The virtual path
+ :return The pre-processed path
+ """
+ if isinstance(virtual_path, PurePosixPath):
+ pre_processed_path = virtual_path.as_posix()
+ else:
+ pre_processed_path = virtual_path
+ gvfs_prefix = f"{PROTOCOL_NAME}://"
+ if pre_processed_path.startswith(gvfs_prefix):
+ pre_processed_path = pre_processed_path[len(gvfs_prefix) :]
+ if not pre_processed_path.startswith("fileset/"):
+ raise GravitinoRuntimeException(
+ f"Invalid path:`{pre_processed_path}`. Expected path to start with `fileset/`."
+ " Example: fileset/{fileset_catalog}/{schema}/{fileset_name}/{sub_path}."
+ )
+ return pre_processed_path
+
+ def _assert_same_fileset(self, gvfs_path1: str, gvfs_path2: str):
+ """Assert that the two gvfs paths are the same fileset.
+ :param gvfs_path1: The first gvfs path
+ :param gvfs_path2: The second gvfs path
+ """
+ src_path = self._pre_process_path(gvfs_path1)
+ dst_path = self._pre_process_path(gvfs_path2)
+ src_identifier: NameIdentifier = extract_identifier(self._metalake, src_path)
+ dst_identifier: NameIdentifier = extract_identifier(self._metalake, dst_path)
+ if src_identifier != dst_identifier:
+ raise GravitinoRuntimeException(
+ f"Destination file path identifier: `{dst_identifier}` should be same with src file path "
+ f"identifier: `{src_identifier}`."
+ )
+
+ def _init_current_location_name(self):
+ """Initialize the current location name.
+ get from configuration first, otherwise use the env variable
+ if both are not set, return null which means use the default location
+ :return: The current location name
+ """
+ current_location_name_env_var = (
+ self._options.get(GVFSConfig.GVFS_FILESYSTEM_CURRENT_LOCATION_NAME_ENV_VAR)
+ if self._options
+ else None
+ ) or self.ENV_CURRENT_LOCATION_NAME_ENV_VAR_DEFAULT
+
+ return (
+ self._options.get(GVFSConfig.GVFS_FILESYSTEM_CURRENT_LOCATION_NAME)
+ if self._options
+ else None
+ ) or os.environ.get(current_location_name_env_var)
+
+ def _get_actual_filesystem(
+ self, gvfs_path: str, location_name: str
+ ) -> AbstractFileSystem:
+ """Get the actual filesystem based on the gvfs path.
+ :param gvfs_path: The gvfs path
+ :param location_name: The location name, None means the default location
+ :return: The actual filesystem
+ """
+ fileset_ident: NameIdentifier = extract_identifier(self._metalake, gvfs_path)
+ return self._get_actual_filesystem_by_location_name(
+ fileset_ident, location_name
+ )
+
+ def _get_actual_filesystem_by_location_name(
+ self, fileset_ident: NameIdentifier, location_name: str
+ ) -> AbstractFileSystem:
+ """Get the actual filesystem based on the fileset identifier and location name.
+ :param fileset_ident: The fileset identifier
+ :param location_name: The location name, None means the default location
+ :return: The actual filesystem
+ """
+ catalog_ident: NameIdentifier = NameIdentifier.of(
+ self._metalake, fileset_ident.namespace().level(1)
+ )
+ catalog = self._get_fileset_catalog(catalog_ident)
+ fileset = catalog.as_fileset_catalog().load_fileset(
+ NameIdentifier.of(fileset_ident.namespace().level(2), fileset_ident.name())
+ )
+ target_location_name = location_name or fileset.properties().get(
+ fileset.PROPERTY_DEFAULT_LOCATION_NAME
+ )
+ actual_location = fileset.storage_locations().get(target_location_name)
+ if actual_location is None:
+ raise NoSuchLocationNameException(
+ f"Cannot find the location: {target_location_name} in fileset: {fileset_ident}"
+ )
+ actual_fs = self._get_filesystem(
+ actual_location, catalog, fileset_ident, target_location_name
+ )
+ return actual_fs
+
+ def _get_actual_file_path(
+ self, gvfs_path: str, location_name: str, operation: FilesetDataOperation
+ ) -> str:
+ """Get the actual file path by the given virtual path and location name.
+ :param gvfs_path: The gvfs path
+ :param location_name: The location name
+ :param operation: The data operation
+ :return: The actual file path
+ """
+ processed_virtual_path: str = self._pre_process_path(gvfs_path)
+ identifier: NameIdentifier = extract_identifier(
+ self._metalake, processed_virtual_path
+ )
+ catalog_ident: NameIdentifier = NameIdentifier.of(
+ self._metalake, identifier.namespace().level(1)
+ )
+ fileset_catalog = self._get_fileset_catalog(catalog_ident)
+
+ sub_path: str = get_sub_path_from_virtual_path(
+ identifier, processed_virtual_path
+ )
+ context = {
+ FilesetAuditConstants.HTTP_HEADER_FILESET_DATA_OPERATION: operation.name,
+ FilesetAuditConstants.HTTP_HEADER_INTERNAL_CLIENT_TYPE: InternalClientType.PYTHON_GVFS.name,
+ }
+ caller_context: CallerContext = CallerContext(context)
+ CallerContextHolder.set(caller_context)
+
+ return fileset_catalog.as_fileset_catalog().get_file_location(
+ NameIdentifier.of(identifier.namespace().level(2), identifier.name()),
+ sub_path,
+ location_name,
+ )
+
+ def _file_system_expired(self, expire_time: int):
+ return expire_time <= time.time() * 1000
+
+ def _get_filesystem(
+ self,
+ actual_file_location: str,
+ fileset_catalog: Catalog,
+ name_identifier: NameIdentifier,
+ location_name: str,
+ ):
+ read_lock = self._cache_lock.gen_rlock()
+ try:
+ read_lock.acquire()
+ cache_value: Tuple[int, AbstractFileSystem] = self._filesystem_cache.get(
+ (name_identifier, location_name)
+ )
+ if cache_value is not None:
+ if not self._file_system_expired(cache_value[0]):
+ return cache_value[1]
+ finally:
+ read_lock.release()
+
+ write_lock = self._cache_lock.gen_wlock()
+ try:
+ write_lock.acquire()
+ cache_value: Tuple[int, AbstractFileSystem] = self._filesystem_cache.get(
+ (name_identifier, location_name)
+ )
+
+ if cache_value is not None:
+ if not self._file_system_expired(cache_value[0]):
+ return cache_value[1]
+
+ fileset: GenericFileset = fileset_catalog.as_fileset_catalog().load_fileset(
+ NameIdentifier.of(
+ name_identifier.namespace().level(2), name_identifier.name()
+ )
+ )
+ credentials = fileset.support_credentials().get_credentials()
+ new_cache_value = get_storage_handler_by_path(
+ actual_file_location
+ ).get_filesystem_with_expiration(
+ credentials,
+ fileset_catalog.properties(),
+ self._options,
+ actual_file_location,
+ )
+ self._filesystem_cache[(name_identifier, location_name)] = new_cache_value
+ return new_cache_value[1]
+ finally:
+ write_lock.release()
+
+ def _get_fileset_catalog(self, catalog_ident: NameIdentifier):
+ read_lock = self._catalog_cache_lock.gen_rlock()
+ try:
+ read_lock.acquire()
+ cache_value: FilesetCatalog = self._catalog_cache.get(catalog_ident)
+ if cache_value is not None:
+ return cache_value
+ finally:
+ read_lock.release()
+
+ write_lock = self._catalog_cache_lock.gen_wlock()
+ try:
+ write_lock.acquire()
+ cache_value: FilesetCatalog = self._catalog_cache.get(catalog_ident)
+ if cache_value is not None:
+ return cache_value
+ catalog = self._client.load_catalog(catalog_ident.name())
+ self._catalog_cache[catalog_ident] = catalog
+ return catalog
+ finally:
+ write_lock.release()
diff --git a/clients/client-python/gravitino/filesystem/gvfs_config.py b/clients/client-python/gravitino/filesystem/gvfs_config.py
index 77dde31e06..a5d797bd9e 100644
--- a/clients/client-python/gravitino/filesystem/gvfs_config.py
+++ b/clients/client-python/gravitino/filesystem/gvfs_config.py
@@ -60,3 +60,7 @@ class GVFSConfig:
# The configuration key for the env variable name that indicates the current location name. If
# not set, the file system will read the location name from CURRENT_LOCATION_NAME env variable.
GVFS_FILESYSTEM_CURRENT_LOCATION_NAME_ENV_VAR = "current_location_name_env_var"
+
+ # The configuration key for the class name of the file system operations.
+ # The default value is "org.apache.gravitino.filesystem.hadoop.DefaultGVFSOperations".
+ GVFS_FILESYSTEM_OPERATIONS = "operations_class"
diff --git a/clients/client-python/gravitino/filesystem/gvfs_default_operations.py b/clients/client-python/gravitino/filesystem/gvfs_default_operations.py
new file mode 100644
index 0000000000..f405ce1ded
--- /dev/null
+++ b/clients/client-python/gravitino/filesystem/gvfs_default_operations.py
@@ -0,0 +1,397 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from gravitino.name_identifier import NameIdentifier
+from gravitino.audit.fileset_data_operation import FilesetDataOperation
+from gravitino.exceptions.base import GravitinoRuntimeException
+from gravitino.filesystem.gvfs_base_operations import BaseGVFSOperations
+from gravitino.filesystem.gvfs_storage_handler import (
+ StorageType,
+ get_storage_handler_by_path,
+)
+from gravitino.filesystem.gvfs_utils import (
+ extract_identifier,
+ get_sub_path_from_virtual_path,
+ to_gvfs_path_prefix,
+)
+
+
+class DefaultGVFSOperations(BaseGVFSOperations):
+ """
+ Default implementation of the Gravitino Virtual File System operations.
+ """
+
+ def ls(self, path, detail=True, **kwargs):
+ """List the files and directories info of the path.
+ :param path: Virtual fileset path
+ :param detail: Whether to show the details for the files and directories info
+ :param kwargs: Extra args
+ :return If details is true, returns a list of file info dicts, else returns a list of file paths
+ """
+ actual_fs = self._get_actual_filesystem(path, self.current_location_name)
+ actual_file_path = self._get_actual_file_path(
+ path, self.current_location_name, FilesetDataOperation.LIST_STATUS
+ )
+ storage_handler = get_storage_handler_by_path(actual_file_path)
+
+ pre_process_path: str = self._pre_process_path(path)
+ identifier: NameIdentifier = extract_identifier(
+ self._metalake, pre_process_path
+ )
+ sub_path: str = get_sub_path_from_virtual_path(identifier, pre_process_path)
+ fileset_location: str = actual_file_path[
+ : len(actual_file_path) - len(sub_path)
+ ]
+
+ paths_or_entries = actual_fs.ls(
+ storage_handler.strip_storage_protocol(actual_file_path),
+ detail=detail,
+ )
+ # return entries with details
+ if detail:
+ virtual_entries = [
+ storage_handler.actual_info_to_gvfs_info(
+ entry, fileset_location, to_gvfs_path_prefix(identifier)
+ )
+ for entry in paths_or_entries
+ ]
+ return virtual_entries
+
+ # only returns paths
+ virtual_entry_paths = [
+ storage_handler.actual_path_to_gvfs_path(
+ entry_path, fileset_location, to_gvfs_path_prefix(identifier)
+ )
+ for entry_path in paths_or_entries
+ ]
+ return virtual_entry_paths
+
+ def info(self, path, **kwargs):
+ """Get file info.
+ :param path: Virtual fileset path
+ :param kwargs: Extra args
+ :return A file info dict
+ """
+ actual_fs = self._get_actual_filesystem(path, self.current_location_name)
+ actual_file_path = self._get_actual_file_path(
+ path, self.current_location_name, FilesetDataOperation.GET_FILE_STATUS
+ )
+ storage_handler = get_storage_handler_by_path(actual_file_path)
+
+ pre_process_path: str = self._pre_process_path(path)
+ identifier: NameIdentifier = extract_identifier(
+ self._metalake, pre_process_path
+ )
+ sub_path: str = get_sub_path_from_virtual_path(identifier, pre_process_path)
+ fileset_location: str = actual_file_path[
+ : len(actual_file_path) - len(sub_path)
+ ]
+
+ entry_info = actual_fs.info(
+ storage_handler.strip_storage_protocol(actual_file_path)
+ )
+ return storage_handler.actual_info_to_gvfs_info(
+ entry_info, fileset_location, to_gvfs_path_prefix(identifier)
+ )
+
+ def exists(self, path, **kwargs):
+ """Check if a file or a directory exists.
+ :param path: Virtual fileset path
+ :param kwargs: Extra args
+ :return If a file or directory exists, it returns True, otherwise False
+ """
+ actual_fs = self._get_actual_filesystem(path, self.current_location_name)
+ actual_file_path = self._get_actual_file_path(
+ path, self.current_location_name, FilesetDataOperation.EXISTS
+ )
+ storage_handler = get_storage_handler_by_path(actual_file_path)
+
+ return actual_fs.exists(
+ storage_handler.strip_storage_protocol(actual_file_path)
+ )
+
+ def cp_file(self, path1, path2, **kwargs):
+ """Copy a file.
+ :param path1: Virtual src fileset path
+ :param path2: Virtual dst fileset path, should be consistent with the src path fileset identifier
+ :param kwargs: Extra args
+ """
+ self._assert_same_fileset(path1, path2)
+ src_path = self._pre_process_path(path1)
+ dst_path = self._pre_process_path(path2)
+
+ actual_fs = self._get_actual_filesystem(src_path, self.current_location_name)
+ actual_src_file_path = self._get_actual_file_path(
+ src_path, self.current_location_name, FilesetDataOperation.COPY_FILE
+ )
+ actual_dst_file_path = self._get_actual_file_path(
+ dst_path, self.current_location_name, FilesetDataOperation.COPY_FILE
+ )
+ storage_handler = get_storage_handler_by_path(actual_src_file_path)
+
+ actual_fs.cp_file(
+ storage_handler.strip_storage_protocol(actual_src_file_path),
+ storage_handler.strip_storage_protocol(actual_dst_file_path),
+ )
+
+ def mv(self, path1, path2, recursive=False, maxdepth=None, **kwargs):
+ """Move a file to another directory.
+ This can move a file to another existing directory.
+ If the target path directory does not exist, an exception will be thrown.
+ :param path1: Virtual src fileset path
+ :param path2: Virtual dst fileset path, should be consistent with the src path fileset identifier
+ :param recursive: Whether to move recursively
+ :param maxdepth: Maximum depth of recursive move
+ :param kwargs: Extra args
+ """
+ self._assert_same_fileset(path1, path2)
+ src_path = self._pre_process_path(path1)
+ dst_path = self._pre_process_path(path2)
+
+ actual_fs = self._get_actual_filesystem(src_path, self.current_location_name)
+ src_actual_path = self._get_actual_file_path(
+ src_path, self.current_location_name, FilesetDataOperation.RENAME
+ )
+ dst_actual_path = self._get_actual_file_path(
+ dst_path, self.current_location_name, FilesetDataOperation.RENAME
+ )
+ storage_handler = get_storage_handler_by_path(src_actual_path)
+
+ if storage_handler.storage_type() == StorageType.LOCAL:
+ actual_fs.mv(
+ storage_handler.strip_storage_protocol(src_actual_path),
+ storage_handler.strip_storage_protocol(dst_actual_path),
+ recursive,
+ maxdepth,
+ )
+ else:
+ actual_fs.mv(
+ storage_handler.strip_storage_protocol(src_actual_path),
+ storage_handler.strip_storage_protocol(dst_actual_path),
+ )
+
+ def rm(self, path, recursive=False, maxdepth=None):
+ """Remove a file or directory.
+ :param path: Virtual fileset path
+ :param recursive: Whether to remove the directory recursively.
+ When removing a directory, this parameter should be True.
+ :param maxdepth: The maximum depth to remove the directory recursively.
+ """
+ actual_fs = self._get_actual_filesystem(path, self.current_location_name)
+ actual_file_path = self._get_actual_file_path(
+ path, self.current_location_name, FilesetDataOperation.DELETE
+ )
+ storage_handler = get_storage_handler_by_path(actual_file_path)
+
+ # S3FileSystem and ocifs don't support maxdepth
+ if storage_handler.storage_type() in [StorageType.S3A]:
+ actual_fs.rm(
+ storage_handler.strip_storage_protocol(actual_file_path),
+ recursive,
+ )
+ else:
+ actual_fs.rm(
+ storage_handler.strip_storage_protocol(actual_file_path),
+ recursive,
+ maxdepth,
+ )
+
+ def rm_file(self, path):
+ """Remove a file.
+ :param path: Virtual fileset path
+ """
+ actual_fs = self._get_actual_filesystem(path, self.current_location_name)
+ actual_file_path = self._get_actual_file_path(
+ path, self.current_location_name, FilesetDataOperation.DELETE
+ )
+ storage_handler = get_storage_handler_by_path(actual_file_path)
+
+ actual_fs.rm_file(storage_handler.strip_storage_protocol(actual_file_path))
+
+ def rmdir(self, path):
+ """Remove a directory.
+ It will delete a directory and all its contents recursively for PyArrow.HadoopFileSystem.
+ And it will throw an exception if delete a directory which is non-empty for LocalFileSystem.
+ :param path: Virtual fileset path
+ """
+ actual_fs = self._get_actual_filesystem(path, self.current_location_name)
+ actual_file_path = self._get_actual_file_path(
+ path, self.current_location_name, FilesetDataOperation.DELETE
+ )
+ storage_handler = get_storage_handler_by_path(actual_file_path)
+
+ actual_fs.rmdir(storage_handler.strip_storage_protocol(actual_file_path))
+
+ def open(
+ self,
+ path,
+ mode="rb",
+ block_size=None,
+ cache_options=None,
+ compression=None,
+ **kwargs,
+ ):
+ """Open a file to read/write/append.
+ :param path: Virtual fileset path
+ :param mode: The mode now supports: rb(read), wb(write), ab(append). See builtin ``open()``
+ :param block_size: Some indication of buffering - this is a value in bytes
+ :param cache_options: Extra arguments to pass through to the cache
+ :param compression: If given, open file using compression codec
+ :param kwargs: Extra args
+ :return A file-like object from the filesystem
+ """
+ if mode in ("w", "wb"):
+ data_operation = FilesetDataOperation.OPEN_AND_WRITE
+ elif mode in ("a", "ab"):
+ data_operation = FilesetDataOperation.OPEN_AND_APPEND
+ else:
+ data_operation = FilesetDataOperation.OPEN
+
+ actual_fs = self._get_actual_filesystem(path, self.current_location_name)
+ actual_file_path = self._get_actual_file_path(
+ path, self.current_location_name, data_operation
+ )
+ storage_handler = get_storage_handler_by_path(actual_file_path)
+
+ return actual_fs.open(
+ storage_handler.strip_storage_protocol(actual_file_path),
+ mode,
+ block_size,
+ cache_options,
+ compression,
+ **kwargs,
+ )
+
+ def mkdir(self, path, create_parents=True, **kwargs):
+ """Make a directory.
+ if create_parents=True, this is equivalent to ``makedirs``.
+
+ :param path: Virtual fileset path
+ :param create_parents: Create parent directories if missing when set to True
+ :param kwargs: Extra args
+ """
+ actual_fs = self._get_actual_filesystem(path, self.current_location_name)
+ actual_file_path = self._get_actual_file_path(
+ path, self.current_location_name, FilesetDataOperation.MKDIRS
+ )
+ storage_handler = get_storage_handler_by_path(actual_file_path)
+
+ actual_fs.mkdir(
+ storage_handler.strip_storage_protocol(actual_file_path),
+ create_parents,
+ **kwargs,
+ )
+
+ def makedirs(self, path, exist_ok=True):
+ """Make a directory recursively.
+ :param path: Virtual fileset path
+ :param exist_ok: Continue if a directory already exists
+ """
+ actual_fs = self._get_actual_filesystem(path, self.current_location_name)
+ actual_file_path = self._get_actual_file_path(
+ path, self.current_location_name, FilesetDataOperation.MKDIRS
+ )
+ storage_handler = get_storage_handler_by_path(actual_file_path)
+
+ actual_fs.makedirs(
+ storage_handler.strip_storage_protocol(actual_file_path),
+ exist_ok,
+ )
+
+ def created(self, path):
+ """Return the created timestamp of a file as a datetime.datetime
+ Only supports for `fsspec.LocalFileSystem` now.
+ :param path: Virtual fileset path
+ :return Created time(datetime.datetime)
+ """
+ actual_fs = self._get_actual_filesystem(path, self.current_location_name)
+ actual_file_path = self._get_actual_file_path(
+ path, self.current_location_name, FilesetDataOperation.CREATED_TIME
+ )
+ storage_handler = get_storage_handler_by_path(actual_file_path)
+ if storage_handler.storage_type() != StorageType.LOCAL:
+ raise GravitinoRuntimeException(
+ f"Storage type:{storage_handler.storage_type()} doesn't support now."
+ )
+
+ created_time = actual_fs.created(
+ storage_handler.strip_storage_protocol(actual_file_path)
+ )
+ return created_time
+
+ def modified(self, path):
+ """Returns the modified time of the path file if it exists.
+ :param path: Virtual fileset path
+ :return Modified time(datetime.datetime)
+ """
+ actual_fs = self._get_actual_filesystem(path, self.current_location_name)
+ actual_file_path = self._get_actual_file_path(
+ path, self.current_location_name, FilesetDataOperation.MODIFIED_TIME
+ )
+ storage_handler = get_storage_handler_by_path(actual_file_path)
+
+ return actual_fs.modified(
+ storage_handler.strip_storage_protocol(actual_file_path)
+ )
+
+ def cat_file(self, path, start=None, end=None, **kwargs):
+ """Get the content of a file.
+ :param path: Virtual fileset path
+ :param start: The offset in bytes to start reading from. It can be None.
+ :param end: The offset in bytes to end reading at. It can be None.
+ :param kwargs: Extra args
+ :return File content
+ """
+ actual_fs = self._get_actual_filesystem(path, self.current_location_name)
+ actual_file_path = self._get_actual_file_path(
+ path, self.current_location_name, FilesetDataOperation.GET_FILE_STATUS
+ )
+ storage_handler = get_storage_handler_by_path(actual_file_path)
+
+ return actual_fs.cat_file(
+ storage_handler.strip_storage_protocol(actual_file_path),
+ start,
+ end,
+ **kwargs,
+ )
+
+ def get_file(self, rpath, lpath, callback=None, outfile=None, **kwargs):
+ """Copy single remote file to local.
+ :param rpath: Remote file path
+ :param lpath: Local file path
+ :param callback: The callback class
+ :param outfile: The output file path
+ :param kwargs: Extra args
+ """
+ if not lpath.startswith(f"{StorageType.LOCAL.value}:") and not lpath.startswith(
+ "/"
+ ):
+ raise GravitinoRuntimeException(
+ "Doesn't support copy a remote gvfs file to an another remote file."
+ )
+
+ actual_fs = self._get_actual_filesystem(rpath, self.current_location_name)
+ actual_file_path = self._get_actual_file_path(
+ rpath, self.current_location_name, FilesetDataOperation.GET_FILE
+ )
+ storage_handler = get_storage_handler_by_path(actual_file_path)
+
+ actual_fs.get_file(
+ storage_handler.strip_storage_protocol(actual_file_path),
+ lpath,
+ **kwargs,
+ )
diff --git a/clients/client-python/gravitino/filesystem/gvfs_storage_handler.py b/clients/client-python/gravitino/filesystem/gvfs_storage_handler.py
new file mode 100644
index 0000000000..b1c024a5c2
--- /dev/null
+++ b/clients/client-python/gravitino/filesystem/gvfs_storage_handler.py
@@ -0,0 +1,739 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+import importlib
+import sys
+import time
+from abc import ABC, abstractmethod
+from enum import Enum
+from typing import Optional, Tuple, List, Dict, Any
+
+from fsspec import AbstractFileSystem
+from fsspec.implementations.arrow import ArrowFSWrapper
+from fsspec.implementations.local import LocalFileSystem
+from fsspec.utils import infer_storage_options
+
+from gravitino.api.credential.adls_token_credential import ADLSTokenCredential
+from gravitino.api.credential.azure_account_key_credential import (
+ AzureAccountKeyCredential,
+)
+from gravitino.api.credential.credential import Credential
+from gravitino.api.credential.gcs_token_credential import GCSTokenCredential
+from gravitino.api.credential.oss_secret_key_credential import OSSSecretKeyCredential
+from gravitino.api.credential.oss_token_credential import OSSTokenCredential
+from gravitino.api.credential.s3_secret_key_credential import S3SecretKeyCredential
+from gravitino.api.credential.s3_token_credential import S3TokenCredential
+from gravitino.exceptions.base import GravitinoRuntimeException
+from gravitino.filesystem.gvfs_config import GVFSConfig
+
+TIME_WITHOUT_EXPIRATION = sys.maxsize
+SLASH = "/"
+
+
+class StorageType(Enum):
+ HDFS = "hdfs"
+ LOCAL = "file"
+ GCS = "gs"
+ S3A = "s3a"
+ OSS = "oss"
+ ABS = "abfss"
+
+
+class StorageHandler(ABC):
+ """A handler class that holds the information about the actual file location and the file system which used in
+ the GravitinoVirtualFileSystem's operations.
+ """
+
+ @abstractmethod
+ def storage_type(self) -> StorageType:
+ """Get the storage type.
+ :return: The storage type
+ """
+ pass
+
+ @abstractmethod
+ def get_filesystem(
+ self, actual_path: Optional[str] = None, **kwargs
+ ) -> AbstractFileSystem:
+ """Get the file system.
+ :return: The file system
+ """
+ pass
+
+ @abstractmethod
+ def get_filesystem_with_expiration(
+ self,
+ credentials: List[Credential],
+ catalog_props: Dict[str, str],
+ options: Dict[str, str],
+ actual_path: Optional[str] = None,
+ **kwargs,
+ ) -> Tuple[int, AbstractFileSystem]:
+ """Get the file system with expiration.
+ :return: The file system and the expiration time
+ """
+ pass
+
+ def actual_info_to_gvfs_info(
+ self,
+ entry: Dict,
+ fileset_location: str,
+ gvfs_path_prefix: str,
+ ):
+ """Convert a file info from an actual entry to a virtual entry.
+ :param entry: A dict of the actual file info
+ :param fileset_location: Storage location of the fileset
+ :param gvfs_path_prefix: The prefix of the virtual path
+ :return A dict of the virtual file info
+ """
+ path = self.actual_path_to_gvfs_path(
+ entry["name"], fileset_location, gvfs_path_prefix
+ )
+ last_modified = self._get_last_modified(entry)
+ return {
+ "name": path,
+ "size": entry["size"],
+ "type": entry["type"],
+ "mtime": last_modified,
+ }
+
+ def actual_path_to_gvfs_path(
+ self,
+ actual_path: str,
+ fileset_location: str,
+ gvfs_path_prefix: str,
+ ):
+ """Convert the actual path to the gvfs path.
+ :param actual_path: The actual path
+ :param fileset_location: The fileset location
+ :param gvfs_path_prefix: The gvfs path prefix
+ :return: The gvfs path
+ """
+ if not fileset_location.startswith(f"{self.storage_type().value}:/"):
+ raise GravitinoRuntimeException(
+ f"Fileset location {fileset_location} is not a {self.storage_type()} path."
+ )
+ actual_prefix = self._get_actual_prefix(fileset_location)
+ normalized_actual_path = self._normalize_actual_path_if_needed(
+ infer_storage_options(actual_prefix), actual_path
+ )
+ if not actual_path.startswith(actual_prefix):
+ raise GravitinoRuntimeException(
+ f"Path {actual_path} does not start with valid prefix {actual_prefix}."
+ )
+
+ # if the fileset location is end with "/",
+ # we should truncate this to avoid replace issues.
+ if actual_prefix.endswith(SLASH) and not gvfs_path_prefix.endswith(SLASH):
+ return f"{normalized_actual_path.replace(actual_prefix[:-1], gvfs_path_prefix)}"
+ return f"{normalized_actual_path.replace(actual_prefix, gvfs_path_prefix)}"
+
+ @abstractmethod
+ def _get_actual_prefix(self, actual_path: str) -> str:
+ """Get the actual path prefix from the actual path.
+ :param actual_path: The actual path
+ :return: The actual path prefix
+ """
+ pass
+
+ @abstractmethod
+ def _get_most_suitable_credential(self, credentials: List[Credential]):
+ """Get the most suitable credential.
+ :param credentials: The credentials
+ :return: The most suitable credential
+ """
+ pass
+
+ def strip_storage_protocol(self, path: str) -> str:
+ """Strip the storage protocol from the path.
+ Before passing the path to the underlying file system for processing,
+ pre-process the protocol information in the path.
+ Some file systems require special processing.
+ For HDFS, we can pass the path like 'hdfs://{host}:{port}/xxx'.
+ For Local, we can pass the path like '/tmp/xxx'.
+ :param path: The path
+ :return: The stripped path
+ """
+ return path
+
+ def _get_expire_time_by_ratio(self, expire_time: int, options: Dict[str, str]):
+ if expire_time <= 0:
+ return TIME_WITHOUT_EXPIRATION
+
+ ratio = float(
+ options.get(
+ GVFSConfig.GVFS_FILESYSTEM_CREDENTIAL_EXPIRED_TIME_RATIO,
+ GVFSConfig.DEFAULT_CREDENTIAL_EXPIRED_TIME_RATIO,
+ )
+ if options
+ else GVFSConfig.DEFAULT_CREDENTIAL_EXPIRED_TIME_RATIO
+ )
+ return time.time() * 1000 + (expire_time - time.time() * 1000) * ratio
+
+ def _normalize_actual_path_if_needed(
+ self, storage_options: Dict[str, Any], actual_path: str
+ ) -> str:
+ return actual_path
+
+ def _get_last_modified(self, entry: Dict):
+ return entry["mtime"]
+
+
+class LocalStorageHandler(StorageHandler):
+ """Local Storage Handler"""
+
+ def storage_type(self):
+ return StorageType.LOCAL
+
+ def get_filesystem(
+ self, actual_path: Optional[str] = None, **kwargs
+ ) -> AbstractFileSystem:
+ return LocalFileSystem(**kwargs)
+
+ def get_filesystem_with_expiration(
+ self,
+ credentials: List[Credential],
+ catalog_props: Dict[str, str],
+ options: Dict[str, str],
+ actual_path: Optional[str] = None,
+ **kwargs,
+ ) -> Tuple[int, AbstractFileSystem]:
+ """Get the file system with expiration.
+ :return: The file system and the expiration time
+ """
+ return TIME_WITHOUT_EXPIRATION, self.get_filesystem(actual_path, **kwargs)
+
+ def _get_actual_prefix(
+ self,
+ actual_path: str,
+ ) -> str:
+ return actual_path[len(f"{self.storage_type().value}:") :]
+
+ def _get_most_suitable_credential(self, credentials: List[Credential]):
+ return None
+
+ def strip_storage_protocol(self, path: str):
+ """Strip the storage protocol from the path.
+ :param path: The path
+ :return: The stripped path
+ """
+ return path[len(f"{self.storage_type().value}:") :]
+
+
+class HDFSStorageHandler(StorageHandler):
+ """HDFS Storage Handler"""
+
+ def storage_type(self):
+ return StorageType.HDFS
+
+ def get_filesystem(
+ self, actual_path: Optional[str] = None, **kwargs
+ ) -> AbstractFileSystem:
+ fs_class = importlib.import_module("pyarrow.fs").HadoopFileSystem
+ return ArrowFSWrapper(fs_class.from_uri(actual_path))
+
+ def get_filesystem_with_expiration(
+ self,
+ credentials: List[Credential],
+ catalog_props: Dict[str, str],
+ options: Dict[str, str],
+ actual_path: Optional[str] = None,
+ **kwargs,
+ ) -> Tuple[int, AbstractFileSystem]:
+ """Get the file system with expiration.
+ :return: The file system and the expiration time
+ """
+ return TIME_WITHOUT_EXPIRATION, self.get_filesystem(actual_path, **kwargs)
+
+ def _get_actual_prefix(
+ self,
+ actual_path: str,
+ ) -> str:
+ return infer_storage_options(actual_path)["path"]
+
+ def _get_most_suitable_credential(self, credentials: List[Credential]):
+ return None
+
+
+class S3StorageHandler(StorageHandler):
+ """S3 Storage Handler"""
+
+ def storage_type(self):
+ return StorageType.S3A
+
+ def get_filesystem_with_expiration(
+ self,
+ credentials: List[Credential],
+ catalog_props: Dict[str, str],
+ options: Dict[str, str],
+ actual_path: Optional[str] = None,
+ **kwargs,
+ ) -> Tuple[int, AbstractFileSystem]:
+ """Get the file system with expiration.
+ :return: The file system and the expiration time
+ """
+ # S3 endpoint from gravitino server, Note: the endpoint may not a real S3 endpoint
+ # it can be a simulated S3 endpoint, such as minio, so though the endpoint is not a required field
+ # for S3FileSystem, we still need to assign the endpoint to the S3FileSystem
+ s3_endpoint = catalog_props.get("s3-endpoint", None) if catalog_props else None
+ # If the s3 endpoint is not found in the fileset catalog, get it from the client options
+ if s3_endpoint is None and options:
+ s3_endpoint = options.get(GVFSConfig.GVFS_FILESYSTEM_S3_ENDPOINT)
+
+ if credentials:
+ credential = self._get_most_suitable_credential(credentials)
+ if credential is not None:
+ expire_time = self._get_expire_time_by_ratio(
+ credential.expire_time_in_ms(),
+ options,
+ )
+ if isinstance(credential, S3TokenCredential):
+ fs = self.get_filesystem(
+ key=credential.access_key_id(),
+ secret=credential.secret_access_key(),
+ token=credential.session_token(),
+ endpoint_url=s3_endpoint,
+ **kwargs,
+ )
+ return expire_time, fs
+ if isinstance(credential, S3SecretKeyCredential):
+ fs = self.get_filesystem(
+ key=credential.access_key_id(),
+ secret=credential.secret_access_key(),
+ endpoint_url=s3_endpoint,
+ **kwargs,
+ )
+ return expire_time, fs
+
+ # this is the old way to get the s3 file system
+ # get 'aws_access_key_id' from s3_options, if the key is not found, throw an exception
+ aws_access_key_id = (
+ options.get(GVFSConfig.GVFS_FILESYSTEM_S3_ACCESS_KEY) if options else None
+ )
+ if aws_access_key_id is None:
+ raise GravitinoRuntimeException(
+ "AWS access key id is not found in the options."
+ )
+
+ # get 'aws_secret_access_key' from s3_options, if the key is not found, throw an exception
+ aws_secret_access_key = (
+ options.get(GVFSConfig.GVFS_FILESYSTEM_S3_SECRET_KEY) if options else None
+ )
+ if aws_secret_access_key is None:
+ raise GravitinoRuntimeException(
+ "AWS secret access key is not found in the options."
+ )
+
+ return (
+ TIME_WITHOUT_EXPIRATION,
+ self.get_filesystem(
+ key=aws_access_key_id,
+ secret=aws_secret_access_key,
+ endpoint_url=s3_endpoint,
+ **kwargs,
+ ),
+ )
+
+ def get_filesystem(
+ self, actual_path: Optional[str] = None, **kwargs
+ ) -> AbstractFileSystem:
+ return importlib.import_module("s3fs").S3FileSystem(**kwargs)
+
+ def _get_actual_prefix(
+ self,
+ actual_path: str,
+ ) -> str:
+ return infer_storage_options(actual_path)["path"]
+
+ def _get_most_suitable_credential(self, credentials: List[Credential]):
+ for credential in credentials:
+ # Prefer to use the token credential, if it does not exist, use the
+ # secret key credential.
+ if isinstance(credential, S3TokenCredential):
+ return credential
+
+ for credential in credentials:
+ if isinstance(credential, S3SecretKeyCredential):
+ return credential
+ return None
+
+ def _get_last_modified(self, entry: Dict):
+ return entry["LastModified"]
+
+
+class GCSStorageHandler(StorageHandler):
+ """GCS Storage Handler"""
+
+ def storage_type(self):
+ return StorageType.GCS
+
+ def get_filesystem(
+ self, actual_path: Optional[str] = None, **kwargs
+ ) -> AbstractFileSystem:
+ return importlib.import_module("gcsfs").GCSFileSystem(**kwargs)
+
+ def get_filesystem_with_expiration(
+ self,
+ credentials: List[Credential],
+ catalog_props: Dict[str, str],
+ options: Dict[str, str],
+ actual_path: Optional[str] = None,
+ **kwargs,
+ ) -> Tuple[int, AbstractFileSystem]:
+ if credentials:
+ credential = self._get_most_suitable_credential(credentials)
+ if credential is not None:
+ expire_time = self._get_expire_time_by_ratio(
+ credential.expire_time_in_ms(),
+ options,
+ )
+ if isinstance(credential, GCSTokenCredential):
+ return (
+ expire_time,
+ self.get_filesystem(
+ token=credential.token(),
+ **kwargs,
+ ),
+ )
+
+ # get 'service-account-key' from gcs_options, if the key is not found, throw an exception
+ service_account_key_path = (
+ options.get(GVFSConfig.GVFS_FILESYSTEM_GCS_SERVICE_KEY_FILE)
+ if options
+ else None
+ )
+ if service_account_key_path is None:
+ raise GravitinoRuntimeException(
+ "Service account key is not found in the options."
+ )
+ return (
+ TIME_WITHOUT_EXPIRATION,
+ self.get_filesystem(
+ token=service_account_key_path,
+ **kwargs,
+ ),
+ )
+
+ def _get_actual_prefix(
+ self,
+ actual_path: str,
+ ) -> str:
+ return infer_storage_options(actual_path)["path"]
+
+ def _get_most_suitable_credential(self, credentials: List[Credential]):
+ for credential in credentials:
+ # Prefer to use the token credential, if it does not exist, return None.
+ if isinstance(credential, GCSTokenCredential):
+ return credential
+ return None
+
+
+class OSSStorageHandler(StorageHandler):
+ """OSS Storage Handler"""
+
+ def storage_type(self):
+ return StorageType.OSS
+
+ def strip_storage_protocol(self, path: str):
+ """Strip the storage protocol from the path.
+ if we do not remove the protocol, it will always return an empty array.
+ :param path: The path
+ :return: The stripped path
+ """
+ if path.startswith(f"{self.storage_type().value}://"):
+ return path[len(f"{self.storage_type().value}://") :]
+ return path
+
+ def get_filesystem(
+ self, actual_path: Optional[str] = None, **kwargs
+ ) -> AbstractFileSystem:
+ return importlib.import_module("ossfs").OSSFileSystem(**kwargs)
+
+ def get_filesystem_with_expiration(
+ self,
+ credentials: List[Credential],
+ catalog_props: Dict[str, str],
+ options: Dict[str, str],
+ actual_path: Optional[str] = None,
+ **kwargs,
+ ) -> Tuple[int, AbstractFileSystem]:
+ # OSS endpoint from gravitino server
+ oss_endpoint = (
+ catalog_props.get("oss-endpoint", None) if catalog_props else None
+ )
+ # If the oss endpoint is not found in the fileset catalog, get it from the client options
+ if oss_endpoint is None and options:
+ oss_endpoint = options.get(GVFSConfig.GVFS_FILESYSTEM_OSS_ENDPOINT)
+
+ if credentials:
+ credential = self._get_most_suitable_credential(credentials)
+ if credential is not None:
+ expire_time = self._get_expire_time_by_ratio(
+ credential.expire_time_in_ms(),
+ options,
+ )
+ if isinstance(credential, OSSTokenCredential):
+ fs = self.get_filesystem(
+ key=credential.access_key_id(),
+ secret=credential.secret_access_key(),
+ token=credential.security_token(),
+ endpoint=oss_endpoint,
+ **kwargs,
+ )
+ return expire_time, fs
+ if isinstance(credential, OSSSecretKeyCredential):
+ return (
+ expire_time,
+ self.get_filesystem(
+ key=credential.access_key_id(),
+ secret=credential.secret_access_key(),
+ endpoint=oss_endpoint,
+ **kwargs,
+ ),
+ )
+
+ # get 'oss_access_key_id' from oss options, if the key is not found, throw an exception
+ oss_access_key_id = (
+ options.get(GVFSConfig.GVFS_FILESYSTEM_OSS_ACCESS_KEY) if options else None
+ )
+ if oss_access_key_id is None:
+ raise GravitinoRuntimeException(
+ "OSS access key id is not found in the options."
+ )
+
+ # get 'oss_secret_access_key' from oss options, if the key is not found, throw an exception
+ oss_secret_access_key = (
+ options.get(GVFSConfig.GVFS_FILESYSTEM_OSS_SECRET_KEY) if options else None
+ )
+ if oss_secret_access_key is None:
+ raise GravitinoRuntimeException(
+ "OSS secret access key is not found in the options."
+ )
+
+ return (
+ TIME_WITHOUT_EXPIRATION,
+ importlib.import_module("ossfs").OSSFileSystem(
+ key=oss_access_key_id,
+ secret=oss_secret_access_key,
+ endpoint=oss_endpoint,
+ **kwargs,
+ ),
+ )
+
+ def _get_last_modified(self, entry: Dict):
+ return entry["LastModified"]
+
+ def _get_actual_prefix(
+ self,
+ actual_path: str,
+ ) -> str:
+ ops = infer_storage_options(actual_path)
+ if "host" not in ops or "path" not in ops:
+ raise GravitinoRuntimeException(
+ f"Storage location:{actual_path} doesn't support now."
+ )
+
+ return ops["host"] + ops["path"]
+
+ def _get_most_suitable_credential(self, credentials: List[Credential]):
+ for credential in credentials:
+ # Prefer to use the token credential, if it does not exist, use the
+ # secret key credential.
+ if isinstance(credential, OSSTokenCredential):
+ return credential
+
+ for credential in credentials:
+ if isinstance(credential, OSSSecretKeyCredential):
+ return credential
+ return None
+
+
+class ABSStorageHandler(StorageHandler):
+ """Azure Blob Storage Handler"""
+
+ def storage_type(self):
+ return StorageType.ABS
+
+ def get_filesystem(
+ self, actual_path: Optional[str] = None, **kwargs
+ ) -> AbstractFileSystem:
+ return importlib.import_module("adlfs").AzureBlobFileSystem(**kwargs)
+
+ def get_filesystem_with_expiration(
+ self,
+ credentials: List[Credential],
+ catalog_props: Dict[str, str],
+ options: Dict[str, str],
+ actual_path: Optional[str] = None,
+ **kwargs,
+ ) -> Tuple[int, AbstractFileSystem]:
+ if credentials:
+ credential = self._get_most_suitable_credential(credentials)
+ if credential is not None:
+ expire_time = self._get_expire_time_by_ratio(
+ credential.expire_time_in_ms(),
+ options,
+ )
+ if isinstance(credential, ADLSTokenCredential):
+ fs = self.get_filesystem(
+ account_name=credential.account_name(),
+ sas_token=credential.sas_token(),
+ **kwargs,
+ )
+ return expire_time, fs
+
+ if isinstance(credential, AzureAccountKeyCredential):
+ fs = self.get_filesystem(
+ account_name=credential.account_name(),
+ account_key=credential.account_key(),
+ **kwargs,
+ )
+ return expire_time, fs
+
+ # get 'abs_account_name' from abs options, if the key is not found, throw an exception
+ abs_account_name = (
+ options.get(GVFSConfig.GVFS_FILESYSTEM_AZURE_ACCOUNT_NAME)
+ if options
+ else None
+ )
+ if abs_account_name is None:
+ raise GravitinoRuntimeException(
+ "ABS account name is not found in the options."
+ )
+
+ # get 'abs_account_key' from abs options, if the key is not found, throw an exception
+ abs_account_key = (
+ options.get(GVFSConfig.GVFS_FILESYSTEM_AZURE_ACCOUNT_KEY)
+ if options
+ else None
+ )
+ if abs_account_key is None:
+ raise GravitinoRuntimeException(
+ "ABS account key is not found in the options."
+ )
+
+ return (
+ TIME_WITHOUT_EXPIRATION,
+ self.get_filesystem(
+ account_name=abs_account_name,
+ account_key=abs_account_key,
+ **kwargs,
+ ),
+ )
+
+ def strip_storage_protocol(self, path: str):
+ """Strip the storage protocol from the path.
+ We need to remove the protocol and account from the path, for instance,
+ the path can be converted from 'abfss://container@account/path' to
+ 'container/path'.
+ :param path: The path
+ :return: The stripped path
+ """
+ ops = infer_storage_options(path)
+ return ops["username"] + ops["path"]
+
+ def _get_actual_prefix(
+ self,
+ actual_path: str,
+ ) -> str:
+ ops = infer_storage_options(actual_path)
+ if "username" not in ops or "host" not in ops or "path" not in ops:
+ raise GravitinoRuntimeException(
+ f"The location:{actual_path} doesn't support now, the username,"
+ f"host and path are required in the location."
+ )
+ return f"{self.storage_type().value}://{ops['username']}@{ops['host']}{ops['path']}"
+
+ def _normalize_actual_path_if_needed(
+ self, storage_options: Dict[str, Any], actual_path: str
+ ) -> str:
+ # the actual path may be '{container}/{path}', we need to add the host and username
+ # get the path from {container}/{path}
+ if not actual_path.startswith(f"{StorageType.ABS}"):
+ path_without_username = actual_path[actual_path.index("/") + 1 :]
+ return (
+ f"{StorageType.ABS.value}://{storage_options['username']}@{storage_options['host']}/"
+ f"{path_without_username}"
+ )
+ return actual_path
+
+ def _get_most_suitable_credential(self, credentials: List[Credential]):
+ for credential in credentials:
+ # Prefer to use the token credential, if it does not exist, use the
+ # account key credential
+ if isinstance(credential, ADLSTokenCredential):
+ return credential
+
+ for credential in credentials:
+ if isinstance(credential, AzureAccountKeyCredential):
+ return credential
+ return None
+
+ def _get_last_modified(self, entry: Dict):
+ return entry["last_modified"]
+
+
+LOCA_HANDLER = LocalStorageHandler()
+HDFS_HANDLER = HDFSStorageHandler()
+S3_HANDLER = S3StorageHandler()
+GCS_HANDLER = GCSStorageHandler()
+OSS_HANDLER = OSSStorageHandler()
+ABS_HANDLER = ABSStorageHandler()
+
+storage_prefixes = {
+ f"{StorageType.HDFS.value}://": StorageType.HDFS,
+ f"{StorageType.LOCAL.value}:/": StorageType.LOCAL,
+ f"{StorageType.GCS.value}://": StorageType.GCS,
+ f"{StorageType.S3A.value}://": StorageType.S3A,
+ f"{StorageType.OSS.value}://": StorageType.OSS,
+ f"{StorageType.ABS.value}://": StorageType.ABS,
+}
+
+storage_handlers: Dict[StorageType, StorageHandler] = {
+ StorageType.LOCAL: LOCA_HANDLER,
+ StorageType.HDFS: HDFS_HANDLER,
+ StorageType.GCS: GCS_HANDLER,
+ StorageType.S3A: S3StorageHandler,
+ StorageType.OSS: OSSSecretKeyCredential,
+ StorageType.ABS: AzureAccountKeyCredential,
+}
+
+
+def get_storage_handler_by_type(storage_type: StorageType) -> StorageHandler:
+ """Get the storage handler by the storage type.
+ :param storage_type: The storage type
+ :return: The storage handler
+ """
+ if storage_type not in storage_handlers:
+ raise GravitinoRuntimeException(
+ f"Storage type: `{storage_type}` doesn't support now."
+ )
+ return storage_handlers[storage_type]
+
+
+def get_storage_handler_by_path(actual_path: str) -> StorageHandler:
+ """Get the storage handler by the actual path.
+ :param actual_path: The actual path
+ :return: The storage handler
+ """
+
+ for prefix, storage_type in storage_prefixes.items():
+ if actual_path.startswith(prefix):
+ return get_storage_handler_by_type(storage_type)
+
+ raise GravitinoRuntimeException(
+ f"Storage type doesn't support now. Path:{actual_path}"
+ )
diff --git a/clients/client-python/tests/integration/test_gvfs_with_hdfs.py b/clients/client-python/tests/integration/test_gvfs_with_hdfs.py
index 29ccc71390..f07a2e0328 100644
--- a/clients/client-python/tests/integration/test_gvfs_with_hdfs.py
+++ b/clients/client-python/tests/integration/test_gvfs_with_hdfs.py
@@ -262,7 +262,7 @@ class TestGvfsWithHDFS(IntegrationTestEnv):
metalake_name=self.metalake_name,
options=options,
)
- token = fs._client._rest_client.auth_data_provider.get_token_data()
+ token = fs._operations._client._rest_client.auth_data_provider.get_token_data()
token_string = base64.b64decode(
token.decode("utf-8")[len(AuthConstants.AUTHORIZATION_BASIC_HEADER) :]
).decode("utf-8")
diff --git a/clients/client-python/tests/unittests/mock_base.py b/clients/client-python/tests/unittests/mock_base.py
index 8a33d96d48..dd3316b697 100644
--- a/clients/client-python/tests/unittests/mock_base.py
+++ b/clients/client-python/tests/unittests/mock_base.py
@@ -20,6 +20,7 @@ from unittest.mock import patch
from gravitino import GravitinoMetalake, Catalog, Fileset
from gravitino.client.fileset_catalog import FilesetCatalog
+from gravitino.client.generic_fileset import GenericFileset
from gravitino.client.generic_model_catalog import GenericModelCatalog
from gravitino.dto.fileset_dto import FilesetDTO
from gravitino.dto.audit_dto import AuditDTO
@@ -101,7 +102,9 @@ def mock_load_fileset(name: str, location: str):
_storage_locations={Fileset.LOCATION_NAME_UNKNOWN: location},
_audit=audit_dto,
)
- return fileset
+ return GenericFileset(
+ fileset, None, Namespace.of("metalake_demo", "fileset_catalog", "tmp")
+ )
def mock_data(cls):
diff --git a/clients/client-python/tests/unittests/test_gvfs_with_local.py b/clients/client-python/tests/unittests/test_gvfs_with_local.py
index a63d3b47f3..8090f051ed 100644
--- a/clients/client-python/tests/unittests/test_gvfs_with_local.py
+++ b/clients/client-python/tests/unittests/test_gvfs_with_local.py
@@ -16,14 +16,12 @@
# under the License.
import base64
import os
-
-# pylint: disable=protected-access,too-many-lines,too-many-locals
-
import random
import string
import time
import unittest
from datetime import datetime
+from unittest import mock
from unittest.mock import patch
import pandas
@@ -32,7 +30,7 @@ import pyarrow.dataset as dt
import pyarrow.parquet as pq
from fsspec.implementations.local import LocalFileSystem
-from gravitino import gvfs, NameIdentifier
+from gravitino import gvfs, NameIdentifier, Fileset
from gravitino.auth.auth_constants import AuthConstants
from gravitino.exceptions.base import (
GravitinoRuntimeException,
@@ -40,7 +38,8 @@ from gravitino.exceptions.base import (
BadRequestException,
)
from gravitino.filesystem.gvfs_config import GVFSConfig
-from gravitino.filesystem.gvfs_utils import extract_identifier
+from gravitino.filesystem.gvfs_storage_handler import LOCA_HANDLER
+from gravitino.filesystem.gvfs_utils import extract_identifier, to_gvfs_path_prefix
from tests.unittests import mock_base
from tests.unittests.auth.mock_base import (
mock_jwt,
@@ -50,6 +49,9 @@ from tests.unittests.auth.mock_base import (
)
+# pylint: disable=protected-access,too-many-lines,too-many-locals
+
+
# pylint: disable=C0302
def generate_unique_random_string(length):
characters = string.ascii_letters + string.digits
@@ -57,6 +59,10 @@ def generate_unique_random_string(length):
return random_string
+@patch(
+ "gravitino.client.generic_fileset.GenericFileset.get_credentials",
+ return_value=[],
+)
@mock_base.mock_data
class TestLocalFilesystem(unittest.TestCase):
_metalake_name: str = "metalake_demo"
@@ -80,9 +86,14 @@ class TestLocalFilesystem(unittest.TestCase):
fileset_storage_location = f"{self._fileset_dir}/test_cache"
fileset_virtual_location = "fileset/fileset_catalog/tmp/test_cache"
actual_path = fileset_storage_location
- with patch(
- "gravitino.client.fileset_catalog.FilesetCatalog.get_file_location",
- return_value=actual_path,
+ with patch.multiple(
+ "gravitino.client.fileset_catalog.FilesetCatalog",
+ load_fileset=mock.MagicMock(
+ return_value=mock_base.mock_load_fileset(
+ "test_cache", fileset_storage_location
+ )
+ ),
+ get_file_location=mock.MagicMock(return_value=actual_path),
):
local_fs = LocalFileSystem()
local_fs.mkdir(fileset_storage_location)
@@ -97,7 +108,14 @@ class TestLocalFilesystem(unittest.TestCase):
self.assertTrue(fs.exists(fileset_virtual_location))
# wait 2 seconds
time.sleep(2)
- self.assertIsNone(fs._cache.get("file:/"))
+ name_identifier = NameIdentifier.of(
+ self._metalake_name, "fileset_catalog", "tmp", "test_cache"
+ )
+ self.assertIsNone(
+ fs._operations._filesystem_cache.get(
+ (name_identifier, Fileset.LOCATION_NAME_UNKNOWN)
+ )
+ )
def test_simple_auth(self, *mock_methods):
options = {"auth_type": "simple"}
@@ -112,7 +130,7 @@ class TestLocalFilesystem(unittest.TestCase):
options=options,
skip_instance_cache=True,
)
- token = fs._client._rest_client.auth_data_provider.get_token_data()
+ token = fs._operations._client._rest_client.auth_data_provider.get_token_data()
token_string = base64.b64decode(
token.decode("utf-8")[len(AuthConstants.AUTHORIZATION_BASIC_HEADER) :]
).decode("utf-8")
@@ -142,9 +160,14 @@ class TestLocalFilesystem(unittest.TestCase):
fileset_storage_location = f"{self._fileset_dir}/test_oauth2_auth"
fileset_virtual_location = "fileset/fileset_catalog/tmp/test_oauth2_auth"
actual_path = fileset_storage_location
- with patch(
- "gravitino.client.fileset_catalog.FilesetCatalog.get_file_location",
- return_value=actual_path,
+ with patch.multiple(
+ "gravitino.client.fileset_catalog.FilesetCatalog",
+ load_fileset=mock.MagicMock(
+ return_value=mock_base.mock_load_fileset(
+ "fileset", fileset_storage_location
+ )
+ ),
+ get_file_location=mock.MagicMock(return_value=actual_path),
):
local_fs = LocalFileSystem()
local_fs.mkdir(fileset_storage_location)
@@ -193,9 +216,14 @@ class TestLocalFilesystem(unittest.TestCase):
fileset_storage_location = f"{self._fileset_dir}/test_ls"
fileset_virtual_location = "fileset/fileset_catalog/tmp/test_ls"
actual_path = fileset_storage_location
- with patch(
- "gravitino.client.fileset_catalog.FilesetCatalog.get_file_location",
- return_value=actual_path,
+ with patch.multiple(
+ "gravitino.client.fileset_catalog.FilesetCatalog",
+ load_fileset=mock.MagicMock(
+ return_value=mock_base.mock_load_fileset(
+ "fileset", fileset_storage_location
+ )
+ ),
+ get_file_location=mock.MagicMock(return_value=actual_path),
):
local_fs = LocalFileSystem()
local_fs.mkdir(fileset_storage_location)
@@ -255,9 +283,14 @@ class TestLocalFilesystem(unittest.TestCase):
metalake_name=self._metalake_name,
skip_instance_cache=True,
)
- with patch(
- "gravitino.client.fileset_catalog.FilesetCatalog.get_file_location",
- return_value=actual_path,
+ with patch.multiple(
+ "gravitino.client.fileset_catalog.FilesetCatalog",
+ load_fileset=mock.MagicMock(
+ return_value=mock_base.mock_load_fileset(
+ "fileset", fileset_storage_location
+ )
+ ),
+ get_file_location=mock.MagicMock(return_value=actual_path),
):
self.assertTrue(fs.exists(fileset_virtual_location))
@@ -297,25 +330,40 @@ class TestLocalFilesystem(unittest.TestCase):
metalake_name=self._metalake_name,
skip_instance_cache=True,
)
- with patch(
- "gravitino.client.fileset_catalog.FilesetCatalog.get_file_location",
- return_value=actual_path,
+ with patch.multiple(
+ "gravitino.client.fileset_catalog.FilesetCatalog",
+ load_fileset=mock.MagicMock(
+ return_value=mock_base.mock_load_fileset(
+ "fileset", fileset_storage_location
+ )
+ ),
+ get_file_location=mock.MagicMock(return_value=actual_path),
):
self.assertTrue(fs.exists(fileset_virtual_location))
dir_virtual_path = fileset_virtual_location + "/test_1"
actual_path = fileset_storage_location + "/test_1"
- with patch(
- "gravitino.client.fileset_catalog.FilesetCatalog.get_file_location",
- return_value=actual_path,
+ with patch.multiple(
+ "gravitino.client.fileset_catalog.FilesetCatalog",
+ load_fileset=mock.MagicMock(
+ return_value=mock_base.mock_load_fileset(
+ "fileset", fileset_storage_location
+ )
+ ),
+ get_file_location=mock.MagicMock(return_value=actual_path),
):
self.assertTrue(fs.exists(dir_virtual_path))
file_virtual_path = fileset_virtual_location + "/test_file_1.par"
actual_path = fileset_storage_location + "/test_file_1.par"
- with patch(
- "gravitino.client.fileset_catalog.FilesetCatalog.get_file_location",
- return_value=actual_path,
+ with patch.multiple(
+ "gravitino.client.fileset_catalog.FilesetCatalog",
+ load_fileset=mock.MagicMock(
+ return_value=mock_base.mock_load_fileset(
+ "fileset", fileset_storage_location
+ )
+ ),
+ get_file_location=mock.MagicMock(return_value=actual_path),
):
self.assertTrue(fs.exists(file_virtual_path))
@@ -337,9 +385,14 @@ class TestLocalFilesystem(unittest.TestCase):
metalake_name=self._metalake_name,
skip_instance_cache=True,
)
- with patch(
- "gravitino.client.fileset_catalog.FilesetCatalog.get_file_location",
- return_value=actual_path,
+ with patch.multiple(
+ "gravitino.client.fileset_catalog.FilesetCatalog",
+ load_fileset=mock.MagicMock(
+ return_value=mock_base.mock_load_fileset(
+ "fileset", fileset_storage_location
+ )
+ ),
+ get_file_location=mock.MagicMock(return_value=actual_path),
):
self.assertTrue(fs.exists(fileset_virtual_location))
@@ -354,6 +407,11 @@ class TestLocalFilesystem(unittest.TestCase):
dst_actual_path,
dst_actual_path,
],
+ ), patch(
+ "gravitino.client.fileset_catalog.FilesetCatalog.load_fileset",
+ return_value=mock_base.mock_load_fileset(
+ "fileset", fileset_storage_location
+ ),
):
self.assertTrue(fs.exists(file_virtual_path))
cp_file_virtual_path = fileset_virtual_location + "/test_cp_file_1.par"
@@ -389,17 +447,27 @@ class TestLocalFilesystem(unittest.TestCase):
metalake_name=self._metalake_name,
skip_instance_cache=True,
)
- with patch(
- "gravitino.client.fileset_catalog.FilesetCatalog.get_file_location",
- return_value=actual_path,
+ with patch.multiple(
+ "gravitino.client.fileset_catalog.FilesetCatalog",
+ load_fileset=mock.MagicMock(
+ return_value=mock_base.mock_load_fileset(
+ "fileset", fileset_storage_location
+ )
+ ),
+ get_file_location=mock.MagicMock(return_value=actual_path),
):
self.assertTrue(fs.exists(fileset_virtual_location))
file_virtual_path = fileset_virtual_location + "/test_file_1.par"
src_actual_path = fileset_storage_location + "/test_file_1.par"
- with patch(
- "gravitino.client.fileset_catalog.FilesetCatalog.get_file_location",
- return_value=src_actual_path,
+ with patch.multiple(
+ "gravitino.client.fileset_catalog.FilesetCatalog",
+ load_fileset=mock.MagicMock(
+ return_value=mock_base.mock_load_fileset(
+ "fileset", fileset_storage_location
+ )
+ ),
+ get_file_location=mock.MagicMock(return_value=src_actual_path),
):
self.assertTrue(fs.exists(file_virtual_path))
@@ -408,6 +476,11 @@ class TestLocalFilesystem(unittest.TestCase):
with patch(
"gravitino.client.fileset_catalog.FilesetCatalog.get_file_location",
side_effect=[src_actual_path, dst_actual_path, dst_actual_path],
+ ), patch(
+ "gravitino.client.fileset_catalog.FilesetCatalog.load_fileset",
+ return_value=mock_base.mock_load_fileset(
+ "fileset", fileset_storage_location
+ ),
):
fs.mv(file_virtual_path, mv_file_virtual_path)
self.assertTrue(fs.exists(mv_file_virtual_path))
@@ -419,6 +492,11 @@ class TestLocalFilesystem(unittest.TestCase):
with patch(
"gravitino.client.fileset_catalog.FilesetCatalog.get_file_location",
side_effect=[dst_actual_path, dst_actual_path1, dst_actual_path1],
+ ), patch(
+ "gravitino.client.fileset_catalog.FilesetCatalog.load_fileset",
+ return_value=mock_base.mock_load_fileset(
+ "fileset", fileset_storage_location
+ ),
):
fs.mv(mv_file_virtual_path, mv_another_dir_virtual_path)
self.assertTrue(fs.exists(mv_another_dir_virtual_path))
@@ -429,6 +507,11 @@ class TestLocalFilesystem(unittest.TestCase):
with patch(
"gravitino.client.fileset_catalog.FilesetCatalog.get_file_location",
side_effect=[dst_actual_path1, dst_actual_path2],
+ ), patch(
+ "gravitino.client.fileset_catalog.FilesetCatalog.load_fileset",
+ return_value=mock_base.mock_load_fileset(
+ "fileset", fileset_storage_location
+ ),
):
with self.assertRaises(FileNotFoundError):
fs.mv(path1=mv_another_dir_virtual_path, path2=not_exist_dst_dir_path)
@@ -459,9 +542,14 @@ class TestLocalFilesystem(unittest.TestCase):
metalake_name=self._metalake_name,
skip_instance_cache=True,
)
- with patch(
- "gravitino.client.fileset_catalog.FilesetCatalog.get_file_location",
- return_value=actual_path,
+ with patch.multiple(
+ "gravitino.client.fileset_catalog.FilesetCatalog",
+ load_fileset=mock.MagicMock(
+ return_value=mock_base.mock_load_fileset(
+ "fileset", fileset_storage_location
+ )
+ ),
+ get_file_location=mock.MagicMock(return_value=actual_path),
):
self.assertTrue(fs.exists(fileset_virtual_location))
@@ -511,9 +599,14 @@ class TestLocalFilesystem(unittest.TestCase):
metalake_name=self._metalake_name,
skip_instance_cache=True,
)
- with patch(
- "gravitino.client.fileset_catalog.FilesetCatalog.get_file_location",
- return_value=actual_path,
+ with patch.multiple(
+ "gravitino.client.fileset_catalog.FilesetCatalog",
+ load_fileset=mock.MagicMock(
+ return_value=mock_base.mock_load_fileset(
+ "fileset", fileset_storage_location
+ )
+ ),
+ get_file_location=mock.MagicMock(return_value=actual_path),
):
self.assertTrue(fs.exists(fileset_virtual_location))
@@ -558,9 +651,14 @@ class TestLocalFilesystem(unittest.TestCase):
metalake_name=self._metalake_name,
skip_instance_cache=True,
)
- with patch(
- "gravitino.client.fileset_catalog.FilesetCatalog.get_file_location",
- return_value=actual_path,
+ with patch.multiple(
+ "gravitino.client.fileset_catalog.FilesetCatalog",
+ load_fileset=mock.MagicMock(
+ return_value=mock_base.mock_load_fileset(
+ "fileset", fileset_storage_location
+ )
+ ),
+ get_file_location=mock.MagicMock(return_value=actual_path),
):
self.assertTrue(fs.exists(fileset_virtual_location))
@@ -605,9 +703,14 @@ class TestLocalFilesystem(unittest.TestCase):
metalake_name=self._metalake_name,
skip_instance_cache=True,
)
- with patch(
- "gravitino.client.fileset_catalog.FilesetCatalog.get_file_location",
- return_value=actual_path,
+ with patch.multiple(
+ "gravitino.client.fileset_catalog.FilesetCatalog",
+ load_fileset=mock.MagicMock(
+ return_value=mock_base.mock_load_fileset(
+ "fileset", fileset_storage_location
+ )
+ ),
+ get_file_location=mock.MagicMock(return_value=actual_path),
):
self.assertTrue(fs.exists(fileset_virtual_location))
@@ -653,9 +756,14 @@ class TestLocalFilesystem(unittest.TestCase):
metalake_name=self._metalake_name,
skip_instance_cache=True,
)
- with patch(
- "gravitino.client.fileset_catalog.FilesetCatalog.get_file_location",
- return_value=actual_path,
+ with patch.multiple(
+ "gravitino.client.fileset_catalog.FilesetCatalog",
+ load_fileset=mock.MagicMock(
+ return_value=mock_base.mock_load_fileset(
+ "fileset", fileset_storage_location
+ )
+ ),
+ get_file_location=mock.MagicMock(return_value=actual_path),
):
self.assertTrue(fs.exists(fileset_virtual_location))
@@ -702,9 +810,14 @@ class TestLocalFilesystem(unittest.TestCase):
metalake_name=self._metalake_name,
skip_instance_cache=True,
)
- with patch(
- "gravitino.client.fileset_catalog.FilesetCatalog.get_file_location",
- return_value=actual_path,
+ with patch.multiple(
+ "gravitino.client.fileset_catalog.FilesetCatalog",
+ load_fileset=mock.MagicMock(
+ return_value=mock_base.mock_load_fileset(
+ "fileset", fileset_storage_location
+ )
+ ),
+ get_file_location=mock.MagicMock(return_value=actual_path),
):
self.assertTrue(fs.exists(fileset_virtual_location))
@@ -740,9 +853,14 @@ class TestLocalFilesystem(unittest.TestCase):
metalake_name=self._metalake_name,
skip_instance_cache=True,
)
- with patch(
- "gravitino.client.fileset_catalog.FilesetCatalog.get_file_location",
- return_value=actual_path,
+ with patch.multiple(
+ "gravitino.client.fileset_catalog.FilesetCatalog",
+ load_fileset=mock.MagicMock(
+ return_value=mock_base.mock_load_fileset(
+ "fileset", fileset_storage_location
+ )
+ ),
+ get_file_location=mock.MagicMock(return_value=actual_path),
):
self.assertTrue(fs.exists(fileset_virtual_location))
@@ -771,9 +889,14 @@ class TestLocalFilesystem(unittest.TestCase):
metalake_name=self._metalake_name,
skip_instance_cache=True,
)
- with patch(
- "gravitino.client.fileset_catalog.FilesetCatalog.get_file_location",
- return_value=actual_path,
+ with patch.multiple(
+ "gravitino.client.fileset_catalog.FilesetCatalog",
+ load_fileset=mock.MagicMock(
+ return_value=mock_base.mock_load_fileset(
+ "fileset", fileset_storage_location
+ )
+ ),
+ get_file_location=mock.MagicMock(return_value=actual_path),
):
self.assertTrue(fs.exists(fileset_virtual_location))
@@ -806,9 +929,14 @@ class TestLocalFilesystem(unittest.TestCase):
metalake_name=self._metalake_name,
skip_instance_cache=True,
)
- with patch(
- "gravitino.client.fileset_catalog.FilesetCatalog.get_file_location",
- return_value=actual_path,
+ with patch.multiple(
+ "gravitino.client.fileset_catalog.FilesetCatalog",
+ load_fileset=mock.MagicMock(
+ return_value=mock_base.mock_load_fileset(
+ "fileset", fileset_storage_location
+ )
+ ),
+ get_file_location=mock.MagicMock(return_value=actual_path),
):
self.assertTrue(fs.exists(fileset_virtual_location))
@@ -858,9 +986,14 @@ class TestLocalFilesystem(unittest.TestCase):
metalake_name=self._metalake_name,
skip_instance_cache=True,
)
- with patch(
- "gravitino.client.fileset_catalog.FilesetCatalog.get_file_location",
- return_value=actual_path,
+ with patch.multiple(
+ "gravitino.client.fileset_catalog.FilesetCatalog",
+ load_fileset=mock.MagicMock(
+ return_value=mock_base.mock_load_fileset(
+ "fileset", fileset_storage_location
+ )
+ ),
+ get_file_location=mock.MagicMock(return_value=actual_path),
):
self.assertTrue(fs.exists(fileset_virtual_location))
@@ -901,23 +1034,20 @@ class TestLocalFilesystem(unittest.TestCase):
fs.get_file(file_virtual_path, remote_path)
def test_convert_actual_path(self, *mock_methods):
- fs = gvfs.GravitinoVirtualFileSystem(
- server_uri=self._server_uri,
- metalake_name=self._metalake_name,
- skip_instance_cache=True,
- )
- storage_location = "hdfs://localhost:8090/fileset/test_f1"
- virtual_location = fs._get_virtual_location(
+ storage_location = "file:/fileset/test_f1"
+ virtual_location = to_gvfs_path_prefix(
NameIdentifier.of("test_metalake", "test_catalog", "test_schema", "test_f1")
)
# test actual path not start with storage location
actual_path = "/not_start_with_storage/ttt"
with self.assertRaises(GravitinoRuntimeException):
- fs._convert_actual_path(actual_path, storage_location, virtual_location)
+ LOCA_HANDLER.actual_path_to_gvfs_path(
+ actual_path, storage_location, virtual_location
+ )
# test actual path start with storage location
actual_path = "/fileset/test_f1/actual_path"
- virtual_path = fs._convert_actual_path(
+ virtual_path = LOCA_HANDLER.actual_path_to_gvfs_path(
actual_path, storage_location, virtual_location
)
self.assertEqual(
@@ -925,23 +1055,20 @@ class TestLocalFilesystem(unittest.TestCase):
)
# test convert actual local path
- fs = gvfs.GravitinoVirtualFileSystem(
- server_uri=self._server_uri,
- metalake_name=self._metalake_name,
- skip_instance_cache=True,
- )
storage_location = "file:/tmp/fileset/test_f1"
- virtual_location = fs._get_virtual_location(
+ virtual_location = to_gvfs_path_prefix(
NameIdentifier.of("test_metalake", "test_catalog", "test_schema", "test_f1")
)
# test actual path not start with storage location
actual_path = "/not_start_with_storage/ttt"
with self.assertRaises(GravitinoRuntimeException):
- fs._convert_actual_path(actual_path, storage_location, virtual_location)
+ LOCA_HANDLER.actual_path_to_gvfs_path(
+ actual_path, storage_location, virtual_location
+ )
# test actual path start with storage location
actual_path = "/tmp/fileset/test_f1/actual_path"
- virtual_path = fs._convert_actual_path(
+ virtual_path = LOCA_HANDLER.actual_path_to_gvfs_path(
actual_path, storage_location, virtual_location
)
self.assertEqual(
@@ -951,13 +1078,13 @@ class TestLocalFilesystem(unittest.TestCase):
# test storage location without "/"
actual_path = "/tmp/test_convert_actual_path/sub_dir/1.parquet"
storage_location = "file:/tmp/test_convert_actual_path"
- virtual_location = fs._get_virtual_location(
+ virtual_location = to_gvfs_path_prefix(
NameIdentifier.of(
"test_metalake", "catalog", "schema", "test_convert_actual_path"
)
)
- virtual_path = fs._convert_actual_path(
+ virtual_path = LOCA_HANDLER.actual_path_to_gvfs_path(
actual_path, storage_location, virtual_location
)
self.assertEqual(
@@ -968,13 +1095,13 @@ class TestLocalFilesystem(unittest.TestCase):
# test storage location with "/"
actual_path = "/tmp/test_convert_actual_path/sub_dir/1.parquet"
storage_location = "file:/tmp/test_convert_actual_path/"
- virtual_location = fs._get_virtual_location(
+ virtual_location = to_gvfs_path_prefix(
NameIdentifier.of(
"test_metalake", "catalog", "schema", "test_convert_actual_path"
)
)
- virtual_path = fs._convert_actual_path(
+ virtual_path = LOCA_HANDLER.actual_path_to_gvfs_path(
actual_path, storage_location, virtual_location
)
self.assertEqual(
@@ -983,11 +1110,6 @@ class TestLocalFilesystem(unittest.TestCase):
)
def test_convert_info(self, *mock_methods):
- fs = gvfs.GravitinoVirtualFileSystem(
- server_uri=self._server_uri,
- metalake_name=self._metalake_name,
- skip_instance_cache=True,
- )
# test actual path not start with storage location
entry = {
"name": "/not_start_with_storage/ttt",
@@ -995,12 +1117,14 @@ class TestLocalFilesystem(unittest.TestCase):
"type": "file",
"mtime": datetime.now(),
}
- storage_location = "hdfs://localhost:8090/fileset/test_f1"
- virtual_location = fs._get_virtual_location(
+ storage_location = "file:/fileset/test_f1"
+ gvfs_path_prefix = to_gvfs_path_prefix(
NameIdentifier.of("test_metalake", "test_catalog", "test_schema", "test_f1")
)
with self.assertRaises(GravitinoRuntimeException):
- fs._convert_actual_info(entry, storage_location, virtual_location)
+ LOCA_HANDLER.actual_info_to_gvfs_info(
+ entry, storage_location, gvfs_path_prefix
+ )
# test actual path start with storage location
entry = {
@@ -1009,17 +1133,14 @@ class TestLocalFilesystem(unittest.TestCase):
"type": "file",
"mtime": datetime.now(),
}
- info = fs._convert_actual_info(entry, storage_location, virtual_location)
+ info = LOCA_HANDLER.actual_info_to_gvfs_info(
+ entry, storage_location, gvfs_path_prefix
+ )
self.assertEqual(
"fileset/test_catalog/test_schema/test_f1/actual_path", info["name"]
)
# test convert actual local path
- fs = gvfs.GravitinoVirtualFileSystem(
- server_uri=self._server_uri,
- metalake_name=self._metalake_name,
- skip_instance_cache=True,
- )
# test actual path not start with storage location
entry = {
"name": "/not_start_with_storage/ttt",
@@ -1028,11 +1149,13 @@ class TestLocalFilesystem(unittest.TestCase):
"mtime": datetime.now(),
}
storage_location = "file:/tmp/fileset/test_f1"
- virtual_location = fs._get_virtual_location(
+ gvfs_path_prefix = to_gvfs_path_prefix(
NameIdentifier.of("test_metalake", "test_catalog", "test_schema", "test_f1")
)
with self.assertRaises(GravitinoRuntimeException):
- fs._convert_actual_info(entry, storage_location, virtual_location)
+ LOCA_HANDLER.actual_info_to_gvfs_info(
+ entry, storage_location, gvfs_path_prefix
+ )
# test actual path start with storage location
entry = {
@@ -1041,7 +1164,9 @@ class TestLocalFilesystem(unittest.TestCase):
"type": "file",
"mtime": datetime.now(),
}
- info = fs._convert_actual_info(entry, storage_location, virtual_location)
+ info = LOCA_HANDLER.actual_info_to_gvfs_info(
+ entry, storage_location, gvfs_path_prefix
+ )
self.assertEqual(
"fileset/test_catalog/test_schema/test_f1/actual_path", info["name"]
)
@@ -1076,9 +1201,14 @@ class TestLocalFilesystem(unittest.TestCase):
skip_instance_cache=True,
)
actual_path = fileset_storage_location + "/test.parquet"
- with patch(
- "gravitino.client.fileset_catalog.FilesetCatalog.get_file_location",
- return_value=actual_path,
+ with patch.multiple(
+ "gravitino.client.fileset_catalog.FilesetCatalog",
+ load_fileset=mock.MagicMock(
+ return_value=mock_base.mock_load_fileset(
+ "fileset", fileset_storage_location
+ )
+ ),
+ get_file_location=mock.MagicMock(return_value=actual_path),
):
# to parquet
data.to_parquet(fileset_virtual_location + "/test.parquet", filesystem=fs)
@@ -1100,6 +1230,11 @@ class TestLocalFilesystem(unittest.TestCase):
with patch(
"gravitino.client.fileset_catalog.FilesetCatalog.get_file_location",
side_effect=[actual_path1, actual_path2, actual_path2],
+ ), patch(
+ "gravitino.client.fileset_catalog.FilesetCatalog.load_fileset",
+ return_value=mock_base.mock_load_fileset(
+ "fileset", fileset_storage_location
+ ),
):
# to csv
data.to_csv(
@@ -1127,9 +1262,14 @@ class TestLocalFilesystem(unittest.TestCase):
skip_instance_cache=True,
)
actual_path = fileset_storage_location + "/test.parquet"
- with patch(
- "gravitino.client.fileset_catalog.FilesetCatalog.get_file_location",
- return_value=actual_path,
+ with patch.multiple(
+ "gravitino.client.fileset_catalog.FilesetCatalog",
+ load_fileset=mock.MagicMock(
+ return_value=mock_base.mock_load_fileset(
+ "fileset", fileset_storage_location
+ )
+ ),
+ get_file_location=mock.MagicMock(return_value=actual_path),
):
# to parquet
data.to_parquet(fileset_virtual_location + "/test.parquet", filesystem=fs)
@@ -1172,9 +1312,14 @@ class TestLocalFilesystem(unittest.TestCase):
metalake_name=self._metalake_name,
skip_instance_cache=True,
)
- with patch(
- "gravitino.client.fileset_catalog.FilesetCatalog.get_file_location",
- return_value=actual_path,
+ with patch.multiple(
+ "gravitino.client.fileset_catalog.FilesetCatalog",
+ load_fileset=mock.MagicMock(
+ return_value=mock_base.mock_load_fileset(
+ "fileset", fileset_storage_location
+ )
+ ),
+ get_file_location=mock.MagicMock(return_value=actual_path),
):
self.assertTrue(fs.exists(fileset_virtual_location))
diff --git a/clients/client-python/tests/unittests/test_gvfs_without_fileset.py b/clients/client-python/tests/unittests/test_gvfs_without_fileset.py
index bc72b224fd..b610254dab 100644
--- a/clients/client-python/tests/unittests/test_gvfs_without_fileset.py
+++ b/clients/client-python/tests/unittests/test_gvfs_without_fileset.py
@@ -17,21 +17,38 @@
import unittest
from unittest.mock import patch
-from gravitino.filesystem.gvfs import (
- GravitinoVirtualFileSystem,
- FilesetPathNotFoundError,
-)
+from gravitino.exceptions.base import NoSuchFilesetException
+from gravitino.filesystem.gvfs import GravitinoVirtualFileSystem
+from gravitino.filesystem.gvfs_base_operations import FilesetPathNotFoundError
class TestGVFSWithoutFileset(unittest.TestCase):
- @patch("gravitino.filesystem.gvfs.create_client")
- @patch.object(GravitinoVirtualFileSystem, "_get_fileset_context")
- def test_when_fileset_not_created(
- self, mock_get_fileset_context, mock_create_client
- ):
- mock_create_client.return_value = None
- mock_get_fileset_context.return_value = None
+ @patch.object(GravitinoVirtualFileSystem, "_get_gvfs_operations_class")
+ def test_when_fileset_not_created(self, mock_get_gvfs_operations):
+ mock_operations = unittest.mock.MagicMock()
+ methods = [
+ "ls",
+ "info",
+ "exists",
+ "cp_file",
+ "mv",
+ "rm",
+ "rm_file",
+ "rmdir",
+ "open",
+ "mkdir",
+ "makedirs",
+ "created",
+ "modified",
+ "cat_file",
+ "get_file",
+ ]
+ for method in methods:
+ getattr(mock_operations, method).side_effect = NoSuchFilesetException(
+ f"{method} failed"
+ )
+ mock_get_gvfs_operations.return_value = mock_operations
fs = GravitinoVirtualFileSystem(
server_uri="http://localhost:9090",
diff --git a/docs/how-to-use-gvfs.md b/docs/how-to-use-gvfs.md
index f03dc041a3..3f768f136e 100644
--- a/docs/how-to-use-gvfs.md
+++ b/docs/how-to-use-gvfs.md
@@ -346,20 +346,21 @@ to recompile the native libraries like `libhdfs` and others, and completely repl
### Configuration
-| Configuration item | Description | Default value | Required | Since version |
-|---------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------|-----------------------------------|------------------|
-| `server_uri` | The Gravitino server uri, e.g. `http://localhost:8090`. | (none) | Yes | 0.6.0-incubating |
-| `metalake_name` | The metalake name which the fileset belongs to. | (none) | Yes | 0.6.0-incubating |
-| `cache_size` | The cache capacity of the Gravitino Virtual File System. | `20` | No | 0.6.0-incubating |
-| `cache_expired_time` | The value of time that the cache expires after accessing in the Gravitino Virtual File System. The value is in `seconds`. | `3600` | No | 0.6.0-incubating |
-| `auth_type` | The auth type to initialize the Gravitino client to use with the Gravitino Virtual File System. Currently supports `simple` and `oauth2` auth types. | `simple` | No | 0.6.0-incubating |
-| `oauth2_server_uri` | The auth server URI for the Gravitino client when using `oauth2` auth type. | (none) | Yes if you use `oauth2` auth type | 0.7.0-incubating |
-| `oauth2_credential` | The auth credential for the Gravitino client when using `oauth2` auth type. | (none) | Yes if you use `oauth2` auth type | 0.7.0-incubating |
-| `oauth2_path` | The auth server path for the Gravitino client when using `oauth2` auth type. Please remove the first slash `/` from the path, for example `oauth/token`. | (none) | Yes if you use `oauth2` auth type | 0.7.0-incubating |
-| `oauth2_scope` | The auth scope for the Gravitino client when using `oauth2` auth type with the Gravitino Virtual File System. | (none) | Yes if you use `oauth2` auth type | 0.7.0-incubating |
-| `credential_expiration_ratio` | The ratio of expiration time for credential from Gravitino. This is used in the cases where Gravitino Hadoop catalogs have enable credential vending. if the expiration time of credential fetched from Gravitino is 1 hour, GVFS client will try to refresh the credential in 1 * 0.9 = 0.5 hour. | 0.5 | No | 0.8.0-incubating |
-| `current_location_name` | The configuration used to select the location of the fileset. If this configuration is not set, the value of environment variable configured by `current_location_name_env_var` will be checked. If neither is set, the value of fileset property `default-location-name` will be used as the location name. | the value of fileset property `default-location-name` | No | 0.9.0-incubating |
-| `current_location_name_env_var` | The environment variable name to get the current location name. | `CURRENT_LOCATION_NAME` | No | 0.9.0-incubating |
+| Configuration item | Description | Default value | Required | Since version |
+|---------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------|-----------------------------------|------------------|
+| `server_uri` | The Gravitino server uri, e.g. `http://localhost:8090`. | (none) | Yes | 0.6.0-incubating |
+| `metalake_name` | The metalake name which the fileset belongs to. | (none) | Yes | 0.6.0-incubating |
+| `cache_size` | The cache capacity of the Gravitino Virtual File System. | `20` | No | 0.6.0-incubating |
+| `cache_expired_time` | The value of time that the cache expires after accessing in the Gravitino Virtual File System. The value is in `seconds`. | `3600` | No | 0.6.0-incubating |
+| `auth_type` | The auth type to initialize the Gravitino client to use with the Gravitino Virtual File System. Currently supports `simple` and `oauth2` auth types. | `simple` | No | 0.6.0-incubating |
+| `oauth2_server_uri` | The auth server URI for the Gravitino client when using `oauth2` auth type. | (none) | Yes if you use `oauth2` auth type | 0.7.0-incubating |
+| `oauth2_credential` | The auth credential for the Gravitino client when using `oauth2` auth type. | (none) | Yes if you use `oauth2` auth type | 0.7.0-incubating |
+| `oauth2_path` | The auth server path for the Gravitino client when using `oauth2` auth type. Please remove the first slash `/` from the path, for example `oauth/token`. | (none) | Yes if you use `oauth2` auth type | 0.7.0-incubating |
+| `oauth2_scope` | The auth scope for the Gravitino client when using `oauth2` auth type with the Gravitino Virtual File System. | (none) | Yes if you use `oauth2` auth type | 0.7.0-incubating |
+| `credential_expiration_ratio` | The ratio of expiration time for credential from Gravitino. This is used in the cases where Gravitino Hadoop catalogs have enable credential vending. if the expiration time of credential fetched from Gravitino is 1 hour, GVFS client will try to refresh the credential in 1 * 0.9 = 0.5 hour. | 0.5 | No | 0.8.0-incubating |
+| `current_location_name` | The configuration used to select the location of the fileset. If this configuration is not set, the value of environment variable configured by `current_location_name_env_var` will be checked. If neither is set, the value of fileset property `default-location-name` will be used as the location name. | the value of fileset property `default-location-name` | No | 0.9.0-incubating |
+| `current_location_name_env_var` | The environment variable name to get the current location name. | `CURRENT_LOCATION_NAME` | No | 0.9.0-incubating |
+| `operations_class` | The operations class to provide the FS operations for the Gravitino Virtual File System. Users can extends `BaseGVFSOperations` to implement their own operations and configure the class name in this conf to use custom FS operations. | `gravitino.filesystem.gvfs_default_operations.DefaultGVFSOperations` | No | 0.9.0-incubating |
#### Configurations for S3, GCS, OSS and Azure Blob storage fileset