Skip to content

Commit bedddb1

Browse files
authored
Make layer builder create reproducible layers. (GoogleContainerTools#98)
- Strip out non-reproducible properties from tarArchiveEntry. - Sort all entries in the tar by name - Allow the user to toggle this feature through build config.
1 parent 2c1dfb8 commit bedddb1

8 files changed

Lines changed: 114 additions & 6 deletions

File tree

‎jib-core/src/main/java/com/google/cloud/tools/jib/blob/Blobs.java‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,14 @@ public static Blob from(BlobWriter writer) {
4343

4444
/** Writes the BLOB to a string. */
4545
public static String writeToString(Blob blob) throws IOException {
46+
return new String(writeToByteArray(blob), StandardCharsets.UTF_8);
47+
}
48+
49+
/** Writes the BLOB to a byte array. */
50+
public static byte[] writeToByteArray(Blob blob) throws IOException {
4651
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
4752
blob.writeTo(byteArrayOutputStream);
48-
return new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8);
53+
return byteArrayOutputStream.toByteArray();
4954
}
5055

5156
private Blobs() {}

‎jib-core/src/main/java/com/google/cloud/tools/jib/builder/BuildAndCacheApplicationLayersStep.java‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,9 @@ private ListenableFuture<CachedLayer> buildAndCacheLayerAsync(
9595
return cachedLayer;
9696
}
9797

98-
LayerBuilder layerBuilder = new LayerBuilder(sourceFiles, extractionPath);
98+
LayerBuilder layerBuilder =
99+
new LayerBuilder(
100+
sourceFiles, extractionPath, buildConfiguration.getEnableReproducibleBuilds());
99101

100102
cachedLayer = new CacheWriter(cache).writeLayer(layerBuilder, layerType);
101103
// TODO: Remove

‎jib-core/src/main/java/com/google/cloud/tools/jib/builder/BuildConfiguration.java‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,9 @@ enum Fields {
4949
/** Known registry credentials to fallback on. */
5050
KNOWN_REGISTRY_CREDENTIALS(false),
5151

52+
/** Tell the layer build to use reproducibility features. */
53+
ENABLE_REPRODUCIBLE_BUILDS(false),
54+
5255
/** The main class to use when running the application. */
5356
MAIN_CLASS(true),
5457

@@ -83,6 +86,7 @@ public static class Builder {
8386
put(Fields.TARGET_REPOSITORY, "target image name");
8487
put(Fields.TARGET_TAG, "target image tag");
8588
put(Fields.CREDENTIAL_HELPER_NAMES, "credential helper names");
89+
put(Fields.ENABLE_REPRODUCIBLE_BUILDS, "enable reproducible layer builds");
8690
put(Fields.MAIN_CLASS, "main class");
8791
put(Fields.JVM_FLAGS, "JVM flags");
8892
put(Fields.ENVIRONMENT, "environment variables");
@@ -101,6 +105,7 @@ private Builder() {
101105
values.put(Fields.KNOWN_REGISTRY_CREDENTIALS, RegistryCredentials.none());
102106
values.put(Fields.JVM_FLAGS, Collections.emptyList());
103107
values.put(Fields.ENVIRONMENT, Collections.emptyMap());
108+
values.put(Fields.ENABLE_REPRODUCIBLE_BUILDS, false);
104109
}
105110

106111
public Builder setBuildLogger(BuildLogger buildLogger) {
@@ -152,6 +157,11 @@ public Builder setKnownRegistryCredentials(RegistryCredentials knownRegistryCred
152157
return this;
153158
}
154159

160+
public Builder setEnableReproducibleBuilds(boolean enable) {
161+
values.put(Fields.ENABLE_REPRODUCIBLE_BUILDS, enable);
162+
return this;
163+
}
164+
155165
public Builder setMainClass(String mainClass) {
156166
values.put(Fields.MAIN_CLASS, mainClass);
157167
return this;
@@ -262,6 +272,10 @@ public List<String> getCredentialHelperNames() {
262272
return getFieldValue(Fields.CREDENTIAL_HELPER_NAMES);
263273
}
264274

275+
public boolean getEnableReproducibleBuilds() {
276+
return getFieldValue(Fields.ENABLE_REPRODUCIBLE_BUILDS);
277+
}
278+
265279
public String getMainClass() {
266280
return getFieldValue(Fields.MAIN_CLASS);
267281
}

‎jib-core/src/main/java/com/google/cloud/tools/jib/builder/PushBlobStep.java‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,9 @@ public Void call()
6161
.setTimer(timer);
6262

6363
if (registryClient.checkBlob(layerDigest) != null) {
64+
buildConfiguration
65+
.getBuildLogger()
66+
.info("BLOB : " + layerDigest + " already exists on registry");
6467
return null;
6568
}
6669

‎jib-core/src/main/java/com/google/cloud/tools/jib/image/LayerBuilder.java‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
import java.nio.file.Path;
2323
import java.util.ArrayList;
2424
import java.util.Collections;
25+
import java.util.Comparator;
2526
import java.util.List;
2627
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
2728

@@ -40,9 +41,14 @@ public class LayerBuilder {
4041
/** The Unix-style path of the file in the partial filesystem changeset. */
4142
private final String extractionPath;
4243

43-
public LayerBuilder(List<Path> sourceFiles, String extractionPath) {
44+
/** Enable reproducible features when building the tar */
45+
private final boolean enableReproducibleBuilds;
46+
47+
public LayerBuilder(
48+
List<Path> sourceFiles, String extractionPath, boolean enableReproducibleBuilds) {
4449
this.sourceFiles = new ArrayList<>(sourceFiles);
4550
this.extractionPath = extractionPath;
51+
this.enableReproducibleBuilds = enableReproducibleBuilds;
4652
}
4753

4854
/** Builds and returns the layer. */
@@ -72,20 +78,36 @@ public UnwrittenLayer build() throws IOException {
7278

7379
TarArchiveEntry tarArchiveEntry =
7480
new TarArchiveEntry(sourceFile.toFile(), extractionPath + "/" + sourceFile.getFileName());
75-
tarArchiveEntry.setModTime(0);
7681
filesystemEntries.add(tarArchiveEntry);
7782
}
7883

79-
TarStreamBuilder tarStreamBuilder = new TarStreamBuilder();
84+
if (enableReproducibleBuilds) {
85+
makeListReproducible(filesystemEntries);
86+
}
8087

8188
// Adds all the files to a tar stream.
89+
TarStreamBuilder tarStreamBuilder = new TarStreamBuilder();
8290
for (TarArchiveEntry entry : filesystemEntries) {
8391
tarStreamBuilder.addEntry(entry);
8492
}
8593

8694
return new UnwrittenLayer(tarStreamBuilder.toBlob());
8795
}
8896

97+
// Sort list and strip out all non-reproducible elements from tar archive entries.
98+
private void makeListReproducible(List<TarArchiveEntry> entries) {
99+
entries.sort(Comparator.comparing(TarArchiveEntry::getName));
100+
for (TarArchiveEntry entry : entries) {
101+
if (enableReproducibleBuilds) {
102+
entry.setModTime(0);
103+
entry.setGroupId(0);
104+
entry.setUserId(0);
105+
entry.setUserName("");
106+
entry.setGroupName("");
107+
}
108+
}
109+
}
110+
89111
public List<Path> getSourceFiles() {
90112
return Collections.unmodifiableList(sourceFiles);
91113
}

‎jib-core/src/main/java/com/google/cloud/tools/jib/tar/TarStreamBuilder.java‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ public class TarStreamBuilder {
3939
/** Writes each entry in the filesystem to the tarball archive stream. */
4040
private static void writeEntriesAsTarArchive(
4141
List<TarArchiveEntry> entries, OutputStream tarByteStream) throws IOException {
42+
4243
try (TarArchiveOutputStream tarArchiveOutputStream =
4344
new TarArchiveOutputStream(tarByteStream)) {
4445
// Enables PAX extended headers to support long file names.

‎jib-core/src/test/java/com/google/cloud/tools/jib/builder/BuildConfigurationTest.java‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ public void testBuilder() {
3737
List<String> expectedCredentialHelperNames =
3838
Arrays.asList("credentialhelper", "anotherCredentialHelper");
3939
String expectedMainClass = "mainclass";
40+
boolean expectedEnableReproducibleBuilds = true;
4041
List<String> expectedJvmFlags = Arrays.asList("some", "jvm", "flags");
4142

4243
BuildConfiguration buildConfiguration =
@@ -50,6 +51,7 @@ public void testBuilder() {
5051
.setCredentialHelperNames(expectedCredentialHelperNames)
5152
.setMainClass(expectedMainClass)
5253
.setJvmFlags(expectedJvmFlags)
54+
.setEnableReproducibleBuilds(true)
5355
.build();
5456
Assert.assertEquals(expectedBaseImageServerUrl, buildConfiguration.getBaseImageRegistry());
5557
Assert.assertEquals(expectedBaseImageName, buildConfiguration.getBaseImageRepository());
@@ -61,6 +63,8 @@ public void testBuilder() {
6163
expectedCredentialHelperNames, buildConfiguration.getCredentialHelperNames());
6264
Assert.assertEquals(expectedMainClass, buildConfiguration.getMainClass());
6365
Assert.assertEquals(expectedJvmFlags, buildConfiguration.getJvmFlags());
66+
Assert.assertEquals(
67+
expectedEnableReproducibleBuilds, buildConfiguration.getEnableReproducibleBuilds());
6468
}
6569

6670
@Test

‎jib-core/src/test/java/com/google/cloud/tools/jib/image/LayerBuilderTest.java‎

Lines changed: 58 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616

1717
package com.google.cloud.tools.jib.image;
1818

19+
import com.google.cloud.tools.jib.blob.Blob;
20+
import com.google.cloud.tools.jib.blob.Blobs;
1921
import com.google.common.io.CharStreams;
2022
import com.google.common.io.Resources;
2123
import java.io.BufferedOutputStream;
@@ -27,10 +29,13 @@
2729
import java.nio.file.Files;
2830
import java.nio.file.Path;
2931
import java.nio.file.Paths;
32+
import java.nio.file.StandardOpenOption;
33+
import java.nio.file.attribute.FileTime;
3034
import java.util.ArrayList;
3135
import java.util.Arrays;
3236
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
3337
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
38+
import org.hamcrest.CoreMatchers;
3439
import org.junit.Assert;
3540
import org.junit.Rule;
3641
import org.junit.Test;
@@ -51,7 +56,8 @@ public void testBuild() throws URISyntaxException, IOException {
5156

5257
String extractionPathBase = "extract/here";
5358
LayerBuilder layerBuilder =
54-
new LayerBuilder(new ArrayList<>(Arrays.asList(layerDirectory, blobA)), extractionPathBase);
59+
new LayerBuilder(
60+
new ArrayList<>(Arrays.asList(layerDirectory, blobA)), extractionPathBase, false);
5561

5662
// Writes the layer tar to a temporary file.
5763
UnwrittenLayer unwrittenLayer = layerBuilder.build();
@@ -111,4 +117,55 @@ public void testBuild() throws URISyntaxException, IOException {
111117
Assert.assertEquals(expectedFileString, extractedFileString);
112118
}
113119
}
120+
121+
@Test
122+
public void testToBlob_reproducibility() throws IOException {
123+
Path testRoot = temporaryFolder.getRoot().toPath();
124+
Path root1 = Files.createDirectories(testRoot.resolve("files1"));
125+
Path root2 = Files.createDirectories(testRoot.resolve("files2"));
126+
127+
String extractionPath = "/somewhere";
128+
129+
// TODO: Currently this test only covers variation in order and modified time, even though
130+
// TODO: the code is designed to clean up userid/groupid, this test does not check that yet.
131+
String contentA = "abcabc";
132+
Path fileA1 = createFile(root1, "fileA", contentA, 10000);
133+
Path fileA2 = createFile(root2, "fileA", contentA, 20000);
134+
String contentB = "yumyum";
135+
Path fileB1 = createFile(root1, "fileB", contentB, 10000);
136+
Path fileB2 = createFile(root2, "fileB", contentB, 20000);
137+
138+
// check if modified times are off
139+
Assert.assertNotEquals(Files.getLastModifiedTime(fileA1), Files.getLastModifiedTime(fileA2));
140+
Assert.assertNotEquals(Files.getLastModifiedTime(fileB1), Files.getLastModifiedTime(fileB2));
141+
142+
// create layers of exact same content but ordered differently and with different timestamps
143+
Blob layer =
144+
new LayerBuilder(Arrays.asList(fileA1, fileB1), extractionPath, true).build().getBlob();
145+
Blob reproduced =
146+
new LayerBuilder(Arrays.asList(fileB2, fileA2), extractionPath, true).build().getBlob();
147+
148+
// this is a control layer that is the same as 'layerReproduced' without reproducibility on
149+
Blob notReproduced =
150+
new LayerBuilder(Arrays.asList(fileB2, fileA2), extractionPath, false).build().getBlob();
151+
152+
byte[] layerContent = Blobs.writeToByteArray(layer);
153+
byte[] reproducedLayerContent = Blobs.writeToByteArray(reproduced);
154+
byte[] notReproducedLayerContent = Blobs.writeToByteArray(notReproduced);
155+
156+
Assert.assertThat(layerContent, CoreMatchers.is(reproducedLayerContent));
157+
Assert.assertThat(layerContent, CoreMatchers.not(notReproducedLayerContent));
158+
}
159+
160+
private Path createFile(Path root, String filename, String content, long lastModifiedTime)
161+
throws IOException {
162+
163+
Path newFile =
164+
Files.write(
165+
root.resolve(filename),
166+
content.getBytes(StandardCharsets.UTF_8),
167+
StandardOpenOption.CREATE_NEW);
168+
Files.setLastModifiedTime(newFile, FileTime.fromMillis(lastModifiedTime));
169+
return newFile;
170+
}
114171
}

0 commit comments

Comments
 (0)