Files
mtusi2026lab4/tools/gc_orphans.sh
T
2026-10-30 21:09:56 +03:00

112 lines
3.6 KiB
Bash
Executable File

#!/bin/sh
# Reconcile S3 orphans: bucket objects with no matching attachments.s3_key in PG.
#
# Upload path compensation: S3 PUT → PG INSERT; on INSERT failure the API
# best-effort DeleteObject. This script cleans leftovers after crashes between
# PUT and compensate (or a failed DeleteObject).
#
# Dry-run by default. Fresh objects inside GRACE_SECONDS are never deleted.
#
# ./tools/gc_orphans.sh
# APPLY=1 GRACE_SECONDS=3600 ./tools/gc_orphans.sh
set -eu
ROOT="$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)"
COMPOSE="docker compose --env-file $ROOT/.env -f $ROOT/compose.yaml"
GRACE_SECONDS="${GRACE_SECONDS:-3600}"
APPLY="${APPLY:-0}"
PREFIX="${ORPHAN_PREFIX:-attachments/}"
S3_BUCKET=$($COMPOSE exec -T api sh -c 'printf %s "$S3_BUCKET"')
[ -n "$S3_BUCKET" ] || { echo "S3_BUCKET empty" >&2; exit 1; }
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
echo "gc_orphans: bucket=$S3_BUCKET grace=${GRACE_SECONDS}s apply=$APPLY prefix=$PREFIX"
$COMPOSE run --rm --no-deps --entrypoint /bin/sh minio-init -c "
set -eu
mc alias set local \"\$S3_ENDPOINT\" \"\$MINIO_ROOT_USER\" \"\$MINIO_ROOT_PASSWORD\" >/dev/null
mc ls --recursive --json \"local/\$S3_BUCKET/$PREFIX\" || true
" > "$TMP/s3.json"
# Known keys: ready attachments + still-pending direct uploads (Track 1).
$COMPOSE exec -T db sh -c \
'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Atc "
SELECT s3_key FROM attachments
UNION
SELECT s3_key FROM direct_uploads WHERE status = '\''pending'\''
"' \
> "$TMP/pg.keys"
python3 - "$TMP/s3.json" "$TMP/pg.keys" "$GRACE_SECONDS" "$TMP/del.keys" <<'PY'
import json, sys, time
from datetime import datetime
s3_path, pg_path, grace_s, out_path = sys.argv[1], sys.argv[2], int(sys.argv[3]), sys.argv[4]
now = time.time()
known = {line.strip() for line in open(pg_path) if line.strip()}
orphans = []
for line in open(s3_path):
line = line.strip()
if not line:
continue
try:
obj = json.loads(line)
except json.JSONDecodeError:
continue
key = obj.get("key") or obj.get("Key")
if not key:
continue
# mc ls under prefix returns keys relative to that prefix.
if not key.startswith("attachments/"):
key = "attachments/" + key.lstrip("/")
if key in known:
continue
age = None
lm = obj.get("lastModified") or obj.get("last_modified")
if lm:
try:
age = now - datetime.fromisoformat(lm.replace("Z", "+00:00")).timestamp()
except Exception:
age = None
orphans.append((key, age, obj.get("size")))
print(f"gc_orphans: scanned orphans={len(orphans)} known_pg={len(known)}")
to_delete = []
for key, age, size in orphans:
age_s = f"{int(age)}s" if age is not None else "?"
if age is not None and age < grace_s:
print(f" SKIP (grace) key={key} age={age_s} size={size}")
continue
print(f" ORPHAN key={key} age={age_s} size={size}")
to_delete.append(key)
with open(out_path, "w") as f:
f.write("\n".join(to_delete) + ("\n" if to_delete else ""))
print(f"gc_orphans: candidates={len(to_delete)}")
PY
if [ "$APPLY" != "1" ]; then
echo "gc_orphans: dry-run; set APPLY=1 to delete candidates older than grace."
exit 0
fi
if [ ! -s "$TMP/del.keys" ]; then
echo "gc_orphans: nothing to delete"
exit 0
fi
$COMPOSE run --rm --no-deps --entrypoint /bin/sh minio-init -c "
set -eu
mc alias set local \"\$S3_ENDPOINT\" \"\$MINIO_ROOT_USER\" \"\$MINIO_ROOT_PASSWORD\" >/dev/null
while IFS= read -r key; do
[ -n \"\$key\" ] || continue
echo \"deleting \$S3_BUCKET/\$key\"
mc rm --force \"local/\$S3_BUCKET/\$key\"
done
" < "$TMP/del.keys"
echo "gc_orphans: delete done"