File size: 4,216 Bytes
a1af790 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | """Verify official multipart archives and extract them as downloads finish."""
from pathlib import Path
import hashlib
import json
import os
import shutil
import subprocess
import time
import traceback
ROOT = Path(__file__).resolve().parents[1]
def save(name, data):
path = ROOT / "audit" / name
temp = path.with_suffix(path.suffix + ".tmp")
temp.write_text(json.dumps(data, indent=2) + "\n")
temp.replace(path)
def merge_dirs(src, dst, duplicates):
if not dst.exists():
src.rename(dst)
return
if not (src.is_dir() and dst.is_dir()):
if src.is_file() and dst.is_file() and src.read_bytes() == dst.read_bytes():
duplicates.append(str(src.relative_to(ROOT)))
src.unlink() # Only a verified identical duplicate in this new download.
return
raise RuntimeError(f"Conflicting archive paths: {src} and {dst}")
for child in list(src.iterdir()):
merge_dirs(child, dst / child.name, duplicates)
src.rmdir()
def run():
manifest = json.loads((ROOT / "audit/images_manifest.json").read_text())
staging = ROOT / "source_layout"
staging.mkdir(exist_ok=True)
results = []
save("images_extraction.json", {"status": "downloading_and_extracting", "started_unix": time.time()})
with (ROOT / "logs/tar_extract.log").open("ab") as log:
tar = subprocess.Popen(
["tar", "--extract", "--ignore-zeros", "--file=-", "--no-same-owner",
"--no-same-permissions", "--directory=" + str(staging)],
stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT,
)
try:
for item in manifest:
path = ROOT / "archives/5fps" / item["name"]
while not (path.exists() and path.stat().st_size == item["bytes"]
and not Path(str(path) + ".aria2").exists()):
if tar.poll() is not None:
raise RuntimeError("tar exited before archives arrived")
time.sleep(5)
md5, sha = hashlib.md5(), hashlib.sha256()
with path.open("rb") as f:
for block in iter(lambda: f.read(8 * 1024 * 1024), b""):
md5.update(block)
sha.update(block)
if md5.hexdigest() != item["md5"]:
raise RuntimeError("Official MD5 mismatch: " + item["name"])
record = dict(item, sha256=sha.hexdigest(), official_md5_match=True)
results.append(record)
save("image_parts_verified.json", {"verified": results, "complete": len(results) == len(manifest)})
print("VERIFIED", len(results), item["name"], flush=True)
with path.open("rb") as f:
shutil.copyfileobj(f, tar.stdin, length=4 * 1024 * 1024)
print("EXTRACTED_STREAM", len(results), flush=True)
tar.stdin.close()
rc = tar.wait()
if rc:
raise RuntimeError(f"tar exited with {rc}; see logs/tar_extract.log")
finally:
if tar.poll() is None:
tar.terminate()
tar.wait()
top = sorted(p.name for p in staging.iterdir())
duplicates = []
for batch in sorted(staging.iterdir()):
if batch.name == "images":
merge_dirs(batch, ROOT / "images", duplicates)
elif batch.is_dir() and (batch / "images").is_dir():
merge_dirs(batch / "images", ROOT / "images", duplicates)
else:
raise RuntimeError(f"Unexpected archive layout: {batch}")
save("images_extraction.json", {"status": "complete", "finished_unix": time.time(),
"original_top_directories": top, "identical_duplicates": duplicates,
"parts_verified": len(results), "images_directory": str(ROOT / "images")})
print("IMAGE_EXTRACTION_COMPLETE", flush=True)
if __name__ == "__main__":
try:
run()
except Exception as exc:
save("images_extraction_failure.json", {"error": str(exc), "time_unix": time.time()})
traceback.print_exc()
raise
|