Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add option to specify base image for cli jar command #2972

Merged
merged 10 commits into from
Jan 8, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,24 @@ public void testSpringBootJar_packagedMode() throws IOException, InterruptedExce
assertThat(getContent(new URL("http://localhost:8080"))).isEqualTo("Hello world");
}

@Test
public void testJar_baseImageSpecified()
throws IOException, URISyntaxException, InterruptedException {
Path jarPath = Paths.get(Resources.getResource("jarTest/standard/noDependencyJar.jar").toURI());
Integer exitCode =
new CommandLine(new JibCli())
.execute(
"jar",
"--target",
"docker://cli-gcr-base",
"--from",
"gcr.io/google-appengine/openjdk:8",
chanseokoh marked this conversation as resolved.
Show resolved Hide resolved
jarPath.toString());
assertThat(exitCode).isEqualTo(0);
String output = new Command("docker", "run", "--rm", "cli-gcr-base").run();
assertThat(output).isEqualTo("Hello World");
}

@Nullable
private static String getContent(URL url) throws InterruptedException {
for (int i = 0; i < 40; i++) {
Expand Down
23 changes: 22 additions & 1 deletion jib-cli/src/main/java/com/google/cloud/tools/jib/cli/Jar.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.Callable;
import picocli.CommandLine;
import picocli.CommandLine.Model.CommandSpec;
Expand Down Expand Up @@ -64,6 +65,13 @@ public class Jar implements Callable<Integer> {
@SuppressWarnings("NullAway.Init") // initialized by picocli
private ProcessingMode mode;

@CommandLine.Option(
names = "--from",
paramLabel = "<from>",
description = "The base image to use.")
@SuppressWarnings("NullAway.Init") // initialized by picocli
private String from;

@Override
public Integer call() {
try {
Expand Down Expand Up @@ -98,7 +106,8 @@ public Integer call() {
}

JarProcessor processor = JarProcessors.from(jarFile, tempDirectoryProvider, mode);
JibContainerBuilder containerBuilder = JarFiles.toJibContainerBuilder(processor);
JibContainerBuilder containerBuilder =
JarFiles.toJibContainerBuilder(processor, this, commonCliOptions, logger);
CacheDirectories cacheDirectories =
CacheDirectories.from(commonCliOptions, jarFile.toAbsolutePath().getParent());
Containerizer containerizer = Containerizers.from(commonCliOptions, logger, cacheDirectories);
Expand All @@ -114,4 +123,16 @@ public Integer call() {
}
return 0;
}

/**
* Returns the user specified base image.
*
* @return an optional base image
*/
public Optional<String> getFrom() {
if (from != null) {
return Optional.of(from);
}
return Optional.empty();
chanseokoh marked this conversation as resolved.
Show resolved Hide resolved
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,27 @@

package com.google.cloud.tools.jib.cli.jar;

import static com.google.cloud.tools.jib.api.Jib.DOCKER_DAEMON_IMAGE_PREFIX;
import static com.google.cloud.tools.jib.api.Jib.REGISTRY_IMAGE_PREFIX;
import static com.google.cloud.tools.jib.api.Jib.TAR_IMAGE_PREFIX;

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.Jib;
import com.google.cloud.tools.jib.api.JibContainerBuilder;
import com.google.cloud.tools.jib.api.RegistryImage;
import com.google.cloud.tools.jib.api.TarImage;
import com.google.cloud.tools.jib.api.buildplan.FileEntriesLayer;
import com.google.cloud.tools.jib.cli.CommonCliOptions;
import com.google.cloud.tools.jib.cli.Credentials;
import com.google.cloud.tools.jib.cli.Jar;
import com.google.cloud.tools.jib.frontend.CredentialRetrieverFactory;
import com.google.cloud.tools.jib.plugins.common.DefaultCredentialRetrievers;
import com.google.cloud.tools.jib.plugins.common.logging.ConsoleLogger;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;

/** Class to build a container representation from the contents of a jar file. */
Expand All @@ -30,20 +46,55 @@ public class JarFiles {
* Generates a {@link JibContainerBuilder} from contents of a jar file.
*
* @param processor jar processor
* @param jarOptions jar cli options
* @param commonCliOptions common cli options
* @param logger console logger
* @return JibContainerBuilder
* @throws IOException if I/O error occurs when opening the jar file or if temporary directory
* provided doesn't exist
* @throws InvalidImageReferenceException if the base image reference is invalid
*/
public static JibContainerBuilder toJibContainerBuilder(JarProcessor processor)
public static JibContainerBuilder toJibContainerBuilder(
JarProcessor processor,
Jar jarOptions,
CommonCliOptions commonCliOptions,
ConsoleLogger logger)
throws IOException, InvalidImageReferenceException {

// Use distroless as the base image.
JibContainerBuilder containerBuilder = Jib.from("gcr.io/distroless/java");
// Use distroless as the default base image.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think here we should try to check if the jar is java8 or java11 and chose the right distroless? (perhaps in a followup PR)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup, good point - we have an issue for this #2871. Will make this change in the next PR.

JibContainerBuilder containerBuilder =
jarOptions.getFrom().isPresent()
? createJibContainerBuilder(jarOptions.getFrom().get(), commonCliOptions, logger)
: Jib.from("gcr.io/distroless/java");

List<FileEntriesLayer> layers = processor.createLayers();
List<String> entrypoint = processor.computeEntrypoint();
containerBuilder.setEntrypoint(entrypoint).setFileEntriesLayers(layers);
return containerBuilder;
}

static JibContainerBuilder createJibContainerBuilder(
String from, CommonCliOptions commonCliOptions, ConsoleLogger logger)
throws InvalidImageReferenceException, FileNotFoundException {
String baseImageReference = from;
chanseokoh marked this conversation as resolved.
Show resolved Hide resolved
if (baseImageReference.startsWith(DOCKER_DAEMON_IMAGE_PREFIX)) {
return Jib.from(
DockerDaemonImage.named(baseImageReference.replaceFirst(DOCKER_DAEMON_IMAGE_PREFIX, "")));
}
if (baseImageReference.startsWith(TAR_IMAGE_PREFIX)) {
return Jib.from(
TarImage.at(Paths.get(baseImageReference.replaceFirst(TAR_IMAGE_PREFIX, ""))));
}
ImageReference imageReference =
ImageReference.parse(baseImageReference.replaceFirst(REGISTRY_IMAGE_PREFIX, ""));
RegistryImage registryImage = RegistryImage.named(imageReference);
DefaultCredentialRetrievers defaultCredentialRetrievers =
DefaultCredentialRetrievers.init(
CredentialRetrieverFactory.forImage(
imageReference,
logEvent -> logger.log(logEvent.getLevel(), logEvent.getMessage())));
Credentials.getFromCredentialRetrievers(commonCliOptions, defaultCredentialRetrievers)
.forEach(registryImage::addCredentialRetriever);
return Jib.from(registryImage);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,14 @@ public void testParse_incompatibleCredentialOptions(String[] authArgs) {
.containsMatch("^Error: (--(from-|to-)?credential-helper|\\[--username)");
}

@Test
public void testParse_from() {
Jar jarCommand =
CommandLine.populateCommand(
new Jar(), "--target", "test-image-ref", "--from", "base-image-ref", "my-app.jar");
assertThat(jarCommand.getFrom()).hasValue("base-image-ref");
}

@Test
public void testValidate_nameMissingFail() {
Jar jarCommand =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,17 @@
import com.google.cloud.tools.jib.api.buildplan.FileEntriesLayer;
import com.google.cloud.tools.jib.api.buildplan.ImageFormat;
import com.google.cloud.tools.jib.api.buildplan.Platform;
import com.google.cloud.tools.jib.cli.CommonCliOptions;
import com.google.cloud.tools.jib.cli.Jar;
import com.google.cloud.tools.jib.plugins.common.logging.ConsoleLogger;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.io.IOException;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collections;
import java.util.Optional;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
Expand All @@ -49,6 +54,12 @@ public class JarFilesTest {

@Mock private SpringBootPackagedProcessor mockSpringBootPackagedProcessor;

@Mock private Jar mockJarCommand;

@Mock private CommonCliOptions mockCommonCliOptions;

@Mock private ConsoleLogger mockLogger;

@Test
public void testToJibContainerBuilder_explodedStandard_basicInfo()
throws IOException, InvalidImageReferenceException {
Expand All @@ -63,9 +74,11 @@ public void testToJibContainerBuilder_explodedStandard_basicInfo()
Mockito.when(mockStandardExplodedProcessor.computeEntrypoint())
.thenReturn(
ImmutableList.of("java", "-cp", "/app/explodedJar:/app/dependencies/*", "HelloWorld"));
Mockito.when(mockJarCommand.getFrom()).thenReturn(Optional.empty());

JibContainerBuilder containerBuilder =
JarFiles.toJibContainerBuilder(mockStandardExplodedProcessor);
JarFiles.toJibContainerBuilder(
mockStandardExplodedProcessor, mockJarCommand, mockCommonCliOptions, mockLogger);
ContainerBuildPlan buildPlan = containerBuilder.toContainerBuildPlan();

assertThat(buildPlan.getBaseImage()).isEqualTo("gcr.io/distroless/java");
Expand Down Expand Up @@ -105,9 +118,11 @@ public void testToJibContainerBuilder_packagedStandard_basicInfo()
Mockito.when(mockStandardPackagedProcessor.createLayers()).thenReturn(Arrays.asList(layer));
Mockito.when(mockStandardPackagedProcessor.computeEntrypoint())
.thenReturn(ImmutableList.of("java", "-jar", "/app/standardJar.jar"));
Mockito.when(mockJarCommand.getFrom()).thenReturn(Optional.empty());

JibContainerBuilder containerBuilder =
JarFiles.toJibContainerBuilder(mockStandardPackagedProcessor);
JarFiles.toJibContainerBuilder(
mockStandardPackagedProcessor, mockJarCommand, mockCommonCliOptions, mockLogger);
ContainerBuildPlan buildPlan = containerBuilder.toContainerBuildPlan();

assertThat(buildPlan.getBaseImage()).isEqualTo("gcr.io/distroless/java");
Expand Down Expand Up @@ -143,13 +158,16 @@ public void testToJibContainerBuilder_explodedLayeredSpringBoot_basicInfo()
Paths.get("path/to/tempDirectory/BOOT-INF/classes/class1.class"),
AbsoluteUnixPath.get("/app/BOOT-INF/classes/class1.class"))
.build();
Mockito.when(mockJarCommand.getFrom()).thenReturn(Optional.empty());
Mockito.when(mockSpringBootExplodedProcessor.createLayers()).thenReturn(Arrays.asList(layer));
Mockito.when(mockSpringBootExplodedProcessor.computeEntrypoint())
.thenReturn(
ImmutableList.of("java", "-cp", "/app", "org.springframework.boot.loader.JarLauncher"));
Mockito.when(mockJarCommand.getFrom()).thenReturn(Optional.empty());

JibContainerBuilder containerBuilder =
JarFiles.toJibContainerBuilder(mockSpringBootExplodedProcessor);
JarFiles.toJibContainerBuilder(
mockSpringBootExplodedProcessor, mockJarCommand, mockCommonCliOptions, mockLogger);
ContainerBuildPlan buildPlan = containerBuilder.toContainerBuildPlan();

assertThat(buildPlan.getBaseImage()).isEqualTo("gcr.io/distroless/java");
Expand Down Expand Up @@ -189,9 +207,11 @@ public void testToJibContainerBuilder_packagedSpringBoot_basicInfo()
Mockito.when(mockSpringBootPackagedProcessor.createLayers()).thenReturn(Arrays.asList(layer));
Mockito.when(mockSpringBootPackagedProcessor.computeEntrypoint())
.thenReturn(ImmutableList.of("java", "-jar", "/app/spring-boot.jar"));
Mockito.when(mockJarCommand.getFrom()).thenReturn(Optional.empty());

JibContainerBuilder containerBuilder =
JarFiles.toJibContainerBuilder(mockSpringBootPackagedProcessor);
JarFiles.toJibContainerBuilder(
mockSpringBootPackagedProcessor, mockJarCommand, mockCommonCliOptions, mockLogger);
ContainerBuildPlan buildPlan = containerBuilder.toContainerBuildPlan();

assertThat(buildPlan.getBaseImage()).isEqualTo("gcr.io/distroless/java");
Expand All @@ -217,4 +237,34 @@ public void testToJibContainerBuilder_packagedSpringBoot_basicInfo()
.build()
.getEntries());
}

@Test
public void testToJibContainerBuilder_dockerBaseImage()
throws IOException, InvalidImageReferenceException {
chanseokoh marked this conversation as resolved.
Show resolved Hide resolved
Mockito.when(mockStandardExplodedProcessor.createLayers()).thenReturn(Collections.EMPTY_LIST);
Mockito.when(mockStandardExplodedProcessor.computeEntrypoint())
.thenReturn(ImmutableList.of("ignore"));
Mockito.when(mockJarCommand.getFrom()).thenReturn(Optional.of("docker://docker-image-ref"));

JibContainerBuilder containerBuilder =
JarFiles.toJibContainerBuilder(
mockStandardExplodedProcessor, mockJarCommand, mockCommonCliOptions, mockLogger);
String baseImage = containerBuilder.toContainerBuildPlan().getBaseImage();
assertThat(baseImage).isEqualTo("docker-image-ref");
}

@Test
public void testToJibContainerBuilder_registry()
throws IOException, InvalidImageReferenceException {
Mockito.when(mockStandardExplodedProcessor.createLayers()).thenReturn(Collections.EMPTY_LIST);
Mockito.when(mockStandardExplodedProcessor.computeEntrypoint())
.thenReturn(ImmutableList.of("ignore"));
Mockito.when(mockJarCommand.getFrom()).thenReturn(Optional.of("registry://registry-image-ref"));

JibContainerBuilder containerBuilder =
JarFiles.toJibContainerBuilder(
mockStandardExplodedProcessor, mockJarCommand, mockCommonCliOptions, mockLogger);
String baseImage = containerBuilder.toContainerBuildPlan().getBaseImage();
assertThat(baseImage).isEqualTo("registry-image-ref");
}
}