Skip to content
Draft
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
8 changes: 4 additions & 4 deletions .github/workflows/release_seaweedfs_with_datasets.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ jobs:
- name: Check out the repo
uses: actions/checkout@v7
with:
sparse-checkout: 'pre-filled-object-storage'
sparse-checkout: 'object-storage-pre-filled'

- name: Extract metadata (labels) for Docker Hub
id: meta_dockerhub
Expand All @@ -48,8 +48,8 @@ jobs:
id: docker_build
uses: docker/build-push-action@v7
with:
context: pre-filled-object-storage
file: pre-filled-object-storage/docker/Dockerfile
context: object-storage-pre-filled
file: object-storage-pre-filled/docker/Dockerfile
tags: openml/seaweedfs-with-datasets:${{ github.event.inputs.docker_tag }}
labels: ${{ steps.meta_dockerhub.outputs.labels }}
platforms: linux/amd64,linux/arm64
Expand All @@ -62,7 +62,7 @@ jobs:
password: ${{ secrets.DOCKERHUB_TOKEN }}
repository: openml/seaweedfs-with-datasets
short-description: "A SeaweedFS object storage pre-filled with OpenML datasets, used for development and tests."
readme-filepath: ./pre-filled-object-storage/docker/README.md
readme-filepath: ./object-storage-pre-filled/docker/README.md

- name: Image digest
run: echo ${{ steps.docker_build.outputs.digest }}
5 changes: 5 additions & 0 deletions object-storage-backup/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
S3_SERVER=https://www.openml.org/minio
S3_ACCESS_KEY=[REDACTED]
S3_SECRET_KEY=[REDACTED]
S3_SUBPATH="/minio"
S3_VERIFY=true
11 changes: 11 additions & 0 deletions object-storage-backup/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Back-up the object-storage

## Development
Installing dependencies:
```bash
python3 -m venv venv
source venv/bin/activate

python -m pip install uv
uv pip install -e ".[dev]"
```
25 changes: 25 additions & 0 deletions object-storage-backup/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
[project]
name = "openml-object-storage-backup"
version = "0.0.1"
authors = [
{ name="Jos van der Velde" },
]
description = "Writing files from our object-storage to disk."
readme = "README.md"
requires-python = ">=3.13"
classifiers = [
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
]
dependencies = [
"boto3==1.44.3",
"boto3-stubs~=1.44.3",
"loguru==0.8.0",
"python-dotenv==1.2.4",
]

[project.optional-dependencies]
dev = [
"boto3-stubs[s3]==1.44.3"
]
116 changes: 116 additions & 0 deletions object-storage-backup/src/cli_backup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import argparse
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path

from dotenv import load_dotenv
from loguru import logger

from s3_helper import create_s3_client

def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument(
"-b", "--bucket",
type=str,
required=True,
help = "The S3 bucket"
)
parser.add_argument(
"-o", "--output",
type=Path,
required=True,
help="Output directory (without the bucket name)"
)
parser.add_argument(
"--n-threads",
type=int,
default=1,
)
parser.add_argument(
"--s3-page-size",
type=int,
default=1000
)
parser.add_argument(
"--ignore-existing-files",
action="store_true"
)
return parser.parse_args()


def _s3_keys(s3_client, bucket, page_size):
paginator = s3_client.get_paginator("list_objects_v2")
pages = paginator.paginate(Bucket=bucket, PaginationConfig={"PageSize": page_size})
logger.info("Reading all s3 keys...")
for page in pages:
logger.debug(f"Page: {page.get('Name')}...")
if "Contents" not in page:
logger.info(f"Empty page: {page.get('Name')}")
else:
for obj in page["Contents"]:
s3_key = obj["Key"]
if not s3_key.endswith("/"):
yield s3_key


