From 1c9e1e94bee065a4b68abc89679dd7438b4a9890 Mon Sep 17 00:00:00 2001 From: Jos van der Velde Date: Mon, 16 Nov 2026 17:00:33 +0100 Subject: [PATCH 1/7] Rename pre-filled-object-storage to object-storage-pre-filled --- .github/workflows/release_seaweedfs_with_datasets.yml | 8 ++++---- .../README.md | 0 .../docker/Dockerfile | 0 .../docker/README.md | 0 .../docker/s3_config.json | 0 5 files changed, 4 insertions(+), 4 deletions(-) rename {pre-filled-object-storage => object-storage-pre-filled}/README.md (100%) rename {pre-filled-object-storage => object-storage-pre-filled}/docker/Dockerfile (100%) rename {pre-filled-object-storage => object-storage-pre-filled}/docker/README.md (100%) rename {pre-filled-object-storage => object-storage-pre-filled}/docker/s3_config.json (100%) diff --git a/.github/workflows/release_seaweedfs_with_datasets.yml b/.github/workflows/release_seaweedfs_with_datasets.yml index 822c365..90223ad 100644 --- a/.github/workflows/release_seaweedfs_with_datasets.yml +++ b/.github/workflows/release_seaweedfs_with_datasets.yml @@ -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 @@ -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 @@ -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 }} diff --git a/pre-filled-object-storage/README.md b/object-storage-pre-filled/README.md similarity index 100% rename from pre-filled-object-storage/README.md rename to object-storage-pre-filled/README.md diff --git a/pre-filled-object-storage/docker/Dockerfile b/object-storage-pre-filled/docker/Dockerfile similarity index 100% rename from pre-filled-object-storage/docker/Dockerfile rename to object-storage-pre-filled/docker/Dockerfile diff --git a/pre-filled-object-storage/docker/README.md b/object-storage-pre-filled/docker/README.md similarity index 100% rename from pre-filled-object-storage/docker/README.md rename to object-storage-pre-filled/docker/README.md diff --git a/pre-filled-object-storage/docker/s3_config.json b/object-storage-pre-filled/docker/s3_config.json similarity index 100% rename from pre-filled-object-storage/docker/s3_config.json rename to object-storage-pre-filled/docker/s3_config.json From 029d70f01364b14162fd4b7c73c45093acb1e3ca Mon Sep 17 00:00:00 2001 From: Jos van der Velde Date: Tue, 17 Nov 2026 14:01:24 +0100 Subject: [PATCH 2/7] Code to download data from S3 --- object-storage-backup/.env.example | 5 ++ object-storage-backup/README.md | 11 ++++ object-storage-backup/pyproject.toml | 25 +++++++++ object-storage-backup/src/cli.py | 71 ++++++++++++++++++++++++++ object-storage-backup/src/s3_helper.py | 50 ++++++++++++++++++ 5 files changed, 162 insertions(+) create mode 100644 object-storage-backup/.env.example create mode 100644 object-storage-backup/README.md create mode 100644 object-storage-backup/pyproject.toml create mode 100644 object-storage-backup/src/cli.py create mode 100644 object-storage-backup/src/s3_helper.py diff --git a/object-storage-backup/.env.example b/object-storage-backup/.env.example new file mode 100644 index 0000000..92e5bc8 --- /dev/null +++ b/object-storage-backup/.env.example @@ -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 \ No newline at end of file diff --git a/object-storage-backup/README.md b/object-storage-backup/README.md new file mode 100644 index 0000000..147b185 --- /dev/null +++ b/object-storage-backup/README.md @@ -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]" +``` diff --git a/object-storage-backup/pyproject.toml b/object-storage-backup/pyproject.toml new file mode 100644 index 0000000..36f9611 --- /dev/null +++ b/object-storage-backup/pyproject.toml @@ -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" +] diff --git a/object-storage-backup/src/cli.py b/object-storage-backup/src/cli.py new file mode 100644 index 0000000..ffc9beb --- /dev/null +++ b/object-storage-backup/src/cli.py @@ -0,0 +1,71 @@ +import argparse +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( + "--bucket", + type=str, + required=True + ) + parser.add_argument( + "-o", "--output", + type=Path, + required=True, + ) + return parser.parse_args() + + +def main(): + load_dotenv() + args = parse_args() + s3_client = create_s3_client() + + bucket = args.bucket + output_dir = args.output / bucket + logger.info(f"From {bucket} to {output_dir}") + + output_dir.mkdir(parents=True, exist_ok=True) + if not output_dir.is_dir() and next(output_dir.iterdir(), None) is None: + logger.error(f"{output_dir} is not empty or not a directory") + exit(1) + + paginator = s3_client.get_paginator("list_objects_v2") + pages = paginator.paginate(Bucket=bucket) + download_count = 0 + logger.info("Connecting to S3...") + for i, page in enumerate(pages): + if i == 0: + logger.info("Connection established") + logger.debug(f"Page: {page.get('Name')}...") + if "Contents" not in page: + logger.info(f"Empty page: {page.get('Name')}") + break + for obj in page["Contents"]: + s3_key = obj["Key"] + if s3_key.endswith("/"): + continue + + output_path = output_dir / s3_key + output_path.parent.mkdir(parents=True, exist_ok=True) + + logger.debug(f"Downloading {s3_key} to {output_path}") + #s3_client.download_file(bucket, s3_key, output_path) + response = s3_client.get_object(Bucket=bucket, Key=s3_key) + with open(output_path, "wb") as f: + for chunk in response["Body"].iter_chunks(chunk_size=1024 * 1024): + f.write(chunk) + + download_count += 1 + if download_count % 100 == 0: + logger.info(f"Downloaded {download_count} files... Last file {output_path}") + logger.info(f"Done! Downloaded {download_count} files to {output_dir}") + + +if __name__ == '__main__': + main() diff --git a/object-storage-backup/src/s3_helper.py b/object-storage-backup/src/s3_helper.py new file mode 100644 index 0000000..4ecfd0b --- /dev/null +++ b/object-storage-backup/src/s3_helper.py @@ -0,0 +1,50 @@ +import os +import typing +from functools import partial +from urllib.parse import urlparse, urlunparse + +import urllib3 +from botocore.config import Config +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 \ No newline at end of file From 56f007ae123ed3e304a2e923aed0d4577dec5b39 Mon Sep 17 00:00:00 2001 From: Jos van der Velde Date: Tue, 17 Nov 2026 14:09:09 +0100 Subject: [PATCH 3/7] Cleanup --- object-storage-backup/src/cli.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/object-storage-backup/src/cli.py b/object-storage-backup/src/cli.py index ffc9beb..8263e15 100644 --- a/object-storage-backup/src/cli.py +++ b/object-storage-backup/src/cli.py @@ -9,14 +9,16 @@ def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument( - "--bucket", + "-b", "--bucket", type=str, - required=True + required=True, + help = "The S3 bucket" ) parser.add_argument( "-o", "--output", type=Path, required=True, + help="Output directory (without the bucket name)" ) return parser.parse_args() @@ -55,7 +57,8 @@ def main(): output_path.parent.mkdir(parents=True, exist_ok=True) logger.debug(f"Downloading {s3_key} to {output_path}") - #s3_client.download_file(bucket, s3_key, output_path) + # 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 f: for chunk in response["Body"].iter_chunks(chunk_size=1024 * 1024): From e9509d8925cb8a6e1113d545695962381bbb0a35 Mon Sep 17 00:00:00 2001 From: Jos van der Velde Date: Tue, 17 Nov 2026 14:48:06 +0100 Subject: [PATCH 4/7] Making it more robust --- object-storage-backup/src/cli.py | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/object-storage-backup/src/cli.py b/object-storage-backup/src/cli.py index 8263e15..59bf859 100644 --- a/object-storage-backup/src/cli.py +++ b/object-storage-backup/src/cli.py @@ -1,6 +1,9 @@ import argparse +import time +from asyncio import IncompleteReadError from pathlib import Path +from botocore.exceptions import ReadTimeoutError from dotenv import load_dotenv from loguru import logger @@ -60,10 +63,22 @@ def main(): # 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 f: - for chunk in response["Body"].iter_chunks(chunk_size=1024 * 1024): - f.write(chunk) - + with open(output_path, "wb") as output_file: + attempt = 0 + try: + with response["Body"] as input_stream: + while True: + chunk = input_stream.read(8 * 1024 * 1024) + if chunk: + output_file.write(chunk) + else: + break + except (IncompleteReadError, ReadTimeoutError) as e: + attempt += 1 + if attempt > 3: + raise RuntimeError(f"Failed to download {s3_key} to {output_path}") from e + logger.warning(f"Exception while downloading {s3_key} to {output_path}: {e}") + time.sleep(2 ** attempt) download_count += 1 if download_count % 100 == 0: logger.info(f"Downloaded {download_count} files... Last file {output_path}") From e0b5084fce64b52c85911a6ee6bc29a83f663e2c Mon Sep 17 00:00:00 2001 From: Jos van der Velde Date: Tue, 17 Nov 2026 14:57:18 +0100 Subject: [PATCH 5/7] ignore-existing --- object-storage-backup/src/cli.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/object-storage-backup/src/cli.py b/object-storage-backup/src/cli.py index 59bf859..953f610 100644 --- a/object-storage-backup/src/cli.py +++ b/object-storage-backup/src/cli.py @@ -23,6 +23,10 @@ def parse_args() -> argparse.Namespace: required=True, help="Output directory (without the bucket name)" ) + parser.add_argument( + "--ignore-existing-files", + action="store_true" + ) return parser.parse_args() @@ -33,7 +37,8 @@ def main(): bucket = args.bucket output_dir = args.output / bucket - logger.info(f"From {bucket} to {output_dir}") + ignore_existing = args.ignore_existing_files + logger.info(f"From {bucket} to {output_dir}.") output_dir.mkdir(parents=True, exist_ok=True) if not output_dir.is_dir() and next(output_dir.iterdir(), None) is None: @@ -58,6 +63,9 @@ def main(): 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}") + continue logger.debug(f"Downloading {s3_key} to {output_path}") # s3_client.download_file(bucket, s3_key, output_path) does not work for MinIO, throwing From 39623b50f1d2877c8728ef997c9d4759a9e75a87 Mon Sep 17 00:00:00 2001 From: Jos van der Velde Date: Tue, 17 Nov 2026 16:07:47 +0100 Subject: [PATCH 6/7] Functionality to upload s3 data --- .../src/{cli.py => cli_backup.py} | 0 object-storage-backup/src/cli_upload.py | 92 +++++++++++++++++++ object-storage-backup/src/s3_helper.py | 45 ++++++++- 3 files changed, 136 insertions(+), 1 deletion(-) rename object-storage-backup/src/{cli.py => cli_backup.py} (100%) create mode 100644 object-storage-backup/src/cli_upload.py diff --git a/object-storage-backup/src/cli.py b/object-storage-backup/src/cli_backup.py similarity index 100% rename from object-storage-backup/src/cli.py rename to object-storage-backup/src/cli_backup.py diff --git a/object-storage-backup/src/cli_upload.py b/object-storage-backup/src/cli_upload.py new file mode 100644 index 0000000..9a420b7 --- /dev/null +++ b/object-storage-backup/src/cli_upload.py @@ -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() diff --git a/object-storage-backup/src/s3_helper.py b/object-storage-backup/src/s3_helper.py index 4ecfd0b..7c4e6a4 100644 --- a/object-storage-backup/src/s3_helper.py +++ b/object-storage-backup/src/s3_helper.py @@ -1,3 +1,4 @@ +import json import os import typing from functools import partial @@ -5,6 +6,7 @@ import urllib3 from botocore.config import Config +from botocore.exceptions import ClientError from dotenv import load_dotenv import boto3 from loguru import logger @@ -47,4 +49,45 @@ def create_s3_client() -> "S3Client": 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 \ No newline at end of file + 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") From 04adbf8d22acf533559e4bb58814647c0d80cee6 Mon Sep 17 00:00:00 2001 From: Jos van der Velde Date: Tue, 17 Nov 2026 17:22:43 +0100 Subject: [PATCH 7/7] Some multi-threading, some small fixes --- object-storage-backup/src/cli_backup.py | 105 ++++++++++++++---------- object-storage-backup/src/cli_upload.py | 2 +- 2 files changed, 63 insertions(+), 44 deletions(-) diff --git a/object-storage-backup/src/cli_backup.py b/object-storage-backup/src/cli_backup.py index 953f610..3d0e51f 100644 --- a/object-storage-backup/src/cli_backup.py +++ b/object-storage-backup/src/cli_backup.py @@ -1,9 +1,8 @@ import argparse import time -from asyncio import IncompleteReadError +from concurrent.futures import ThreadPoolExecutor, as_completed from pathlib import Path -from botocore.exceptions import ReadTimeoutError from dotenv import load_dotenv from loguru import logger @@ -23,6 +22,16 @@ def parse_args() -> argparse.Namespace: 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" @@ -30,6 +39,40 @@ def parse_args() -> argparse.Namespace: 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() @@ -38,58 +81,34 @@ def main(): bucket = args.bucket output_dir = args.output / bucket ignore_existing = args.ignore_existing_files - logger.info(f"From {bucket} to {output_dir}.") - + 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) - if not output_dir.is_dir() and next(output_dir.iterdir(), None) is None: - logger.error(f"{output_dir} is not empty or not a directory") - exit(1) - paginator = s3_client.get_paginator("list_objects_v2") - pages = paginator.paginate(Bucket=bucket) - download_count = 0 - logger.info("Connecting to S3...") - for i, page in enumerate(pages): - if i == 0: - logger.info("Connection established") - logger.debug(f"Page: {page.get('Name')}...") - if "Contents" not in page: - logger.info(f"Empty page: {page.get('Name')}") - break - for obj in page["Contents"]: - s3_key = obj["Key"] - if s3_key.endswith("/"): - continue + 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 - logger.debug(f"Downloading {s3_key} to {output_path}") - # 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: - attempt = 0 - try: - with response["Body"] as input_stream: - while True: - chunk = input_stream.read(8 * 1024 * 1024) - if chunk: - output_file.write(chunk) - else: - break - except (IncompleteReadError, ReadTimeoutError) as e: - attempt += 1 - if attempt > 3: - raise RuntimeError(f"Failed to download {s3_key} to {output_path}") from e - logger.warning(f"Exception while downloading {s3_key} to {output_path}: {e}") - time.sleep(2 ** attempt) + 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... Last file {output_path}") + logger.info(f"Downloaded {download_count} files...") logger.info(f"Done! Downloaded {download_count} files to {output_dir}") diff --git a/object-storage-backup/src/cli_upload.py b/object-storage-backup/src/cli_upload.py index 9a420b7..5740a76 100644 --- a/object-storage-backup/src/cli_upload.py +++ b/object-storage-backup/src/cli_upload.py @@ -27,7 +27,7 @@ def parse_args() -> argparse.Namespace: "/my/path/[bucket] will be uploaded." ) parser.add_argument( - "--n_threads", + "--n-threads", type=int, default=1, )