-
Notifications
You must be signed in to change notification settings - Fork 105
add S3 upload tool for sandbox attachments #113
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
hezhefly
wants to merge
20
commits into
agentscope-ai:main
Choose a base branch
from
hezhefly:hezhefly-patch-1
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
82b488e
Create s3_storage.py
hezhefly 9d85dd1
Update sandbox_manager.py
hezhefly b12e9a4
Update config.py
hezhefly 96cd86e
Update manager_config.py
hezhefly 6af1d77
Update app.py
hezhefly 2e7dc2f
Update __init__.py
hezhefly 983396e
Remove unnecessary sys.path modification
hezhefly 904ab18
Refactor S3 field validation for clarity
hezhefly e0da279
Validate ETag format for S3 file comparison
hezhefly eab88f6
Add boto3 dependency to pyproject.toml
hezhefly 149d24f
fix: fix line length issues in manager_config.py
38b57e0
Merge branch 'main' into hezhefly-patch-1
27021d7
Merge branch 'main' into hezhefly-patch-1
hezhefly da00115
Merge branch 'main' into hezhefly-patch-1
hezhefly c80482d
Align pyproject.toml with main branch
3baec21
docs(cookbook): 添加S3存储支持的相关文档
b1bda28
style(storage): 统一代码格式并优化S3存储实现
a954e5d
Merge branch 'main' into hezhefly-patch-1
hezhefly bb983a4
Merge main branch into hezhefly-patch-1
4335425
merge main to hezhefly-patch-1
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
167 changes: 167 additions & 0 deletions
167
src/agentscope_runtime/sandbox/manager/storage/s3_storage.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,167 @@ | ||
| # -*- coding: utf-8 -*- | ||
| import os | ||
| import hashlib | ||
| import boto3 | ||
| from botocore.exceptions import ClientError | ||
|
|
||
| from .data_storage import DataStorage | ||
|
|
||
|
|
||
| def calculate_md5(file_path): | ||
| """Calculate the MD5 checksum of a file.""" | ||
| with open(file_path, "rb") as f: | ||
| md5 = hashlib.md5() | ||
| while chunk := f.read(8192): | ||
| md5.update(chunk) | ||
| return md5.hexdigest() | ||
|
|
||
|
|
||
| class S3Storage(DataStorage): | ||
| def __init__( | ||
| self, | ||
| access_key_id, | ||
| access_key_secret, | ||
| endpoint_url, | ||
| bucket_name, | ||
| region_name="us-east-1", | ||
| ): | ||
| """ | ||
| Initialize S3 storage client. | ||
|
|
||
| Args: | ||
| access_key_id (str): AWS access key ID | ||
| access_key_secret (str): AWS secret access key | ||
| endpoint_url (str): S3 endpoint URL | ||
| (for MinIO, use http://localhost:9000) | ||
| bucket_name (str): S3 bucket name | ||
| region_name (str): AWS region name (default: us-east-1) | ||
| """ | ||
| self.bucket_name = bucket_name | ||
| self.s3_client = boto3.client( | ||
| "s3", | ||
| aws_access_key_id=access_key_id, | ||
| aws_secret_access_key=access_key_secret, | ||
| endpoint_url=endpoint_url, | ||
| region_name=region_name, | ||
| ) | ||
|
|
||
| # Ensure bucket exists | ||
| self._ensure_bucket_exists() | ||
|
|
||
| def _ensure_bucket_exists(self): | ||
| """Ensure the bucket exists, create it if it doesn't.""" | ||
| try: | ||
| self.s3_client.head_bucket(Bucket=self.bucket_name) | ||
| except ClientError as e: | ||
| error_code = int(e.response["Error"]["Code"]) | ||
| if error_code == 404: | ||
| # Bucket doesn't exist, create it | ||
| self.s3_client.create_bucket(Bucket=self.bucket_name) | ||
| else: | ||
| raise | ||
|
|
||
| def download_folder(self, source_path, destination_path): | ||
| """Download a folder from S3 to the local filesystem.""" | ||
| if not os.path.exists(destination_path): | ||
| os.makedirs(destination_path) | ||
|
|
||
| # Ensure source_path ends with '/' | ||
| if not source_path.endswith("/"): | ||
| source_path += "/" | ||
|
|
||
| # List all objects with the given prefix | ||
| paginator = self.s3_client.get_paginator("list_objects_v2") | ||
| pages = paginator.paginate(Bucket=self.bucket_name, Prefix=source_path) | ||
|
|
||
| for page in pages: | ||
| if "Contents" in page: | ||
| for obj in page["Contents"]: | ||
| # Calculate relative path | ||
| relative_path = os.path.relpath(obj["Key"], source_path) | ||
| local_path = os.path.join(destination_path, relative_path) | ||
|
|
||
| # Create directory structure | ||
| if obj["Key"].endswith("/"): | ||
| # This is a directory | ||
| os.makedirs(local_path, exist_ok=True) | ||
| else: | ||
| # This is a file | ||
| os.makedirs(os.path.dirname(local_path), exist_ok=True) | ||
| # Download file | ||
| self.s3_client.download_file( | ||
| self.bucket_name, | ||
| obj["Key"], | ||
| local_path, | ||
| ) | ||
|
|
||
| def upload_folder(self, source_path, destination_path): | ||
| """Upload a local folder to S3.""" | ||
| # Ensure destination_path ends with '/' | ||
| if not destination_path.endswith("/"): | ||
| destination_path += "/" | ||
|
|
||
| for root, dirs, files in os.walk(source_path): | ||
| # Upload directory structure | ||
| for d in dirs: | ||
| dir_path = os.path.join(root, d) | ||
| relative_path = os.path.relpath(dir_path, source_path) | ||
| s3_dir_path = ( | ||
| os.path.join( | ||
| destination_path, | ||
| relative_path, | ||
| ).replace(os.sep, "/") | ||
| + "/" | ||
| ) | ||
|
|
||
| # Create directory object in S3 | ||
| self.s3_client.put_object( | ||
| Bucket=self.bucket_name, | ||
| Key=s3_dir_path, | ||
| Body=b"", | ||
| ) | ||
|
|
||
| # Upload files | ||
| for file in files: | ||
| local_file_path = os.path.join(root, file) | ||
| relative_path = os.path.relpath(local_file_path, source_path) | ||
| s3_file_path = os.path.join( | ||
| destination_path, | ||
| relative_path, | ||
| ).replace(os.sep, "/") | ||
|
|
||
| local_md5 = calculate_md5(local_file_path) | ||
|
|
||
| # Check if file exists in S3 and compare MD5 | ||
| try: | ||
| response = self.s3_client.head_object( | ||
| Bucket=self.bucket_name, | ||
| Key=s3_file_path, | ||
| ) | ||
| # Extract ETag from response and | ||
| # check if it's a plain MD5 hash | ||
| etag = response["ETag"].strip('"') | ||
| import re | ||
|
|
||
| if re.fullmatch(r"[a-fA-F0-9]{32}", etag): | ||
| s3_md5 = etag | ||
| else: | ||
| # ETag is not a plain MD5 hash, | ||
| # assume multipart or encrypted | ||
| s3_md5 = None | ||
| except ClientError as e: | ||
| if e.response["Error"]["Code"] == "404": | ||
| s3_md5 = None | ||
| else: | ||
| raise | ||
|
|
||
| # Upload if MD5 does not match or file does not exist | ||
| if local_md5 != s3_md5: | ||
| self.s3_client.upload_file( | ||
| local_file_path, | ||
| self.bucket_name, | ||
| s3_file_path, | ||
| ) | ||
|
|
||
| def path_join(self, *args): | ||
| """Join path components for S3.""" | ||
| return "/".join(args) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.