def _download_object(s3_client, bucket, s3_key, output_path):
logger.debug(f"Downloading {s3_key} to {output_path}...")
for attempt in range(3):
try:
# s3_client.download_file(bucket, s3_key, output_path) does not work for MinIO, throwing
# a KeyError: 'ContentLength'. So manually getting and writing the objects
response = s3_client.get_object(Bucket=bucket, Key=s3_key)
with open(output_path, "wb") as output_file:
with response["Body"] as input_stream:
while chunk := input_stream.read(8 * 1024 * 1024):
output_file.write(chunk)
logger.debug(f"Downloading {s3_key} to {output_path} done.")
return
except Exception as e:
logger.warning(f"Exception while downloading {s3_key} to {output_path}: {e}")
time.sleep(2 ** attempt)
raise RuntimeError(f"Failed to download {s3_key} to {output_path}") from e


def main():
load_dotenv()
args = parse_args()
s3_client = create_s3_client()

bucket = args.bucket
output_dir = args.output / bucket
ignore_existing = args.ignore_existing_files
n_threads = args.n_threads
page_size = args.s3_page_size
logger.info(f"From {bucket} to {output_dir} using {n_threads} threads.")
output_dir.mkdir(parents=True, exist_ok=True)


futures = []
download_count = 0
previous_ignored = False
with ThreadPoolExecutor(max_workers=n_threads) as executor:
for s3_key in _s3_keys(s3_client, bucket, page_size):
output_path = output_dir / s3_key
output_path.parent.mkdir(parents=True, exist_ok=True)
if output_path.exists() and ignore_existing:
logger.debug(f"Ignoring existing file {output_path}")
previous_ignored = True
continue
if previous_ignored:
logger.info(f"Ignored the previous file, continuing with {s3_key}...")
previous_ignored = False

future = executor.submit(_download_object, s3_client, bucket, s3_key, output_path)
futures.append(future)
for future in as_completed(futures):
future.result() # Will raise RuntimeError if a thread failed
download_count += 1
if download_count % 100 == 0:
logger.info(f"Downloaded {download_count} files...")
logger.info(f"Done! Downloaded {download_count} files to {output_dir}")


if __name__ == '__main__':
main()
92 changes: 92 additions & 0 deletions object-storage-backup/src/cli_upload.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import argparse
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path

from boto3.s3.transfer import TransferConfig
from botocore.exceptions import ClientError
from dotenv import load_dotenv
from loguru import logger


from s3_helper import create_s3_client, file_exists, create_public_bucket_if_not_exists


def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument(
"-b", "--bucket",
type=str,
required=True,
help = "The S3 bucket"
)
parser.add_argument(
"-input", "--input",
type=Path,
required=True,
help="The input directory (without the bucket name). E.g., /my/path/. All data from "
"/my/path/[bucket] will be uploaded."
)
parser.add_argument(
"--n-threads",
type=int,
default=1,
)
parser.add_argument(
"--ignore-existing-files",
action="store_true"
)
return parser.parse_args()


def main():
load_dotenv()
args = parse_args()
s3_client = create_s3_client()

bucket = args.bucket
input_dir = args.input / bucket
ignore_existing = args.ignore_existing_files
n_threads = args.n_threads
logger.info(f"From {input_dir} to {bucket} using {n_threads} threads.")

config = TransferConfig(
multipart_threshold=25 * 1024 * 1024, # 25 MB
multipart_chunksize=25 * 1024 * 1024, # 25 MB
max_concurrency=10,
use_threads=True,
)
files_to_upload = [p for p in input_dir.rglob("*") if p.is_file()]

def _upload_single_file(file_path: Path):
s3_key = file_path.relative_to(input_dir).as_posix()
if ignore_existing and file_exists(s3_client, bucket, s3_key):
logger.debug(f"File {file_path} already exists! Ignoring the upload.")
return
logger.debug(f"Uploading {file_path} to bucket {bucket} key {s3_key}...")
s3_client.upload_file(Filename=str(file_path), Bucket=bucket, Key=s3_key, Config=config)
logger.debug(f"Uploading {file_path} to bucket {bucket} key {s3_key} done.")

