1 #!/usr/bin/env python32 """Canonicalise an OCI layout produced by `docker save` for hu13.3 4 The rootless Docker builder on the release host writes uncompressed OCI5 layer blobs. hu13 imports gzip layers only, so compress each uncompressed6 layer deterministically and update the manifest/index descriptors. The7 image config's diff_ids stay as the uncompressed digests, as the OCI8 specification requires.9 """10 import gzip11 import hashlib12 import io13 import json14 import sys15 from pathlib import Path16 17 18 def sha256(data: bytes) -> str:19 return hashlib.sha256(data).hexdigest()20 21 22 def blob_path(root: Path, digest: str) -> Path:23 return root / "blobs" / "sha256" / digest.removeprefix("sha256:")24 25 26 def gzip_bytes(data: bytes) -> bytes:27 out = io.BytesIO()28 with gzip.GzipFile(fileobj=out, mode="wb", compresslevel=9, mtime=0) as gz:29 gz.write(data)30 return out.getvalue()31 32 33 def main() -> int:34 if len(sys.argv) != 2:35 print("usage: oci-gzip.py <oci-layout>", file=sys.stderr)36 return 237 root = Path(sys.argv[1])38 index_path = root / "index.json"39 index = json.loads(index_path.read_text())40 for entry in index.get("manifests", []):41 manifest_path = blob_path(root, entry["digest"])42 manifest = json.loads(manifest_path.read_text())43 changed = False44 for layer in manifest.get("layers", []):45 if layer.get("mediaType") != "application/vnd.oci.image.layer.v1.tar":46 continue47 raw = blob_path(root, layer["digest"]).read_bytes()48 packed = gzip_bytes(raw)49 digest = sha256(packed)50 blob_path(root, digest).write_bytes(packed)51 layer["digest"] = "sha256:" + digest52 layer["size"] = len(packed)53 layer["mediaType"] = "application/vnd.oci.image.layer.v1.tar+gzip"54 changed = True55 if not changed:56 continue57 encoded = json.dumps(manifest, separators=(",", ":")).encode()58 digest = sha256(encoded)59 blob_path(root, digest).write_bytes(encoded)60 entry["digest"] = "sha256:" + digest61 entry["size"] = len(encoded)62 index_path.write_text(json.dumps(index, separators=(",", ":")))63 return 064 65 66 if __name__ == "__main__":67 raise SystemExit(main())