Complete Lab 4 attachment service
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
"""Find orphan objects older than a safety grace period; deletion requires --apply."""
|
||||
import argparse
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import os
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from sqlalchemy import select
|
||||
|
||||
from .db import SessionLocal
|
||||
from .models import Attachment
|
||||
from .settings import _secret
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--apply", action="store_true", help="delete confirmed stale orphans")
|
||||
args = parser.parse_args()
|
||||
endpoint = os.environ.get("S3_ENDPOINT", "http://s3:9000").rstrip("/")
|
||||
region = os.environ.get("S3_REGION", "us-east-1")
|
||||
bucket = os.environ.get("S3_BUCKET", "messenger-attachments")
|
||||
try:
|
||||
grace_seconds = int(os.environ.get("ORPHAN_GRACE_SECONDS", "86400"))
|
||||
except ValueError as exc:
|
||||
raise SystemExit("ORPHAN_GRACE_SECONDS must be an integer") from exc
|
||||
if grace_seconds < 3600:
|
||||
raise SystemExit("ORPHAN_GRACE_SECONDS must be at least 3600 seconds")
|
||||
|
||||
client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=endpoint,
|
||||
region_name=region,
|
||||
aws_access_key_id=_secret("S3_ROOT_ACCESS_KEY_FILE", "S3_ROOT_ACCESS_KEY"),
|
||||
aws_secret_access_key=_secret("S3_ROOT_SECRET_ACCESS_KEY_FILE", "S3_ROOT_SECRET_ACCESS_KEY"),
|
||||
config=Config(connect_timeout=2, read_timeout=5, retries={"total_max_attempts": 1}, s3={"addressing_style": "path"}),
|
||||
)
|
||||
with SessionLocal() as session:
|
||||
known_keys = set(session.scalars(select(Attachment.object_key)).all())
|
||||
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(seconds=grace_seconds)
|
||||
scanned = stale = deleted = 0
|
||||
paginator = client.get_paginator("list_objects_v2")
|
||||
for page in paginator.paginate(Bucket=bucket, Prefix="originals/"):
|
||||
for obj in page.get("Contents", []):
|
||||
scanned += 1
|
||||
key = obj["Key"]
|
||||
if key in known_keys or obj.get("LastModified") is None or obj["LastModified"] > cutoff:
|
||||
continue
|
||||
stale += 1
|
||||
if args.apply:
|
||||
client.delete_object(Bucket=bucket, Key=key)
|
||||
deleted += 1
|
||||
print(
|
||||
f"orphan_reconciliation mode={'apply' if args.apply else 'dry-run'} "
|
||||
f"grace_seconds={grace_seconds} scanned={scanned} stale={stale} deleted={deleted}"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user