Implement lab4 S3 attachments and reliability checks
This commit is contained in:
@@ -0,0 +1,208 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from collections import Counter
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from uuid import UUID
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
from app.object_locks import object_lock_id
|
||||
from app.storage import bucket_name, get_client
|
||||
|
||||
|
||||
def managed_key(key: str) -> bool:
|
||||
prefix = "originals/"
|
||||
if not key.startswith(prefix):
|
||||
return False
|
||||
|
||||
suffix = key[len(prefix):]
|
||||
try:
|
||||
return str(UUID(suffix)) == suffix
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def database_connection():
|
||||
return psycopg.connect(
|
||||
host=os.getenv("PGHOST", "postgres"),
|
||||
port=int(os.getenv("PGPORT", "5432")),
|
||||
dbname=os.getenv("PGDATABASE", "messenger"),
|
||||
user=os.getenv("PGUSER", "messenger"),
|
||||
password=os.environ["PGPASSWORD"],
|
||||
connect_timeout=3,
|
||||
options=(
|
||||
"-c statement_timeout=3000 "
|
||||
"-c lock_timeout=2000 "
|
||||
"-c idle_in_transaction_session_timeout=10000"
|
||||
),
|
||||
autocommit=True,
|
||||
row_factory=dict_row,
|
||||
)
|
||||
|
||||
|
||||
def sweep(*, apply: bool, grace_seconds: int) -> dict:
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(
|
||||
seconds=grace_seconds
|
||||
)
|
||||
counts = Counter({
|
||||
"scanned": 0,
|
||||
"kept": 0,
|
||||
"fresh": 0,
|
||||
"busy": 0,
|
||||
"ignored": 0,
|
||||
"gone": 0,
|
||||
"candidates": 0,
|
||||
"deleted": 0,
|
||||
})
|
||||
|
||||
with database_connection() as conn:
|
||||
client = get_client()
|
||||
bucket = bucket_name()
|
||||
pages = client.get_paginator("list_objects_v2")
|
||||
|
||||
for page in pages.paginate(
|
||||
Bucket=bucket,
|
||||
Prefix="originals/",
|
||||
PaginationConfig={"PageSize": 200},
|
||||
):
|
||||
for item in page.get("Contents", []):
|
||||
counts["scanned"] += 1
|
||||
key = item["Key"]
|
||||
|
||||
if not managed_key(key):
|
||||
counts["ignored"] += 1
|
||||
continue
|
||||
|
||||
if item["LastModified"] >= cutoff:
|
||||
counts["fresh"] += 1
|
||||
continue
|
||||
|
||||
with conn.transaction():
|
||||
conn.execute(
|
||||
"SET LOCAL "
|
||||
"idle_in_transaction_session_timeout = '60s'"
|
||||
)
|
||||
|
||||
locked = conn.execute(
|
||||
"SELECT pg_try_advisory_xact_lock(%s) AS locked",
|
||||
(object_lock_id(bucket, key),),
|
||||
).fetchone()["locked"]
|
||||
|
||||
if not locked:
|
||||
counts["busy"] += 1
|
||||
continue
|
||||
|
||||
metadata = conn.execute(
|
||||
"""
|
||||
SELECT 1
|
||||
FROM attachments
|
||||
WHERE object_key = %s
|
||||
""",
|
||||
(key,),
|
||||
).fetchone()
|
||||
|
||||
if metadata is not None:
|
||||
counts["kept"] += 1
|
||||
continue
|
||||
|
||||
try:
|
||||
current = client.head_object(
|
||||
Bucket=bucket,
|
||||
Key=key,
|
||||
)
|
||||
except ClientError as exc:
|
||||
status = exc.response.get(
|
||||
"ResponseMetadata", {}
|
||||
).get("HTTPStatusCode")
|
||||
if status == 404:
|
||||
counts["gone"] += 1
|
||||
continue
|
||||
raise
|
||||
|
||||
if current["LastModified"] >= cutoff:
|
||||
counts["fresh"] += 1
|
||||
continue
|
||||
|
||||
counts["candidates"] += 1
|
||||
print(
|
||||
json.dumps({
|
||||
"action": "delete" if apply else "would_delete",
|
||||
"key": key,
|
||||
}),
|
||||
flush=True,
|
||||
)
|
||||
|
||||
if apply:
|
||||
client.delete_object(
|
||||
Bucket=bucket,
|
||||
Key=key,
|
||||
)
|
||||
counts["deleted"] += 1
|
||||
|
||||
return {
|
||||
"mode": "apply" if apply else "dry-run",
|
||||
"grace_seconds": grace_seconds,
|
||||
**dict(counts),
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--apply", action="store_true")
|
||||
parser.add_argument("--grace-seconds", type=int, default=86400)
|
||||
parser.add_argument("--allow-short-grace", action="store_true")
|
||||
parser.add_argument("--interval-seconds", type=int, default=0)
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.grace_seconds < 60:
|
||||
parser.error("grace must be at least 60 seconds")
|
||||
|
||||
if args.grace_seconds < 3600 and not args.allow_short_grace:
|
||||
parser.error(
|
||||
"short test grace requires --allow-short-grace"
|
||||
)
|
||||
|
||||
if args.interval_seconds != 0 and args.interval_seconds < 60:
|
||||
parser.error("interval must be zero or at least 60 seconds")
|
||||
|
||||
if args.grace_seconds < 3600:
|
||||
print(
|
||||
"WARNING: short grace is for controlled local tests",
|
||||
file=sys.stderr,
|
||||
flush=True,
|
||||
)
|
||||
|
||||
while True:
|
||||
try:
|
||||
result = sweep(
|
||||
apply=args.apply,
|
||||
grace_seconds=args.grace_seconds,
|
||||
)
|
||||
except Exception as exc:
|
||||
print(
|
||||
json.dumps({
|
||||
"status": "failed",
|
||||
"error_type": type(exc).__name__,
|
||||
}),
|
||||
file=sys.stderr,
|
||||
flush=True,
|
||||
)
|
||||
return 1
|
||||
|
||||
print(json.dumps(result, sort_keys=True), flush=True)
|
||||
|
||||
if args.interval_seconds == 0:
|
||||
return 0
|
||||
|
||||
time.sleep(args.interval_seconds)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user