Skip to content

Commit cfc2d9f

Browse files
committed
feat(registry): publish a base image plus one layer without a daemon
1 parent 496a695 commit cfc2d9f

3 files changed

Lines changed: 286 additions & 0 deletions

File tree

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
package io.github.intisy.docker.registry;
2+
3+
import com.google.gson.Gson;
4+
import com.google.gson.JsonArray;
5+
import com.google.gson.JsonObject;
6+
7+
import java.io.IOException;
8+
import java.io.InputStream;
9+
import java.nio.charset.StandardCharsets;
10+
import java.nio.file.Files;
11+
12+
/**
13+
* Publishes an image that is a base image plus one layer, moving only the blobs the target is
14+
* missing. Never contacts a Docker daemon.
15+
*
16+
* @author Finn Birich
17+
*/
18+
public final class ImagePublisher {
19+
private static final Gson GSON = new Gson();
20+
21+
public static String publish(RegistryClient source, ImageReference base,
22+
RegistryClient target, ImageReference targetReference,
23+
Layer layer, ImageConfigOverrides overrides) throws IOException {
24+
RegistryClient.Manifest baseManifest = resolveToPlatformManifest(source, base);
25+
JsonObject manifestJson = GSON.fromJson(baseManifest.text(), JsonObject.class);
26+
27+
String baseConfigDigest = manifestJson.getAsJsonObject("config").get("digest").getAsString();
28+
String baseConfigJson = new String(
29+
source.getBlob(base.repository(), baseConfigDigest).bytes(), StandardCharsets.UTF_8);
30+
31+
ImageAssembler.Assembled assembled =
32+
ImageAssembler.append(baseConfigJson, baseManifest.text(), layer, overrides);
33+
34+
copyBaseLayers(source, base, target, targetReference, manifestJson);
35+
uploadNewLayer(target, targetReference, layer);
36+
uploadConfig(target, targetReference, assembled);
37+
38+
target.putManifest(targetReference, assembled.manifestMediaType(),
39+
assembled.manifestJson().getBytes(StandardCharsets.UTF_8));
40+
return Digests.sha256(assembled.manifestJson().getBytes(StandardCharsets.UTF_8));
41+
}
42+
43+
/**
44+
* @implNote a base image is normally published as a multi-architecture index, so the first read
45+
* yields the index and the platform manifest needs a second read by digest. A base that is
46+
* already a single manifest skips straight through.
47+
*/
48+
private static RegistryClient.Manifest resolveToPlatformManifest(RegistryClient source, ImageReference base)
49+
throws IOException {
50+
RegistryClient.Manifest first = source.getManifest(base);
51+
if (!PlatformSelector.isIndex(first.mediaType())) {
52+
return first;
53+
}
54+
String digest = PlatformSelector.digestFor(first.text(), "linux", "amd64");
55+
return source.getManifest(base.withReference(digest, true));
56+
}
57+
58+
private static void copyBaseLayers(RegistryClient source, ImageReference base,
59+
RegistryClient target, ImageReference targetReference,
60+
JsonObject manifestJson) throws IOException {
61+
JsonArray layers = manifestJson.getAsJsonArray("layers");
62+
for (int i = 0; i < layers.size(); i++) {
63+
String digest = layers.get(i).getAsJsonObject().get("digest").getAsString();
64+
copyBlobIfMissing(source, base, target, targetReference, digest);
65+
}
66+
}
67+
68+
private static void copyBlobIfMissing(RegistryClient source, ImageReference base,
69+
RegistryClient target, ImageReference targetReference,
70+
String digest) throws IOException {
71+
if (target.blobExists(targetReference.repository(), digest)) {
72+
return;
73+
}
74+
byte[] blob = source.getBlob(base.repository(), digest).bytes();
75+
target.putBlob(targetReference.repository(), digest, RegistryBody.ofBytes(blob));
76+
}
77+
78+
private static void uploadNewLayer(RegistryClient target, ImageReference targetReference, Layer layer)
79+
throws IOException {
80+
if (target.blobExists(targetReference.repository(), layer.digest())) {
81+
return;
82+
}
83+
InputStream content = Files.newInputStream(layer.file());
84+
try {
85+
target.putBlob(targetReference.repository(), layer.digest(),
86+
RegistryBody.ofStream(content, layer.size()));
87+
} finally {
88+
content.close();
89+
}
90+
}
91+
92+
private static void uploadConfig(RegistryClient target, ImageReference targetReference,
93+
ImageAssembler.Assembled assembled) throws IOException {
94+
if (target.blobExists(targetReference.repository(), assembled.configDigest())) {
95+
return;
96+
}
97+
target.putBlob(targetReference.repository(), assembled.configDigest(),
98+
RegistryBody.ofBytes(assembled.configJson().getBytes(StandardCharsets.UTF_8)));
99+
}
100+
101+
private ImagePublisher() {}
102+
}

