ci: push the published images with zstd -19 layers (#7159)

BuildKit compresses zstd at about level 11 at most, so the release and
nightly images now go through a composite action: the image is built
into an OCI layout, every layer is recompressed with the zstd CLI at
level 19, and a second build that only names the layout pushes it.
BuildKit keeps the recompressed layers and still attaches provenance
and the SBOM to the pushed digests.

On 2.4.0 this takes the native image from 94.6 to 70.1 MB on amd64 and
from 92.6 to 67.1 MB on arm64, and compat amd64 from 223.2 to 167.7 MB.
Pulling zstd layers needs Docker Engine 23.0 or later, so the
installation requirements move up from 20.10.

A new workflow tests the action on the pull requests that change it:
recompress.py against fixture layouts, then the whole action pushing a
two-platform image to a registry on the runner.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-31 21:38:13 -05:00
1 parent 00425b7824
commit e77823feed
10 files changed
+480 -27

No files matched your search

@@ -0,0 +1,3 @@
# The recompressed image, passed in as the "image" build context. Naming it alone re-exports its
# layers and config as they are.
FROM image
@@ -0,0 +1,93 @@
name: Build and push with zstd -19 layers
description: >-
Builds an image and pushes it with every layer compressed by zstd at level 19. BuildKit
compresses zstd at about level 11 at most, so the image is first exported to an OCI layout,
recompressed there, and pushed by a second build that only names it: BuildKit keeps the
recompressed layers and still attaches provenance and the SBOM to the digests it pushes.
Pulling zstd layers needs Docker Engine 23.0 or later.
inputs:
file:
description: Dockerfile, relative to the repository root
required: true
platforms:
description: Target platforms
required: true
tags:
description: Tags to push
required: true
build-args:
description: Build arguments
required: false
labels:
description: Labels added to the pushed image
required: false
cache-from:
description: Cache import for the image build
required: false
cache-to:
description: Cache export for the image build
required: false
provenance:
description: Provenance attestation of the pushed image
required: false
sbom:
description: Whether to attach an SBOM attestation to the pushed image
required: false
source-date-epoch:
description: SOURCE_DATE_EPOCH for both builds
required: false
outputs:
digest:
description: Digest of the pushed image index
value: ${{ steps.push.outputs.digest }}
runs:
using: composite
steps:
- name: Create the OCI layout directory
id: layout
shell: bash
run: |
dir=$(mktemp -d "$RUNNER_TEMP/oci-layout.XXXXXX")
echo "dir=$dir" >> "$GITHUB_OUTPUT"
- name: Build the image into an OCI layout
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
env:
SOURCE_DATE_EPOCH: ${{ inputs.source-date-epoch }}
with:
context: .
file: ${{ inputs.file }}
platforms: ${{ inputs.platforms }}
build-args: ${{ inputs.build-args }}
outputs: type=oci,dest=${{ steps.layout.outputs.dir }},tar=false,oci-mediatypes=true,compression=uncompressed
provenance: false
sbom: false
cache-from: ${{ inputs.cache-from }}
cache-to: ${{ inputs.cache-to }}
- name: Recompress the layers with zstd -19
id: recompress
shell: bash
env:
LAYOUT: ${{ steps.layout.outputs.dir }}
run: |
digest=$(python3 "$GITHUB_ACTION_PATH/recompress.py" "$LAYOUT" 19)
echo "digest=$digest" >> "$GITHUB_OUTPUT"
- name: Push the recompressed image
id: push
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
env:
SOURCE_DATE_EPOCH: ${{ inputs.source-date-epoch }}
with:
context: ${{ github.action_path }}
build-contexts: image=oci-layout://${{ steps.layout.outputs.dir }}@${{ steps.recompress.outputs.digest }}
platforms: ${{ inputs.platforms }}
outputs: type=image,push=true,compression=zstd,oci-mediatypes=true
tags: ${{ inputs.tags }}
labels: ${{ inputs.labels }}
provenance: ${{ inputs.provenance }}
sbom: ${{ inputs.sbom }}
@@ -0,0 +1,117 @@
#!/usr/bin/env python3
"""Recompress the layers of the images in an OCI layout with zstd.
Usage: recompress.py <layout-dir> <level>
BuildKit compresses zstd at about level 11 at most, so the image is exported to an OCI layout and
its layers are recompressed here with the zstd CLI. Every manifest and index that points at a
rewritten blob is rewritten too, and the digest of the image that index.json names is printed for
the second build to push it from. Each layer's uncompressed content is checked against its
diff_id in the image config, so the image content cannot change on the way.
"""
import argparse
import gzip
import hashlib
import json
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
INDEX = 'application/vnd.oci.image.index.v1+json'
MANIFEST = 'application/vnd.oci.image.manifest.v1+json'
ZSTD = 'application/vnd.oci.image.layer.v1.tar+zstd'
OPENERS = {
'application/vnd.oci.image.layer.v1.tar': open,
'application/vnd.oci.image.layer.v1.tar+gzip': gzip.open,
'application/vnd.docker.image.rootfs.diff.tar.gzip': gzip.open,
}
DIGEST = re.compile(r'sha256:[0-9a-f]{64}')
CHUNK = 1 << 20
def blob(layout, digest):
if not DIGEST.fullmatch(digest):
sys.exit(f'{digest} is not a sha256 digest')
return layout / 'blobs' / 'sha256' / digest.removeprefix('sha256:')
def sha256_of(path):
h = hashlib.sha256()
with open(path, 'rb') as f:
while chunk := f.read(CHUNK):
h.update(chunk)
return 'sha256:' + h.hexdigest()
def write_json(layout, document):
data = json.dumps(document, separators=(',', ':')).encode()
digest = 'sha256:' + hashlib.sha256(data).hexdigest()
blob(layout, digest).write_bytes(data)
return digest, len(data)
def recompress_layer(layout, layer, diff_id, level):
if layer['mediaType'] == ZSTD:
return layer
opener = OPENERS.get(layer['mediaType'])
if opener is None:
sys.exit(f"layer {layer['digest']} has media type {layer['mediaType']}, which this cannot recompress")
uncompressed = hashlib.sha256()
with tempfile.NamedTemporaryFile(dir=layout / 'blobs' / 'sha256', delete=False) as out:
zstd = subprocess.Popen(['zstd', f'-{level}', '-T0', '-q', '-c'], stdin=subprocess.PIPE, stdout=out)
with opener(blob(layout, layer['digest']), 'rb') as src:
while chunk := src.read(CHUNK):
uncompressed.update(chunk)
zstd.stdin.write(chunk)
zstd.stdin.close()
if zstd.wait() != 0:
sys.exit(f"zstd failed on layer {layer['digest']}")
if 'sha256:' + uncompressed.hexdigest() != diff_id:
sys.exit(f"layer {layer['digest']} does not decompress to its diff_id {diff_id}")
digest = sha256_of(out.name)
shutil.move(out.name, blob(layout, digest))
size = blob(layout, digest).stat().st_size
print(f"{layer['digest'][:19]} {layer['size'] / 1e6:8.1f} MB -> zstd -{level} {size / 1e6:8.1f} MB",
file=sys.stderr)
return {**layer, 'mediaType': ZSTD, 'digest': digest, 'size': size}
def rewrite(layout, descriptor, level):
document = json.loads(blob(layout, descriptor['digest']).read_bytes())
if descriptor['mediaType'] == INDEX:
document['manifests'] = [rewrite(layout, d, level) for d in document['manifests']]
elif descriptor['mediaType'] == MANIFEST:
config = json.loads(blob(layout, document['config']['digest']).read_bytes())
diff_ids = config['rootfs']['diff_ids']
if len(diff_ids) != len(document['layers']):
sys.exit(f"manifest {descriptor['digest']} has {len(document['layers'])} layers but {len(diff_ids)} diff_ids")
document['layers'] = [recompress_layer(layout, layer, diff_id, level)
for layer, diff_id in zip(document['layers'], diff_ids)]
else:
sys.exit(f"{descriptor['digest']} has media type {descriptor['mediaType']}; export with oci-mediatypes=true")
digest, size = write_json(layout, document)
return {**descriptor, 'digest': digest, 'size': size}
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('layout', type=Path)
parser.add_argument('level', type=int)
args = parser.parse_args()
index_path = args.layout / 'index.json'
index = json.loads(index_path.read_text())
if len(index['manifests']) != 1:
sys.exit(f"{index_path} names {len(index['manifests'])} images, expected one")
index['manifests'] = [rewrite(args.layout, index['manifests'][0], args.level)]
index_path.write_text(json.dumps(index, separators=(',', ':')))
print(index['manifests'][0]['digest'])
if __name__ == '__main__':
main()
@@ -0,0 +1,4 @@
# Built for amd64 and arm64 by .github/workflows/push-zstd-image.yml. The base layers come from a
# registry in gzip and the COPY layer is built here. No RUN, so arm64 needs no emulation.
FROM registry.access.redhat.com/ubi9-micro:9.8
COPY docker/healthcheck.sh /usr/local/bin/
@@ -0,0 +1,162 @@
"""Test recompress.py against small OCI layouts written here.
Each layout holds real layer tars, so every check runs the zstd CLI the way the action does: a
layer must come out as zstd that decompresses back to its diff_id, and every manifest and index
above it must point at the new blobs.
"""
from pathlib import Path
import gzip
import hashlib
import io
import json
import subprocess
import sys
import tarfile
import tempfile
import unittest
RECOMPRESS = Path(__file__).resolve().parent / 'recompress.py'
INDEX = 'application/vnd.oci.image.index.v1+json'
MANIFEST = 'application/vnd.oci.image.manifest.v1+json'
CONFIG = 'application/vnd.oci.image.config.v1+json'
TAR = 'application/vnd.oci.image.layer.v1.tar'
GZIP = TAR + '+gzip'
ZSTD = TAR + '+zstd'
def layer_tar(name, content):
out = io.BytesIO()
with tarfile.open(fileobj=out, mode='w', format=tarfile.PAX_FORMAT) as tar:
info = tarfile.TarInfo(name)
info.size = len(content)
tar.addfile(info, io.BytesIO(content))
return out.getvalue()
def sha256(data):
return 'sha256:' + hashlib.sha256(data).hexdigest()
class Layout:
def __init__(self, root):
self.root = root
(root / 'blobs' / 'sha256').mkdir(parents=True)
(root / 'oci-layout').write_text('{"imageLayoutVersion":"1.0.0"}')
def blob(self, digest):
return self.root / 'blobs' / 'sha256' / digest.removeprefix('sha256:')
def put(self, data, media_type, **extra):
self.blob(sha256(data)).write_bytes(data)
return {'mediaType': media_type, 'digest': sha256(data), 'size': len(data), **extra}
def put_json(self, document, media_type, **extra):
return self.put(json.dumps(document).encode(), media_type, **extra)
def image(self, layers, diff_ids=None, architecture='amd64'):
"""layers: (tar bytes, media type) pairs. Returns the manifest descriptor."""
descriptors = [self.put(gzip.compress(tar, mtime=0) if media_type == GZIP else tar, media_type)
for tar, media_type in layers]
config = {'architecture': architecture, 'os': 'linux',
'rootfs': {'type': 'layers', 'diff_ids': diff_ids or [sha256(tar) for tar, _ in layers]}}
manifest = {'schemaVersion': 2, 'mediaType': MANIFEST, 'config': self.put_json(config, CONFIG),
'layers': descriptors}
return self.put_json(manifest, MANIFEST, platform={'architecture': architecture, 'os': 'linux'})
def index(self, manifests):
return self.put_json({'schemaVersion': 2, 'mediaType': INDEX, 'manifests': manifests}, INDEX)
def name(self, descriptor):
(self.root / 'index.json').write_text(json.dumps(
{'schemaVersion': 2, 'mediaType': INDEX, 'manifests': [descriptor]}))
def read(self, digest):
return json.loads(self.blob(digest).read_bytes())
def recompress(self):
return subprocess.run([sys.executable, str(RECOMPRESS), str(self.root), '3'], capture_output=True, text=True)
class RecompressTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.layout = Layout(Path(self.tmp.name))
def tearDown(self):
self.tmp.cleanup()
def run_ok(self):
result = self.layout.recompress()
self.assertEqual(result.returncode, 0, result.stderr)
return result.stdout.strip()
def assert_zstd_layers(self, manifest_digest):
manifest = self.layout.read(manifest_digest)
diff_ids = self.layout.read(manifest['config']['digest'])['rootfs']['diff_ids']
for layer, diff_id in zip(manifest['layers'], diff_ids):
self.assertEqual(layer['mediaType'], ZSTD)
data = self.layout.blob(layer['digest']).read_bytes()
self.assertEqual(sha256(data), layer['digest'])
self.assertEqual(len(data), layer['size'])
tar = subprocess.run(['zstd', '-dc'], input=data, capture_output=True, check=True).stdout
self.assertEqual(sha256(tar), diff_id)
return manifest
def test_single_platform_manifest(self):
self.layout.name(self.layout.image([(layer_tar('base', b'base' * 1000), GZIP),
(layer_tar('app', b'app' * 1000), TAR)]))
digest = self.run_ok()
named = json.loads((self.layout.root / 'index.json').read_text())['manifests'][0]
self.assertEqual(named['digest'], digest)
self.assertEqual(named['platform'], {'architecture': 'amd64', 'os': 'linux'})
self.assertEqual(len(self.assert_zstd_layers(digest)['layers']), 2)
def test_nested_index_with_a_layer_shared_between_platforms(self):
shared = (layer_tar('entrypoint.sh', b'#!/bin/sh\n'), TAR)
amd64 = self.layout.image([(layer_tar('base', b'amd64'), GZIP), shared], architecture='amd64')
arm64 = self.layout.image([(layer_tar('base', b'arm64'), GZIP), shared], architecture='arm64')
self.layout.name(self.layout.index([amd64, arm64]))
digest = self.run_ok()
manifests = self.layout.read(digest)['manifests']
self.assertEqual([m['platform']['architecture'] for m in manifests], ['amd64', 'arm64'])
layers = [self.assert_zstd_layers(m['digest'])['layers'] for m in manifests]
self.assertEqual(layers[0][1], layers[1][1])
self.assertNotEqual(layers[0][0]['digest'], layers[1][0]['digest'])
def test_layer_that_does_not_match_its_diff_id_fails(self):
self.layout.name(self.layout.image([(layer_tar('app', b'app'), TAR)], diff_ids=[sha256(b'other')]))
result = self.layout.recompress()
self.assertNotEqual(result.returncode, 0)
self.assertIn('does not decompress to its diff_id', result.stderr)
def test_second_run_changes_nothing(self):
amd64 = self.layout.image([(layer_tar('base', b'amd64'), GZIP)], architecture='amd64')
arm64 = self.layout.image([(layer_tar('base', b'arm64'), TAR)], architecture='arm64')
self.layout.name(self.layout.index([amd64, arm64]))
first = self.run_ok()
index_json = (self.layout.root / 'index.json').read_bytes()
second = self.run_ok()
self.assertEqual(first, second)
self.assertEqual((self.layout.root / 'index.json').read_bytes(), index_json)
def test_docker_media_type_manifest_fails(self):
self.layout.name(self.layout.put_json({'schemaVersion': 2}, 'application/vnd.docker.distribution.manifest.v2+json'))
result = self.layout.recompress()
self.assertNotEqual(result.returncode, 0)
self.assertIn('oci-mediatypes=true', result.stderr)
if __name__ == '__main__':
unittest.main()
+3 -1
View File
@@ -34,7 +34,9 @@ updates:
- "java"
- package-ecosystem: "github-actions"
directory: "/"
directories:
- "/"
- "/.github/actions/*"
schedule:
interval: "monthly"
open-pull-requests-limit: 5
+4 -10
View File
@@ -216,14 +216,11 @@ jobs:
registry-type: public
- name: Build and push native nightly image
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
env:
SOURCE_DATE_EPOCH: ${{ steps.source_date.outputs.epoch }}
uses: ./.github/actions/push-zstd-image
with:
context: .
source-date-epoch: ${{ steps.source_date.outputs.epoch }}
file: docker/Dockerfile.native-package
platforms: linux/amd64,linux/arm64
push: true
tags: |
floci/floci:nightly
floci/floci:nightly-${{ needs.prepare.outputs.version }}
@@ -242,14 +239,11 @@ jobs:
cache-to: type=gha,mode=max
- name: Build and push compat nightly image
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
env:
SOURCE_DATE_EPOCH: ${{ steps.source_date.outputs.epoch }}
uses: ./.github/actions/push-zstd-image
with:
context: .
source-date-epoch: ${{ steps.source_date.outputs.epoch }}
file: docker/Dockerfile.compat
platforms: linux/amd64,linux/arm64
push: true
tags: |
floci/floci:nightly-compat
floci/floci:nightly-${{ needs.prepare.outputs.version }}-compat
+87
View File
@@ -0,0 +1,87 @@
name: zstd image action
# Only release.yml and nightly.yml call .github/actions/push-zstd-image, so this checks it on the
# pull requests that change it: recompress.py against fixture layouts, then the whole action
# pushing a two-platform image to a registry on the runner.
on:
pull_request:
paths:
- '.github/actions/push-zstd-image/**'
- '.github/workflows/push-zstd-image.yml'
push:
branches:
- main
paths:
- '.github/actions/push-zstd-image/**'
- '.github/workflows/push-zstd-image.yml'
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
# Cancel a superseded run only on pull requests; a run on main is left to finish (see ci.yml).
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
test:
name: Test the zstd image action
runs-on: ubuntu-latest
timeout-minutes: 15
services:
registry:
image: registry:3@sha256:d4032d4cc323c1731c707931ecada07a53076eac38e3b61ae57533f170f2c6c3
ports:
- 5000:5000
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Test recompress.py
run: python3 .github/actions/push-zstd-image/test_recompress.py
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
with:
driver-opts: network=host
buildkitd-config-inline: |
[registry."localhost:5000"]
http = true
- name: Push a two-platform image through the action
id: push
uses: ./.github/actions/push-zstd-image
with:
file: .github/actions/push-zstd-image/test/Dockerfile
platforms: linux/amd64,linux/arm64
tags: localhost:5000/floci/zstd-test:ci
provenance: mode=max
sbom: true
- name: Check the pushed image
# Every layer must be zstd and every platform image must carry its attestations, and the
# runner's Docker must be able to pull and run the result.
env:
DIGEST: ${{ steps.push.outputs.digest }}
run: |
registry=http://localhost:5000/v2/floci/zstd-test
accept='Accept: application/vnd.oci.image.index.v1+json,application/vnd.oci.image.manifest.v1+json'
index=$(curl -fsS -H "$accept" "$registry/manifests/$DIGEST")
images=$(jq -r '.manifests[] | select(.platform.os == "linux") | .digest' <<<"$index")
if [ "$(wc -w <<<"$images")" -ne 2 ]; then
echo "::error::expected two platform images in $DIGEST, got: $images"
exit 1
fi
for image in $images; do
types=$(curl -fsS -H "$accept" "$registry/manifests/$image" | jq -r '[.layers[].mediaType] | unique | join(" ")')
if [ "$types" != application/vnd.oci.image.layer.v1.tar+zstd ]; then
echo "::error::$image has layers of type $types"
exit 1
fi
if ! jq -e --arg image "$image" 'any(.manifests[]; .annotations["vnd.docker.reference.digest"] == $image)' <<<"$index" > /dev/null; then
echo "::error::$image has no attestation manifest"
exit 1
fi
done
docker run --rm "localhost:5000/floci/zstd-test@$DIGEST" ls -l /usr/local/bin/healthcheck.sh
+6 -15
View File
@@ -437,14 +437,11 @@ jobs:
- name: Build and push native multi-arch image
id: native
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
env:
SOURCE_DATE_EPOCH: ${{ steps.source_date.outputs.epoch }}
uses: ./.github/actions/push-zstd-image
with:
context: .
source-date-epoch: ${{ steps.source_date.outputs.epoch }}
file: docker/Dockerfile.native-package
platforms: linux/amd64,linux/arm64
push: true
provenance: mode=max
sbom: true
tags: |
@@ -479,14 +476,11 @@ jobs:
- name: Build and push ARMv8.0 baseline image
id: baseline
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
env:
SOURCE_DATE_EPOCH: ${{ steps.source_date.outputs.epoch }}
uses: ./.github/actions/push-zstd-image
with:
context: .
source-date-epoch: ${{ steps.source_date.outputs.epoch }}
file: docker/Dockerfile.native-package
platforms: linux/arm64
push: true
provenance: mode=max
sbom: true
tags: |
@@ -508,14 +502,11 @@ jobs:
- name: Build and push compat multi-arch image
id: compat
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
env:
SOURCE_DATE_EPOCH: ${{ steps.source_date.outputs.epoch }}
uses: ./.github/actions/push-zstd-image
with:
context: .
source-date-epoch: ${{ steps.source_date.outputs.epoch }}
file: docker/Dockerfile.compat
platforms: linux/amd64,linux/arm64
push: true
provenance: mode=max
sbom: true
tags: |
+1 -1
View File
@@ -12,7 +12,7 @@ docker pull floci/floci:latest
### Requirements
- Docker 20.10+
- Docker 23.0+ (the image layers are compressed with zstd, which older engines cannot pull)
- `docker compose` v2+ (plugin syntax, not standalone `docker-compose`)
## Image Tags