/
JibProcessor.java
428 lines (380 loc) · 20.8 KB
/
JibProcessor.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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
package io.quarkus.container.image.jib.deployment;
import static io.quarkus.container.util.PathsUtil.findMainSourcesRoot;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.jboss.logging.Logger;
import com.google.cloud.tools.jib.api.Containerizer;
import com.google.cloud.tools.jib.api.DockerDaemonImage;
import com.google.cloud.tools.jib.api.ImageReference;
import com.google.cloud.tools.jib.api.InvalidImageReferenceException;
import com.google.cloud.tools.jib.api.JavaContainerBuilder;
import com.google.cloud.tools.jib.api.Jib;
import com.google.cloud.tools.jib.api.JibContainer;
import com.google.cloud.tools.jib.api.JibContainerBuilder;
import com.google.cloud.tools.jib.api.LogEvent;
import com.google.cloud.tools.jib.api.RegistryImage;
import com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath;
import com.google.cloud.tools.jib.api.buildplan.FileEntriesLayer;
import com.google.cloud.tools.jib.api.buildplan.FilePermissions;
import com.google.cloud.tools.jib.frontend.CredentialRetrieverFactory;
import io.quarkus.bootstrap.util.ZipUtils;
import io.quarkus.container.image.deployment.ContainerImageConfig;
import io.quarkus.container.image.deployment.util.NativeBinaryUtil;
import io.quarkus.container.spi.ContainerImageBuildRequestBuildItem;
import io.quarkus.container.spi.ContainerImageInfoBuildItem;
import io.quarkus.container.spi.ContainerImageLabelBuildItem;
import io.quarkus.container.spi.ContainerImagePushRequestBuildItem;
import io.quarkus.container.util.PathsUtil;
import io.quarkus.deployment.Capability;
import io.quarkus.deployment.IsNormal;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.ApplicationInfoBuildItem;
import io.quarkus.deployment.builditem.CapabilityBuildItem;
import io.quarkus.deployment.builditem.MainClassBuildItem;
import io.quarkus.deployment.pkg.PackageConfig;
import io.quarkus.deployment.pkg.builditem.ArtifactResultBuildItem;
import io.quarkus.deployment.pkg.builditem.JarBuildItem;
import io.quarkus.deployment.pkg.builditem.NativeImageBuildItem;
import io.quarkus.deployment.pkg.builditem.OutputTargetBuildItem;
import io.quarkus.deployment.pkg.steps.JarResultBuildStep;
import io.quarkus.deployment.pkg.steps.NativeBuild;
public class JibProcessor {
private static final Logger log = Logger.getLogger(JibProcessor.class);
public static final String JIB = "jib";
private static final IsClassPredicate IS_CLASS_PREDICATE = new IsClassPredicate();
private static final String BINARY_NAME_IN_CONTAINER = "application";
@BuildStep(onlyIf = JibBuild.class)
public CapabilityBuildItem capability() {
return new CapabilityBuildItem(Capability.CONTAINER_IMAGE_JIB);
}
@BuildStep(onlyIf = { IsNormal.class, JibBuild.class }, onlyIfNot = NativeBuild.class)
public void buildFromJar(ContainerImageConfig containerImageConfig, JibConfig jibConfig,
PackageConfig packageConfig,
ContainerImageInfoBuildItem containerImage,
JarBuildItem sourceJar,
MainClassBuildItem mainClass,
OutputTargetBuildItem outputTarget, ApplicationInfoBuildItem applicationInfo,
Optional<ContainerImageBuildRequestBuildItem> buildRequest,
Optional<ContainerImagePushRequestBuildItem> pushRequest,
List<ContainerImageLabelBuildItem> containerImageLabels,
BuildProducer<ArtifactResultBuildItem> artifactResultProducer) {
if (!containerImageConfig.build && !containerImageConfig.push && !buildRequest.isPresent()
&& !pushRequest.isPresent()) {
return;
}
JibContainerBuilder jibContainerBuilder;
String packageType = packageConfig.type;
if (packageConfig.isLegacyJar() || packageType.equalsIgnoreCase(PackageConfig.UBER_JAR)) {
jibContainerBuilder = createContainerBuilderFromLegacyJar(jibConfig,
sourceJar, outputTarget, mainClass, containerImageLabels);
} else if (packageConfig.isFastJar()) {
jibContainerBuilder = createContainerBuilderFromFastJar(jibConfig, sourceJar, containerImageLabels);
} else {
throw new IllegalArgumentException(
"Package type '" + packageType + "' is not supported by the container-image-jib extension");
}
handleExtraFiles(outputTarget, jibContainerBuilder);
containerize(applicationInfo, containerImageConfig, containerImage, jibContainerBuilder,
pushRequest.isPresent());
artifactResultProducer.produce(new ArtifactResultBuildItem(null, "jar-container", Collections.emptyMap()));
}
@BuildStep(onlyIf = { IsNormal.class, JibBuild.class, NativeBuild.class })
public void buildFromNative(ContainerImageConfig containerImageConfig, JibConfig jibConfig,
ContainerImageInfoBuildItem containerImage,
NativeImageBuildItem nativeImage,
ApplicationInfoBuildItem applicationInfo,
OutputTargetBuildItem outputTarget,
Optional<ContainerImageBuildRequestBuildItem> buildRequest,
Optional<ContainerImagePushRequestBuildItem> pushRequest,
List<ContainerImageLabelBuildItem> containerImageLabels,
BuildProducer<ArtifactResultBuildItem> artifactResultProducer) {
if (!containerImageConfig.build && !containerImageConfig.push && !buildRequest.isPresent()
&& !pushRequest.isPresent()) {
return;
}
if (!NativeBinaryUtil.nativeIsLinuxBinary(nativeImage)) {
throw new RuntimeException(
"The native binary produced by the build is not a Linux binary and therefore cannot be used in a Linux container image. Consider adding \"quarkus.native.container-build=true\" to your configuration");
}
JibContainerBuilder jibContainerBuilder = createContainerBuilderFromNative(containerImageConfig, jibConfig,
nativeImage, containerImageLabels);
handleExtraFiles(outputTarget, jibContainerBuilder);
containerize(applicationInfo, containerImageConfig, containerImage, jibContainerBuilder,
pushRequest.isPresent());
artifactResultProducer.produce(new ArtifactResultBuildItem(null, "native-container", Collections.emptyMap()));
}
private JibContainer containerize(ApplicationInfoBuildItem applicationInfo, ContainerImageConfig containerImageConfig,
ContainerImageInfoBuildItem containerImage, JibContainerBuilder jibContainerBuilder, boolean pushRequested) {
Containerizer containerizer = createContainerizer(containerImageConfig, containerImage, applicationInfo, pushRequested);
for (String additionalTag : containerImage.getAdditionalTags()) {
containerizer.withAdditionalTag(additionalTag);
}
try {
log.info("Starting container image build");
JibContainer container = jibContainerBuilder.containerize(containerizer);
log.infof("%s container image %s (%s)\n",
containerImageConfig.push ? "Pushed" : "Created",
container.getTargetImage(),
container.getDigest());
return container;
} catch (Exception e) {
throw new RuntimeException("Unable to create container image", e);
}
}
private Containerizer createContainerizer(ContainerImageConfig containerImageConfig,
ContainerImageInfoBuildItem containerImage,
ApplicationInfoBuildItem applicationInfo, boolean pushRequested) {
Containerizer containerizer;
ImageReference imageReference = getImageReference(containerImageConfig, containerImage, applicationInfo);
for (String additionalTag : containerImage.getAdditionalTags()) {
if (!ImageReference.isValidTag(additionalTag)) {
throw new IllegalArgumentException(
"The supplied container-image additional tag '" + additionalTag + "' is invalid");
}
}
if (pushRequested || containerImageConfig.push) {
if (!containerImageConfig.registry.isPresent()) {
log.info("No container image registry was set, so 'docker.io' will be used");
}
RegistryImage registryImage = toRegistryImage(imageReference, containerImageConfig.username,
containerImageConfig.password);
containerizer = Containerizer.to(registryImage);
} else {
containerizer = Containerizer.to(DockerDaemonImage.named(imageReference));
}
containerizer.setToolName("Quarkus");
containerizer.addEventHandler(LogEvent.class, (e) -> {
if (!e.getMessage().isEmpty()) {
log.log(toJBossLoggingLevel(e.getLevel()), e.getMessage());
}
});
containerizer.setAllowInsecureRegistries(containerImageConfig.insecure);
return containerizer;
}
private RegistryImage toRegistryImage(ImageReference imageReference, Optional<String> username, Optional<String> password) {
CredentialRetrieverFactory credentialRetrieverFactory = CredentialRetrieverFactory.forImage(imageReference,
log::info);
RegistryImage registryImage = RegistryImage.named(imageReference);
registryImage.addCredentialRetriever(credentialRetrieverFactory.wellKnownCredentialHelpers());
registryImage.addCredentialRetriever(credentialRetrieverFactory.dockerConfig());
if (username.isPresent() && password.isPresent()) {
registryImage.addCredential(username.get(), password.get());
}
return registryImage;
}
private Logger.Level toJBossLoggingLevel(LogEvent.Level level) {
switch (level) {
case ERROR:
return Logger.Level.ERROR;
case WARN:
return Logger.Level.WARN;
case LIFECYCLE:
return Logger.Level.INFO;
default:
return Logger.Level.DEBUG;
}
}
private ImageReference getImageReference(ContainerImageConfig containerImageConfig,
ContainerImageInfoBuildItem containerImage,
ApplicationInfoBuildItem applicationInfo) {
String registry = containerImageConfig.registry.orElse(null);
if ((registry != null) && !ImageReference.isValidRegistry(registry)) {
throw new IllegalArgumentException("The supplied container-image registry '" + registry + "' is invalid");
}
String repository = (containerImageConfig.getEffectiveGroup().map(s -> s + "/").orElse(""))
+ containerImageConfig.name.orElse(applicationInfo.getName());
if (!ImageReference.isValidRepository(repository)) {
throw new IllegalArgumentException("The supplied container-image repository '" + repository + "' is invalid");
}
final String tag = containerImage.getTag();
if (!ImageReference.isValidTag(tag)) {
throw new IllegalArgumentException("The supplied container-image tag '" + tag + "' is invalid");
}
return ImageReference.of(registry, repository, tag);
}
/**
* We don't use Jib's JavaContainerBuilder here because we need to support the custom fast-jar format
* We create the following layers (least likely to change to most likely to change):
*
* <ul>
* <li>lib</li>
* <li>boot-lib</li>
* <li>quarkus-run.jar</li>
* <li>quarkus</li>
* <li>app</li>
* </ul>
*/
private JibContainerBuilder createContainerBuilderFromFastJar(JibConfig jibConfig,
JarBuildItem sourceJarBuildItem,
List<ContainerImageLabelBuildItem> containerImageLabels) {
Path componentsPath = sourceJarBuildItem.getPath().getParent();
AbsoluteUnixPath workDirInContainer = AbsoluteUnixPath.get("/work");
List<String> entrypoint;
if (jibConfig.jvmEntrypoint.isPresent()) {
entrypoint = jibConfig.jvmEntrypoint.get();
} else {
entrypoint = new ArrayList<>(3 + jibConfig.jvmArguments.size());
entrypoint.add("java");
entrypoint.addAll(jibConfig.jvmArguments);
entrypoint.add("-jar");
entrypoint.add(JarResultBuildStep.QUARKUS_RUN_JAR);
}
try {
return Jib.from(toRegistryImage(ImageReference.parse(jibConfig.baseJvmImage), jibConfig.baseRegistryUsername,
jibConfig.baseRegistryPassword))
.addLayer(Collections.singletonList(componentsPath.resolve(JarResultBuildStep.LIB)), workDirInContainer)
.addLayer(Collections.singletonList(componentsPath.resolve(JarResultBuildStep.QUARKUS_RUN_JAR)),
workDirInContainer)
.addLayer(Collections.singletonList(componentsPath.resolve(JarResultBuildStep.APP)), workDirInContainer)
.addLayer(Collections.singletonList(componentsPath.resolve(JarResultBuildStep.QUARKUS)), workDirInContainer)
.setWorkingDirectory(workDirInContainer)
.setEntrypoint(entrypoint)
.setEnvironment(jibConfig.environmentVariables)
.setLabels(allLabels(jibConfig, containerImageLabels))
.setCreationTime(Instant.now());
} catch (IOException e) {
throw new UncheckedIOException(e);
} catch (InvalidImageReferenceException e) {
throw new RuntimeException(e);
}
}
private JibContainerBuilder createContainerBuilderFromLegacyJar(JibConfig jibConfig,
JarBuildItem sourceJarBuildItem,
OutputTargetBuildItem outputTargetBuildItem, MainClassBuildItem mainClassBuildItem,
List<ContainerImageLabelBuildItem> containerImageLabels) {
try {
// not ideal since this has been previously zipped - we would like to just reuse it
Path classesDir = outputTargetBuildItem.getOutputDirectory().resolve("jib");
ZipUtils.unzip(sourceJarBuildItem.getPath(), classesDir);
JavaContainerBuilder javaContainerBuilder = JavaContainerBuilder
.from(toRegistryImage(ImageReference.parse(jibConfig.baseJvmImage), jibConfig.baseRegistryUsername,
jibConfig.baseRegistryPassword))
.addResources(classesDir, IS_CLASS_PREDICATE.negate())
.addClasses(classesDir, IS_CLASS_PREDICATE);
// when there is no custom entry point, we just set everything up for a regular java run
if (!jibConfig.jvmEntrypoint.isPresent()) {
javaContainerBuilder
.addJvmFlags(jibConfig.jvmArguments)
.setMainClass(mainClassBuildItem.getClassName());
}
if (sourceJarBuildItem.getLibraryDir() != null) {
javaContainerBuilder
.addDependencies(
Files.list(sourceJarBuildItem.getLibraryDir())
.filter(p -> Files.isRegularFile(p) && p.getFileName().toString().endsWith(".jar"))
.sorted(Comparator.comparing(Path::getFileName))
.collect(Collectors.toList()));
}
JibContainerBuilder jibContainerBuilder = javaContainerBuilder.toContainerBuilder()
.setEnvironment(jibConfig.environmentVariables)
.setLabels(allLabels(jibConfig, containerImageLabels))
.setCreationTime(Instant.now());
if (jibConfig.jvmEntrypoint.isPresent()) {
jibContainerBuilder.setEntrypoint(jibConfig.jvmEntrypoint.get());
}
return jibContainerBuilder;
} catch (IOException e) {
throw new UncheckedIOException(e);
} catch (InvalidImageReferenceException e) {
throw new RuntimeException(e);
}
}
private JibContainerBuilder createContainerBuilderFromNative(ContainerImageConfig containerImageConfig, JibConfig jibConfig,
NativeImageBuildItem nativeImageBuildItem, List<ContainerImageLabelBuildItem> containerImageLabels) {
List<String> entrypoint;
if (jibConfig.nativeEntrypoint.isPresent()) {
entrypoint = jibConfig.nativeEntrypoint.get();
} else {
List<String> nativeArguments = jibConfig.nativeArguments.orElse(Collections.emptyList());
entrypoint = new ArrayList<>(nativeArguments.size() + 1);
entrypoint.add("./" + BINARY_NAME_IN_CONTAINER);
entrypoint.addAll(nativeArguments);
}
try {
AbsoluteUnixPath workDirInContainer = AbsoluteUnixPath.get("/work");
return Jib
.from(toRegistryImage(ImageReference.parse(jibConfig.baseNativeImage), containerImageConfig.username,
containerImageConfig.password))
.addFileEntriesLayer(FileEntriesLayer.builder()
.addEntry(nativeImageBuildItem.getPath(), workDirInContainer.resolve(BINARY_NAME_IN_CONTAINER),
FilePermissions.fromOctalString("775"))
.build())
.setWorkingDirectory(workDirInContainer)
.setEntrypoint(entrypoint)
.setEnvironment(jibConfig.environmentVariables)
.setLabels(allLabels(jibConfig, containerImageLabels))
.setCreationTime(Instant.now());
} catch (InvalidImageReferenceException e) {
throw new RuntimeException(e);
}
}
/**
* Allow users to have custom files in {@code src/main/jib} that will be copied into the built container's file system
* in same manner as the Jib Maven and Gradle plugins do.
* For example, {@code src/main/jib/foo/bar} would add {@code /foo/bar} into the container filesystem.
*
* See: https://github.com/GoogleContainerTools/jib/blob/v0.15.0-core/docs/faq.md#can-i-add-a-custom-directory-to-the-image
*/
private void handleExtraFiles(OutputTargetBuildItem outputTarget, JibContainerBuilder jibContainerBuilder) {
Path outputDirectory = outputTarget.getOutputDirectory();
PathsUtil.findMainSourcesRoot(outputTarget.getOutputDirectory());
Map.Entry<Path, Path> mainSourcesRoot = findMainSourcesRoot(outputDirectory);
if (mainSourcesRoot == null) { // this should never happen
return;
}
Path jibFilesRoot = mainSourcesRoot.getKey().resolve("jib");
if (!jibFilesRoot.toFile().exists()) {
return;
}
FileEntriesLayer extraFilesLayer;
try {
extraFilesLayer = ContainerBuilderHelper.extraDirectoryLayerConfiguration(
jibFilesRoot,
AbsoluteUnixPath.get("/"),
Collections.emptyMap(),
(localPath, ignored2) -> {
try {
return Files.getLastModifiedTime(localPath).toInstant();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
jibContainerBuilder.addFileEntriesLayer(
extraFilesLayer);
} catch (IOException e) {
throw new UncheckedIOException(
"Unable to add extra files in '" + jibFilesRoot.toAbsolutePath().toString() + "' to the container", e);
}
}
private Map<String, String> allLabels(JibConfig jibConfig, List<ContainerImageLabelBuildItem> containerImageLabels) {
if (jibConfig.labels.isEmpty() && containerImageLabels.isEmpty()) {
return Collections.emptyMap();
}
final Map<String, String> allLabels = new HashMap<>(jibConfig.labels);
for (ContainerImageLabelBuildItem containerImageLabel : containerImageLabels) {
// we want the user supplied labels to take precedence so the user can override labels generated from other extensions if desired
allLabels.putIfAbsent(containerImageLabel.getName(), containerImageLabel.getValue());
}
return allLabels;
}
// TODO: this predicate is rather simplistic since it results in creating the directory structure in both the resources and classes so it should probably be improved to remove empty directories
private static class IsClassPredicate implements Predicate<Path> {
@Override
public boolean test(Path path) {
return path.getFileName().toString().endsWith(".class");
}
}
}