Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion oasis_data_manager/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = '0.2.3'
__version__ = '0.2.4'
113 changes: 113 additions & 0 deletions oasis_data_manager/filestore/archive.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
"""Tar archive helpers used by the storage backends to `put` and `extract` directories

Archives are written as gzip (``tar.gz``, the default) or zstandard (``tar.zst``).
zstd uses the standard library ``compression.zstd`` module on Python 3.14+, or the
``zstandard`` package (``pip install oasis-data-manager[zstd]``) on older versions.
"""
import contextlib
import os
import tarfile

from oasis_data_manager.errors import OasisDataManagerException

GZIP = "gz"
ZSTD = "zst"
ARCHIVE_SUFFIXES = {GZIP: "tar.gz", ZSTD: "tar.zst"}

# Speed over size: on Oasis inputs gzip level 1 is ~11x faster than level 9 for a ~10% larger archive
DEFAULT_COMPRESSLEVEL = {GZIP: 1, ZSTD: 3}

ZSTD_MAGIC = b"\x28\xb5\x2f\xfd"


def validate_compression(compression):
if compression not in ARCHIVE_SUFFIXES:
raise OasisDataManagerException(
f"Unsupported archive compression '{compression}', expected one of {list(ARCHIVE_SUFFIXES)}"
)
return compression


def _zstd_threads(threads):
"""-1 uses every available core, 0 compresses in the calling thread"""
if threads is None or threads < 0:
return os.cpu_count() or 1
return threads


def _stdlib_zstd():
try:
from compression import zstd
except ImportError:
return None
return zstd


def _zstandard():
try:
import zstandard
except ImportError:
raise OasisDataManagerException(
"zstd archives need Python 3.14+ or the 'zstandard' package, install with 'pip install oasis-data-manager[zstd]'"
)
return zstandard


def is_zstd(archive_fp):
with open(archive_fp, "rb") as f:
return f.read(4) == ZSTD_MAGIC


def compress_dir(archive_fp, directory, arcname="/", compression=GZIP, compresslevel=None, threads=-1):
"""Write `directory` to a tar archive at `archive_fp`

:param compression: `gz` or `zst`
:param compresslevel: compression level, defaults to `DEFAULT_COMPRESSLEVEL` for the format
:param threads: zstd worker threads, -1 for every core (ignored for gzip)
"""
validate_compression(compression)
level = DEFAULT_COMPRESSLEVEL[compression] if compresslevel is None else int(compresslevel)

if compression == GZIP:
with tarfile.open(archive_fp, "w:gz", compresslevel=level) as tar:
tar.add(directory, arcname=arcname)
return

threads = _zstd_threads(threads)
zstd = _stdlib_zstd()
if zstd:
options = {zstd.CompressionParameter.compression_level: level}
if threads and zstd.CompressionParameter.nb_workers.bounds()[1] > 0:
options[zstd.CompressionParameter.nb_workers] = threads
with tarfile.open(archive_fp, "w:zst", options=options) as tar:
tar.add(directory, arcname=arcname)
return

cctx = _zstandard().ZstdCompressor(level=level, threads=threads)
with open(archive_fp, "wb") as fh, cctx.stream_writer(fh, closefd=False) as writer, \
tarfile.open(fileobj=writer, mode="w|") as tar:
tar.add(directory, arcname=arcname)


@contextlib.contextmanager
def open_archive(archive_fp):
"""Open a gzip, zstd or uncompressed tar archive for reading

zstd archives read with the `zstandard` package are opened as a stream: iterate or `extractall`,
don't seek back to earlier members.
"""
# tarfile detects zstd itself when compression.zstd is available
if _stdlib_zstd() or not is_zstd(archive_fp):
with tarfile.open(archive_fp) as tar:
yield tar
return

dctx = _zstandard().ZstdDecompressor()
with open(archive_fp, "rb") as fh, dctx.stream_reader(fh) as reader, tarfile.open(fileobj=reader, mode="r|") as tar:
yield tar


def extract_archive(archive_fp, directory):
with open_archive(archive_fp) as tar:
os.makedirs(directory, exist_ok=True)
tar.extractall(directory)
4 changes: 2 additions & 2 deletions oasis_data_manager/filestore/backends/aws.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,12 +261,12 @@ def url(self, object_name, parameters=None, expire=None):
else:
return self._strip_signing_parameters(url)

def put(self, reference, filename=None, subdir="", suffix=None, arcname=None):
def put(self, reference, filename=None, subdir="", suffix=None, arcname=None, compression=None):
# Prepend location so the returned key is bucket-relative (location/subdir/file).
# The server's CopyObject and is_in_bucket() both use the raw bucket key, so the
# returned value must include the location prefix, not be relative to it.
effective_subdir = os.path.join(self.location, subdir) if self.location else subdir
return super().put(reference, filename=filename, subdir=effective_subdir, suffix=suffix, arcname=arcname)
return super().put(reference, filename=filename, subdir=effective_subdir, suffix=suffix, arcname=arcname, compression=compression)

