/
BuildImageMojo.java
408 lines (352 loc) · 12.4 KB
/
BuildImageMojo.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
/*
* Copyright 2012-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.maven;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.time.Duration;
import java.util.Collections;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.archivers.tar.TarConstants;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugins.annotations.Parameter;
import org.springframework.boot.buildpack.platform.build.AbstractBuildLog;
import org.springframework.boot.buildpack.platform.build.BuildLog;
import org.springframework.boot.buildpack.platform.build.BuildRequest;
import org.springframework.boot.buildpack.platform.build.Builder;
import org.springframework.boot.buildpack.platform.build.Creator;
import org.springframework.boot.buildpack.platform.build.PullPolicy;
import org.springframework.boot.buildpack.platform.docker.TotalProgressEvent;
import org.springframework.boot.buildpack.platform.docker.configuration.DockerConfiguration;
import org.springframework.boot.buildpack.platform.io.Owner;
import org.springframework.boot.buildpack.platform.io.TarArchive;
import org.springframework.boot.loader.tools.EntryWriter;
import org.springframework.boot.loader.tools.ImagePackager;
import org.springframework.boot.loader.tools.LayoutFactory;
import org.springframework.boot.loader.tools.Libraries;
import org.springframework.util.StringUtils;
/**
* Package an application into an OCI image using a buildpack.
*
* @author Phillip Webb
* @author Scott Frederick
* @author Jeroen Meijer
* @since 2.3.0
*/
public abstract class BuildImageMojo extends AbstractPackagerMojo {
static {
System.setProperty("org.slf4j.simpleLogger.log.org.apache.http.wire", "ERROR");
}
/**
* Directory containing the source archive.
* @since 2.3.0
*/
@Parameter(defaultValue = "${project.build.directory}", required = true)
private File sourceDirectory;
/**
* Name of the source archive.
* @since 2.3.0
*/
@Parameter(defaultValue = "${project.build.finalName}", readonly = true)
private String finalName;
/**
* Skip the execution.
* @since 2.3.0
*/
@Parameter(property = "spring-boot.build-image.skip", defaultValue = "false")
private boolean skip;
/**
* Classifier used when finding the source archive.
* @since 2.3.0
*/
@Parameter
private String classifier;
/**
* Image configuration, with {@code builder}, {@code runImage}, {@code name},
* {@code env}, {@code cleanCache}, {@code verboseLogging}, {@code pullPolicy}, and
* {@code publish} options.
* @since 2.3.0
*/
@Parameter
private Image image;
/**
* Alias for {@link Image#name} to support configuration via command-line property.
* @since 2.3.0
*/
@Parameter(property = "spring-boot.build-image.imageName", readonly = true)
String imageName;
/**
* Alias for {@link Image#builder} to support configuration via command-line property.
* @since 2.3.0
*/
@Parameter(property = "spring-boot.build-image.builder", readonly = true)
String imageBuilder;
/**
* Alias for {@link Image#runImage} to support configuration via command-line
* property.
* @since 2.3.1
*/
@Parameter(property = "spring-boot.build-image.runImage", readonly = true)
String runImage;
/**
* Alias for {@link Image#cleanCache} to support configuration via command-line
* property.
* @since 2.4.0
*/
@Parameter(property = "spring-boot.build-image.cleanCache", readonly = true)
Boolean cleanCache;
/**
* Alias for {@link Image#pullPolicy} to support configuration via command-line
* property.
*/
@Parameter(property = "spring-boot.build-image.pullPolicy", readonly = true)
PullPolicy pullPolicy;
/**
* Alias for {@link Image#publish} to support configuration via command-line property.
*/
@Parameter(property = "spring-boot.build-image.publish", readonly = true)
Boolean publish;
/**
* Alias for {@link Image#network} to support configuration via command-line property.
* @since 2.6.0
*/
@Parameter(property = "spring-boot.build-image.network", readonly = true)
String network;
/**
* Docker configuration options.
* @since 2.4.0
*/
@Parameter
private Docker docker;
/**
* The type of archive (which corresponds to how the dependencies are laid out inside
* it). Possible values are {@code JAR}, {@code WAR}, {@code ZIP}, {@code DIR},
* {@code NONE}. Defaults to a guess based on the archive type.
* @since 2.3.11
*/
@Parameter
private LayoutType layout;
/**
* The layout factory that will be used to create the executable archive if no
* explicit layout is set. Alternative layouts implementations can be provided by 3rd
* parties.
* @since 2.3.11
*/
@Parameter
private LayoutFactory layoutFactory;
/**
* Return the type of archive that should be used when building the image.
* @return the value of the {@code layout} parameter, or {@code null} if the parameter
* is not provided
*/
@Override
protected LayoutType getLayout() {
return this.layout;
}
/**
* Return the layout factory that will be used to determine the
* {@link AbstractPackagerMojo.LayoutType} if no explicit layout is set.
* @return the value of the {@code layoutFactory} parameter, or {@code null} if the
* parameter is not provided
*/
@Override
protected LayoutFactory getLayoutFactory() {
return this.layoutFactory;
}
@Override
public void execute() throws MojoExecutionException {
if (this.project.getPackaging().equals("pom")) {
getLog().debug("build-image goal could not be applied to pom project.");
return;
}
if (this.skip) {
getLog().debug("skipping build-image as per configuration.");
return;
}
buildImage();
}
private void buildImage() throws MojoExecutionException {
Libraries libraries = getLibraries(Collections.emptySet());
try {
DockerConfiguration dockerConfiguration = (this.docker != null) ? this.docker.asDockerConfiguration()
: new Docker().asDockerConfiguration();
BuildRequest request = getBuildRequest(libraries);
Builder builder = new Builder(new MojoBuildLog(this::getLog), dockerConfiguration);
builder.build(request);
}
catch (IOException ex) {
throw new MojoExecutionException(ex.getMessage(), ex);
}
}
private BuildRequest getBuildRequest(Libraries libraries) {
ImagePackager imagePackager = new ImagePackager(getArchiveFile(), getBackupFile());
Function<Owner, TarArchive> content = (owner) -> getApplicationContent(owner, libraries, imagePackager);
Image image = (this.image != null) ? this.image : new Image();
if (image.name == null && this.imageName != null) {
image.setName(this.imageName);
}
if (image.builder == null && this.imageBuilder != null) {
image.setBuilder(this.imageBuilder);
}
if (image.runImage == null && this.runImage != null) {
image.setRunImage(this.runImage);
}
if (image.cleanCache == null && this.cleanCache != null) {
image.setCleanCache(this.cleanCache);
}
if (image.pullPolicy == null && this.pullPolicy != null) {
image.setPullPolicy(this.pullPolicy);
}
if (image.publish == null && this.publish != null) {
image.setPublish(this.publish);
}
if (image.network == null && this.network != null) {
image.setNetwork(this.network);
}
return customize(image.getBuildRequest(this.project.getArtifact(), content));
}
private TarArchive getApplicationContent(Owner owner, Libraries libraries, ImagePackager imagePackager) {
ImagePackager packager = getConfiguredPackager(() -> imagePackager);
return new PackagedTarArchive(owner, libraries, packager);
}
private File getArchiveFile() {
// We can use 'project.getArtifact().getFile()' because that was done in a
// forked lifecycle and is now null
File archiveFile = getTargetFile(this.finalName, this.classifier, this.sourceDirectory);
if (!archiveFile.exists()) {
archiveFile = getSourceArtifact(this.classifier).getFile();
}
if (!archiveFile.exists()) {
throw new IllegalStateException("A jar or war file is required for building image");
}
return archiveFile;
}
/**
* Return the {@link File} to use to back up the original source.
* @return the file to use to back up the original source
*/
private File getBackupFile() {
Artifact source = getSourceArtifact(null);
if (this.classifier != null && !this.classifier.equals(source.getClassifier())) {
return source.getFile();
}
return null;
}
private BuildRequest customize(BuildRequest request) {
request = customizeCreator(request);
return request;
}
private BuildRequest customizeCreator(BuildRequest request) {
String springBootVersion = VersionExtractor.forClass(BuildImageMojo.class);
if (StringUtils.hasText(springBootVersion)) {
request = request.withCreator(Creator.withVersion(springBootVersion));
}
return request;
}
/**
* {@link BuildLog} backed by Mojo logging.
*/
private static class MojoBuildLog extends AbstractBuildLog {
private static final long THRESHOLD = Duration.ofSeconds(2).toMillis();
private final Supplier<Log> log;
MojoBuildLog(Supplier<Log> log) {
this.log = log;
}
@Override
protected void log(String message) {
this.log.get().info(message);
}
@Override
protected Consumer<TotalProgressEvent> getProgressConsumer(String message) {
return new ProgressLog(message);
}
private class ProgressLog implements Consumer<TotalProgressEvent> {
private final String message;
private long last;
ProgressLog(String message) {
this.message = message;
this.last = System.currentTimeMillis();
}
@Override
public void accept(TotalProgressEvent progress) {
log(progress.getPercent());
}
private void log(int percent) {
if (percent == 100 || (System.currentTimeMillis() - this.last) > THRESHOLD) {
MojoBuildLog.this.log.get().info(this.message + " " + percent + "%");
this.last = System.currentTimeMillis();
}
}
}
}
/**
* Adapter class to expose the packaged jar as a {@link TarArchive}.
*/
static class PackagedTarArchive implements TarArchive {
static final long NORMALIZED_MOD_TIME = TarArchive.NORMALIZED_TIME.toEpochMilli();
private final Owner owner;
private final Libraries libraries;
private final ImagePackager packager;
PackagedTarArchive(Owner owner, Libraries libraries, ImagePackager packager) {
this.owner = owner;
this.libraries = libraries;
this.packager = packager;
}
@Override
public void writeTo(OutputStream outputStream) throws IOException {
TarArchiveOutputStream tar = new TarArchiveOutputStream(outputStream);
tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
try {
this.packager.packageImage(this.libraries, (entry, entryWriter) -> write(entry, entryWriter, tar));
}
catch (RuntimeException ex) {
outputStream.close();
throw new RuntimeException("Error packaging archive for image", ex);
}
}
private void write(ZipEntry jarEntry, EntryWriter entryWriter, TarArchiveOutputStream tar) {
try {
TarArchiveEntry tarEntry = convert(jarEntry);
tar.putArchiveEntry(tarEntry);
if (tarEntry.isFile()) {
entryWriter.write(tar);
}
tar.closeArchiveEntry();
}
catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
private TarArchiveEntry convert(ZipEntry entry) {
byte linkFlag = (entry.isDirectory()) ? TarConstants.LF_DIR : TarConstants.LF_NORMAL;
TarArchiveEntry tarEntry = new TarArchiveEntry(entry.getName(), linkFlag, true);
tarEntry.setUserId(this.owner.getUid());
tarEntry.setGroupId(this.owner.getGid());
tarEntry.setModTime(NORMALIZED_MOD_TIME);
if (!entry.isDirectory()) {
tarEntry.setSize(entry.getSize());
}
return tarEntry;
}
}
}