Skip to content

Commit da18e85

Browse files
authored
Removes explicit synchronization by refactoring build steps to not mutate a CacheMetadata. (GoogleContainerTools#426)
* Removes explicit synchronization by refactoring build steps to not mutate a CacheMetadata. * Makes CacheMetadata immutable.
1 parent 9ecd2ba commit da18e85

18 files changed

Lines changed: 241 additions & 159 deletions

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

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -184,15 +184,21 @@ public void run()
184184

185185
try (Timer timer = new Timer(buildConfiguration.getBuildLogger(), description)) {
186186
try (Caches caches = cachesInitializer.init()) {
187-
Cache baseLayersCache = caches.getBaseCache();
187+
Cache baseImageLayersCache = caches.getBaseCache();
188188
Cache applicationLayersCache = caches.getApplicationCache();
189189

190-
stepsRunnerConsumer.accept(
190+
StepsRunner stepsRunner =
191191
new StepsRunner(
192192
buildConfiguration,
193193
sourceFilesConfiguration,
194-
baseLayersCache,
195-
applicationLayersCache));
194+
baseImageLayersCache,
195+
applicationLayersCache);
196+
stepsRunnerConsumer.accept(stepsRunner);
197+
198+
// Writes the cached layers to the cache metadata.
199+
baseImageLayersCache.addCachedLayersToMetadata(stepsRunner.getCachedBaseImageLayers());
200+
applicationLayersCache.addCachedLayersWithMetadataToMetadata(
201+
stepsRunner.getCachedApplicationLayers());
196202
}
197203
}
198204

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

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,7 @@
2424
import com.google.cloud.tools.jib.cache.CacheMetadataCorruptedException;
2525
import com.google.cloud.tools.jib.cache.CacheReader;
2626
import com.google.cloud.tools.jib.cache.CacheWriter;
27-
import com.google.cloud.tools.jib.cache.CachedLayer;
28-
import com.google.cloud.tools.jib.image.LayerPropertyNotFoundException;
27+
import com.google.cloud.tools.jib.cache.CachedLayerWithMetadata;
2928
import com.google.cloud.tools.jib.image.ReproducibleLayerBuilder;
3029
import com.google.common.collect.ImmutableList;
3130
import com.google.common.util.concurrent.ListenableFuture;
@@ -35,7 +34,8 @@
3534
import java.util.concurrent.Callable;
3635

