Skip to content

Commit e0fcb5d

Browse files
authored
Attach build to docker daemon functionality to maven goal (GoogleContainerTools#266)
1 parent a0ce78d commit e0fcb5d

2 files changed

Lines changed: 182 additions & 1 deletion

File tree

‎jib-maven-plugin/src/main/java/com/google/cloud/tools/jib/maven/BuildDockerMojo.java‎

Lines changed: 110 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,17 +16,126 @@
1616

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

19+
import com.google.cloud.tools.jib.builder.BuildConfiguration;
20+
import com.google.cloud.tools.jib.builder.SourceFilesConfiguration;
21+
import com.google.cloud.tools.jib.frontend.BuildDockerStepsRunner;
22+
import com.google.cloud.tools.jib.frontend.BuildImageStepsExecutionException;
23+
import com.google.cloud.tools.jib.frontend.CacheDirectoryCreationException;
24+
import com.google.cloud.tools.jib.frontend.HelpfulSuggestions;
25+
import com.google.cloud.tools.jib.image.ImageReference;
26+
import com.google.cloud.tools.jib.image.InvalidImageReferenceException;
27+
import com.google.cloud.tools.jib.registry.credentials.RegistryCredentials;
28+
import com.google.common.base.Preconditions;
29+
import java.nio.file.Path;
30+
import java.nio.file.Paths;
31+
import javax.annotation.Nullable;
32+
import org.apache.maven.execution.MavenSession;
1933
import org.apache.maven.plugin.MojoExecutionException;
2034
import org.apache.maven.plugin.MojoFailureException;
2135
import org.apache.maven.plugins.annotations.Mojo;
36+
import org.apache.maven.plugins.annotations.Parameter;
2237
import org.apache.maven.plugins.annotations.ResolutionScope;
2338

2439
/** Builds a container image and exports to the default Docker daemon. */
2540
@Mojo(name = "buildDocker", requiresDependencyResolution = ResolutionScope.RUNTIME_PLUS_SYSTEM)
2641
public class BuildDockerMojo extends JibPluginConfiguration {
2742

43+
/**
44+
* Directory name for the cache. The directory will be relative to the build output directory.
45+
*
46+
* <p>TODO: Move to ProjectProperties.
47+
*/
48+
private static final String CACHE_DIRECTORY_NAME = "jib-cache";
49+
50+
private static final HelpfulSuggestions HELPFUL_SUGGESTIONS =
51+
HelpfulSuggestionsProvider.get("Build image failed");
52+
53+
@Nullable
54+
@Parameter(defaultValue = "${session}", readonly = true)
55+
private MavenSession session;
56+
57+
/** TODO: Consolidate with BuildImageMojo. */
2858
@Override
2959
public void execute() throws MojoExecutionException, MojoFailureException {
30-
getLog().warn("Doing maven jib:buildDocker!");
60+
ProjectProperties projectProperties = new ProjectProperties(getProject(), getLog());
61+
String inferredMainClass = projectProperties.getMainClass(getMainClass());
62+
63+
SourceFilesConfiguration sourceFilesConfiguration =
64+
projectProperties.getSourceFilesConfiguration();
65+
66+
// Parses 'from' and 'to' into image reference.
67+
ImageReference baseImage = getBaseImageReference();
68+
ImageReference targetImage = getTargetImageReference();
69+
70+
// Checks Maven settings for registry credentials.
71+
MavenSettingsServerCredentials mavenSettingsServerCredentials =
72+
new MavenSettingsServerCredentials(Preconditions.checkNotNull(session).getSettings());
73+
RegistryCredentials knownBaseRegistryCredentials =
74+
mavenSettingsServerCredentials.retrieve(baseImage.getRegistry());
75+
76+
BuildConfiguration buildConfiguration =
77+
BuildConfiguration.builder(new MavenBuildLogger(getLog()))
78+
.setBaseImage(baseImage)
79+
.setBaseImageCredentialHelperName(getBaseImageCredentialHelperName())
80+
.setKnownBaseRegistryCredentials(knownBaseRegistryCredentials)
81+
.setTargetImage(targetImage)
82+
.setMainClass(inferredMainClass)
83+
.setJvmFlags(getJvmFlags())
84+
.setEnvironment(getEnvironment())
85+
.build();
86+
87+
// Uses a directory in the Maven build cache as the Jib cache.
88+
Path cacheDirectory = Paths.get(getProject().getBuild().getDirectory(), CACHE_DIRECTORY_NAME);
89+
try {
90+
BuildDockerStepsRunner buildDockerStepsRunner =
91+
BuildDockerStepsRunner.newRunner(
92+
buildConfiguration,
93+
sourceFilesConfiguration,
94+
cacheDirectory,
95+
getUseOnlyProjectCache());
96+
97+
getLog().info("");
98+
getLog().info("Building to docker daemon as " + targetImage);
99+
getLog().info("");
100+
101+
buildDockerStepsRunner.buildDocker(HELPFUL_SUGGESTIONS);
102+
103+
getLog().info("");
104+
getLog().info("Built image to Docker daemon as " + targetImage);
105+
getLog().info("");
106+
107+
} catch (CacheDirectoryCreationException | BuildImageStepsExecutionException ex) {
108+
throw new MojoExecutionException(ex.getMessage(), ex.getCause());
109+
}
110+
}
111+
112+
/** @return the {@link ImageReference} parsed from {@link #from}. */
113+
private ImageReference getBaseImageReference() throws MojoFailureException {
114+
try {
115+
ImageReference baseImage = ImageReference.parse(getBaseImage());
116+
117+
if (baseImage.usesDefaultTag()) {
118+
getLog()
119+
.warn(
120+
"Base image '"
121+
+ baseImage
122+
+ "' does not use a specific image digest - build may not be reproducible");
123+
}
124+
125+
return baseImage;
126+
127+
} catch (InvalidImageReferenceException ex) {
128+
throw new MojoFailureException("Parameter 'from' is invalid", ex);
129+
}
130+
}
131+
132+
/** @return the {@link ImageReference} parsed from {@link #to}. */
133+
private ImageReference getTargetImageReference() throws MojoFailureException {
134+
try {
135+
return ImageReference.parse(getTargetImage());
136+
137+
} catch (InvalidImageReferenceException ex) {
138+
throw new MojoFailureException("Parameter 'to' is invalid", ex);
139+
}
31140
}
32141
}
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
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.maven;
18+
19+
import com.google.cloud.tools.jib.Command;
20+
import java.io.IOException;
21+
import java.nio.file.Path;
22+
import org.apache.maven.it.VerificationException;
23+
import org.apache.maven.it.Verifier;
24+
import org.junit.Assert;
25+
import org.junit.ClassRule;
26+
import org.junit.Test;
27+
28+
/** Integration tests for {@link BuildDockerMojo}. */
29+
public class BuildDockerMojoIT {
30+
31+
@ClassRule public static final TestPlugin testPlugin = new TestPlugin();
32+
33+
@ClassRule
34+
public static final TestProject simpleTestProject = new TestProject(testPlugin, "simple");
35+
36+
@ClassRule
37+
public static final TestProject emptyTestProject = new TestProject(testPlugin, "empty");
38+
39+
/**
40+
* Builds and runs jib:buildDocker on a project at {@code projectRoot} pushing to {@code
41+
* imageReference}.
42+
*/
43+
private static String buildToDockerDaemonAndRun(Path projectRoot, String imageReference)
44+
throws VerificationException, IOException, InterruptedException {
45+
Verifier verifier = new Verifier(projectRoot.toString());
46+
verifier.setAutoclean(false);
47+
verifier.executeGoal("package");
48+
49+
// Builds twice, and checks if the second build took less time.
50+
verifier.executeGoal("jib:buildDocker");
51+
verifier.verifyErrorFreeLog();
52+
53+
return new Command("docker", "run", imageReference).run();
54+
}
55+
56+
@Test
57+
public void testExecute_simple() throws VerificationException, IOException, InterruptedException {
58+
Assert.assertEquals(
59+
"Hello, world\n",
60+
buildToDockerDaemonAndRun(
61+
simpleTestProject.getProjectRoot(),
62+
"gcr.io/jib-integration-testing/simpleimage:maven"));
63+
}
64+
65+
@Test
66+
public void testExecute_empty() throws InterruptedException, IOException, VerificationException {
67+
Assert.assertEquals(
68+
"",
69+
buildToDockerDaemonAndRun(
70+
emptyTestProject.getProjectRoot(), "gcr.io/jib-integration-testing/emptyimage:maven"));
71+
}
72+
}

0 commit comments

Comments
 (0)