Skip to content

Enable platform tags plugin with mvn #4332

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

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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 @@ -19,13 +19,15 @@
import com.google.cloud.tools.jib.Command;
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.Platform;
import com.google.cloud.tools.jib.event.events.ProgressEvent;
import com.google.cloud.tools.jib.event.progress.ProgressEventHandler;
import com.google.cloud.tools.jib.global.JibSystemProperties;
import com.google.cloud.tools.jib.registry.LocalRegistry;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.Resources;
import java.io.IOException;
import java.net.URISyntaxException;
Expand All @@ -35,6 +37,8 @@
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.stream.Stream;
import org.hamcrest.CoreMatchers;
Expand Down Expand Up @@ -83,6 +87,8 @@ private void checkCompletion() {
private static final Logger logger = LoggerFactory.getLogger(ContainerizerIntegrationTest.class);
private static final String DISTROLESS_DIGEST =
"sha256:f488c213f278bc5f9ffe3ddf30c5dbb2303a15a74146b738d12453088e662880";
private static final String MULTI_PLATFORM_DIGEST =
"sha256:c737fc29fc2556d3377d6a719a9842a500777fce35a7f1299acd569c73f65247";
private static final double DOUBLE_ERROR_MARGIN = 1e-10;

public static ImmutableList<FileEntriesLayer> fakeLayerConfigurations;
Expand Down Expand Up @@ -228,6 +234,30 @@ public void testSteps_forBuildToDockerRegistry_multipleTags()
new Command("docker", "run", "--rm", imageReference3).run());
}

@Test
public void testSteps_forBuildToDockerRegistry_multiplePlatforms()
throws IOException, InterruptedException, ExecutionException, RegistryException,
CacheDirectoryCreationException, InvalidImageReferenceException {
buildImage(
ImageReference.of("gcr.io", "distroless/java17-debian11", MULTI_PLATFORM_DIGEST),
Containerizer.to(RegistryImage.named(dockerHost + ":5000/testimage:testtag")),
Collections.singletonList("testtag"),
ImmutableSet.of(new Platform("amd64", "linux"), new Platform("arm64", "linux")));

String imageReference = dockerHost + ":5000/testimage:testtag-amd64";
localRegistry.pull(imageReference);
assertDockerInspect(imageReference);
Assert.assertEquals(
"Hello, world. An argument.\n", new Command("docker", "run", "--rm", imageReference).run());

String imageReference2 = dockerHost + ":5000/testimage:testtag-arm64";
localRegistry.pull(imageReference2);
assertDockerInspect(imageReference2);
Assert.assertEquals(
"Hello, world. An argument.\n",
new Command("docker", "run", "--rm", imageReference2).run());
}

@Test
public void testSteps_forBuildToDockerRegistry_skipExistingDigest()
throws IOException, InterruptedException, ExecutionException, RegistryException,
Expand Down Expand Up @@ -336,6 +366,16 @@ private JibContainer buildImage(
ImageReference baseImage, Containerizer containerizer, List<String> additionalTags)
throws IOException, InterruptedException, RegistryException, CacheDirectoryCreationException,
ExecutionException {
return buildImage(baseImage, containerizer, additionalTags, null);
}

