|
| 1 | +""" |
| 2 | +Copyright 2025 Man Group Operations Limited |
| 3 | +
|
| 4 | +Use of this software is governed by the Business Source License 1.1 included in the file LICENSE.txt. |
| 5 | +
|
| 6 | +As of the Change Date specified in that file, in accordance with the Business Source License, use of this software will be governed by the Apache License, version 2.0. |
| 7 | +""" |
| 8 | + |
| 9 | +from datetime import datetime, timedelta, timezone |
| 10 | +from concurrent.futures import ThreadPoolExecutor |
| 11 | +import boto3 |
| 12 | +import os |
| 13 | +from typing import Callable, Optional |
| 14 | +from botocore.client import BaseClient |
| 15 | +from botocore.exceptions import ClientError |
| 16 | +from azure.storage.blob import BlobServiceClient |
| 17 | +from azure.storage.blob import BlobProperties |
| 18 | +from arcticdb.util.logger import get_logger |
| 19 | + |
| 20 | + |
| 21 | +logger = get_logger() |
| 22 | + |
| 23 | + |
| 24 | +def s3_client(client_type: str = "s3") -> BaseClient: |
| 25 | + """Create a boto S3 client to Amazon AWS S3 store |
| 26 | +
|
| 27 | + Parameters: |
| 28 | + client_type - s3, iam etc valid boto clients |
| 29 | + """ |
| 30 | + return boto3.client( |
| 31 | + client_type, |
| 32 | + aws_access_key_id=os.getenv("ARCTICDB_REAL_S3_ACCESS_KEY"), |
| 33 | + aws_secret_access_key=os.getenv("ARCTICDB_REAL_S3_SECRET_KEY"), |
| 34 | + ) |
| 35 | + |
| 36 | + |
| 37 | +def gcp_client() -> BaseClient: |
| 38 | + """Returns a boto client to GCP stoage""" |
| 39 | + session = boto3.session.Session() |
| 40 | + return session.client( |
| 41 | + service_name="s3", |
| 42 | + aws_access_key_id=os.getenv("ARCTICDB_REAL_GCP_ACCESS_KEY"), |
| 43 | + aws_secret_access_key=os.getenv("ARCTICDB_REAL_GCP_SECRET_KEY"), |
| 44 | + endpoint_url=os.getenv("ARCTICDB_REAL_GCP_ENDPOINT"), |
| 45 | + ) |
| 46 | + |
| 47 | + |
| 48 | +def azure_client() -> BlobServiceClient: |
| 49 | + """Creates and returns a BlobServiceClient using the provided connection string.""" |
| 50 | + connection_string = os.getenv("ARCTICDB_REAL_AZURE_CONNECTION_STRING") |
| 51 | + return BlobServiceClient.from_connection_string(connection_string) |
| 52 | + |
| 53 | + |
| 54 | +def list_bucket( |
| 55 | + client: BaseClient, bucket_name: str, handler: Callable[[dict], None], cutoff_date: Optional[datetime] = None |
| 56 | +) -> None: |
| 57 | + """ |
| 58 | + Lists objects in a bucket that were last modified before a given date, |
| 59 | + and applies a handler function to each. |
| 60 | +
|
| 61 | + Parameters: |
| 62 | + client: boto3 S3-compatible client (e.g., for GCS via HMAC). |
| 63 | + bucket_name: Name of the bucket. |
| 64 | + handler : Function to apply to each qualifying object. |
| 65 | + cutoff_date (Optional): Only include objects older than this date. |
| 66 | + Defaults to current UTC time. |
| 67 | + """ |
| 68 | + if cutoff_date is None: |
| 69 | + cutoff_date = datetime.now(timezone.utc) |
| 70 | + |
| 71 | + paginator = client.get_paginator("list_objects_v2") |
| 72 | + for page in paginator.paginate(Bucket=bucket_name): |
| 73 | + for obj in page.get("Contents", []): |
| 74 | + if obj["LastModified"] < cutoff_date: |
| 75 | + handler(obj) |
| 76 | + |
| 77 | + |
| 78 | +def delete_gcp_bucket( |
| 79 | + client: BaseClient, bucket_name: str, cutoff_date: Optional[datetime] = None, max_workers: int = 50 |
| 80 | +) -> None: |
| 81 | + """ |
| 82 | + Deletes objects in a GCS bucket that were last modified before a given date, |
| 83 | + using parallel deletion via HMAC credentials. |
| 84 | +
|
| 85 | + Parameters: |
| 86 | + bucket_name (str): Name of the GCS bucket. |
| 87 | + cutoff_date (Optional[datetime]): Only delete objects older than this date. |
| 88 | + Defaults to current UTC time. |
| 89 | + max_workers (int): Number of parallel threads for deletion. |
| 90 | + """ |
| 91 | + keys_to_delete: list[str] = [] |
| 92 | + |
| 93 | + def collect_key(obj: dict) -> None: |
| 94 | + keys_to_delete.append(obj["Key"]) |
| 95 | + |
| 96 | + list_bucket(client, bucket_name, collect_key, cutoff_date) |
| 97 | + logger.info(f"Found {len(keys_to_delete)} objects to delete before {cutoff_date or datetime.now(timezone.utc)}") |
| 98 | + |
| 99 | + def delete_key(key: str) -> None: |
| 100 | + client.delete_object(Bucket=bucket_name, Key=key) |
| 101 | + logger.info(f"Deleted: {key}") |
| 102 | + |
| 103 | + with ThreadPoolExecutor(max_workers=max_workers) as executor: |
| 104 | + executor.map(delete_key, keys_to_delete) |
| 105 | + |
| 106 | + |
| 107 | +def get_gcp_bucket_size( |
| 108 | + client: BaseClient, |
| 109 | + bucket_name: str, |
| 110 | + cutoff_date: Optional[datetime] = None, |
| 111 | +) -> int: |
| 112 | + """Returns the size of specified GCP bucket |
| 113 | +
|
| 114 | + Parameters: |
| 115 | + client: boto3 S3-compatible client (e.g., for GCS via HMAC). |
| 116 | + bucket_name: Name of the bucket. |
| 117 | + cutoff_date (Optional): Only include objects older than this date. |
| 118 | + Defaults to current UTC time. |
| 119 | + """ |
| 120 | + return get_s3_bucket_size(client, bucket_name, cutoff_date) |
| 121 | + |
| 122 | + |
| 123 | +def list_azure_container( |
| 124 | + client: BlobServiceClient, |
| 125 | + container_name: str, |
| 126 | + handler: Callable[[BlobProperties], None], |
| 127 | + cutoff_date: Optional[datetime] = None, |
| 128 | +) -> None: |
| 129 | + """ |
| 130 | + Lists blobs in a container that were last modified before a given date, |
| 131 | + and applies a handler function to each. |
| 132 | +
|
| 133 | + Parameters: |
| 134 | + client : Authenticated BlobServiceClient. |
| 135 | + container_name : Name of the container. |
| 136 | + handler : Function to apply to each qualifying blob. |
| 137 | + cutoff_date (Optional[datetime]): Only include blobs older than this date. |
| 138 | + Defaults to current UTC time. |
| 139 | + """ |
| 140 | + if cutoff_date is None: |
| 141 | + cutoff_date = datetime.now(timezone.utc) |
| 142 | + |
| 143 | + container_client = client.get_container_client(container_name) |
| 144 | + for blob in container_client.list_blobs(): |
| 145 | + if blob.last_modified and blob.last_modified < cutoff_date: |
| 146 | + handler(blob) |
| 147 | + |
| 148 | + |
| 149 | +def get_azure_container_size( |
| 150 | + blob_service_client: BlobServiceClient, container_name: str, cutoff_date: Optional[datetime] = None |
| 151 | +) -> int: |
| 152 | + """Calculates the total size of all blobs in a container.""" |
| 153 | + total_size = 0 |
| 154 | + |
| 155 | + def size_accumulator(blob: BlobProperties) -> None: |
| 156 | + nonlocal total_size |
| 157 | + total_size += blob.size |
| 158 | + |
| 159 | + list_azure_container(blob_service_client, container_name, size_accumulator, cutoff_date) |
| 160 | + return total_size |
| 161 | + |
| 162 | + |
| 163 | +def delete_azure_container( |
| 164 | + client: BlobServiceClient, container_name: str, cutoff_date: Optional[datetime] = None, max_workers: int = 20 |
| 165 | +) -> None: |
| 166 | + """ |
| 167 | + Deletes blobs in an Azure container that were last modified before the cutoff date. |
| 168 | +
|
| 169 | + Parameters: |
| 170 | + client : Authenticated BlobServiceClient. |
| 171 | + container_name : Name of the container. |
| 172 | + cutoff_date : Only delete blobs older than this date. |
| 173 | + Defaults to current UTC time. |
| 174 | + max_workers : Number of parallel threads for deletion. |
| 175 | + """ |
| 176 | + container_client = client.get_container_client(container_name) |
| 177 | + blobs_to_delete: list[str] = [] |
| 178 | + |
| 179 | + def collect_blob(blob: BlobProperties) -> None: |
| 180 | + blobs_to_delete.append(blob.name) |
| 181 | + |
| 182 | + list_azure_container(client, container_name, collect_blob, cutoff_date) |
| 183 | + |
| 184 | + logger.info(f"Found {len(blobs_to_delete)} blobs to delete before {cutoff_date or datetime.now(timezone.utc)}") |
| 185 | + |
| 186 | + def delete_blob(blob_name: str) -> None: |
| 187 | + try: |
| 188 | + # If needed we should optimize with |
| 189 | + # https://learn.microsoft.com/en-us/dotnet/api/azure.storage.blobs.specialized.blobbatchclient.deleteblobs?view=azure-dotnet |
| 190 | + container_client.delete_blob(blob_name) |
| 191 | + logger.info(f"Deleted: {blob_name}") |
| 192 | + except Exception as e: |
| 193 | + logger.error(f"Failed to delete {blob_name}: {e}") |
| 194 | + |
| 195 | + with ThreadPoolExecutor(max_workers=max_workers) as executor: |
| 196 | + executor.map(delete_blob, blobs_to_delete) |
| 197 | + |
| 198 | + |
| 199 | +def get_s3_bucket_size(client: BaseClient, bucket_name: str, cutoff_date: Optional[datetime] = None) -> int: |
| 200 | + """ |
| 201 | + Calculates the total size of all objects in an S3 bucket. |
| 202 | +
|
| 203 | + Parameters: |
| 204 | + client : A boto3 S3 client. |
| 205 | + bucket_name : Name of the S3 bucket. |
| 206 | + cutoff_date : Only delete blobs older than this date. |
| 207 | + Defaults to current UTC time. |
| 208 | +
|
| 209 | + Returns: |
| 210 | + int: Total size in bytes. |
| 211 | + """ |
| 212 | + total_size = 0 |
| 213 | + |
| 214 | + def size_accumulator(obj: dict) -> None: |
| 215 | + nonlocal total_size |
| 216 | + total_size += obj["Size"] |
| 217 | + |
| 218 | + list_bucket(client, bucket_name, size_accumulator, cutoff_date) |
| 219 | + return total_size |
| 220 | + |
| 221 | + |
| 222 | +def delete_s3_bucket_batch( |
| 223 | + client: BaseClient, bucket_name: str, cutoff_date: Optional[datetime] = None, batch_size: int = 1000 |
| 224 | +) -> None: |
| 225 | + """ |
| 226 | + Deletes objects in an S3-compatible bucket that were last modified before the cutoff date, |
| 227 | + using batch deletion (up to 1000 objects per request). |
| 228 | +
|
| 229 | + Args: |
| 230 | + client : boto3 S3-compatible client |
| 231 | + bucket_name : Name of the bucket. |
| 232 | + cutoff_date : Only delete objects older than this date. |
| 233 | + Defaults to current UTC time. |
| 234 | + batch_size : Maximum number of objects per delete request (max 1000). |
| 235 | + """ |
| 236 | + batch: list[dict] = [] |
| 237 | + |
| 238 | + def delete_batch(batch): |
| 239 | + client.delete_objects(Bucket=bucket_name, Delete={"Objects": batch}) |
| 240 | + logger.info(f"Deleted batch of {len(batch)} AWS S3 objects") |
| 241 | + |
| 242 | + def collect_keys(obj: dict) -> None: |
| 243 | + batch.append({"Key": obj["Key"]}) |
| 244 | + if len(batch) == batch_size: |
| 245 | + try: |
| 246 | + delete_batch(batch) |
| 247 | + except Exception as e: |
| 248 | + logger.error(f"Batch delete failed: {e}") |
| 249 | + batch.clear() |
| 250 | + |
| 251 | + list_bucket(client, bucket_name, collect_keys, cutoff_date) |
| 252 | + |
| 253 | + # Delete any remaining objects |
| 254 | + if batch: |
| 255 | + try: |
| 256 | + delete_batch(batch) |
| 257 | + except Exception as e: |
| 258 | + logger.error(f"Final batch delete failed: {e}") |
0 commit comments