Skip to content

Commit bb0b3cf

Browse files
committed
feat(registry): build deterministic gzipped tar layers
1 parent ecef669 commit bb0b3cf

3 files changed

Lines changed: 323 additions & 0 deletions

File tree

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package io.github.intisy.docker.registry;
2+
3+
import java.nio.file.Path;
4+
5+
/**
6+
* A built image layer: the gzipped tar on disk, the digest of that file, and the digest of the
7+
* tar inside it.
8+
*
9+
* @author Finn Birich
10+
*/
11+
public final class Layer {
12+
private final Path file;
13+
private final String diffId;
14+
private final String digest;
15+
private final long size;
16+
17+
public Layer(Path file, String diffId, String digest, long size) {
18+
this.file = file;
19+
this.diffId = diffId;
20+
this.digest = digest;
21+
this.size = size;
22+
}
23+
24+
public Path file() {
25+
return file;
26+
}
27+
28+
/** Digest of the UNCOMPRESSED tar, which is what the image config records. */
29+
public String diffId() {
30+
return diffId;
31+
}
32+
33+
/** Digest of the gzipped blob, which is what the manifest and the registry record. */
34+
public String digest() {
35+
return digest;
36+
}
37+
38+
public long size() {
39+
return size;
40+
}
41+
}
Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
package io.github.intisy.docker.registry;
2+
3+
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
4+
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
5+
6+
import java.io.FileInputStream;
7+
import java.io.IOException;
8+
import java.io.InputStream;
9+
import java.io.OutputStream;
10+
import java.nio.file.FileVisitResult;
11+
import java.nio.file.Files;
12+
import java.nio.file.Path;
13+
import java.nio.file.SimpleFileVisitor;
14+
import java.nio.file.attribute.BasicFileAttributes;
15+
import java.util.ArrayList;
16+
import java.util.Collections;
17+
import java.util.List;
18+
import java.util.zip.GZIPOutputStream;
19+
20+
/**
21+
* Turns a directory into one gzipped tar layer.
22+
*
23+
* @implNote every field that could vary between two builds of the same tree is pinned: entries are
24+
* sorted, modification times are zero, and uid and gid are zero with no owner names. Without that
25+
* the digest changes on every build and the node re-pulls a layer whose content is identical.
26+
*
27+
* @author Finn Birich
28+
*/
29+
public final class LayerBuilder {
30+
private static final int EXECUTABLE_MODE = 0755;
31+
private static final int REGULAR_MODE = 0644;
32+
private static final int DIRECTORY_MODE = 0755;
33+
private static final int BUFFER_BYTES = 64 * 1024;
34+
35+
public static Layer fromDirectory(Path source, String pathInImage, Path outputFile) throws IOException {
36+
final List<Path> files = new ArrayList<Path>();
37+
Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
38+
@Override
39+
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) {
40+
files.add(file);
41+
return FileVisitResult.CONTINUE;
42+
}
43+
});
44+
Collections.sort(files);
45+
46+
String prefix = pathInImage.startsWith("/") ? pathInImage.substring(1) : pathInImage;
47+
if (!prefix.endsWith("/")) {
48+
prefix = prefix + "/";
49+
}
50+
51+
Files.createDirectories(outputFile.getParent());
52+
OutputStream fileOut = Files.newOutputStream(outputFile);
53+
TarArchiveOutputStream tar = new TarArchiveOutputStream(new GZIPOutputStream(fileOut));
54+
try {
55+
tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
56+
for (String directory : directoriesFor(prefix, source, files)) {
57+
TarArchiveEntry entry = new TarArchiveEntry(directory);
58+
pin(entry, DIRECTORY_MODE, 0);
59+
tar.putArchiveEntry(entry);
60+
tar.closeArchiveEntry();
61+
}
62+
for (Path file : files) {
63+
String name = prefix + source.relativize(file).toString().replace('\\', '/');
64+
long size = Files.size(file);
65+
TarArchiveEntry entry = new TarArchiveEntry(name);
66+
pin(entry, isUnderBin(name) ? EXECUTABLE_MODE : REGULAR_MODE, size);
67+
tar.putArchiveEntry(entry);
68+
copy(file, tar);
69+
tar.closeArchiveEntry();
70+
}
71+
} finally {
72+
tar.close();
73+
}
74+
75+
String digest = digestOf(Files.newInputStream(outputFile));
76+
String diffId = digestOf(new java.util.zip.GZIPInputStream(Files.newInputStream(outputFile)));
77+
return new Layer(outputFile, diffId, digest, Files.size(outputFile));
78+
}
79+
80+
/**
81+
* @implNote a rule, not an inspection: Windows cannot report the POSIX executable bit, so
82+
* reading it would make the layer depend on which machine built it, and the launcher script
83+
* would be non-executable exactly on the machine this project is developed on.
84+
*/
85+
static boolean isUnderBin(String nameInArchive) {
86+
return nameInArchive.contains("/bin/");
87+
}
88+
89+
static List<String> directoriesFor(String prefix, Path source, List<Path> files) {
90+
List<String> directories = new ArrayList<String>();
91+
java.util.Set<String> seen = new java.util.TreeSet<String>();
92+
for (Path file : files) {
93+
String relative = source.relativize(file).toString().replace('\\', '/');
94+
int slash = relative.indexOf('/');
95+
while (slash >= 0) {
96+
seen.add(prefix + relative.substring(0, slash) + "/");
97+
slash = relative.indexOf('/', slash + 1);
98+
}
99+
}
100+
String[] segments = prefix.split("/");
101+
StringBuilder built = new StringBuilder();
102+
for (int i = 0; i < segments.length; i++) {
103+
built.append(segments[i]).append('/');
104+
directories.add(built.toString());
105+
}
106+
directories.addAll(seen);
107+
return directories;
108+
}
109+
110+
private static void pin(TarArchiveEntry entry, int mode, long size) {
111+
entry.setMode((entry.isDirectory() ? TarArchiveEntry.DEFAULT_DIR_MODE : 0) | mode);
112+
entry.setModTime(0L);
113+
entry.setUserId(0);
114+
entry.setGroupId(0);
115+
entry.setUserName("");
116+
entry.setGroupName("");
117+
entry.setSize(size);
118+
}
119+
120+
private static void copy(Path file, OutputStream out) throws IOException {
121+
InputStream in = new FileInputStream(file.toFile());
122+
try {
123+
byte[] buffer = new byte[BUFFER_BYTES];
124+
int read;
125+
while ((read = in.read(buffer)) != -1) {
126+
out.write(buffer, 0, read);
127+
}
128+
} finally {
129+
in.close();
130+
}
131+
}
132+
133+
private static String digestOf(InputStream stream) throws IOException {
134+
try {
135+
return Digests.sha256(stream);
136+
} finally {
137+
stream.close();
138+
}
139+
}
140+
141+
private LayerBuilder() {}
142+
}
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
package io.github.intisy.docker.unit;
2+
3+
import io.github.intisy.docker.registry.Digests;
4+
import io.github.intisy.docker.registry.Layer;
5+
import io.github.intisy.docker.registry.LayerBuilder;
6+
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
7+
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
8+
import org.junit.jupiter.api.Tag;
9+
import org.junit.jupiter.api.Test;
10+
import org.junit.jupiter.api.io.TempDir;
11+
12+
import java.io.FileInputStream;
13+
import java.io.IOException;
14+
import java.io.InputStream;
15+
import java.nio.charset.StandardCharsets;
16+
import java.nio.file.Files;
17+
import java.nio.file.Path;
18+
import java.util.ArrayList;
19+
import java.util.List;
20+
import java.util.zip.GZIPInputStream;
21+
22+
import static org.junit.jupiter.api.Assertions.assertEquals;
23+
import static org.junit.jupiter.api.Assertions.assertNotEquals;
24+
import static org.junit.jupiter.api.Assertions.assertTrue;
25+
26+
@Tag("unit")
27+
public class LayerBuilderTest {
28+
29+
private static Path launcherLikeTree(Path root) throws IOException {
30+
Path dist = root.resolve("dist");
31+
Files.createDirectories(dist.resolve("bin"));
32+
Files.createDirectories(dist.resolve("lib"));
33+
Files.write(dist.resolve("bin/launcher"), "#!/bin/sh\nexec java -cp ...\n".getBytes(StandardCharsets.UTF_8));
34+
Files.write(dist.resolve("bin/launcher.bat"), "@echo off\n".getBytes(StandardCharsets.UTF_8));
35+
Files.write(dist.resolve("lib/launcher.jar"), new byte[] {0x50, 0x4b, 0x03, 0x04});
36+
return dist;
37+
}
38+
39+
@Test
40+
public void entriesAreRootedAtThePathInImage(@TempDir Path tmp) throws IOException {
41+
Layer layer = LayerBuilder.fromDirectory(
42+
launcherLikeTree(tmp), "/opt/spisor/launcher", tmp.resolve("layer.tar.gz"));
43+
44+
List<String> names = entryNames(layer.file());
45+
assertTrue(names.contains("opt/spisor/launcher/bin/launcher"), names.toString());
46+
assertTrue(names.contains("opt/spisor/launcher/lib/launcher.jar"), names.toString());
47+
}
48+
49+
@Test
50+
public void filesUnderBinAreExecutableAndOthersAreNot(@TempDir Path tmp) throws IOException {
51+
Layer layer = LayerBuilder.fromDirectory(
52+
launcherLikeTree(tmp), "/opt/spisor/launcher", tmp.resolve("layer.tar.gz"));
53+
54+
assertEquals(0755, modeOf(layer.file(), "opt/spisor/launcher/bin/launcher"));
55+
assertEquals(0644, modeOf(layer.file(), "opt/spisor/launcher/lib/launcher.jar"));
56+
}
57+
58+
@Test
59+
public void twoBuildsOfTheSameTreeProduceTheSameDigest(@TempDir Path tmp) throws IOException {
60+
Path source = launcherLikeTree(tmp);
61+
Layer first = LayerBuilder.fromDirectory(source, "/opt/spisor/launcher", tmp.resolve("a.tar.gz"));
62+
Layer second = LayerBuilder.fromDirectory(source, "/opt/spisor/launcher", tmp.resolve("b.tar.gz"));
63+
64+
assertEquals(first.diffId(), second.diffId());
65+
assertEquals(first.digest(), second.digest());
66+
}
67+
68+
@Test
69+
public void changingAFileChangesTheDigest(@TempDir Path tmp) throws IOException {
70+
Path source = launcherLikeTree(tmp);
71+
Layer before = LayerBuilder.fromDirectory(source, "/opt/spisor/launcher", tmp.resolve("a.tar.gz"));
72+
Files.write(source.resolve("lib/launcher.jar"), new byte[] {0x50, 0x4b, 0x03, 0x05});
73+
Layer after = LayerBuilder.fromDirectory(source, "/opt/spisor/launcher", tmp.resolve("b.tar.gz"));
74+
75+
assertNotEquals(before.diffId(), after.diffId());
76+
}
77+
78+
/**
79+
* The diff id is the digest of the uncompressed tar and the digest is the digest of the gzip.
80+
* Conflating them produces a config whose rootfs entry no layer can satisfy, and the registry
81+
* accepts the push and the node then fails to unpack.
82+
*/
83+
@Test
84+
public void diffIdIsTheUncompressedDigestAndDigestIsTheCompressedOne(@TempDir Path tmp) throws IOException {
85+
Layer layer = LayerBuilder.fromDirectory(
86+
launcherLikeTree(tmp), "/opt/spisor/launcher", tmp.resolve("layer.tar.gz"));
87+
88+
assertNotEquals(layer.diffId(), layer.digest());
89+
assertEquals(layer.digest(), sha256Closing(new FileInputStream(layer.file().toFile())));
90+
assertEquals(layer.diffId(),
91+
sha256Closing(new GZIPInputStream(new FileInputStream(layer.file().toFile()))));
92+
assertEquals(Files.size(layer.file()), layer.size());
93+
}
94+
95+
/**
96+
* @implNote {@link Digests#sha256(InputStream)} does not close its argument; on Windows a
97+
* lingering open handle on the layer file blocks {@code @TempDir} cleanup after the test.
98+
*/
99+
private static String sha256Closing(InputStream stream) throws IOException {
100+
try {
101+
return Digests.sha256(stream);
102+
} finally {
103+
stream.close();
104+
}
105+
}
106+
107+
private static List<String> entryNames(Path archive) throws IOException {
108+
List<String> names = new ArrayList<String>();
109+
TarArchiveInputStream tar = openTar(archive);
110+
try {
111+
TarArchiveEntry entry;
112+
while ((entry = tar.getNextTarEntry()) != null) {
113+
names.add(entry.getName());
114+
}
115+
} finally {
116+
tar.close();
117+
}
118+
return names;
119+
}
120+
121+
private static int modeOf(Path archive, String name) throws IOException {
122+
TarArchiveInputStream tar = openTar(archive);
123+
try {
124+
TarArchiveEntry entry;
125+
while ((entry = tar.getNextTarEntry()) != null) {
126+
if (name.equals(entry.getName())) {
127+
return entry.getMode() & 0777;
128+
}
129+
}
130+
} finally {
131+
tar.close();
132+
}
133+
throw new IOException("no entry " + name + " in " + archive);
134+
}
135+
136+
private static TarArchiveInputStream openTar(Path archive) throws IOException {
137+
InputStream raw = new FileInputStream(archive.toFile());
138+
return new TarArchiveInputStream(new GZIPInputStream(raw));
139+
}
140+
}

0 commit comments

Comments
 (0)