logger.info("Creating public bucket if it doesn't exist...")
create_public_bucket_if_not_exists(s3_client, bucket)
logger.info(f"Starting upload of {len(files_to_upload)} files to s3://{bucket}...")
uploaded_count = 0
failed_count = 0
with ThreadPoolExecutor(max_workers=n_threads) as executor:
futures = {
executor.submit(_upload_single_file, file_path): file_path
for file_path in files_to_upload
}
for future in as_completed(futures):
file_path = futures[future]
try:
future.result()
uploaded_count += 1
if uploaded_count % 100 == 0:
logger.info(f"Uploaded {uploaded_count} of {len(files_to_upload)} (excluding {failed_count} failed uploads)")
except ClientError as e:
logger.warning(f"Failed to upload {file_path}! {e}")
failed_count += 1
logger.info(f"Finished! {uploaded_count} of {len(files_to_upload)} files uploaded. There were {failed_count} failed uploads.")

if __name__ == '__main__':
main()
93 changes: 93 additions & 0 deletions object-storage-backup/src/s3_helper.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import json
import os
import typing
from functools import partial
from urllib.parse import urlparse, urlunparse

import urllib3
from botocore.config import Config
from botocore.exceptions import ClientError
from dotenv import load_dotenv
import boto3
from loguru import logger

if typing.TYPE_CHECKING:
from mypy_boto3_s3.client import S3Client


def strip_subpath_before_sign(request, subpath, **_):
"""Fixing SignatureDoesNotMatch error when MinIO is hosted on SubPath"""
parsed = urlparse(request.url)
if parsed.path.startswith(subpath):
new_path = parsed.path[len(subpath):] or "/"
request.url = urlunparse(parsed._replace(path=new_path))

def restore_subpath_before_send(request, subpath, **_):
"""Fixing SignatureDoesNotMatch error when MinIO is hosted on SubPath"""
parsed = urlparse(request.url)
if not parsed.path.startswith(subpath):
clean_path = parsed.path if parsed.path.startswith("/") else f"/{parsed.path}"
request.url = urlunparse(parsed._replace(path=f"{subpath}{clean_path}"))


def create_s3_client() -> "S3Client":
load_dotenv() # take environment variables from .env.
server = os.environ.get("S3_SERVER", default="https://www.openml.org/s3/")
verify = os.environ.get("S3_VERIFY", default="true") != "false"
if not verify:
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
logger.info(f"Creating S3 client with server {server} and verify {verify}")
client = boto3.client(
's3',
endpoint_url=server,
aws_access_key_id=os.environ["S3_ACCESS_KEY"],
aws_secret_access_key=os.environ["S3_SECRET_KEY"],
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),
verify=verify,
)
subpath = os.environ.get("S3_SUBPATH")
if subpath:
client.meta.events.register("before-sign.s3", partial(strip_subpath_before_sign, subpath=subpath))
client.meta.events.register("before-send.s3", partial(restore_subpath_before_send, subpath=subpath))
return client

def file_exists(client: "S3Client", bucket_name: str, file_path: str) -> bool:
try:
client.head_object(Bucket=bucket_name, Key=file_path)
return True
except ClientError as e:
if e.response["Error"]["Code"] == "404":
return False
raise

def create_public_bucket_if_not_exists(client: "S3Client", bucket_name: str):
try:
client.head_bucket(Bucket=bucket_name)
logger.info(f"Bucket {bucket_name} already exists")
return
except ClientError as e:
if e.response["Error"]["Code"] != "404":
raise
client.create_bucket(Bucket=bucket_name)
_make_bucket_public(client, bucket_name)
logger.info(f"Created bucket {bucket_name}")

def _make_bucket_public(client: "S3Client", bucket_name: str):
public_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublicReadGetObject",
"Effect": "Allow",
"Principal": "*",
"Action": ["s3:GetObject"],
"Resource": [f"arn:aws:s3:::{bucket_name}/*"],
}
],
}

client.put_bucket_policy(
Bucket=bucket_name,
Policy=json.dumps(public_policy),
)
logger.info(f"Made bucket {bucket_name} public")