3736
/** Builds and caches application layers. */
38-
class BuildAndCacheApplicationLayerStep implements AsyncStep<CachedLayer>, Callable<CachedLayer> {
37+
class BuildAndCacheApplicationLayerStep
38+
implements AsyncStep<CachedLayerWithMetadata>, Callable<CachedLayerWithMetadata> {
3939

4040
private static final String DESCRIPTION = "Building application layers";
4141

@@ -80,7 +80,7 @@ static ImmutableList<BuildAndCacheApplicationLayerStep> makeList(
8080
private final String extractionPath;
8181
private final Cache cache;
8282

83-
private final ListenableFuture<CachedLayer> listenableFuture;
83+
private final ListenableFuture<CachedLayerWithMetadata> listenableFuture;
8484

8585
private BuildAndCacheApplicationLayerStep(
8686
String layerType,
@@ -99,20 +99,20 @@ private BuildAndCacheApplicationLayerStep(
9999
}
100100

101101
@Override
102-
public ListenableFuture<CachedLayer> getFuture() {
102+
public ListenableFuture<CachedLayerWithMetadata> getFuture() {
103103
return listenableFuture;
104104
}
105105

106106
@Override
107-
public CachedLayer call()
108-
throws IOException, LayerPropertyNotFoundException, CacheMetadataCorruptedException {
107+
public CachedLayerWithMetadata call() throws IOException, CacheMetadataCorruptedException {
109108
String description = "Building " + layerType + " layer";
110109

111110
buildConfiguration.getBuildLogger().lifecycle(description + "...");
112111

113112
try (Timer ignored = new Timer(buildConfiguration.getBuildLogger(), description)) {
114113
// Don't build the layer if it exists already.
115-
CachedLayer cachedLayer = new CacheReader(cache).getUpToDateLayerBySourceFiles(sourceFiles);
114+
CachedLayerWithMetadata cachedLayer =
115+
new CacheReader(cache).getUpToDateLayerBySourceFiles(sourceFiles);
116116
if (cachedLayer != null) {
117117
return cachedLayer;
118118
}
@@ -121,10 +121,11 @@ public CachedLayer call()
121121
new ReproducibleLayerBuilder(sourceFiles, extractionPath);
122122

123123
cachedLayer = new CacheWriter(cache).writeLayer(reproducibleLayerBuilder);
124-
// TODO: Remove
124+
125125
buildConfiguration
126126
.getBuildLogger()
127127
.debug(description + " built " + cachedLayer.getBlobDescriptor().getDigest());
128+
128129
return cachedLayer;
129130
}
130131
}

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@
2525
import com.google.cloud.tools.jib.cache.CachedLayer;
2626
import com.google.cloud.tools.jib.http.Authorization;
2727
import com.google.cloud.tools.jib.image.DescriptorDigest;
28-
import com.google.cloud.tools.jib.image.LayerPropertyNotFoundException;
2928
import com.google.cloud.tools.jib.registry.RegistryClient;
3029
import com.google.cloud.tools.jib.registry.RegistryException;
3130
import com.google.common.io.CountingOutputStream;
@@ -67,7 +66,7 @@ public ListenableFuture<CachedLayer> getFuture() {
6766
}
6867

6968
@Override
70-
public CachedLayer call() throws IOException, RegistryException, LayerPropertyNotFoundException {
69+
public CachedLayer call() throws IOException, RegistryException {
7170
try (Timer ignored =
7271
new Timer(buildConfiguration.getBuildLogger(), String.format(DESCRIPTION, layerDigest))) {
7372
RegistryClient registryClient =
@@ -85,7 +84,8 @@ public CachedLayer call() throws IOException, RegistryException, LayerPropertyNo
8584
CacheWriter cacheWriter = new CacheWriter(cache);
8685
CountingOutputStream layerOutputStream = cacheWriter.getLayerOutputStream(layerDigest);
8786
registryClient.pullBlob(layerDigest, layerOutputStream);
88-
return cacheWriter.getCachedLayer(layerDigest, layerOutputStream);
87+
layerOutputStream.close();
88+
return cacheWriter.getCachedLayer(layerOutputStream.getCount(), layerDigest);
8989
}
9090
}
9191
}

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

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ class PushLayersStep
3636

3737
private final BuildConfiguration buildConfiguration;
3838
private final AuthenticatePushStep authenticatePushStep;
39-
private final AsyncStep<? extends ImmutableList<? extends AsyncStep<CachedLayer>>>
39+
private final AsyncStep<? extends ImmutableList<? extends AsyncStep<? extends CachedLayer>>>
4040
cachedLayerStepsStep;
4141

4242
private final ListeningExecutorService listeningExecutorService;
@@ -46,7 +46,8 @@ class PushLayersStep
4646
ListeningExecutorService listeningExecutorService,
4747
BuildConfiguration buildConfiguration,
4848
AuthenticatePushStep authenticatePushStep,
49-
AsyncStep<? extends ImmutableList<? extends AsyncStep<CachedLayer>>> cachedLayerStepsStep) {
49+
AsyncStep<? extends ImmutableList<? extends AsyncStep<? extends CachedLayer>>>
50+
cachedLayerStepsStep) {
5051
this.listeningExecutorService = listeningExecutorService;
5152
this.buildConfiguration = buildConfiguration;
5253
this.authenticatePushStep = authenticatePushStep;
@@ -65,12 +66,12 @@ public ListenableFuture<ImmutableList<AsyncStep<PushBlobStep>>> getFuture() {
6566
@Override
6667
public ImmutableList<AsyncStep<PushBlobStep>> call() throws ExecutionException {
6768
try (Timer ignored = new Timer(buildConfiguration.getBuildLogger(), DESCRIPTION)) {
68-
ImmutableList<? extends AsyncStep<CachedLayer>> cachedLayerSteps =
69+
ImmutableList<? extends AsyncStep<? extends CachedLayer>> cachedLayerSteps =
6970
NonBlockingSteps.get(cachedLayerStepsStep);
7071

7172
// Constructs a PushBlobStep for each layer.
7273
ImmutableList.Builder<AsyncStep<PushBlobStep>> pushBlobStepsBuilder = ImmutableList.builder();
73-
for (AsyncStep<CachedLayer> cachedLayerStep : cachedLayerSteps) {
74+
for (AsyncStep<? extends CachedLayer> cachedLayerStep : cachedLayerSteps) {
7475
ListenableFuture<PushBlobStep> pushBlobStepFuture =
7576
Futures.whenAllSucceed(cachedLayerStep.getFuture())
7677
.call(() -> makePushBlobStep(cachedLayerStep), listeningExecutorService);
@@ -81,7 +82,7 @@ public ImmutableList<AsyncStep<PushBlobStep>> call() throws ExecutionException {
8182
}
8283
}
8384

84-
private PushBlobStep makePushBlobStep(AsyncStep<CachedLayer> cachedLayerStep)
85+
private PushBlobStep makePushBlobStep(AsyncStep<? extends CachedLayer> cachedLayerStep)
8586
throws ExecutionException {
8687
CachedLayer cachedLayer = NonBlockingSteps.get(cachedLayerStep);
8788
return new PushBlobStep(

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

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,20 @@
1717
package com.google.cloud.tools.jib.builder.steps;
1818

1919
import com.google.cloud.tools.jib.async.AsyncSteps;
20+
import com.google.cloud.tools.jib.async.NonBlockingSteps;
2021
import com.google.cloud.tools.jib.builder.BuildConfiguration;
2122
import com.google.cloud.tools.jib.builder.SourceFilesConfiguration;
2223
import com.google.cloud.tools.jib.cache.Cache;
24+
import com.google.cloud.tools.jib.cache.CachedLayer;
25+
import com.google.cloud.tools.jib.cache.CachedLayerWithMetadata;
2326
import com.google.common.base.Preconditions;
2427
import com.google.common.collect.ImmutableList;
2528
import com.google.common.util.concurrent.ListeningExecutorService;
2629
import com.google.common.util.concurrent.MoreExecutors;
30+
import java.util.ArrayList;
2731
import java.util.Arrays;
2832
import java.util.Collections;
33+
import java.util.List;
2934
import java.util.concurrent.ExecutionException;
3035
import java.util.concurrent.Executors;
3136
import javax.annotation.Nullable;
@@ -205,4 +210,36 @@ public void waitOnBuildTarballAndLoadDockerStep()
205210
throws ExecutionException, InterruptedException {
206211
Preconditions.checkNotNull(buildTarballAndLoadDockerStep).getFuture().get();
207212
}
213+
214+
/**
215+
* @return the layers cached by {@link #pullAndCacheBaseImageLayersStep}
216+
* @throws ExecutionException if {@link #pullAndCacheBaseImageLayersStep} threw an exception
217+
* during execution
218+
*/
219+
public List<CachedLayer> getCachedBaseImageLayers() throws ExecutionException {
220+
ImmutableList<PullAndCacheBaseImageLayerStep> pullAndCacheBaseImageLayerSteps =
221+
NonBlockingSteps.get(Preconditions.checkNotNull(pullAndCacheBaseImageLayersStep));
222+
223+
List<CachedLayer> cachedLayers = new ArrayList<>(pullAndCacheBaseImageLayerSteps.size());
224+
for (PullAndCacheBaseImageLayerStep pullAndCacheBaseImageLayerStep :
225+
pullAndCacheBaseImageLayerSteps) {
226+
cachedLayers.add(NonBlockingSteps.get(pullAndCacheBaseImageLayerStep));
227+
}
228+
return cachedLayers;
229+
}
230+
231+
/**
232+
* @return the layers cached by {@link #buildAndCacheApplicationLayerSteps}
233+
* @throws ExecutionException if {@link #buildAndCacheApplicationLayerSteps} threw an exception
234+
* during execution
235+
*/
236+
public List<CachedLayerWithMetadata> getCachedApplicationLayers() throws ExecutionException {
237+
List<CachedLayerWithMetadata> cachedLayersWithMetadata =
238+
new ArrayList<>(Preconditions.checkNotNull(buildAndCacheApplicationLayerSteps).size());
239+
for (BuildAndCacheApplicationLayerStep buildAndCacheApplicationLayerStep :
240+
buildAndCacheApplicationLayerSteps) {
241+
cachedLayersWithMetadata.add(NonBlockingSteps.get(buildAndCacheApplicationLayerStep));
242+
}
243+
return cachedLayersWithMetadata;
244+
}
208245
}

‎jib-core/src/main/java/com/google/cloud/tools/jib/cache/Cache.java‎

Lines changed: 37 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
package com.google.cloud.tools.jib.cache;
1818

1919
import com.google.cloud.tools.jib.cache.json.CacheMetadataTemplate;
20-
import com.google.cloud.tools.jib.image.LayerPropertyNotFoundException;
2120
import com.google.cloud.tools.jib.json.JsonTemplateMapper;
2221
import com.google.common.annotations.VisibleForTesting;
2322
import java.io.BufferedOutputStream;
@@ -27,17 +26,11 @@
2726
import java.nio.file.Files;
2827
import java.nio.file.NotDirectoryException;
2928
import java.nio.file.Path;
30-
import javax.annotation.Nullable;
29+
import java.util.List;
3130

3231
/** Manages a cache. Implementation is thread-safe. */
3332
public class Cache implements Closeable {
3433

35-
/** The path to the root of the cache. */
36-
private final Path cacheDirectory;
37-
38-
/** The metadata that corresponds to the cache at {@link #cacheDirectory}. */
39-
private final CacheMetadata cacheMetadata;
40-
4134
/**
4235
* Initializes a cache with a directory. This also loads the cache metadata if it exists in the
4336
* directory.
@@ -62,7 +55,7 @@ private static CacheMetadata loadCacheMetadata(Path cacheDirectory)
6255
Path cacheMetadataJsonFile = cacheDirectory.resolve(CacheFiles.METADATA_FILENAME);
6356

6457
if (!Files.exists(cacheMetadataJsonFile)) {
65-
return new CacheMetadata();
58+
return CacheMetadata.builder().build();
6659
}
6760

6861
try {
@@ -76,9 +69,19 @@ private static CacheMetadata loadCacheMetadata(Path cacheDirectory)
7669
}
7770
}
7871

72+
/** The path to the root of the cache. */
73+
private final Path cacheDirectory;
74+
75+
/** The metadata that corresponds to the cache at {@link #cacheDirectory}. */
76+
private final CacheMetadata cacheMetadata;
77+
78+
/** Builds the updated cache metadata to save back to the cache. */
79+
private final CacheMetadata.Builder cacheMetadataBuilder;
80+
7981
private Cache(Path cacheDirectory, CacheMetadata cacheMetadata) {
8082
this.cacheDirectory = cacheDirectory;
8183
this.cacheMetadata = cacheMetadata;
84+
cacheMetadataBuilder = cacheMetadata.newAppendingBuilder();
8285
}
8386

8487
/**
@@ -92,15 +95,26 @@ public void close() throws IOException {
9295
}
9396

9497
/**
95-
* Adds the cached layer to the cache metadata.
98+
* Adds the cached layer to the cache metadata. This is <b>NOT</b> thread-safe.
9699
*
97-
* @param cachedLayer the layer to add.
98-
* @param layerMetadata the metadata to add the layer to.
99-
* @throws LayerPropertyNotFoundException if adding the layer fails.
100+
* @param cachedLayers the layers to add
100101
*/
101-
void addLayerToMetadata(CachedLayer cachedLayer, @Nullable LayerMetadata layerMetadata)
102-
throws LayerPropertyNotFoundException {
103-
cacheMetadata.addLayer(new CachedLayerWithMetadata(cachedLayer, layerMetadata));
102+
public void addCachedLayersToMetadata(List<CachedLayer> cachedLayers) {
103+
for (CachedLayer cachedLayer : cachedLayers) {
104+
cacheMetadataBuilder.addLayer(new CachedLayerWithMetadata(cachedLayer, null));
105+
}
106+
}
107+
108+
/**
109+
* Adds the cached layer to the cache metadata. This is <b>NOT</b> thread-safe.
110+
*
111+
* @param cachedLayersWithMetadata the layers to add
112+
*/
113+
public void addCachedLayersWithMetadataToMetadata(
114+
List<CachedLayerWithMetadata> cachedLayersWithMetadata) {
115+
for (CachedLayerWithMetadata cachedLayerWithMetadata : cachedLayersWithMetadata) {
116+
cacheMetadataBuilder.addLayer(cachedLayerWithMetadata);
117+
}
104118
}
105119

106120
@VisibleForTesting
@@ -113,11 +127,17 @@ CacheMetadata getMetadata() {
113127
return cacheMetadata;
114128
}
115129

130+
@VisibleForTesting
131+
CacheMetadata getUpdatedMetadata() {
132+
return cacheMetadataBuilder.build();
133+
}
134+
116135
/** Saves the updated cache metadata back to the cache. */
117136
private void saveCacheMetadata(Path cacheDirectory) throws IOException {
118137
Path cacheMetadataJsonFile = cacheDirectory.resolve(CacheFiles.METADATA_FILENAME);
119138

120-
CacheMetadataTemplate cacheMetadataJson = CacheMetadataTranslator.toTemplate(cacheMetadata);
139+
CacheMetadataTemplate cacheMetadataJson =
140+
CacheMetadataTranslator.toTemplate(cacheMetadataBuilder.build());
121141

122142
try (OutputStream fileOutputStream =
123143
new BufferedOutputStream(Files.newOutputStream(cacheMetadataJsonFile))) {

‎jib-core/src/main/java/com/google/cloud/tools/jib/cache/CacheMetadata.java‎

Lines changed: 42 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,31 @@
3131
*/
3232
class CacheMetadata {
3333

34-
private final ImageLayers.Builder<CachedLayerWithMetadata> layersBuilder = ImageLayers.builder();
34+
static class Builder {
35+
36+
private final ImageLayers.Builder<CachedLayerWithMetadata> layersBuilder =
37+
ImageLayers.builder();
38+
39+
private Builder(ImageLayers<CachedLayerWithMetadata> initialLayers) {
40+
layersBuilder.addAll(initialLayers);
41+
}
42+
43+
private Builder() {}
44+
45+
/**
46+
* Adds a layer. This method is <b>NOT</b> thread-safe.
47+
*
48+
* @param layer the layer to add
49+
*/
50+
Builder addLayer(CachedLayerWithMetadata layer) {
51+
layersBuilder.add(layer);
52+
return this;
53+
}
54+
55+
CacheMetadata build() {
56+
return new CacheMetadata(layersBuilder.build());
57+
}
58+
}
3559

3660
/** Can be used to filter layers in the metadata. */
3761
static class LayerFilter {
@@ -83,17 +107,26 @@ ImageLayers<CachedLayerWithMetadata> filter() throws CacheMetadataCorruptedExcep
83107
}
84108
}
85109

86-
// TODO: Remove explicit synchronization by refactoring build steps to not mutate a common
87-
// CacheMetadata.
88-
synchronized ImageLayers<CachedLayerWithMetadata> getLayers() {
89-
return layersBuilder.build();
110+
static Builder builder() {
111+
return new Builder();
112+
}
113+
114+
private final ImageLayers<CachedLayerWithMetadata> layers;
115+
116+
private CacheMetadata(ImageLayers<CachedLayerWithMetadata> layers) {
117+
this.layers = layers;
118+
}
119+
120+
ImageLayers<CachedLayerWithMetadata> getLayers() {
121+
return layers;
90122
}
91123

92-
synchronized void addLayer(CachedLayerWithMetadata layer) throws LayerPropertyNotFoundException {
93-
layersBuilder.add(layer);
124+
LayerFilter filterLayers() {
125+
return new LayerFilter(layers);
94126
}
95127

96-
synchronized LayerFilter filterLayers() {
97-
return new LayerFilter(layersBuilder.build());
128+
/** @return a {@link Builder} starts with all the layers in this metadata */
129+
Builder newAppendingBuilder() {
130+
return new Builder(layers);
98131
}
99132
}

0 commit comments

Comments
 (0)