private JibContainer buildImage(
ImageReference baseImage,
Containerizer containerizer,
List<String> additionalTags,
Set<Platform> additionalPlatforms)
throws IOException, InterruptedException, RegistryException, CacheDirectoryCreationException,
ExecutionException {
JibContainerBuilder containerBuilder =
Jib.from(baseImage)
.setEntrypoint(
Expand All @@ -346,6 +386,9 @@ private JibContainer buildImage(
.setExposedPorts(Ports.parse(Arrays.asList("1000", "2000-2002/tcp", "3000/udp")))
.setLabels(ImmutableMap.of("key1", "value1", "key2", "value2"))
.setFileEntriesLayers(fakeLayerConfigurations);
if (Objects.nonNull(additionalPlatforms)) {
containerBuilder.setPlatforms(additionalPlatforms);
}

containerizer
.setAllowInsecureRegistries(true)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ public static Containerizer to(DockerClient dockerClient, DockerDaemonImage dock
@Nullable private String toolVersion = DEFAULT_TOOL_VERSION;
private boolean alwaysCacheBaseImage = false;
private ListMultimap<String, String> registryMirrors = ArrayListMultimap.create();
private boolean enablePlatformTags = false;

/** Instantiate with {@link #to}. */
private Containerizer(
Expand Down Expand Up @@ -339,6 +340,18 @@ public Containerizer addRegistryMirrors(String registry, List<String> mirrors) {
return this;
}

/**
* Enables adding platform tags to images.
*
* @param enablePlatformTags if {@code true}, adds platform tags to images. If {@code false}
* images are not tagged with platform tags.
* @return this
*/
public Containerizer setEnablePlatformTags(boolean enablePlatformTags) {
this.enablePlatformTags = enablePlatformTags;
return this;
}

Set<String> getAdditionalTags() {
return ImmutableSet.copyOf(additionalTags);
}
Expand Down Expand Up @@ -394,6 +407,10 @@ boolean getAlwaysCacheBaseImage() {
return alwaysCacheBaseImage;
}

boolean getEnablePlatformTags() {
return enablePlatformTags;
}

String getDescription() {
return description;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -736,6 +736,7 @@ BuildContext toBuildContext(Containerizer containerizer) throws CacheDirectoryCr
.setEventHandlers(containerizer.buildEventHandlers())
.setAlwaysCacheBaseImage(containerizer.getAlwaysCacheBaseImage())
.setRegistryMirrors(containerizer.getRegistryMirrors())
.setEnablePlatformTags(containerizer.getEnablePlatformTags())
.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ private void verifyTo(Containerizer containerizer) throws CacheDirectoryCreation
.setBaseImageLayersCache(Paths.get("base/image/layers"))
.setApplicationLayersCache(Paths.get("application/layers"))
.setAllowInsecureRegistries(true)
.setToolName("tool");
.setToolName("tool")
.setEnablePlatformTags(true);

Assert.assertEquals(ImmutableSet.of("tag1", "tag2"), containerizer.getAdditionalTags());
Assert.assertTrue(containerizer.getExecutorService().isPresent());
Expand All @@ -77,6 +78,7 @@ private void verifyTo(Containerizer containerizer) throws CacheDirectoryCreation
Paths.get("application/layers"), containerizer.getApplicationLayersCacheDirectory());
Assert.assertTrue(containerizer.getAllowInsecureRegistries());
Assert.assertEquals("tool", containerizer.getToolName());
Assert.assertTrue(containerizer.getEnablePlatformTags());
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,8 @@ public void testToBuildContext()
.setApplicationLayersCache(Paths.get("application/layers"))
.setExecutorService(executorService)
.addEventHandler(mockJibEventConsumer)
.setAlwaysCacheBaseImage(false);
.setAlwaysCacheBaseImage(false)
.setEnablePlatformTags(true);

ImageConfiguration baseImageConfiguration =
ImageConfiguration.builder(ImageReference.parse("base/image"))
Expand Down Expand Up @@ -220,6 +221,8 @@ public void testToBuildContext()
ImmutableSet.of("latest", "tag1", "tag2"), buildContext.getAllTargetImageTags());
Assert.assertEquals("toolName", buildContext.getToolName());
Assert.assertFalse(buildContext.getAlwaysCacheBaseImage());

Assert.assertTrue(buildContext.getEnablePlatformTags());
}

@Test
Expand Down
1 change: 1 addition & 0 deletions jib-gradle-plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@ Property | Type | Default | Description
`auth` | [`auth`](#auth-closure) | *None* | Specifies credentials directly (alternative to `credHelper`).
`credHelper` | `String` | *None* | Specifies a credential helper that can authenticate pushing the target image. This parameter can either be configured as an absolute path to the credential helper executable or as a credential helper suffix (following `docker-credential-`).
`tags` | `List<String>` | *None* | Additional tags to push to.
`enablePlatformTags` | `boolean` | `false` | Sets whether to automatically add architecture suffix to tags for platform-specific images when building multi-platform images. For example, when building amd64 and arm64 images for a given tag, the final tags will be `<tag>-amd64` and `<tag>-arm64`.

<a name="auth-closure"></a>`auth` is a closure with the following properties (see [Using Specific Credentials](#using-specific-credentials)):

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -222,4 +222,9 @@ public List<? extends ExtensionConfiguration> getPluginExtensions() {
public List<? extends PlatformConfiguration> getPlatforms() {
return jibExtension.getFrom().getPlatforms().get();
}

@Override
public boolean getEnablePlatformTags() {
return jibExtension.getTo().getEnablePlatformTags();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ public class TargetImageParameters {
private final Property<String> image;
private final SetProperty<String> tags;
private final CredHelperParameters credHelper;
private boolean enablePlatformTags;

@Inject
public TargetImageParameters(ObjectFactory objectFactory) {
Expand Down Expand Up @@ -123,4 +124,16 @@ public AuthParameters getAuth() {
public void auth(Action<? super AuthParameters> action) {
action.execute(auth);
}

@Input
public boolean getEnablePlatformTags() {
if (System.getProperty(PropertyNames.ENABLE_PLATFORM_TAGS) != null) {
return Boolean.parseBoolean(System.getProperty(PropertyNames.ENABLE_PLATFORM_TAGS));
}
return enablePlatformTags;
}

public void setEnablePlatformTags(boolean expand) {
enablePlatformTags = expand;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ public void testGetters() {
Mockito.when(toCredHelperParameters.getEnvironment())
.thenReturn(Collections.singletonMap("ENV_VARIABLE", "Value2"));
Mockito.when(targetImageParameters.getCredHelper()).thenReturn(toCredHelperParameters);
Mockito.when(targetImageParameters.getEnablePlatformTags()).thenReturn(true);

Mockito.when(containerParameters.getAppRoot()).thenReturn("/app/root");
Mockito.when(containerParameters.getArgs()).thenReturn(Arrays.asList("--log", "info"));
Expand Down Expand Up @@ -150,5 +151,6 @@ public void testGetters() {
Assert.assertEquals(Paths.get("id/path"), rawConfiguration.getImageIdOutputPath());
Assert.assertEquals(Paths.get("json/path"), rawConfiguration.getImageJsonOutputPath());
Assert.assertEquals(Paths.get("tar/path"), rawConfiguration.getTarOutputPath());
Assert.assertTrue(rawConfiguration.getEnablePlatformTags());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,8 @@ public void testProperties() {
assertThat(testJibExtension.getTo().getTags()).containsExactly("tag1", "tag2", "tag3");
System.setProperty("jib.to.credHelper", "credHelper");
assertThat(testJibExtension.getTo().getCredHelper().getHelper()).isEqualTo("credHelper");
System.setProperty("jib.to.enablePlatformTags", "true");
assertThat(testJibExtension.getTo().getEnablePlatformTags()).isTrue();

System.setProperty("jib.container.appRoot", "appRoot");
assertThat(testJibExtension.getContainer().getAppRoot()).isEqualTo("appRoot");
Expand Down
1 change: 1 addition & 0 deletions jib-maven-plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,7 @@ Property | Type | Default | Description
`auth` | [`auth`](#auth-object) | *None* | Specifies credentials directly (alternative to `credHelper`).
`credHelper` | string | *None* | Specifies a credential helper that can authenticate pushing the target image. This parameter can either be configured as an absolute path to the credential helper executable or as a credential helper suffix (following `docker-credential-`).
`tags` | list | *None* | Additional tags to push to.
`enablePlatformTags` | `boolean` | `false` | Sets whether to automatically add architecture suffix to tags for platform-specific images when building multi-platform images. For example, when building amd64 and arm64 images for a given tag, the final tags will be `<tag>-amd64` and `<tag>-arm64`.

<a name="auth-object"></a>`auth` is an object with the following properties (see [Using Specific Credentials](#using-specific-credentials)):

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package com.google.cloud.tools.jib.maven;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import com.google.cloud.tools.jib.Command;
Expand Down Expand Up @@ -714,7 +715,8 @@ public void testExecute_springBootPackaged()
@Test
public void testExecute_multiPlatformBuild()
throws IOException, VerificationException, RegistryException {
String targetImage = dockerHost + ":5000/multiplatform:maven" + System.nanoTime();
String standardTag = "maven" + System.nanoTime();
String targetImage = dockerHost + ":5000/multiplatform:" + standardTag;

Verifier verifier = new Verifier(simpleTestProject.getProjectRoot().toString());
verifier.setSystemProperty("_TARGET_IMAGE", targetImage);
Expand All @@ -723,6 +725,7 @@ public void testExecute_multiPlatformBuild()
verifier.setSystemProperty("jib.to.auth.password", "testpassword");
verifier.setSystemProperty("sendCredentialsOverHttp", "true");
verifier.setSystemProperty("jib.allowInsecureRegistries", "true");
verifier.setSystemProperty("jib.to.enablePlatformTags", "true");

verifier.setAutoclean(false);
verifier.addCliOption("--file=pom-multiplatform-build.xml");
Expand Down Expand Up @@ -773,6 +776,9 @@ public void testExecute_multiPlatformBuild()
assertThat(arm64Config).contains("\"architecture\":\"arm64\"");
assertThat(arm64Config).contains("\"os\":\"linux\"");

assertEquals(
arm64Digest, registryClient.pullManifest(standardTag + "-arm64").getDigest().toString());

// Check amd64/linux container config.
List<String> amd64Digests = v22ManifestList.getDigestsForPlatform("amd64", "linux");
assertThat(amd64Digests.size()).isEqualTo(1);
Expand All @@ -787,6 +793,9 @@ public void testExecute_multiPlatformBuild()
String amd64Config = Blobs.writeToString(amd64ConfigBlob);
assertThat(amd64Config).contains("\"architecture\":\"amd64\"");
assertThat(amd64Config).contains("\"os\":\"linux\"");

assertEquals(
amd64Digest, registryClient.pullManifest(standardTag + "-amd64").getDigest().toString());
}

private void buildAndRunWebApp(TestProject project, String label, String pomXml)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,7 @@ public static class ToConfiguration {
@Parameter private List<String> tags = Collections.emptyList();
@Parameter private CredHelperParameters credHelper = new CredHelperParameters();
@Parameter private ToAuthConfiguration auth = new ToAuthConfiguration();
@Parameter private boolean enablePlatformTags;

public void set(String image) {
this.image = image;
Expand Down Expand Up @@ -811,6 +812,14 @@ boolean isSkipped() {
return skip;
}

boolean getEnablePlatformTags() {
final String property = getProperty(PropertyNames.ENABLE_PLATFORM_TAGS);
if (property != null) {
return Boolean.parseBoolean(property);
}
return to.enablePlatformTags;
}

List<ExtensionParameters> getPluginExtensions() {
return pluginExtensions;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -219,4 +219,9 @@ public List<? extends ExtensionConfiguration> getPluginExtensions() {
public List<? extends PlatformConfiguration> getPlatforms() {
return jibPluginConfiguration.getPlatforms();
}

@Override
public boolean getEnablePlatformTags() {
return jibPluginConfiguration.getEnablePlatformTags();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1054,6 +1054,8 @@ private static void configureContainerizer(
PropertyNames.APPLICATION_CACHE, projectProperties.getDefaultCacheDirectory()));

rawConfiguration.getToTags().forEach(containerizer::withAdditionalTag);

containerizer.setEnablePlatformTags(rawConfiguration.getEnablePlatformTags());
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ public class PropertyNames {
public static final String TO_IMAGE = "jib.to.image";
public static final String TO_IMAGE_ALTERNATE = "image";
public static final String TO_TAGS = "jib.to.tags";
public static final String ENABLE_PLATFORM_TAGS = "jib.to.enablePlatformTags";
public static final String TO_CRED_HELPER = "jib.to.credHelper";
public static final String TO_AUTH_USERNAME = "jib.to.auth.username";
public static final String TO_AUTH_PASSWORD = "jib.to.auth.password";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,4 +134,6 @@ interface CredHelperConfiguration {
Path getImageJsonOutputPath();

List<? extends ExtensionConfiguration> getPluginExtensions();

boolean getEnablePlatformTags();
}
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,8 @@ public void testPluginConfigurationProcessor_defaults()
verify(containerizer).setBaseImageLayersCache(Containerizer.DEFAULT_BASE_CACHE_DIRECTORY);
verify(containerizer).setApplicationLayersCache(appCacheDirectory);

verify(containerizer).setEnablePlatformTags(false);

ArgumentMatcher<LogEvent> isLogWarn = logEvent -> logEvent.getLevel() == LogEvent.Level.WARN;
verify(logger, never()).accept(argThat(isLogWarn));
}
Expand Down