74 lines
2.6 KiB
Python
Executable File
74 lines
2.6 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Reconcile attachment metadata in PostgreSQL against the MinIO object store."""
|
|
import argparse
|
|
import datetime
|
|
import os
|
|
|
|
import boto3
|
|
import psycopg
|
|
from botocore.config import Config
|
|
|
|
|
|
def main():
|
|
p = argparse.ArgumentParser()
|
|
p.add_argument("--apply", action="store_true")
|
|
p.add_argument("--grace-hours", type=int, default=24)
|
|
p.add_argument("--bucket", default=os.environ.get("S3_BUCKET", "messenger-attachments"))
|
|
args = p.parse_args()
|
|
|
|
s3 = boto3.client(
|
|
"s3",
|
|
endpoint_url=os.environ["S3_ENDPOINT"],
|
|
aws_access_key_id=os.environ["S3_ACCESS_KEY_ID"],
|
|
aws_secret_access_key=os.environ["S3_SECRET_ACCESS_KEY"],
|
|
config=Config(s3={"addressing_style": "path"}),
|
|
region_name=os.environ.get("S3_REGION", "us-east-1"),
|
|
)
|
|
objects = set()
|
|
token = None
|
|
while True:
|
|
kwargs = {"Bucket": args.bucket}
|
|
if token:
|
|
kwargs["ContinuationToken"] = token
|
|
page = s3.list_objects_v2(**kwargs)
|
|
objects.update(x["Key"] for x in page.get("Contents", []))
|
|
if not page.get("IsTruncated"):
|
|
break
|
|
token = page["NextContinuationToken"]
|
|
|
|
with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
|
|
rows = conn.execute(
|
|
"SELECT id,object_key,status,created_at FROM attachments"
|
|
).fetchall()
|
|
|
|
db_keys = {row[1]: row for row in rows}
|
|
missing = [row for key, row in db_keys.items() if key not in objects]
|
|
orphaned = [key for key in objects if key not in db_keys]
|
|
print(f"metadata={len(db_keys)} objects={len(objects)} missing={len(missing)} orphaned={len(orphaned)}")
|
|
|
|
if args.apply:
|
|
grace = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(hours=args.grace_hours)
|
|
with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
|
|
for row in missing:
|
|
if row[3] < grace:
|
|
conn.execute(
|
|
"UPDATE attachments SET status='failed',error_code='missing_object' WHERE id=%s",
|
|
(row[0],),
|
|
)
|
|
deleted = 0
|
|
for key in orphaned:
|
|
head = s3.head_object(Bucket=args.bucket, Key=key)
|
|
modified = head["LastModified"]
|
|
if modified.tzinfo is None:
|
|
modified = modified.replace(tzinfo=datetime.timezone.utc)
|
|
if modified < grace:
|
|
s3.delete_object(Bucket=args.bucket, Key=key)
|
|
deleted += 1
|
|
print(f"marked_missing={len(missing)} deleted_orphans={deleted}")
|
|
else:
|
|
print("dry-run only; use --apply to make changes")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|