Add dry-run-first one-time FSAssets scanner and optional Garage S3 import utility
This commit is contained in:
1 parent
761941142e
commit
aec3f87cb7
1 file changed
+117
@@ -0,0 +1,117 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read-only FSAssets filesystem scanner and opt-in Garage S3 one-time import.
|
||||
|
||||
FSAssets stores SHA256 payloads as raw files or .gz compressed files under
|
||||
hash-derived directories. This importer never modifies FSAssets or SQL.
|
||||
Dry-run is the default; --upload is required for writes to the S3 test bucket.
|
||||
"""
|
||||
import argparse
|
||||
import gzip
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
|
||||
HEX = re.compile(r"^[0-9a-fA-F]{64}$")
|
||||
|
||||
|
||||
def inspect(path, root, osgrid=False):
|
||||
name = path.name
|
||||
compressed = name.endswith(".gz")
|
||||
stem = name[:-3] if compressed else name
|
||||
if not HEX.fullmatch(stem):
|
||||
return None
|
||||
digest = stem.lower()
|
||||
# FSAssets HashToFile uses the original (upper-case) SQL SHA-256 hash.
|
||||
# Validate both historical casing conventions.
|
||||
h = stem
|
||||
subdir = Path(h[:3], h[3:6]) if osgrid else Path(h[:2], h[2:4], h[4:6], h[6:10])
|
||||
expected = root / subdir / stem
|
||||
if path != (expected.with_name(expected.name + ".gz") if compressed else expected):
|
||||
return None
|
||||
hasher = hashlib.sha256()
|
||||
chunks = []
|
||||
opener = gzip.open if compressed else open
|
||||
with opener(path, "rb") as stream:
|
||||
while True:
|
||||
chunk = stream.read(1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
hasher.update(chunk)
|
||||
chunks.append(chunk)
|
||||
if hasher.hexdigest() != digest:
|
||||
raise ValueError("FSAssets SHA-256 mismatch")
|
||||
return digest, b"".join(chunks)
|
||||
|
||||
|
||||
def scan(root, osgrid=False):
|
||||
for path in root.rglob("*"):
|
||||
if path.is_file():
|
||||
try:
|
||||
result = inspect(path, root, osgrid)
|
||||
except (OSError, ValueError, EOFError):
|
||||
yield path, None
|
||||
continue
|
||||
if result:
|
||||
yield path, result
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description="FSAssets to Garage S3, dry-run by default")
|
||||
p.add_argument("--fsassets", required=True, type=Path)
|
||||
p.add_argument("--osgrid-format", action="store_true")
|
||||
p.add_argument("--upload", action="store_true", help="explicitly upload validated assets")
|
||||
p.add_argument("--max-assets", type=int, default=0, help="limit uploaded files; 0 = unlimited")
|
||||
p.add_argument("--report", type=Path, required=True)
|
||||
args = p.parse_args()
|
||||
root = args.fsassets.expanduser().resolve(strict=True)
|
||||
if not root.is_dir() or args.max_assets < 0:
|
||||
p.error("FSAssets directory must exist and max-assets must be nonnegative")
|
||||
s3 = None
|
||||
if args.upload:
|
||||
try:
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
except ImportError:
|
||||
p.error("boto3 is required for --upload (install in a private virtualenv)")
|
||||
endpoint = os.environ.get("OGL_S3_ENDPOINT", "")
|
||||
bucket = os.environ.get("OGL_S3_BUCKET", "")
|
||||
if not endpoint or not bucket:
|
||||
p.error("OGL_S3_ENDPOINT and OGL_S3_BUCKET are required for upload")
|
||||
if endpoint.startswith("http://") and os.environ.get("OGL_S3_ALLOW_PRIVATE_HTTP") != "true":
|
||||
p.error("HTTP endpoint requires explicit private-network opt-in")
|
||||
s3 = boto3.client("s3", endpoint_url=endpoint,
|
||||
aws_access_key_id=os.environ.get("OGL_S3_ACCESS_KEY"),
|
||||
aws_secret_access_key=os.environ.get("OGL_S3_SECRET_KEY"),
|
||||
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}))
|
||||
stats = dict(scanned=0, valid=0, invalid=0, uploaded=0, bytes=0, failures=0)
|
||||
for path, record in scan(root, args.osgrid_format):
|
||||
stats["scanned"] += 1
|
||||
if record is None:
|
||||
stats["invalid"] += 1
|
||||
continue
|
||||
digest, payload = record
|
||||
stats["valid"] += 1
|
||||
stats["bytes"] += len(payload)
|
||||
if s3:
|
||||
if args.max_assets and stats["uploaded"] >= args.max_assets:
|
||||
break
|
||||
try:
|
||||
s3.put_object(Bucket=bucket, Key=f"sha256/{digest[:2]}/{digest}", Body=payload)
|
||||
stats["uploaded"] += 1
|
||||
except Exception:
|
||||
stats["failures"] += 1
|
||||
# Never expose S3 endpoints, bucket identifiers or credentials.
|
||||
print("S3 upload failed; continuing", file=sys.stderr)
|
||||
args.report.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.report.write_text(json.dumps(stats, indent=2) + "\n", encoding="utf-8")
|
||||
os.chmod(args.report, 0o600)
|
||||
print(json.dumps(stats, indent=2))
|
||||
if stats["invalid"] or stats["failures"]:
|
||||
raise SystemExit(2)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user