Skip to content

Commit aadb947

Browse files
authored
Add core functionality for build to docker daemon (GoogleContainerTools#260)
1 parent e13f6d9 commit aadb947

12 files changed

Lines changed: 544 additions & 4 deletions

File tree

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/*
2+
* Copyright 2018 Google LLC. All rights reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
5+
* use this file except in compliance with the License. You may obtain a copy of
6+
* the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations under
14+
* the License.
15+
*/
16+
17+
package com.google.cloud.tools.jib.builder;
18+
19+
import com.google.cloud.tools.jib.Command;
20+
import com.google.cloud.tools.jib.cache.Caches;
21+
import com.google.cloud.tools.jib.image.ImageReference;
22+
import com.google.cloud.tools.jib.registry.LocalRegistry;
23+
import java.nio.file.Path;
24+
import org.junit.Assert;
25+
import org.junit.ClassRule;
26+
import org.junit.Rule;
27+
import org.junit.Test;
28+
import org.junit.rules.TemporaryFolder;
29+
30+
/** Integration tests for {@link BuildDockerSteps}. */
31+
public class BuildDockerStepsIntegrationTest {
32+
33+
@ClassRule public static LocalRegistry localRegistry = new LocalRegistry(5000);
34+
35+
private static final TestBuildLogger logger = new TestBuildLogger();
36+
37+
@Rule public TemporaryFolder temporaryCacheDirectory = new TemporaryFolder();
38+
39+
@Test
40+
public void testSteps() throws Exception {
41+
SourceFilesConfiguration sourceFilesConfiguration = new TestSourceFilesConfiguration();
42+
BuildConfiguration buildConfiguration =
43+
BuildConfiguration.builder(logger)
44+
.setBaseImage(ImageReference.of("gcr.io", "distroless/java", "latest"))
45+
.setTargetImage(ImageReference.of(null, "testdocker", null))
46+
.setMainClass("HelloWorld")
47+
.build();
48+
49+
Path cacheDirectory = temporaryCacheDirectory.newFolder().toPath();
50+
BuildDockerSteps buildDockerSteps =
51+
new BuildDockerSteps(
52+
buildConfiguration,
53+
sourceFilesConfiguration,
54+
Caches.newInitializer(cacheDirectory).setBaseCacheDirectory(cacheDirectory));
55+
56+
buildDockerSteps.run();
57+
Assert.assertEquals("Hello world\n", new Command("docker", "run", "testdocker").run());
58+
}
59+
}

jib-core/src/integration-test/java/com/google/cloud/tools/jib/Command.java renamed to jib-core/src/main/java/com/google/cloud/tools/jib/Command.java

File renamed without changes.

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,10 @@ public RegistryCredentials getKnownBaseRegistryCredentials() {
244244
return knownBaseRegistryCredentials;
245245
}
246246

247+
public ImageReference getTargetImageReference() {
248+
return targetImageReference;
249+
}
250+
247251
public String getTargetImageRegistry() {
248252
return targetImageReference.getRegistry();
249253
}
Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
/*
2+
* Copyright 2018 Google LLC. All Rights Reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
5+
* use this file except in compliance with the License. You may obtain a copy of
6+
* the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations under
14+
* the License.
15+
*/
16+
17+
package com.google.cloud.tools.jib.builder;
18+
19+
import com.google.cloud.tools.jib.Timer;
20+
import com.google.cloud.tools.jib.blob.Blob;
21+
import com.google.cloud.tools.jib.cache.Cache;
22+
import com.google.cloud.tools.jib.cache.CacheDirectoryNotOwnedException;
23+
import com.google.cloud.tools.jib.cache.CacheMetadataCorruptedException;
24+
import com.google.cloud.tools.jib.cache.CachedLayer;
25+
import com.google.cloud.tools.jib.cache.Caches;
26+
import com.google.cloud.tools.jib.http.Authorization;
27+
import com.google.cloud.tools.jib.image.Image;
28+
import com.google.common.util.concurrent.Futures;
29+
import com.google.common.util.concurrent.ListenableFuture;
30+
import com.google.common.util.concurrent.ListeningExecutorService;
31+
import com.google.common.util.concurrent.MoreExecutors;
32+
import java.io.IOException;
33+
import java.util.List;
34+
import java.util.concurrent.ExecutionException;
35+
import java.util.concurrent.Executors;
36+
37+
/**
38+
* All the steps to build to Docker daemon.
39+
*
40+
* <p>TODO: Refactor for less duplicate code w/ BuildImageSteps
41+
*/
42+
public class BuildDockerSteps {
43+
44+
private static final String DESCRIPTION = "Building and pushing image";
45+
46+
private final BuildConfiguration buildConfiguration;
47+
private final SourceFilesConfiguration sourceFilesConfiguration;
48+
private final Caches.Initializer cachesInitializer;
49+
50+
BuildDockerSteps(
51+
BuildConfiguration buildConfiguration,
52+
SourceFilesConfiguration sourceFilesConfiguration,
53+
Caches.Initializer cachesInitializer) {
54+
this.buildConfiguration = buildConfiguration;
55+
this.sourceFilesConfiguration = sourceFilesConfiguration;
56+
this.cachesInitializer = cachesInitializer;
57+
}
58+
59+
public BuildConfiguration getBuildConfiguration() {
60+
return buildConfiguration;
61+
}
62+
63+
public void run()
64+
throws InterruptedException, ExecutionException, CacheMetadataCorruptedException, IOException,
65+
CacheDirectoryNotOwnedException {
66+
List<String> entrypoint =
67+
EntrypointBuilder.makeEntrypoint(
68+
sourceFilesConfiguration,
69+
buildConfiguration.getJvmFlags(),
70+
buildConfiguration.getMainClass());
71+
72+
try (Timer timer = new Timer(buildConfiguration.getBuildLogger(), DESCRIPTION)) {
73+
try (Timer timer2 = timer.subTimer("Initializing cache")) {
74+
ListeningExecutorService listeningExecutorService =
75+
MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
76+
77+
try (Caches caches = cachesInitializer.init()) {
78+
Cache baseLayersCache = caches.getBaseCache();
79+
Cache applicationLayersCache = caches.getApplicationCache();
80+
81+
timer2.lap("Setting up credential retrieval");
82+
ListenableFuture<Authorization> retrieveBaseImageRegistryCredentialsFuture =
83+
listeningExecutorService.submit(
84+
RetrieveRegistryCredentialsStep.forBaseImage(buildConfiguration));
85+
86+
timer2.lap("Setting up image pull authentication");
87+
// Authenticates base image pull.
88+
ListenableFuture<Authorization> authenticatePullFuture =
89+
Futures.whenAllSucceed(retrieveBaseImageRegistryCredentialsFuture)
90+
.call(
91+
new AuthenticatePullStep(
92+
buildConfiguration, retrieveBaseImageRegistryCredentialsFuture),
93+
listeningExecutorService);
94+
95+
timer2.lap("Setting up base image pull");
96+
// Pulls the base image.
97+
ListenableFuture<Image> pullBaseImageFuture =
98+
Futures.whenAllSucceed(authenticatePullFuture)
99+
.call(
100+
new PullBaseImageStep(buildConfiguration, authenticatePullFuture),
101+
listeningExecutorService);
102+
timer2.lap("Setting up base image layer pull");
103+
// Pulls and caches the base image layers.
104+
ListenableFuture<List<ListenableFuture<CachedLayer>>> pullBaseImageLayerFuturesFuture =
105+
Futures.whenAllSucceed(pullBaseImageFuture)
106+
.call(
107+
new PullAndCacheBaseImageLayersStep(
108+
buildConfiguration,
109+
baseLayersCache,
110+
listeningExecutorService,
111+
authenticatePullFuture,
112+
pullBaseImageFuture),
113+
listeningExecutorService);
114+
115+
timer2.lap("Setting up build application layers");
116+
// Builds the application layers.
117+
List<ListenableFuture<CachedLayer>> buildAndCacheApplicationLayerFutures =
118+
new BuildAndCacheApplicationLayersStep(
119+
buildConfiguration,
120+
sourceFilesConfiguration,
121+
applicationLayersCache,
122+
listeningExecutorService)
123+
.call();
124+
125+
timer2.lap("Setting up build container configuration");
126+
// Builds the container configuration.
127+
ListenableFuture<ListenableFuture<Blob>> buildContainerConfigurationFutureFuture =
128+
Futures.whenAllSucceed(pullBaseImageLayerFuturesFuture)
129+
.call(
130+
new BuildContainerConfigurationStep(
131+
buildConfiguration,
132+
listeningExecutorService,
133+
pullBaseImageLayerFuturesFuture,
134+
buildAndCacheApplicationLayerFutures,
135+
entrypoint),
136+
listeningExecutorService);
137+
138+
timer2.lap("Setting up build to docker daemon");
139+
// Builds the image tarball and loads into the Docker daemon.
140+
ListenableFuture<Void> buildToDockerFutureFuture =
141+
Futures.whenAllSucceed(
142+
pullBaseImageLayerFuturesFuture, buildContainerConfigurationFutureFuture)
143+
.call(
144+
new BuildTarballAndLoadDockerStep(
145+
buildConfiguration,
146+
listeningExecutorService,
147+
pullBaseImageLayerFuturesFuture,
148+
buildAndCacheApplicationLayerFutures,
149+
buildContainerConfigurationFutureFuture),
150+
listeningExecutorService);
151+
152+
timer2.lap("Running build to docker daemon");
153+
buildToDockerFutureFuture.get();
154+
}
155+
}
156+
}
157+
158+
buildConfiguration.getBuildLogger().lifecycle("");
159+
buildConfiguration.getBuildLogger().lifecycle("Container entrypoint set to " + entrypoint);
160+
}
161+
}
Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
/*
2+
* Copyright 2018 Google LLC. All Rights Reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
5+
* use this file except in compliance with the License. You may obtain a copy of
6+
* the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations under
14+
* the License.
15+
*/
16+
17+
package com.google.cloud.tools.jib.builder;
18+
19+
import com.google.cloud.tools.jib.Command;
20+
import com.google.cloud.tools.jib.blob.Blob;
21+
import com.google.cloud.tools.jib.blob.Blobs;
22+
import com.google.cloud.tools.jib.cache.CachedLayer;
23+
import com.google.cloud.tools.jib.docker.json.DockerLoadManifestTemplate;
24+
import com.google.cloud.tools.jib.image.ImageReference;
25+
import com.google.cloud.tools.jib.json.JsonTemplateMapper;
26+
import com.google.cloud.tools.jib.tar.TarStreamBuilder;
27+
import com.google.common.annotations.VisibleForTesting;
28+
import com.google.common.util.concurrent.Futures;
29+
import com.google.common.util.concurrent.ListenableFuture;
30+
import com.google.common.util.concurrent.ListeningExecutorService;
31+
import java.io.BufferedOutputStream;
32+
import java.io.IOException;
33+
import java.io.OutputStream;
34+
import java.nio.file.Files;
35+
import java.nio.file.Path;
36+
import java.util.ArrayList;
37+
import java.util.List;
38+
import java.util.concurrent.Callable;
39+
import java.util.concurrent.ExecutionException;
40+
import java.util.concurrent.Future;
41+
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
42+
43+
/** Adds image layers to a tarball and loads into Docker daemon. */
44+
class BuildTarballAndLoadDockerStep implements Callable<Void> {
45+
46+
/**
47+
* Builds a {@link DockerLoadManifestTemplate} from image parameters and returns the result as a
48+
* blob.
49+
*/
50+
@VisibleForTesting
51+
static Blob getManifestBlob(ImageReference imageReference, List<String> layerFiles) {
52+
// Set up the JSON template.
53+
DockerLoadManifestTemplate template = new DockerLoadManifestTemplate();
54+
template.setRepoTags(imageReference.toStringWithTag());
55+
template.addLayerFiles(layerFiles);
56+
57+
// Serializes into JSON.
58+
return JsonTemplateMapper.toBlob(template);
59+
}
60+
61+
private final BuildConfiguration buildConfiguration;
62+
private final ListeningExecutorService listeningExecutorService;
63+
private final ListenableFuture<List<ListenableFuture<CachedLayer>>>
64+
pullBaseImageLayerFuturesFuture;
65+
private final List<ListenableFuture<CachedLayer>> buildApplicationLayerFutures;
66+
private final ListenableFuture<ListenableFuture<Blob>> buildConfigurationFutureFuture;
67+
68+
BuildTarballAndLoadDockerStep(
69+
BuildConfiguration buildConfiguration,
70+
ListeningExecutorService listeningExecutorService,
71+
ListenableFuture<List<ListenableFuture<CachedLayer>>> pullBaseImageLayerFuturesFuture,
72+
List<ListenableFuture<CachedLayer>> buildApplicationLayerFutures,
73+
ListenableFuture<ListenableFuture<Blob>> buildConfigurationFutureFuture) {
74+
this.buildConfiguration = buildConfiguration;
75+
this.listeningExecutorService = listeningExecutorService;
76+
this.pullBaseImageLayerFuturesFuture = pullBaseImageLayerFuturesFuture;
77+
this.buildApplicationLayerFutures = buildApplicationLayerFutures;
78+
this.buildConfigurationFutureFuture = buildConfigurationFutureFuture;
79+
}
80+
81+
/**
82+
* Depends on {@code pullBaseImageLayerFuturesFuture} and {@code buildConfigurationFutureFuture}.
83+
*/
84+
@Override
85+
public Void call() throws ExecutionException, InterruptedException {
86+
List<ListenableFuture<?>> dependencies = new ArrayList<>();
87+
dependencies.addAll(NonBlockingFutures.get(pullBaseImageLayerFuturesFuture));
88+
dependencies.addAll(buildApplicationLayerFutures);
89+
dependencies.add(NonBlockingFutures.get(buildConfigurationFutureFuture));
90+
return Futures.whenAllComplete(dependencies)
91+
.call(this::afterPushBaseImageLayerFuturesFuture, listeningExecutorService)
92+
.get();
93+
}
94+
95+
/**
96+
* Depends on {@code pullBaseImageLayerFuturesFuture.get()} and (@code
97+
* buildConfigurationFutureFuture.get()}.
98+
*
99+
* <p>TODO: Refactor into testable components
100+
*/
101+
private Void afterPushBaseImageLayerFuturesFuture()
102+
throws ExecutionException, InterruptedException, IOException {
103+
// Add layers to image tarball
104+
TarStreamBuilder tarStreamBuilder = new TarStreamBuilder();
105+
List<String> layerFiles = new ArrayList<>();
106+
for (Future<CachedLayer> cachedLayerFuture :
107+
NonBlockingFutures.get(pullBaseImageLayerFuturesFuture)) {
108+
Path layerFile = NonBlockingFutures.get(cachedLayerFuture).getContentFile();
109+
layerFiles.add(layerFile.getFileName().toString());
110+
tarStreamBuilder.addEntry(
111+
new TarArchiveEntry(layerFile.toFile(), layerFile.getFileName().toString()));
112+
}
113+
for (Future<CachedLayer> cachedLayerFuture : buildApplicationLayerFutures) {
114+
Path layerFile = NonBlockingFutures.get(cachedLayerFuture).getContentFile();
115+
layerFiles.add(layerFile.getFileName().toString());
116+
tarStreamBuilder.addEntry(
117+
new TarArchiveEntry(layerFile.toFile(), layerFile.getFileName().toString()));
118+
}
119+
120+
// Add config to tarball
121+
// TODO: Add ability to add blobs as entries to TarStreamBuilder without using temp files
122+
Blob containerConfigurationBlob =
123+
NonBlockingFutures.get(NonBlockingFutures.get(buildConfigurationFutureFuture));
124+
Path tempConfig = Files.createTempFile(null, null);
125+
tempConfig.toFile().deleteOnExit();
126+
try (OutputStream bufferedOutputStream =
127+
new BufferedOutputStream(Files.newOutputStream(tempConfig))) {
128+
containerConfigurationBlob.writeTo(bufferedOutputStream);
129+
}
130+
tarStreamBuilder.addEntry(new TarArchiveEntry(tempConfig.toFile(), "config.json"));
131+
132+
// Add manifest to tarball
133+
Blob manifestBlob = getManifestBlob(buildConfiguration.getTargetImageReference(), layerFiles);
134+
Path tempManifest = Files.createTempFile(null, null);
135+
tempManifest.toFile().deleteOnExit();
136+
try (OutputStream bufferedOutputStream =
137+
new BufferedOutputStream(Files.newOutputStream(tempManifest))) {
138+
manifestBlob.writeTo(bufferedOutputStream);
139+
}
140+
tarStreamBuilder.addEntry(new TarArchiveEntry(tempManifest.toFile(), "manifest.json"));
141+
142+
// Load the image to docker daemon
143+
// TODO: Command is untested/not very robust
144+
new Command("docker", "load").run(Blobs.writeToByteArray(tarStreamBuilder.toBlob()));
145+
146+
return null;
147+
}
148+
}

0 commit comments

Comments
 (0)