fix(lab5): protect pipeline objects and verify overload recovery
This commit is contained in:
+34
-7
@@ -15,6 +15,7 @@ import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import asyncpg
|
||||
@@ -23,6 +24,17 @@ from . import config
|
||||
from .s3 import S3
|
||||
|
||||
|
||||
def object_owner(key):
|
||||
"""Recognize server-generated prefixes, including effects not committed yet."""
|
||||
parts = key.split("/")
|
||||
if (parts[0] == "att" and len(parts) >= 3) or (parts[0] == "staging" and len(parts) == 2):
|
||||
try:
|
||||
return uuid.UUID(parts[1])
|
||||
except ValueError:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
async def reconcile(apply, grace, prefix):
|
||||
started = time.perf_counter()
|
||||
s3 = S3()
|
||||
@@ -30,9 +42,15 @@ async def reconcile(apply, grace, prefix):
|
||||
conn = await asyncpg.connect(config.DATABASE_URL, timeout=5)
|
||||
try:
|
||||
t0 = time.perf_counter()
|
||||
rows = await conn.fetch("SELECT id, s3_key, size_bytes, status, created_at FROM attachments")
|
||||
rows = await conn.fetch("SELECT id, s3_key, staging_key, size_bytes, status, created_at FROM attachments")
|
||||
variants = await conn.fetch(
|
||||
"SELECT a.id, v.s3_key, v.size_bytes, a.status, a.created_at "
|
||||
"FROM attachment_variants v JOIN attachments a ON a.id = v.attachment_id")
|
||||
db_ms = (time.perf_counter() - t0) * 1000
|
||||
by_key = {r["s3_key"]: r for r in rows}
|
||||
by_key = {r["s3_key"]: dict(r, check=True) for r in [*rows, *variants]}
|
||||
# Staging may already be removed after ready, or retained for failed/replay.
|
||||
by_key.update({r["staging_key"]: dict(r, check=False) for r in rows if r["staging_key"]})
|
||||
owners = {r["id"] for r in rows}
|
||||
t0 = time.perf_counter()
|
||||
objects = {}
|
||||
async for key, size, modified in s3.list_keys(prefix):
|
||||
@@ -41,23 +59,32 @@ async def reconcile(apply, grace, prefix):
|
||||
now = datetime.now(timezone.utc)
|
||||
cutoff = now - timedelta(seconds=grace)
|
||||
report = {"mode": "apply" if apply else "dry-run", "grace_seconds": grace, "db_rows": len(rows), "s3_objects": len(objects),
|
||||
"orphan_objects": [], "orphans_skipped_fresh": 0, "missing_objects": [], "size_mismatch": [], "fixed": {"deleted_orphans": 0, "marked_failed": 0}}
|
||||
"orphan_objects": [], "orphans_skipped_fresh": 0, "owned_objects_skipped": 0,
|
||||
"missing_objects": [], "size_mismatch": [], "fixed": {"deleted_orphans": 0, "marked_failed": 0}}
|
||||
for key, (size, modified) in objects.items():
|
||||
row = by_key.get(key)
|
||||
if row is None:
|
||||
if modified < cutoff:
|
||||
if object_owner(key) in owners:
|
||||
# Worker can write S3 variants before committing their metadata.
|
||||
report["owned_objects_skipped"] += 1
|
||||
elif modified < cutoff:
|
||||
report["orphan_objects"].append(key)
|
||||
else:
|
||||
report["orphans_skipped_fresh"] += 1
|
||||
elif row["status"] == "ready" and row["size_bytes"] != size:
|
||||
elif row["check"] and row["status"] == "ready" and row["size_bytes"] != size:
|
||||
report["size_mismatch"].append(str(row["id"]))
|
||||
for key, row in by_key.items():
|
||||
if key.startswith(prefix) and key not in objects and row["status"] == "ready" and row["created_at"] < cutoff:
|
||||
if row["check"] and key.startswith(prefix) and key not in objects and row["status"] == "ready" and row["created_at"] < cutoff:
|
||||
report["missing_objects"].append(str(row["id"]))
|
||||
for field in ("missing_objects", "size_mismatch"):
|
||||
report[field] = sorted(set(report[field]))
|
||||
if apply:
|
||||
for key in report["orphan_objects"]:
|
||||
# повторная проверка перед удалением: за время обхода строка могла появиться
|
||||
if await conn.fetchval("SELECT 1 FROM attachments WHERE s3_key = $1", key) is None:
|
||||
referenced = await conn.fetchval(
|
||||
"SELECT EXISTS (SELECT 1 FROM attachments WHERE s3_key = $1 OR staging_key = $1 OR id = $2) "
|
||||
"OR EXISTS (SELECT 1 FROM attachment_variants WHERE s3_key = $1)", key, object_owner(key))
|
||||
if not referenced:
|
||||
await s3.delete(key)
|
||||
report["fixed"]["deleted_orphans"] += 1
|
||||
for ids, code in ((report["missing_objects"], "object_missing"), (report["size_mismatch"], "size_mismatch")):
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Read-only operator probe after a full restart: LIST and ranged GET of existing objects.
|
||||
|
||||
An open S3 socket / HEAD bucket does not prove that SeaweedFS volume locations
|
||||
have been registered. Read one byte per nonempty object, including staging.
|
||||
This is a bounded recovery hook, not an expensive per-request health check.
|
||||
"""
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
from . import config
|
||||
from .s3 import S3
|
||||
|
||||
|
||||
async def probe(s3):
|
||||
count = 0
|
||||
batch = []
|
||||
|
||||
async def read(key, size):
|
||||
params = {"Bucket": config.S3_BUCKET, "Key": key}
|
||||
if size:
|
||||
params["Range"] = "bytes=0-0"
|
||||
response = await s3.client.get_object(**params)
|
||||
async with response["Body"] as stream:
|
||||
data = await stream.read()
|
||||
if len(data) != min(size, 1):
|
||||
raise ValueError("unexpected ranged read size")
|
||||
|
||||
async def flush():
|
||||
results = await asyncio.gather(*(read(key, size) for key, size in batch), return_exceptions=True)
|
||||
for result in results:
|
||||
if isinstance(result, BaseException):
|
||||
raise result
|
||||
|
||||
await s3.ping()
|
||||
async for key, size, _ in s3.list_keys(""):
|
||||
batch.append((key, size))
|
||||
count += 1
|
||||
if len(batch) == 8:
|
||||
await flush()
|
||||
batch.clear()
|
||||
if batch:
|
||||
await flush()
|
||||
return count
|
||||
|
||||
|
||||
async def main():
|
||||
s3 = S3()
|
||||
await s3.start()
|
||||
try:
|
||||
async with asyncio.timeout(45):
|
||||
while True:
|
||||
try:
|
||||
count = await probe(s3)
|
||||
print(f"PASS: S3 recovery, {count} existing objects readable")
|
||||
return 0
|
||||
except Exception as exc:
|
||||
# Do not print SDK requests/credentials or object contents.
|
||||
print(f"Waiting for S3 data volumes: {type(exc).__name__}", flush=True)
|
||||
await asyncio.sleep(1)
|
||||
except TimeoutError:
|
||||
print("FAIL: S3 data recovery exceeded 45 seconds")
|
||||
return 1
|
||||
finally:
|
||||
await s3.stop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(asyncio.run(main()))
|
||||
Reference in New Issue
Block a user