def get_storage_url(self, filename=None, suffix="tar.gz", encode_params=True):
filename = (
Expand Down
61 changes: 47 additions & 14 deletions oasis_data_manager/filestore/backends/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import logging
import os
import shutil
import tarfile
# import tarfile # archive handling moved to oasis_data_manager.filestore.archive
import tempfile
import uuid
from pathlib import Path
Expand All @@ -14,10 +14,10 @@
from fsspec.implementations.dirfs import DirFileSystem

from oasis_data_manager.errors import OasisDataManagerException
from oasis_data_manager.filestore.archive import ARCHIVE_SUFFIXES, GZIP, compress_dir, extract_archive, validate_compression
import xxhash

LOG_FILE_SUFFIX = "txt"
ARCHIVE_FILE_SUFFIX = "tar.gz"


class MissingInputsException(OasisDataManagerException):
Expand Down Expand Up @@ -69,12 +69,25 @@ class BaseStorage(object):
fsspec_filesystem_class: Optional[Type[fsspec.AbstractFileSystem]]

def __init__(
self, root_dir="", cache_dir: Union[str, None] = "/tmp/data-cache", logger=None, **kwargs
self,
root_dir="",
cache_dir: Union[str, None] = "/tmp/data-cache",
logger=None,
archive_compression: str = GZIP,
archive_compresslevel: Optional[int] = None,
archive_threads: int = -1,
**kwargs
):
# Use for caching files across multiple runs, set value 'None' or 'False' to disable
self.cache_root = cache_dir
self.root_dir = root_dir

# How directories are archived by `put`: 'gz' or 'zst', level (None for the format default)
# and zstd worker threads (-1 for every core)
self.archive_compression = validate_compression(archive_compression)
self.archive_compresslevel = archive_compresslevel
self.archive_threads = archive_threads

self.logger = logger or logging.getLogger()
self._fs: Optional[StrictRootDirFs] = None

Expand All @@ -86,9 +99,18 @@ def _normalize_root_dir(container, root_dir):
def to_config(self) -> dict:
return {
"storage_class": f"{self.__module__}.{type(self).__name__}",
"options": self.config_options,
"options": {
**self.config_options,
"archive_compression": self.archive_compression,
"archive_compresslevel": self.archive_compresslevel,
"archive_threads": self.archive_threads,
},
}

def archive_suffix(self, compression=None):
"""Filename extension of directory archives written by `put`, e.g. `tar.gz`"""
return ARCHIVE_SUFFIXES[validate_compression(compression or self.archive_compression)]

@property
def config_options(self):
raise NotImplementedError()
Expand Down Expand Up @@ -148,11 +170,9 @@ def extract(self, archive_fp, directory, storage_subdir=""):
os.path.join(temp_dir_path, os.path.basename(archive_fp)),
subdir=storage_subdir,
)
with tarfile.open(local_archive_path) as f:
os.makedirs(directory, exist_ok=True)
f.extractall(directory)
extract_archive(local_archive_path, directory)

def compress(self, archive_fp, directory, arcname=None):
def compress(self, archive_fp, directory, arcname=None, compression=None):
"""Compress a directory

Parameters
Expand All @@ -166,10 +186,19 @@ def compress(self, archive_fp, directory, arcname=None):
:param arcname: If given, `arcname' set an alternative
name for the file in the archive.
:type arcname: str

:param compression: `gz` or `zst`, defaults to `self.archive_compression`
:type compression: str
"""
arcname = arcname if arcname else "/"
with tarfile.open(archive_fp, "w:gz") as tar:
tar.add(directory, arcname=arcname)
compress_dir(
archive_fp,
directory,
arcname=arcname,
compression=compression or self.archive_compression,
compresslevel=self.archive_compresslevel,
threads=self.archive_threads,
)

def get_from_cache(self, reference, required=False, no_cache_target=None):
"""
Expand Down Expand Up @@ -326,7 +355,7 @@ def get(self, reference, output_path="", subdir="", required=False):

return None

def put(self, reference, filename=None, subdir="", suffix=None, arcname=None):
def put(self, reference, filename=None, subdir="", suffix=None, arcname=None, compression=None):
"""Place object in storage

Top level send to storage function,
Expand All @@ -348,9 +377,13 @@ def put(self, reference, filename=None, subdir="", suffix=None, arcname=None):
name for the file in the archive.
:type arcname: str

:param suffix: Set the filename extension defaults to `tar.gz`
:param suffix: Set the filename extension defaults to the archive suffix, e.g. `tar.gz`
:type suffix: str

:param compression: Archive compression for a directory, `gz` or `zst`,
defaults to `self.archive_compression`
:type compression: str

:return: access storage reference returned from self._store_file, self._store_dir
This will either be a pre-signed URL or absolute filepath
:rtype str
Expand All @@ -370,14 +403,14 @@ def put(self, reference, filename=None, subdir="", suffix=None, arcname=None):
return storage_location

elif os.path.isdir(reference):
ext = "tar.gz" if not suffix else suffix
ext = self.archive_suffix(compression) if not suffix else suffix
filename = filename if filename else self._get_unique_filename(ext)
storage_path = os.path.join(subdir, filename) if subdir else filename
self.fs.mkdirs(os.path.dirname(storage_path), exist_ok=True)

self.logger.info("Store dir: {} -> {}".format(reference, storage_path))
with tempfile.NamedTemporaryFile() as f:
self.compress(f.name, reference, arcname)
self.compress(f.name, reference, arcname, compression=compression)
self.fs.put(f.name, storage_path)
return storage_path
else:
Expand Down
1 change: 1 addition & 0 deletions optional-package.in
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ distributed
geopandas==0.14.4
pyogrio
s3fs>=2023.12.2
zstandard; python_version < '3.14'
4 changes: 4 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,15 @@ s3 = [
azure = [
"adlfs",
]
zstd = [
"zstandard; python_version < '3.14'",
]
extra = [
"oasis-data-manager[geo]",
"oasis-data-manager[dask]",
"oasis-data-manager[s3]",
"oasis-data-manager[azure]",
"oasis-data-manager[zstd]",
]

[project.urls]
Expand Down
Loading