|
| 1 | +import io |
| 2 | +import os |
| 3 | +from pathlib import Path |
| 4 | + |
| 5 | +import boto3 |
| 6 | +from botocore.exceptions import ClientError |
| 7 | + |
| 8 | +from omnistore.objstore.objstore import ObjStore |
| 9 | + |
| 10 | + |
| 11 | +class S3(ObjStore): |
| 12 | + def __init__(self, bucket: str, endpoint: str = None): |
| 13 | + """ |
| 14 | + Construct a new client to communicate with the AWS S3 provider. |
| 15 | + |
| 16 | + AWS credentials are expected to be provided via environment variables: |
| 17 | + - AWS_ACCESS_KEY_ID |
| 18 | + - AWS_SECRET_ACCESS_KEY |
| 19 | + - AWS_DEFAULT_REGION |
| 20 | + """ |
| 21 | + region = os.environ.get("AWS_DEFAULT_REGION") |
| 22 | + |
| 23 | + # If a region is not specified, the bucket is created in the S3 default region (us-east-1). |
| 24 | + # If the user explicitly provides an endpoint_url, the region is not used. |
| 25 | + kwargs = {} |
| 26 | + if endpoint: |
| 27 | + kwargs['endpoint_url'] = endpoint |
| 28 | + if region: |
| 29 | + kwargs['region_name'] = region |
| 30 | + |
| 31 | + self.client = boto3.client('s3', **kwargs) |
| 32 | + self.resource = boto3.resource('s3', **kwargs) |
| 33 | + self.bucket_name = bucket |
| 34 | + |
| 35 | + # Make sure the bucket exists |
| 36 | + try: |
| 37 | + self.client.head_bucket(Bucket=bucket) |
| 38 | + except ClientError as e: |
| 39 | + # If bucket doesn't exist, create it |
| 40 | + if e.response['Error']['Code'] == '404': |
| 41 | + kwargs = {} |
| 42 | + # For non us-east-1 region, we need to specify the LocationConstraint parameter when creating the bucket |
| 43 | + if region: |
| 44 | + kwargs['CreateBucketConfiguration'] = { |
| 45 | + "LocationConstraint": region |
| 46 | + } |
| 47 | + self.client.create_bucket(Bucket=bucket, **kwargs) |
| 48 | + else: |
| 49 | + raise e |
| 50 | + |
| 51 | + def create_dir(self, dirname: str): |
| 52 | + if not dirname.endswith("/"): |
| 53 | + dirname += "/" |
| 54 | + empty_stream = io.BytesIO(b"") |
| 55 | + self.client.put_object(Bucket=self.bucket_name, Key=dirname, Body=empty_stream) |
| 56 | + |
| 57 | + def delete_dir(self, dirname: str): |
| 58 | + if not dirname.endswith("/"): |
| 59 | + dirname += "/" |
| 60 | + |
| 61 | + bucket = self.resource.Bucket(self.bucket_name) |
| 62 | + bucket.objects.filter(Prefix=dirname).delete() |
| 63 | + |
| 64 | + def upload(self, src: str, dest: str): |
| 65 | + self.client.upload_file(src, self.bucket_name, dest) |
| 66 | + |
| 67 | + def upload_dir(self, src_dir: str, dest_dir: str): |
| 68 | + for file in Path(src_dir).rglob("*"): |
| 69 | + if file.is_file(): |
| 70 | + dest_path = f"{dest_dir}/{file.relative_to(src_dir)}" |
| 71 | + self.upload(str(file), dest_path) |
| 72 | + elif file.is_dir(): |
| 73 | + self.create_dir(f"{dest_dir}/{file.relative_to(src_dir)}/") |
| 74 | + |
| 75 | + def download(self, src: str, dest: str): |
| 76 | + self.client.download_file(self.bucket_name, src, dest) |
| 77 | + |
| 78 | + def download_dir(self, src_dir: str, dest_dir: str): |
| 79 | + if not src_dir.endswith("/"): |
| 80 | + src_dir += "/" |
| 81 | + path = Path(dest_dir) |
| 82 | + if not path.exists(): |
| 83 | + path.mkdir(parents=True) |
| 84 | + |
| 85 | + paginator = self.client.get_paginator('list_objects_v2') |
| 86 | + pages = paginator.paginate(Bucket=self.bucket_name, Prefix=src_dir) |
| 87 | + |
| 88 | + for page in pages: |
| 89 | + if 'Contents' not in page: |
| 90 | + continue |
| 91 | + |
| 92 | + for obj in page['Contents']: |
| 93 | + key = obj['Key'] |
| 94 | + if key.endswith('/'): # Skip directories |
| 95 | + continue |
| 96 | + |
| 97 | + file_path = Path(dest_dir, Path(key).relative_to(src_dir)) |
| 98 | + if not file_path.parent.exists(): |
| 99 | + file_path.parent.mkdir(parents=True, exist_ok=True) |
| 100 | + |
| 101 | + self.download(key, str(file_path)) |
| 102 | + |
| 103 | + def delete(self, filename: str): |
| 104 | + self.client.delete_object(Bucket=self.bucket_name, Key=filename) |
| 105 | + |
| 106 | + def exists(self, filename: str): |
| 107 | + try: |
| 108 | + self.client.head_object(Bucket=self.bucket_name, Key=filename) |
| 109 | + return True |
| 110 | + except ClientError as e: |
| 111 | + if e.response['Error']['Code'] == '404': |
| 112 | + return False |
| 113 | + else: |
| 114 | + raise e |
0 commit comments