‎src/test/java/io/github/intisy/docker/unit/FakeRegistryHttp.java‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ public final class FakeRegistryHttp implements RegistryHttp {
2121
private final Map<String, List<RegistryResponse>> answers =
2222
new LinkedHashMap<String, List<RegistryResponse>>();
2323
private final Map<String, byte[]> sentBodies = new LinkedHashMap<String, byte[]>();
24+
private boolean headsDefaultTo404;
25+
private boolean acceptAnyBlobUpload;
2426

2527
public List<String> calls() {
2628
return new ArrayList<String>(calls);
@@ -47,6 +49,14 @@ public void answerText(String methodAndUrl, int status, String body, String... h
4749
answer(methodAndUrl, new RegistryResponse(status, headers, body.getBytes(StandardCharsets.UTF_8)));
4850
}
4951

52+
public void answerMissingHeadsAs404() {
53+
this.headsDefaultTo404 = true;
54+
}
55+
56+
public void acceptAnyBlobUpload() {
57+
this.acceptAnyBlobUpload = true;
58+
}
59+
5060
@Override
5161
public RegistryResponse send(String method, String url, Map<String, String> headers, RegistryBody body)
5262
throws IOException {
@@ -55,6 +65,19 @@ public RegistryResponse send(String method, String url, Map<String, String> head
5565
if (body != null && body.bytes() != null) {
5666
sentBodies.put(key, body.bytes());
5767
}
68+
if (headsDefaultTo404 && "HEAD".equals(method) && !answers.containsKey(key)) {
69+
return new RegistryResponse(404, new HashMap<String, String>(), new byte[0]);
70+
}
71+
if (acceptAnyBlobUpload && !answers.containsKey(key)) {
72+
if ("POST".equals(method) && url.endsWith("/blobs/uploads/")) {
73+
Map<String, String> location = new HashMap<String, String>();
74+
location.put("Location", url + "u1");
75+
return new RegistryResponse(202, location, new byte[0]);
76+
}
77+
if ("PUT".equals(method) && url.contains("/blobs/uploads/")) {
78+
return new RegistryResponse(201, new HashMap<String, String>(), new byte[0]);
79+
}
80+
}
5881
List<RegistryResponse> queued = answers.get(key);
5982
if (queued == null || queued.isEmpty()) {
6083
throw new IOException("no fake answer queued for " + key + "; queued keys are " + answers.keySet());
Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
package io.github.intisy.docker.unit;
2+
3+
import io.github.intisy.docker.registry.ImageConfigOverrides;
4+
import io.github.intisy.docker.registry.ImagePublisher;
5+
import io.github.intisy.docker.registry.ImageReference;
6+
import io.github.intisy.docker.registry.Layer;
7+
import io.github.intisy.docker.registry.RegistryClient;
8+
import io.github.intisy.docker.registry.RegistryResponse;
9+
import org.junit.jupiter.api.Tag;
10+
import org.junit.jupiter.api.Test;
11+
import org.junit.jupiter.api.io.TempDir;
12+
13+
import java.io.IOException;
14+
import java.nio.charset.StandardCharsets;
15+
import java.nio.file.Files;
16+
import java.nio.file.Path;
17+
import java.util.Arrays;
18+
import java.util.HashMap;
19+
import java.util.List;
20+
21+
import static org.junit.jupiter.api.Assertions.assertEquals;
22+
import static org.junit.jupiter.api.Assertions.assertFalse;
23+
import static org.junit.jupiter.api.Assertions.assertTrue;
24+
25+
@Tag("unit")
26+
public class ImagePublisherTest {
27+
private static final String INDEX_DIGEST =
28+
"sha256:2222222222222222222222222222222222222222222222222222222222222222";
29+
private static final String CONFIG_DIGEST =
30+
"sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc";
31+
private static final String BASE_LAYER_DIGEST =
32+
"sha256:dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd";
33+
private static final String NEW_LAYER_DIGEST =
34+
"sha256:5678567856785678567856785678567856785678567856785678567856785678";
35+
36+
private static final String INDEX = "{\"schemaVersion\":2,\"manifests\":[{\"digest\":\"" + INDEX_DIGEST
37+
+ "\",\"platform\":{\"os\":\"linux\",\"architecture\":\"amd64\"}}]}";
38+
private static final String MANIFEST = "{\"schemaVersion\":2,"
39+
+ "\"mediaType\":\"application/vnd.oci.image.manifest.v1+json\","
40+
+ "\"config\":{\"mediaType\":\"application/vnd.oci.image.config.v1+json\",\"digest\":\""
41+
+ CONFIG_DIGEST + "\",\"size\":10},"
42+
+ "\"layers\":[{\"mediaType\":\"application/vnd.oci.image.layer.v1.tar+gzip\",\"digest\":\""
43+
+ BASE_LAYER_DIGEST + "\",\"size\":30}]}";
44+
private static final String CONFIG = "{\"architecture\":\"amd64\",\"os\":\"linux\","
45+
+ "\"config\":{\"Env\":[\"PATH=/usr/bin\"]},"
46+
+ "\"rootfs\":{\"type\":\"layers\",\"diff_ids\":[\"sha256:aaaa\"]},\"history\":[]}";
47+
48+
private FakeRegistryHttp sourceHttp;
49+
private FakeRegistryHttp targetHttp;
50+
51+
private RegistryClient source() {
52+
sourceHttp = new FakeRegistryHttp();
53+
sourceHttp.answerText("GET https://registry-1.docker.io/v2/library/eclipse-temurin/manifests/21-jre",
54+
200, INDEX, "Content-Type", RegistryClient.OCI_INDEX);
55+
sourceHttp.answerText("GET https://registry-1.docker.io/v2/library/eclipse-temurin/manifests/"
56+
+ INDEX_DIGEST, 200, MANIFEST, "Content-Type", RegistryClient.OCI_MANIFEST);
57+
sourceHttp.answer("GET https://registry-1.docker.io/v2/library/eclipse-temurin/blobs/" + CONFIG_DIGEST,
58+
new RegistryResponse(200, new HashMap<String, String>(), CONFIG.getBytes(StandardCharsets.UTF_8)));
59+
sourceHttp.answer("GET https://registry-1.docker.io/v2/library/eclipse-temurin/blobs/" + BASE_LAYER_DIGEST,
60+
new RegistryResponse(200, new HashMap<String, String>(), new byte[] {9, 9, 9}));
61+
return new RegistryClient(sourceHttp, "registry-1.docker.io", false);
62+
}
63+
64+
private RegistryClient target(boolean baseLayerAlreadyPresent) {
65+
targetHttp = new FakeRegistryHttp();
66+
String root = "http://registry.spisor.internal/v2/spisor/core";
67+
targetHttp.answer("HEAD " + root + "/blobs/" + BASE_LAYER_DIGEST, new RegistryResponse(
68+
baseLayerAlreadyPresent ? 200 : 404, new HashMap<String, String>(), new byte[0]));
69+
targetHttp.answer("HEAD " + root + "/blobs/" + NEW_LAYER_DIGEST,
70+
new RegistryResponse(404, new HashMap<String, String>(), new byte[0]));
71+
targetHttp.answer("POST " + root + "/blobs/uploads/", new RegistryResponse(202,
72+
location(root + "/blobs/uploads/u1"), new byte[0]));
73+
targetHttp.answer("PUT " + root + "/blobs/uploads/u1?digest=" + encoded(BASE_LAYER_DIGEST),
74+
new RegistryResponse(201, new HashMap<String, String>(), new byte[0]));
75+
targetHttp.answer("PUT " + root + "/blobs/uploads/u1?digest=" + encoded(NEW_LAYER_DIGEST),
76+
new RegistryResponse(201, new HashMap<String, String>(), new byte[0]));
77+
targetHttp.answer("PUT " + root + "/manifests/0.1.0",
78+
new RegistryResponse(201, new HashMap<String, String>(), new byte[0]));
79+
targetHttp.answerMissingHeadsAs404();
80+
targetHttp.acceptAnyBlobUpload();
81+
return new RegistryClient(targetHttp, "registry.spisor.internal", true);
82+
}
83+
84+
private static java.util.Map<String, String> location(String value) {
85+
java.util.Map<String, String> headers = new HashMap<String, String>();
86+
headers.put("Location", value);
87+
return headers;
88+
}
89+
90+
private static String encoded(String digest) {
91+
return digest.replace(":", "%3A");
92+
}
93+
94+
private Layer layer(Path tmp) throws IOException {
95+
Path file = tmp.resolve("layer.tar.gz");
96+
Files.write(file, new byte[] {1, 2, 3, 4});
97+
return new Layer(file,
98+
"sha256:1234123412341234123412341234123412341234123412341234123412341234",
99+
NEW_LAYER_DIGEST, 4L);
100+
}
101+
102+
private static ImageConfigOverrides overrides() {
103+
List<String> entrypoint = Arrays.asList("/opt/spisor/launcher/bin/launcher");
104+
return new ImageConfigOverrides().withEntrypoint(entrypoint).withCmd(null);
105+
}
106+
107+
@Test
108+
public void publishesConfigLayerAndManifestAndReturnsTheManifestDigest(@TempDir Path tmp) throws IOException {
109+
String digest = ImagePublisher.publish(source(), ImageReference.parse("eclipse-temurin:21-jre"),
110+
target(false), ImageReference.parse("registry.spisor.internal/spisor/core:0.1.0"),
111+
layer(tmp), overrides());
112+
113+
assertTrue(digest.startsWith("sha256:"), digest);
114+
List<String> calls = targetHttp.calls();
115+
assertTrue(calls.contains("PUT http://registry.spisor.internal/v2/spisor/core/manifests/0.1.0"),
116+
calls.toString());
117+
}
118+
119+
/**
120+
* The manifest must be the LAST thing pushed. A registry rejects a manifest whose blobs are
121+
* not all present, so an ordering slip here produces a MANIFEST_BLOB_UNKNOWN that reads like a
122+
* corruption problem.
123+
*/
124+
@Test
125+
public void theManifestIsPushedLast(@TempDir Path tmp) throws IOException {
126+
ImagePublisher.publish(source(), ImageReference.parse("eclipse-temurin:21-jre"),
127+
target(false), ImageReference.parse("registry.spisor.internal/spisor/core:0.1.0"),
128+
layer(tmp), overrides());
129+
130+
List<String> calls = targetHttp.calls();
131+
assertEquals("PUT http://registry.spisor.internal/v2/spisor/core/manifests/0.1.0",
132+
calls.get(calls.size() - 1));
133+
}
134+
135+
/**
136+
* The base is tens of megabytes. Re-sending it on every publish would make the day-to-day loop
137+
* unusable, and the HEAD that prevents it is cheap.
138+
*/
139+
@Test
140+
public void aBaseLayerAlreadyInTheTargetIsNotReUploaded(@TempDir Path tmp) throws IOException {
141+
ImagePublisher.publish(source(), ImageReference.parse("eclipse-temurin:21-jre"),
142+
target(true), ImageReference.parse("registry.spisor.internal/spisor/core:0.1.0"),
143+
layer(tmp), overrides());
144+
145+
assertFalse(sourceHttp.calls().contains("GET https://registry-1.docker.io/v2/library/eclipse-temurin/blobs/"
146+
+ BASE_LAYER_DIGEST),
147+
"an already-present layer must not even be fetched from the source");
148+
}
149+
150+
@Test
151+
public void theIndexIsResolvedToTheAmd64ManifestBeforeAnythingIsRead(@TempDir Path tmp) throws IOException {
152+
ImagePublisher.publish(source(), ImageReference.parse("eclipse-temurin:21-jre"),
153+
target(false), ImageReference.parse("registry.spisor.internal/spisor/core:0.1.0"),
154+
layer(tmp), overrides());
155+
156+
assertEquals("GET https://registry-1.docker.io/v2/library/eclipse-temurin/manifests/21-jre",
157+
sourceHttp.calls().get(0));
158+
assertEquals("GET https://registry-1.docker.io/v2/library/eclipse-temurin/manifests/" + INDEX_DIGEST,
159+
sourceHttp.calls().get(1));
160+
}
161+
}

0 commit comments

Comments
 (0)