| 1 | #!/usr/bin/env python3 |
| 2 | """Check a docker-save stream against the registry's per-request size budget. |
| 3 | |
| 4 | Docker's classic save format names layers */layer.tar. Newer exports may |
| 5 | put raw tar or already compressed layers under blobs/sha256/. Inspect both |
| 6 | without unpacking the image or retaining layers in memory. |
| 7 | """ |
| 8 | |
| 9 | import argparse |
| 10 | import sys |
| 11 | import tarfile |
| 12 | import zlib |
| 13 | |
| 14 | |
| 15 | def check(stream, limit): |
| 16 | layers = 0 |
| 17 | oversized = False |
| 18 | with tarfile.open(fileobj=stream, mode="r|") as archive: |
| 19 | for member in archive: |
| 20 | if not member.isfile(): |
| 21 | continue |
| 22 | if not (member.name.endswith(".tar") or "/blobs/" in "/" + member.name): |
| 23 | continue |
| 24 | source = archive.extractfile(member) |
| 25 | first = source.read(512) |
| 26 | if first.startswith(b"\x1f\x8b"): |
| 27 | size = member.size |
| 28 | elif member.name.endswith(".tar") or first[257:263] in (b"ustar\0", b"ustar "): |
| 29 | compressor = zlib.compressobj(level=6, wbits=31) |
| 30 | size = len(compressor.compress(first)) |
| 31 | while chunk := source.read(1024 * 1024): |
| 32 | size += len(compressor.compress(chunk)) |
| 33 | size += len(compressor.flush()) |
| 34 | elif first.startswith(b"\x28\xb5\x2f\xfd"): |
| 35 | raise ValueError("zstd layers are unsupported; export gzip layers for this registry") |
| 36 | else: |
| 37 | # Manifests, image configuration and other non-layer blobs. |
| 38 | continue |
| 39 | layers += 1 |
| 40 | status = "FAIL" if size >= limit else "OK" |
| 41 | print(f"{status}: {member.name}: {size:,} compressed bytes", flush=True) |
| 42 | oversized |= size >= limit |
| 43 | if layers == 0: |
| 44 | raise ValueError("no image layers found in docker save stream") |
| 45 | print(f"Checked {layers} layers; each must be smaller than {limit:,} bytes.") |
| 46 | return not oversized |
| 47 | |
| 48 | |
| 49 | def main(): |
| 50 | parser = argparse.ArgumentParser(description=__doc__) |
| 51 | parser.add_argument("--max-bytes", type=int, default=90_000_000) |
| 52 | options = parser.parse_args() |
| 53 | if options.max_bytes <= 0: |
| 54 | parser.error("--max-bytes must be positive") |
| 55 | try: |
| 56 | return 0 if check(sys.stdin.buffer, options.max_bytes) else 1 |
| 57 | except (tarfile.TarError, ValueError, OSError) as error: |
| 58 | print(f"Layer check failed: {error}", file=sys.stderr) |
| 59 | return 1 |
| 60 | |
| 61 | |
| 62 | if __name__ == "__main__": |
| 63 | sys.exit(main()) |