diff --git a/CHANGELOG.md b/CHANGELOG.md index 85e8ef81da..35149ec496 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ Usage: ./scripts/extract-changelog-for-version.sh 1.3.37 5 ``` ### 1.11-SNAPSHOT +* Fix #1316: Add support for adding InitContainers via plugin configuration * Fix #1459: Route Generation should support `8443` as default web port * Fix #1546: Migrate to JUnit5 testing framework * Fix #1858: Properties in image name not replaced diff --git a/jkube-kit/build/api/src/test/java/org/eclipse/jkube/kit/build/api/assembly/AssemblyConfigurationUtilsTest.java b/jkube-kit/build/api/src/test/java/org/eclipse/jkube/kit/build/api/assembly/AssemblyConfigurationUtilsTest.java index ce5df243ef..75ff425fb8 100644 --- a/jkube-kit/build/api/src/test/java/org/eclipse/jkube/kit/build/api/assembly/AssemblyConfigurationUtilsTest.java +++ b/jkube-kit/build/api/src/test/java/org/eclipse/jkube/kit/build/api/assembly/AssemblyConfigurationUtilsTest.java @@ -25,7 +25,7 @@ import org.eclipse.jkube.kit.common.AssemblyFile; import org.eclipse.jkube.kit.common.AssemblyFileEntry; import org.eclipse.jkube.kit.common.AssemblyFileSet; -import org.eclipse.jkube.kit.config.image.build.Arguments; +import org.eclipse.jkube.kit.common.Arguments; import org.eclipse.jkube.kit.config.image.build.BuildConfiguration; import org.junit.jupiter.api.Test; diff --git a/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/RunService.java b/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/RunService.java index ec0769bca6..de67b691d7 100644 --- a/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/RunService.java +++ b/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/RunService.java @@ -39,7 +39,7 @@ import org.eclipse.jkube.kit.common.KitLogger; import org.eclipse.jkube.kit.common.util.EnvUtil; import org.eclipse.jkube.kit.config.image.ImageConfiguration; -import org.eclipse.jkube.kit.config.image.build.Arguments; +import org.eclipse.jkube.kit.common.Arguments; import java.io.File; import java.util.ArrayList; diff --git a/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/access/ContainerCreateConfig.java b/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/access/ContainerCreateConfig.java index eb66e9a12e..7b212a4407 100644 --- a/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/access/ContainerCreateConfig.java +++ b/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/access/ContainerCreateConfig.java @@ -24,7 +24,7 @@ import org.eclipse.jkube.kit.common.JsonFactory; import org.eclipse.jkube.kit.common.util.EnvUtil; -import org.eclipse.jkube.kit.config.image.build.Arguments; +import org.eclipse.jkube.kit.common.Arguments; import com.google.gson.JsonArray; import com.google.gson.JsonObject; diff --git a/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/access/DockerAccess.java b/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/access/DockerAccess.java index 8aa28d5e49..6728ecb87e 100644 --- a/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/access/DockerAccess.java +++ b/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/access/DockerAccess.java @@ -24,7 +24,7 @@ import org.eclipse.jkube.kit.build.service.docker.access.log.LogGetHandle; import org.eclipse.jkube.kit.build.service.docker.access.log.LogOutputSpec; import org.eclipse.jkube.kit.common.archive.ArchiveCompression; -import org.eclipse.jkube.kit.config.image.build.Arguments; +import org.eclipse.jkube.kit.common.Arguments; import java.io.File; import java.util.List; diff --git a/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/access/hc/DockerAccessWithHcClient.java b/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/access/hc/DockerAccessWithHcClient.java index 18a4554a9b..63cb0229a4 100644 --- a/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/access/hc/DockerAccessWithHcClient.java +++ b/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/access/hc/DockerAccessWithHcClient.java @@ -62,7 +62,7 @@ import org.eclipse.jkube.kit.common.util.EnvUtil; import org.eclipse.jkube.kit.config.image.ImageName; import org.eclipse.jkube.kit.common.archive.ArchiveCompression; -import org.eclipse.jkube.kit.config.image.build.Arguments; +import org.eclipse.jkube.kit.common.Arguments; import org.apache.commons.io.IOUtils; import org.apache.http.HttpHeaders; import org.apache.http.client.HttpResponseException; diff --git a/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/config/handler/compose/DockerComposeServiceWrapper.java b/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/config/handler/compose/DockerComposeServiceWrapper.java index 3253755904..b08d6ef221 100644 --- a/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/config/handler/compose/DockerComposeServiceWrapper.java +++ b/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/config/handler/compose/DockerComposeServiceWrapper.java @@ -20,7 +20,7 @@ import org.eclipse.jkube.kit.config.image.RunVolumeConfiguration; import org.eclipse.jkube.kit.config.image.UlimitConfig; import org.eclipse.jkube.kit.build.service.docker.helper.VolumeBindingUtil; -import org.eclipse.jkube.kit.config.image.build.Arguments; +import org.eclipse.jkube.kit.common.Arguments; import java.io.File; import java.util.ArrayList; diff --git a/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/config/handler/property/PropertyConfigHandler.java b/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/config/handler/property/PropertyConfigHandler.java index 4d2e60357c..5640949a98 100644 --- a/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/config/handler/property/PropertyConfigHandler.java +++ b/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/config/handler/property/PropertyConfigHandler.java @@ -27,7 +27,7 @@ import org.eclipse.jkube.kit.common.util.EnvUtil; import org.eclipse.jkube.kit.common.util.JKubeProjectUtil; import org.eclipse.jkube.kit.common.util.MapUtil; -import org.eclipse.jkube.kit.config.image.build.Arguments; +import org.eclipse.jkube.kit.common.Arguments; import org.eclipse.jkube.kit.common.AssemblyConfiguration; import org.eclipse.jkube.kit.config.image.build.BuildConfiguration; import org.eclipse.jkube.kit.config.image.build.HealthCheckConfiguration; diff --git a/jkube-kit/build/service/jib/src/main/java/org/eclipse/jkube/kit/service/jib/JibServiceUtil.java b/jkube-kit/build/service/jib/src/main/java/org/eclipse/jkube/kit/service/jib/JibServiceUtil.java index 1e666d77ee..c90c32446e 100644 --- a/jkube-kit/build/service/jib/src/main/java/org/eclipse/jkube/kit/service/jib/JibServiceUtil.java +++ b/jkube-kit/build/service/jib/src/main/java/org/eclipse/jkube/kit/service/jib/JibServiceUtil.java @@ -37,7 +37,7 @@ import org.eclipse.jkube.kit.common.KitLogger; import org.eclipse.jkube.kit.config.image.ImageConfiguration; import org.eclipse.jkube.kit.config.image.ImageName; -import org.eclipse.jkube.kit.config.image.build.Arguments; +import org.eclipse.jkube.kit.common.Arguments; import org.eclipse.jkube.kit.config.image.build.BuildConfiguration; import com.google.cloud.tools.jib.api.CacheDirectoryCreationException; diff --git a/jkube-kit/build/service/jib/src/test/java/org/eclipse/jkube/kit/service/jib/JibServiceUtilTest.java b/jkube-kit/build/service/jib/src/test/java/org/eclipse/jkube/kit/service/jib/JibServiceUtilTest.java index 80fd64f415..d4efa21942 100644 --- a/jkube-kit/build/service/jib/src/test/java/org/eclipse/jkube/kit/service/jib/JibServiceUtilTest.java +++ b/jkube-kit/build/service/jib/src/test/java/org/eclipse/jkube/kit/service/jib/JibServiceUtilTest.java @@ -31,7 +31,7 @@ import org.eclipse.jkube.kit.common.JKubeConfiguration; import org.eclipse.jkube.kit.common.JavaProject; import org.eclipse.jkube.kit.config.image.ImageConfiguration; -import org.eclipse.jkube.kit.config.image.build.Arguments; +import org.eclipse.jkube.kit.common.Arguments; import org.eclipse.jkube.kit.config.image.build.BuildConfiguration; import com.google.cloud.tools.jib.api.JibContainerBuilder; diff --git a/jkube-kit/config/image/src/main/java/org/eclipse/jkube/kit/config/image/build/Arguments.java b/jkube-kit/common/src/main/java/org/eclipse/jkube/kit/common/Arguments.java similarity index 98% rename from jkube-kit/config/image/src/main/java/org/eclipse/jkube/kit/config/image/build/Arguments.java rename to jkube-kit/common/src/main/java/org/eclipse/jkube/kit/common/Arguments.java index ac68792ed6..5c4bdfb60c 100644 --- a/jkube-kit/config/image/src/main/java/org/eclipse/jkube/kit/config/image/build/Arguments.java +++ b/jkube-kit/common/src/main/java/org/eclipse/jkube/kit/common/Arguments.java @@ -11,7 +11,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation */ -package org.eclipse.jkube.kit.config.image.build; +package org.eclipse.jkube.kit.common; import java.io.Serializable; import java.util.ArrayList; diff --git a/jkube-kit/common/src/test/java/org/eclipse/jkube/kit/common/ArgumentsTest.java b/jkube-kit/common/src/test/java/org/eclipse/jkube/kit/common/ArgumentsTest.java new file mode 100644 index 0000000000..012d8ae152 --- /dev/null +++ b/jkube-kit/common/src/test/java/org/eclipse/jkube/kit/common/ArgumentsTest.java @@ -0,0 +1,123 @@ +/** + * Copyright (c) 2019 Red Hat, Inc. + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at: + * + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + */ +package org.eclipse.jkube.kit.common; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + +class ArgumentsTest { + + @Test + void testShellArgWithSpaceEscape() { + String[] testSubject = { "java", "-jar", "$HOME/name with space.jar" }; + Arguments arg = Arguments.builder().shell("java -jar $HOME/name\\ with\\ space.jar").build(); + assertThat(arg.asStrings()).containsExactly(testSubject); + } + + @Test + void set_whenInvoked_shouldSetShell() { + // Given + Arguments arg = new Arguments(); + + // When + arg.set("sleep 10"); + + // Then + assertThat(arg.getShell()).isEqualTo("sleep 10"); + assertThat(arg.asStrings()).containsExactly("sleep", "10"); + } + + @Test + void exec_withSpaceEscapeArg_shouldReturnCorrectCmd() { + // Given + Arguments arg = Arguments.builder().exec(Arrays.asList("wget", "-O", "/work-dir/index.html", "http://info.cern.ch")).build(); + + // When + List result = arg.asStrings(); + + // Then + assertThat(result).containsExactly("wget", "-O", "/work-dir/index.html", "http://info.cern.ch"); + } + + @Test + void execInlined_withSpaceEscapeArg_shouldReturnCorrectCmd() { + // Given + List execInline = Arrays.asList("wget", "-O", "/work-dir/index.html", "http://info.cern.ch"); + Arguments arg = new Arguments(null, null, execInline); + + // When + List result = arg.asStrings(); + + // Then + assertThat(arg.getExecInlined()).isEqualTo(execInline); + assertThat(result).containsExactly("wget", "-O", "/work-dir/index.html", "http://info.cern.ch"); + } + + @Test + void getExec_whenInvoked_thenReturnsEitherExecOrExecInlined() { + // Given + Arguments arg = new Arguments(null, null, Arrays.asList("wget", "-O", "/work-dir/index.html", "http://info.cern.ch")); + + // When + List exec = arg.getExec(); + + // Then + assertThat(exec).containsExactly("wget", "-O", "/work-dir/index.html", "http://info.cern.ch"); + } + + @Test + void validate_withValidObjects_thenNoExceptionThrown() { + // Given + Arguments shell = new Arguments("sleep 10", null, null); + Arguments exec = new Arguments(null, Arrays.asList("sleep", "10"), null); + Arguments execInlined = new Arguments(null, null, Arrays.asList("sleep", "10")); + + // When + shell.validate(); + exec.validate(); + execInlined.validate(); + + // Then + assertThat(shell).isNotNull(); + assertThat(exec).isNotNull(); + assertThat(execInlined).isNotNull(); + } + + @Test + void validate_whenWrongObjectProvided_thenThrowException() { + // Given + Arguments arg = new Arguments(); + + // When + Then + assertThatIllegalArgumentException() + .isThrownBy(arg::validate) + .withMessage("Argument conflict: either shell or args should be specified and only in one form."); + } + + @Test + void equalsAndHashCodeShouldMatch() { + // Given + Arguments a1 = Arguments.builder().shell("sleep 10").build(); + Arguments a2 = Arguments.builder().shell("sleep 10").build(); + // When + Then + assertThat(a1) + .isEqualTo(a2) + .hasSameHashCodeAs(a2); + } +} diff --git a/jkube-kit/config/image/src/main/java/org/eclipse/jkube/kit/config/image/RunImageConfiguration.java b/jkube-kit/config/image/src/main/java/org/eclipse/jkube/kit/config/image/RunImageConfiguration.java index 2edba4e279..378c1a2ec4 100644 --- a/jkube-kit/config/image/src/main/java/org/eclipse/jkube/kit/config/image/RunImageConfiguration.java +++ b/jkube-kit/config/image/src/main/java/org/eclipse/jkube/kit/config/image/RunImageConfiguration.java @@ -26,7 +26,7 @@ import lombok.Getter; import lombok.NoArgsConstructor; import org.eclipse.jkube.kit.common.util.EnvUtil; -import org.eclipse.jkube.kit.config.image.build.Arguments; +import org.eclipse.jkube.kit.common.Arguments; /** * @author roland diff --git a/jkube-kit/config/image/src/main/java/org/eclipse/jkube/kit/config/image/build/BuildConfiguration.java b/jkube-kit/config/image/src/main/java/org/eclipse/jkube/kit/config/image/build/BuildConfiguration.java index 6cb72814f9..741961a9d8 100644 --- a/jkube-kit/config/image/src/main/java/org/eclipse/jkube/kit/config/image/build/BuildConfiguration.java +++ b/jkube-kit/config/image/src/main/java/org/eclipse/jkube/kit/config/image/build/BuildConfiguration.java @@ -32,6 +32,7 @@ import lombok.NoArgsConstructor; import lombok.Setter; import lombok.Singular; +import org.eclipse.jkube.kit.common.Arguments; import org.eclipse.jkube.kit.common.AssemblyConfiguration; import org.eclipse.jkube.kit.common.archive.ArchiveCompression; import org.eclipse.jkube.kit.common.util.EnvUtil; diff --git a/jkube-kit/config/image/src/main/java/org/eclipse/jkube/kit/config/image/build/DockerFileBuilder.java b/jkube-kit/config/image/src/main/java/org/eclipse/jkube/kit/config/image/build/DockerFileBuilder.java index d95c6a4675..07ebf47f2b 100644 --- a/jkube-kit/config/image/src/main/java/org/eclipse/jkube/kit/config/image/build/DockerFileBuilder.java +++ b/jkube-kit/config/image/src/main/java/org/eclipse/jkube/kit/config/image/build/DockerFileBuilder.java @@ -31,6 +31,7 @@ import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; +import org.eclipse.jkube.kit.common.Arguments; /** * Create a dockerfile diff --git a/jkube-kit/config/image/src/main/java/org/eclipse/jkube/kit/config/image/build/HealthCheckConfiguration.java b/jkube-kit/config/image/src/main/java/org/eclipse/jkube/kit/config/image/build/HealthCheckConfiguration.java index 3258a1ebb5..4f3d544c12 100644 --- a/jkube-kit/config/image/src/main/java/org/eclipse/jkube/kit/config/image/build/HealthCheckConfiguration.java +++ b/jkube-kit/config/image/src/main/java/org/eclipse/jkube/kit/config/image/build/HealthCheckConfiguration.java @@ -18,6 +18,7 @@ import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; +import org.eclipse.jkube.kit.common.Arguments; import java.io.Serializable; import java.util.Optional; diff --git a/jkube-kit/config/image/src/test/java/org/eclipse/jkube/kit/config/image/build/ArgumentsTest.java b/jkube-kit/config/image/src/test/java/org/eclipse/jkube/kit/config/image/build/ArgumentsTest.java deleted file mode 100644 index 51c19dffd1..0000000000 --- a/jkube-kit/config/image/src/test/java/org/eclipse/jkube/kit/config/image/build/ArgumentsTest.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright (c) 2019 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at: - * - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.jkube.kit.config.image.build; - -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -class ArgumentsTest { - - @Test - void testShellArgWithSpaceEscape() { - String[] testSubject = { "java", "-jar", "$HOME/name with space.jar" }; - Arguments arg = Arguments.builder().shell("java -jar $HOME/name\\ with\\ space.jar").build(); - assertThat(arg.asStrings()).containsExactly(testSubject); - } -} diff --git a/jkube-kit/config/image/src/test/java/org/eclipse/jkube/kit/config/image/build/DockerFileBuilderTest.java b/jkube-kit/config/image/src/test/java/org/eclipse/jkube/kit/config/image/build/DockerFileBuilderTest.java index b2b366bd23..31e057309b 100644 --- a/jkube-kit/config/image/src/test/java/org/eclipse/jkube/kit/config/image/build/DockerFileBuilderTest.java +++ b/jkube-kit/config/image/src/test/java/org/eclipse/jkube/kit/config/image/build/DockerFileBuilderTest.java @@ -25,6 +25,7 @@ import java.util.regex.Pattern; import org.apache.commons.io.IOUtils; +import org.eclipse.jkube.kit.common.Arguments; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; diff --git a/jkube-kit/config/image/src/test/java/org/eclipse/jkube/kit/config/image/build/HealthCheckConfigTest.java b/jkube-kit/config/image/src/test/java/org/eclipse/jkube/kit/config/image/build/HealthCheckConfigTest.java index 8d17df1dae..3e47808563 100644 --- a/jkube-kit/config/image/src/test/java/org/eclipse/jkube/kit/config/image/build/HealthCheckConfigTest.java +++ b/jkube-kit/config/image/src/test/java/org/eclipse/jkube/kit/config/image/build/HealthCheckConfigTest.java @@ -16,6 +16,7 @@ import java.util.stream.Stream; +import org.eclipse.jkube.kit.common.Arguments; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; diff --git a/jkube-kit/config/resource/src/main/java/org/eclipse/jkube/kit/config/resource/ControllerResourceConfig.java b/jkube-kit/config/resource/src/main/java/org/eclipse/jkube/kit/config/resource/ControllerResourceConfig.java new file mode 100644 index 0000000000..0f6aa94330 --- /dev/null +++ b/jkube-kit/config/resource/src/main/java/org/eclipse/jkube/kit/config/resource/ControllerResourceConfig.java @@ -0,0 +1,45 @@ +/** + * Copyright (c) 2019 Red Hat, Inc. + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at: + * + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + */ +package org.eclipse.jkube.kit.config.resource; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Singular; + +import java.util.List; +import java.util.Map; + +@Builder(toBuilder = true) +@AllArgsConstructor +@NoArgsConstructor +@Getter +@EqualsAndHashCode +public class ControllerResourceConfig { + private Map env; + @Singular + private List volumes; + @Singular + private List initContainers; + private String controllerName; + private ProbeConfig liveness; + private ProbeConfig readiness; + private ProbeConfig startup; + private boolean containerPrivileged; + private String imagePullPolicy; + private Integer replicas; + private String restartPolicy; +} diff --git a/jkube-kit/config/resource/src/main/java/org/eclipse/jkube/kit/config/resource/InitContainerConfig.java b/jkube-kit/config/resource/src/main/java/org/eclipse/jkube/kit/config/resource/InitContainerConfig.java new file mode 100644 index 0000000000..6dc33fa51f --- /dev/null +++ b/jkube-kit/config/resource/src/main/java/org/eclipse/jkube/kit/config/resource/InitContainerConfig.java @@ -0,0 +1,38 @@ +/** + * Copyright (c) 2019 Red Hat, Inc. + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at: + * + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + */ +package org.eclipse.jkube.kit.config.resource; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.eclipse.jkube.kit.common.Arguments; + +import java.util.List; +import java.util.Map; + +@Builder(toBuilder = true) +@AllArgsConstructor +@NoArgsConstructor +@Getter +@EqualsAndHashCode +public class InitContainerConfig { + private Map env; + private String name; + private String imageName; + private String imagePullPolicy; + private Arguments cmd; + private List volumes; +} diff --git a/jkube-kit/config/resource/src/main/java/org/eclipse/jkube/kit/config/resource/MappingConfig.java b/jkube-kit/config/resource/src/main/java/org/eclipse/jkube/kit/config/resource/MappingConfig.java index bde31c8d49..8d2b4a6f31 100644 --- a/jkube-kit/config/resource/src/main/java/org/eclipse/jkube/kit/config/resource/MappingConfig.java +++ b/jkube-kit/config/resource/src/main/java/org/eclipse/jkube/kit/config/resource/MappingConfig.java @@ -13,20 +13,23 @@ */ package org.eclipse.jkube.kit.config.resource; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Builder(toBuilder = true) +@AllArgsConstructor +@NoArgsConstructor +@Getter +@EqualsAndHashCode public class MappingConfig { private String kind; private String filenameTypes; - public String getKind() { - return kind; - } - - public String getFilenameTypes() { - return filenameTypes; - } - public String[] getFilenamesAsArray() { if (this.filenameTypes == null) { return new String[0]; @@ -37,5 +40,4 @@ public String[] getFilenamesAsArray() { public boolean isValid() { return kind != null && filenameTypes != null && filenameTypes.length() > 0; } - } diff --git a/jkube-kit/config/resource/src/main/java/org/eclipse/jkube/kit/config/resource/ResourceConfig.java b/jkube-kit/config/resource/src/main/java/org/eclipse/jkube/kit/config/resource/ResourceConfig.java index 53958d8288..3c26c2a0c1 100644 --- a/jkube-kit/config/resource/src/main/java/org/eclipse/jkube/kit/config/resource/ResourceConfig.java +++ b/jkube-kit/config/resource/src/main/java/org/eclipse/jkube/kit/config/resource/ResourceConfig.java @@ -19,7 +19,9 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Singular; +import org.apache.commons.lang3.StringUtils; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; @@ -34,37 +36,67 @@ @EqualsAndHashCode public class ResourceConfig { + /** + * @deprecated Use nested controller configuration instead + */ + @Deprecated private Map env; private MetaDataConfig labels; private MetaDataConfig annotations; + /** + * @deprecated Use nested controller configuration instead + */ + @Deprecated @Singular private List volumes; @Singular private List secrets; + /** + * @deprecated Use nested controller configuration instead + */ + @Deprecated private String controllerName; @Singular private List services; @Singular private List remotes; private ConfigMap configMap; + /** + * @deprecated Use nested controller configuration instead + */ + @Deprecated private ProbeConfig liveness; + /** + * @deprecated Use nested controller configuration instead + */ + @Deprecated private ProbeConfig readiness; + /** + * @deprecated Use nested controller configuration instead + */ + @Deprecated private ProbeConfig startup; private MetricsConfig metrics; /** * Run container in privileged mode. + * @deprecated Use nested controller configuration instead */ + @Deprecated private boolean containerPrivileged; /** * How images should be pulled (maps to ImagePullPolicy). + * @deprecated Use nested controller configuration instead */ + @Deprecated private String imagePullPolicy; /** * Number of replicas to create. + * @deprecated Use nested controller configuration instead */ + @Deprecated private Integer replicas; private String namespace; private String serviceAccount; @@ -76,13 +108,74 @@ public class ResourceConfig { private Boolean createExternalUrls; private IngressConfig ingress; private String routeDomain; + /** + * @deprecated Use nested controller configuration instead + */ + @Deprecated private String restartPolicy; + private ControllerResourceConfig controller; + private List controllers; public static ResourceConfigBuilder toBuilder(ResourceConfig original) { return Optional.ofNullable(original).orElse(new ResourceConfig()).toBuilder(); } - // TODO: SCC + public ControllerResourceConfig getController() { + if (controller == null) { + controller = createNewControllerConfig(); + } + return controller; + } + + public List getControllers() { + if (controllers == null || controllers.isEmpty()) { + controllers = new ArrayList<>(); + controllers.add(createNewControllerConfig()); + } + return controllers; + } + + private ControllerResourceConfig createNewControllerConfig() { + if (controller == null) { + controller = createNewControllerConfigFromLegacy(); + } + return controller; + } + + private ControllerResourceConfig createNewControllerConfigFromLegacy() { + ControllerResourceConfig.ControllerResourceConfigBuilder builder = ControllerResourceConfig.builder(); + if (env != null && !env.isEmpty()) { + builder.env(env); + } + if (volumes != null) { + builder.volumes(volumes); + } + if (StringUtils.isNotBlank(controllerName)) { + builder.controllerName(controllerName); + } + if (liveness != null) { + builder.liveness(liveness); + } + if (readiness != null) { + builder.readiness(readiness); + } + if (startup != null) { + builder.startup(startup); + } + if (imagePullPolicy != null) { + builder.imagePullPolicy(imagePullPolicy); + } + if (replicas != null) { + builder.replicas(replicas); + } + if (StringUtils.isNotBlank(restartPolicy)) { + builder.restartPolicy(restartPolicy); + } + builder.containerPrivileged(containerPrivileged); + return builder.build(); + } + + // TODO: SCC // =============================== // TODO: diff --git a/jkube-kit/config/resource/src/test/java/org/eclipse/jkube/kit/config/resource/ControllerResourceConfigTest.java b/jkube-kit/config/resource/src/test/java/org/eclipse/jkube/kit/config/resource/ControllerResourceConfigTest.java new file mode 100644 index 0000000000..5785d07daf --- /dev/null +++ b/jkube-kit/config/resource/src/test/java/org/eclipse/jkube/kit/config/resource/ControllerResourceConfigTest.java @@ -0,0 +1,135 @@ +/** + * Copyright (c) 2019 Red Hat, Inc. + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at: + * + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + */ +package org.eclipse.jkube.kit.config.resource; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.assertj.core.api.InstanceOfAssertFactories; +import org.eclipse.jkube.kit.common.Arguments; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Collections; + +import static org.assertj.core.api.Assertions.assertThat; + +class ControllerResourceConfigTest { + @Test + void rawDeserialization() throws IOException { + // Given + final ObjectMapper mapper = new ObjectMapper(); + // When + final ControllerResourceConfig result = mapper.readValue( + getClass().getResourceAsStream("/controller-config.json"), + ControllerResourceConfig.class); + // Then + assertControllerResourceConfig(result); + } + + @Test + void builder() { + // Given + ControllerResourceConfig.ControllerResourceConfigBuilder initContainerConfigBuilder = ControllerResourceConfig.builder() + .env(Collections.singletonMap("KEY1", "VALUE1")) + .controllerName("test-controller") + .containerPrivileged(false) + .imagePullPolicy("IfNotPresent") + .replicas(3) + .restartPolicy("OnFailure") + .liveness(ProbeConfig.builder() + .getUrl("http://:8080/q/health") + .initialDelaySeconds(3) + .timeoutSeconds(3) + .build()) + .readiness(ProbeConfig.builder() + .getUrl("http://:8080/q/health") + .initialDelaySeconds(3) + .timeoutSeconds(3) + .build()) + .startup(ProbeConfig.builder() + .getUrl("http://:8080/q/health") + .initialDelaySeconds(3) + .timeoutSeconds(3) + .build()) + .initContainer(InitContainerConfig.builder() + .env(Collections.singletonMap("FOO", "BAR")) + .name("init1") + .imageName("busybox:latest") + .imagePullPolicy("IfNotPresent") + .cmd(Arguments.builder().exec(Arrays.asList("sleep", "10")).build()) + .volumes(Collections.singletonList(VolumeConfig.builder() + .name("workdir") + .path("/work-dir") + .build())).build()) + .volumes(Collections.singletonList(VolumeConfig.builder() + .name("workdir") + .type("emptyDir") + .path("/work-dir") + .build())); + + // When + ControllerResourceConfig controllerResourceConfig = initContainerConfigBuilder.build(); + + // Then + assertControllerResourceConfig(controllerResourceConfig); + } + + @Test + void equalsAndHashCodeShouldMatch() { + // Given + ControllerResourceConfig c1 = ControllerResourceConfig.builder().controllerName("test-controller").build(); + ControllerResourceConfig c2 = ControllerResourceConfig.builder().controllerName("test-controller").build(); + // When + Then + assertThat(c1) + .isEqualTo(c2) + .hasSameHashCodeAs(c2); + } + + private void assertControllerResourceConfig(ControllerResourceConfig controllerResourceConfig) { + assertThat(controllerResourceConfig) + .hasFieldOrPropertyWithValue("env", Collections.singletonMap("KEY1", "VALUE1")) + .hasFieldOrPropertyWithValue("controllerName", "test-controller") + .hasFieldOrPropertyWithValue("imagePullPolicy", "IfNotPresent") + .hasFieldOrPropertyWithValue("containerPrivileged", false) + .hasFieldOrPropertyWithValue("replicas", 3) + .hasFieldOrPropertyWithValue("restartPolicy", "OnFailure") + .satisfies(c -> assertProbe(c.getLiveness())) + .satisfies(c -> assertProbe(c.getReadiness())) + .satisfies(c -> assertProbe(c.getStartup())) + .satisfies(c -> assertThat(c.getInitContainers()) + .singleElement(InstanceOfAssertFactories.type(InitContainerConfig.class)) + .hasFieldOrPropertyWithValue("env", Collections.singletonMap("FOO", "BAR")) + .hasFieldOrPropertyWithValue("name", "init1") + .hasFieldOrPropertyWithValue("imageName", "busybox:latest") + .hasFieldOrPropertyWithValue("imagePullPolicy", "IfNotPresent") + .hasFieldOrPropertyWithValue("cmd", Arguments.builder().exec(Arrays.asList("sleep", "10")).build()) + .extracting(InitContainerConfig::getVolumes) + .asList() + .singleElement(InstanceOfAssertFactories.type(VolumeConfig.class)) + .hasFieldOrPropertyWithValue("name", "workdir") + .hasFieldOrPropertyWithValue("path", "/work-dir")) + .satisfies(c -> assertThat(c.getVolumes()) + .singleElement(InstanceOfAssertFactories.type(VolumeConfig.class)) + .hasFieldOrPropertyWithValue("name", "workdir") + .hasFieldOrPropertyWithValue("type", "emptyDir") + .hasFieldOrPropertyWithValue("path", "/work-dir")); + } + + private void assertProbe(ProbeConfig probeConfig) { + assertThat(probeConfig) + .hasFieldOrPropertyWithValue("getUrl", "http://:8080/q/health") + .hasFieldOrPropertyWithValue("initialDelaySeconds", 3) + .hasFieldOrPropertyWithValue("timeoutSeconds", 3); + } +} diff --git a/jkube-kit/config/resource/src/test/java/org/eclipse/jkube/kit/config/resource/InitContainerConfigTest.java b/jkube-kit/config/resource/src/test/java/org/eclipse/jkube/kit/config/resource/InitContainerConfigTest.java new file mode 100644 index 0000000000..5542740c92 --- /dev/null +++ b/jkube-kit/config/resource/src/test/java/org/eclipse/jkube/kit/config/resource/InitContainerConfigTest.java @@ -0,0 +1,85 @@ +/** + * Copyright (c) 2019 Red Hat, Inc. + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at: + * + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + */ +package org.eclipse.jkube.kit.config.resource; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.assertj.core.api.InstanceOfAssertFactories; +import org.eclipse.jkube.kit.common.Arguments; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Collections; + +import static org.assertj.core.api.Assertions.assertThat; + +class InitContainerConfigTest { + @Test + void rawDeserialization() throws IOException { + // Given + final ObjectMapper mapper = new ObjectMapper(); + // When + final InitContainerConfig result = mapper.readValue( + getClass().getResourceAsStream("/initcontainer-config.json"), + InitContainerConfig.class); + // Then + assertInitContainerConfig(result); + } + + @Test + void builder() { + // Given + InitContainerConfig.InitContainerConfigBuilder initContainerConfigBuilder = InitContainerConfig.builder() + .env(Collections.singletonMap("FOO", "BAR")) + .name("init1") + .imageName("busybox:latest") + .imagePullPolicy("IfNotPresent") + .cmd(Arguments.builder().exec(Arrays.asList("sleep", "10")).build()) + .volumes(Collections.singletonList(VolumeConfig.builder() + .name("workdir") + .path("/work-dir") + .build())); + + // When + InitContainerConfig initContainerConfig = initContainerConfigBuilder.build(); + + // Then + assertInitContainerConfig(initContainerConfig); + } + + @Test + void equalsAndHashCodeShouldMatch() { + // Given + InitContainerConfig ic1 = InitContainerConfig.builder().name("init1").build(); + InitContainerConfig ic2 = InitContainerConfig.builder().name("init1").build(); + // When + Then + assertThat(ic1) + .isEqualTo(ic2) + .hasSameHashCodeAs(ic2); + } + + private void assertInitContainerConfig(InitContainerConfig initContainerConfig) { + assertThat(initContainerConfig) + .hasFieldOrPropertyWithValue("env", Collections.singletonMap("FOO", "BAR")) + .hasFieldOrPropertyWithValue("name", "init1") + .hasFieldOrPropertyWithValue("imageName", "busybox:latest") + .hasFieldOrPropertyWithValue("imagePullPolicy", "IfNotPresent") + .hasFieldOrPropertyWithValue("cmd", Arguments.builder().exec(Arrays.asList("sleep", "10")).build()) + .extracting(InitContainerConfig::getVolumes) + .asList() + .singleElement(InstanceOfAssertFactories.type(VolumeConfig.class)) + .hasFieldOrPropertyWithValue("name", "workdir") + .hasFieldOrPropertyWithValue("path", "/work-dir"); + } +} diff --git a/jkube-kit/config/resource/src/test/java/org/eclipse/jkube/kit/config/resource/MappingConfigTest.java b/jkube-kit/config/resource/src/test/java/org/eclipse/jkube/kit/config/resource/MappingConfigTest.java new file mode 100644 index 0000000000..21e61070c1 --- /dev/null +++ b/jkube-kit/config/resource/src/test/java/org/eclipse/jkube/kit/config/resource/MappingConfigTest.java @@ -0,0 +1,94 @@ +/** + * Copyright (c) 2019 Red Hat, Inc. + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at: + * + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + */ +package org.eclipse.jkube.kit.config.resource; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +import static org.assertj.core.api.Assertions.assertThat; + +class MappingConfigTest { + @Test + void rawDeserialization() throws IOException { + // Given + final ObjectMapper mapper = new ObjectMapper(); + // When + final MappingConfig result = mapper.readValue( + getClass().getResourceAsStream("/mapping-config.json"), + MappingConfig.class); + // Then + assertThat(result) + .hasFieldOrPropertyWithValue("kind", "CronTab") + .hasFieldOrPropertyWithValue("filenameTypes", "crontab,cr"); + } + + @Test + void getFilenamesAsArray_whenNoTypesPresent_thenReturnsEmptyArray() { + // Given + final MappingConfig config = MappingConfig.builder().kind("Foo").build(); + // When + Then + assertThat(config.getFilenamesAsArray()) + .isEmpty(); + } + + @Test + void getFilenamesAsArray_whenTypesPresent_thenReturnsArray() { + // Given + final MappingConfig config = MappingConfig.builder().kind("Foo").filenameTypes("foo,foos").build(); + // When + Then + assertThat(config.getFilenamesAsArray()) + .contains("foo", "foos"); + } + + @Test + void isValid_withInvalidObject_shouldReturnFalse() { + // Given + MappingConfig config = MappingConfig.builder() + .build(); + + // When + boolean result = config.isValid(); + + // Then + assertThat(result).isFalse(); + } + + @Test + void isValid_withValidObject_shouldReturnTrue() { + // Given + MappingConfig config = MappingConfig.builder() + .kind("Foo") + .filenameTypes("foos") + .build(); + + // When + boolean result = config.isValid(); + + // Then + assertThat(result).isTrue(); + } + + @Test + void equalsAndHashCodeShouldMatch() { + // Given + MappingConfig mc1 = MappingConfig.builder().kind("Foo").filenameTypes("foos").build(); + MappingConfig mc2 = MappingConfig.builder().kind("Foo").filenameTypes("foos").build(); + // When + Then + assertThat(mc1) + .isEqualTo(mc2) + .hasSameHashCodeAs(mc2); + } +} diff --git a/jkube-kit/config/resource/src/test/java/org/eclipse/jkube/kit/config/resource/ResourceConfigTest.java b/jkube-kit/config/resource/src/test/java/org/eclipse/jkube/kit/config/resource/ResourceConfigTest.java new file mode 100644 index 0000000000..1577b89533 --- /dev/null +++ b/jkube-kit/config/resource/src/test/java/org/eclipse/jkube/kit/config/resource/ResourceConfigTest.java @@ -0,0 +1,187 @@ +/** + * Copyright (c) 2019 Red Hat, Inc. + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at: + * + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + */ +package org.eclipse.jkube.kit.config.resource; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.assertj.core.api.InstanceOfAssertFactories; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.Collections; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +class ResourceConfigTest { + @Test + void getController_whenInvoked_shouldMergeLegacyOptionsWithController() { + // Given + ProbeConfig probeConfig = ProbeConfig.builder().build(); + ResourceConfig resourceConfig = ResourceConfig.builder() + .env(Collections.singletonMap("FOO", "BAR")) + .liveness(probeConfig) + .readiness(probeConfig) + .startup(probeConfig) + .controllerName("test-controller") + .imagePullPolicy("Always") + .restartPolicy("OnFailure") + .replicas(2) + .containerPrivileged(false) + .build(); + + // When + ControllerResourceConfig controllerResourceConfig = resourceConfig.getController(); + + // Then + assertThat(controllerResourceConfig) + .hasFieldOrPropertyWithValue("controllerName", "test-controller") + .hasFieldOrPropertyWithValue("env", Collections.singletonMap("FOO", "BAR")) + .hasFieldOrPropertyWithValue("imagePullPolicy", "Always") + .hasFieldOrPropertyWithValue("replicas", 2) + .hasFieldOrPropertyWithValue("liveness", probeConfig) + .hasFieldOrPropertyWithValue("readiness", probeConfig) + .hasFieldOrPropertyWithValue("startup", probeConfig) + .hasFieldOrPropertyWithValue("restartPolicy", "OnFailure") + .hasFieldOrPropertyWithValue("containerPrivileged", false); + } + + @Test + void getControllers_whenInvoked_shouldMergeSingleControllerConfig() { + // Given + ResourceConfig resourceConfig = ResourceConfig.builder() + .controller(ControllerResourceConfig.builder() + .controllerName("test-controller") + .imagePullPolicy("Always") + .replicas(2) + .containerPrivileged(false) + .build()) + .build(); + + // When + List controllerConfigList = resourceConfig.getControllers(); + + // Then + assertThat(controllerConfigList) + .singleElement() + .hasFieldOrPropertyWithValue("controllerName", "test-controller") + .hasFieldOrPropertyWithValue("imagePullPolicy", "Always") + .hasFieldOrPropertyWithValue("replicas", 2) + .hasFieldOrPropertyWithValue("containerPrivileged", false); + } + + @Test + void toBuilder_whenProvidedNullObject_thenReturnsValidObject() { + assertThat(ResourceConfig.toBuilder(null)).isNotNull(); + } + + @Test + void rawDeserialization() throws IOException { + // Given + final ObjectMapper mapper = new ObjectMapper(); + // When + final ResourceConfig result = mapper.readValue( + getClass().getResourceAsStream("/resource-config.json"), + ResourceConfig.class); + // Then + assertThat(result) + .hasFieldOrPropertyWithValue("env", Collections.singletonMap("KEY1", "VALUE1")) + .hasFieldOrPropertyWithValue("controllerName", "test-controller") + .hasFieldOrPropertyWithValue("imagePullPolicy", "IfNotPresent") + .hasFieldOrPropertyWithValue("containerPrivileged", false) + .hasFieldOrPropertyWithValue("replicas", 3) + .hasFieldOrPropertyWithValue("restartPolicy", "OnFailure") + .hasFieldOrPropertyWithValue("remotes", Collections.singletonList("http://example.com/manifests/deployment.yaml")) + .hasFieldOrPropertyWithValue("namespace", "foo-ns") + .hasFieldOrPropertyWithValue("serviceAccount", "foo-sa") + .hasFieldOrPropertyWithValue("customResourceDefinitions", Collections.singletonList("crontab.sample.example.com")) + .hasFieldOrPropertyWithValue("createExternalUrls", true) + .hasFieldOrPropertyWithValue("routeDomain", "example.com") + .satisfies(r -> assertProbe(r.getLiveness())) + .satisfies(r -> assertProbe(r.getReadiness())) + .satisfies(r -> assertProbe(r.getStartup())) + .satisfies(r -> assertThat(r.getVolumes()) + .singleElement(InstanceOfAssertFactories.type(VolumeConfig.class)) + .hasFieldOrPropertyWithValue("name", "workdir") + .hasFieldOrPropertyWithValue("type", "emptyDir") + .hasFieldOrPropertyWithValue("path", "/work-dir")) + .satisfies(r -> assertThat(r.getLabels()) + .extracting(MetaDataConfig::getAll) + .hasFieldOrPropertyWithValue("label_key", "label_value")) + .satisfies(r -> assertThat(r.getAnnotations()) + .extracting(MetaDataConfig::getAll) + .hasFieldOrPropertyWithValue("annotation_key", "annotation_value")) + .satisfies(r -> assertThat(r.getSecrets()) + .singleElement(InstanceOfAssertFactories.type(SecretConfig.class)) + .hasFieldOrPropertyWithValue("name", "secret1") + .hasFieldOrPropertyWithValue("dockerServerId", "dockerhub")) + .satisfies(r -> assertThat(r.getServices()) + .singleElement(InstanceOfAssertFactories.type(ServiceConfig.class)) + .hasFieldOrPropertyWithValue("name", "service1") + .hasFieldOrPropertyWithValue("headless", true) + .extracting(ServiceConfig::getPorts) + .asList() + .singleElement() + .hasFieldOrPropertyWithValue("port", 8080)) + .satisfies(r -> assertThat(r.getConfigMap()) + .hasFieldOrPropertyWithValue("name", "configmap1") + .extracting(ConfigMap::getEntries) + .asList() + .singleElement(InstanceOfAssertFactories.type(ConfigMapEntry.class)) + .hasFieldOrPropertyWithValue("name", "entryKey") + .hasFieldOrPropertyWithValue("value", "entryValue")) + .satisfies(r -> assertThat(r.getServiceAccounts()) + .singleElement(InstanceOfAssertFactories.type(ServiceAccountConfig.class)) + .hasFieldOrPropertyWithValue("name", "foo-sa") + .hasFieldOrPropertyWithValue("deploymentRef", "foo-deployment")) + .satisfies(r -> assertThat(r.getOpenshiftBuildConfig()) + .hasFieldOrPropertyWithValue("limits.memory", "128Mi") + .hasFieldOrPropertyWithValue("limits.cpu", "500m") + .hasFieldOrPropertyWithValue("requests.memory", "64Mi") + .hasFieldOrPropertyWithValue("requests.cpu", "250m")) + .satisfies(r -> assertThat(r.getIngress()) + .hasFieldOrPropertyWithValue("ingressTlsConfigs", Collections.singletonList(IngressTlsConfig.builder() + .host("example.com") + .secretName("testsecret-tls") + .build())) + .extracting(IngressConfig::getIngressRules) + .asList() + .singleElement(InstanceOfAssertFactories.type(IngressRuleConfig.class)) + .hasFieldOrPropertyWithValue("host", "example.com") + .extracting(IngressRuleConfig::getPaths) + .asList() + .singleElement(InstanceOfAssertFactories.type(IngressRulePathConfig.class)) + .hasFieldOrPropertyWithValue("pathType", "Prefix") + .hasFieldOrPropertyWithValue("path", "/foo") + .hasFieldOrPropertyWithValue("serviceName", "service1") + .hasFieldOrPropertyWithValue("servicePort", 8080)); + } + + @Test + void equalsAndHashCodeShouldMatch() { + // Given + ResourceConfig rc1 = ResourceConfig.builder().namespace("ns1").build(); + ResourceConfig rc2 = ResourceConfig.builder().namespace("ns1").build(); + // When + Then + assertThat(rc1) + .isEqualTo(rc2) + .hasSameHashCodeAs(rc2); + } + + private void assertProbe(ProbeConfig probeConfig) { + assertThat(probeConfig) + .hasFieldOrPropertyWithValue("getUrl", "http://:8080/q/health") + .hasFieldOrPropertyWithValue("initialDelaySeconds", 3) + .hasFieldOrPropertyWithValue("timeoutSeconds", 3); + } +} diff --git a/jkube-kit/config/resource/src/test/resources/controller-config.json b/jkube-kit/config/resource/src/test/resources/controller-config.json new file mode 100644 index 0000000000..2e09f2f698 --- /dev/null +++ b/jkube-kit/config/resource/src/test/resources/controller-config.json @@ -0,0 +1,45 @@ +{ + "env": { + "KEY1": "VALUE1" + }, + "volumes": [{ + "name": "workdir", + "type": "emptyDir", + "path": "/work-dir" + }], + "controllerName": "test-controller", + "containerPrivileged": false, + "imagePullPolicy": "IfNotPresent", + "replicas": 3, + "restartPolicy": "OnFailure", + "initContainers": [{ + "name": "init1", + "env": { + "FOO": "BAR" + }, + "imageName": "busybox:latest", + "imagePullPolicy": "IfNotPresent", + "cmd": { + "exec": ["sleep", "10"] + }, + "volumes": [{ + "name": "workdir", + "path": "/work-dir" + }] + }], + "liveness": { + "getUrl": "http://:8080/q/health", + "initialDelaySeconds": 3, + "timeoutSeconds": 3 + }, + "readiness": { + "getUrl": "http://:8080/q/health", + "initialDelaySeconds": 3, + "timeoutSeconds": 3 + }, + "startup": { + "getUrl": "http://:8080/q/health", + "initialDelaySeconds": 3, + "timeoutSeconds": 3 + } +} \ No newline at end of file diff --git a/jkube-kit/config/resource/src/test/resources/initcontainer-config.json b/jkube-kit/config/resource/src/test/resources/initcontainer-config.json new file mode 100644 index 0000000000..20b9becf40 --- /dev/null +++ b/jkube-kit/config/resource/src/test/resources/initcontainer-config.json @@ -0,0 +1,15 @@ +{ + "name": "init1", + "env": { + "FOO": "BAR" + }, + "imageName": "busybox:latest", + "imagePullPolicy": "IfNotPresent", + "cmd": { + "exec": ["sleep", "10"] + }, + "volumes": [{ + "name": "workdir", + "path": "/work-dir" + }] +} \ No newline at end of file diff --git a/jkube-kit/config/resource/src/test/resources/mapping-config.json b/jkube-kit/config/resource/src/test/resources/mapping-config.json new file mode 100644 index 0000000000..38d8102971 --- /dev/null +++ b/jkube-kit/config/resource/src/test/resources/mapping-config.json @@ -0,0 +1,4 @@ +{ + "kind": "CronTab", + "filenameTypes": "crontab,cr" +} \ No newline at end of file diff --git a/jkube-kit/config/resource/src/test/resources/resource-config.json b/jkube-kit/config/resource/src/test/resources/resource-config.json new file mode 100644 index 0000000000..888b84d8eb --- /dev/null +++ b/jkube-kit/config/resource/src/test/resources/resource-config.json @@ -0,0 +1,138 @@ +{ + "env": { + "KEY1": "VALUE1" + }, + "labels": { + "all": { + "label_key": "label_value" + } + }, + "annotations": { + "all": { + "annotation_key": "annotation_value" + } + }, + "secrets": [{ + "name": "secret1", + "dockerServerId": "dockerhub" + }], + "services": [{ + "name": "service1", + "headless": true, + "ports": [{ + "port": 8080 + }] + }], + "remotes": ["http://example.com/manifests/deployment.yaml"], + "configMap": { + "name": "configmap1", + "entries": [{ + "name": "entryKey", + "value": "entryValue" + }] + }, + "volumes": [{ + "name": "workdir", + "type": "emptyDir", + "path": "/work-dir" + }], + "controllerName": "test-controller", + "containerPrivileged": false, + "imagePullPolicy": "IfNotPresent", + "replicas": 3, + "restartPolicy": "OnFailure", + "namespace": "foo-ns", + "serviceAccount": "foo-sa", + "serviceAccounts": [{ + "name": "foo-sa", + "deploymentRef": "foo-deployment" + }], + "customResourceDefinitions": ["crontab.sample.example.com"], + "createExternalUrls": true, + "routeDomain": "example.com", + "liveness": { + "getUrl": "http://:8080/q/health", + "initialDelaySeconds": 3, + "timeoutSeconds": 3 + }, + "readiness": { + "getUrl": "http://:8080/q/health", + "initialDelaySeconds": 3, + "timeoutSeconds": 3 + }, + "startup": { + "getUrl": "http://:8080/q/health", + "initialDelaySeconds": 3, + "timeoutSeconds": 3 + }, + "controller": { + "env": { + "KEY1": "VALUE1" + }, + "volumes": [{ + "name": "workdir", + "type": "emptyDir", + "path": "/work-dir" + }], + "controllerName": "test-controller", + "containerPrivileged": false, + "imagePullPolicy": "IfNotPresent", + "replicas": 3, + "restartPolicy": "OnFailure", + "initContainers": [{ + "name": "init1", + "env": { + "FOO": "BAR" + }, + "imageName": "busybox:latest", + "imagePullPolicy": "IfNotPresent", + "cmd": { + "exec": ["sleep", "10"] + }, + "volumes": [{ + "name": "workdir", + "path": "/work-dir" + }] + }], + "liveness": { + "getUrl": "http://:8080/q/health", + "initialDelaySeconds": 3, + "timeoutSeconds": 3 + }, + "readiness": { + "getUrl": "http://:8080/q/health", + "initialDelaySeconds": 3, + "timeoutSeconds": 3 + }, + "startup": { + "getUrl": "http://:8080/q/health", + "initialDelaySeconds": 3, + "timeoutSeconds": 3 + } + }, + "openshiftBuildConfig": { + "limits": { + "memory": "128Mi", + "cpu": "500m" + }, + "requests": { + "memory": "64Mi", + "cpu": "250m" + } + }, + "ingress": { + "ingressRules": [{ + "host": "example.com", + "paths": [{ + "pathType": "Prefix", + "path": "/foo", + "serviceName": "service1", + "servicePort": "8080" + }] + }], + "ingressTlsConfigs": [{ + "hosts": ["example.com"], + "secretName": "testsecret-tls" + }] + } +} \ No newline at end of file diff --git a/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/api/BaseEnricher.java b/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/api/BaseEnricher.java index a1f4bfd9ea..24e3f65b25 100644 --- a/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/api/BaseEnricher.java +++ b/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/api/BaseEnricher.java @@ -22,6 +22,7 @@ import org.eclipse.jkube.kit.common.Configs; import org.eclipse.jkube.kit.common.KitLogger; import org.eclipse.jkube.kit.common.PrefixedLogger; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; import org.eclipse.jkube.kit.config.resource.RuntimeMode; import org.eclipse.jkube.kit.config.resource.PlatformMode; import org.eclipse.jkube.kit.config.resource.ResourceConfig; @@ -148,29 +149,37 @@ protected Long getOpenshiftDeployTimeoutInSeconds(Long defaultValue) { /** * This method overrides the controller name value by the value provided in XML config. * - * @param resourceConfig resource config from plugin configuration + * @param controllerResourceConfig Controller Resource config from plugin configuration * @param defaultValue default value * @return string as controller name */ - protected String getControllerName(ResourceConfig resourceConfig, String defaultValue) { - return Optional.ofNullable(resourceConfig).map(ResourceConfig::getControllerName).orElse(defaultValue); + protected String getControllerName(ControllerResourceConfig controllerResourceConfig, String defaultValue) { + return Optional.ofNullable(controllerResourceConfig).map(ControllerResourceConfig::getControllerName).orElse(defaultValue); + } + + protected ControllerResourceConfig getControllerResourceConfig() { + ResourceConfig resourceConfig = getConfiguration().getResource(); + if (resourceConfig != null && resourceConfig.getController() != null) { + return resourceConfig.getController(); + } + return ControllerResourceConfig.builder().build(); } /** * This method overrides the ImagePullPolicy value by the value provided in * XML config. * - * @param resourceConfig resource config from plugin configuration + * @param controllerResourceConfig controller resource config from plugin configuration * @param enricherConfig Enricher specific configuration for ImagePullPolicy * @return string as image pull policy */ - protected String getImagePullPolicy(ResourceConfig resourceConfig, Configs.Config enricherConfig) { + protected String getImagePullPolicy(ControllerResourceConfig controllerResourceConfig, Configs.Config enricherConfig) { String imagePullPolicyFromProperty = getValueFromConfig(JKUBE_ENFORCED_IMAGE_PULL_POLICY, null); if (StringUtils.isNotBlank(imagePullPolicyFromProperty)) { return imagePullPolicyFromProperty; } - if (resourceConfig != null && StringUtils.isNotBlank(resourceConfig.getImagePullPolicy())) { - return resourceConfig.getImagePullPolicy(); + if (controllerResourceConfig != null && StringUtils.isNotBlank(controllerResourceConfig.getImagePullPolicy())) { + return controllerResourceConfig.getImagePullPolicy(); } final String imagePullPolicyFromEnricherConfig = enricherConfig != null ? getConfig(enricherConfig) : null; if (StringUtils.isNotBlank(imagePullPolicyFromEnricherConfig)) { @@ -196,12 +205,12 @@ protected boolean getCreateExternalUrls() { * topmost priority. * * @param builder kubernetes list builder containing objects - * @param xmlResourceConfig xml resource config from plugin configuration + * @param controllerResourceConfig xml resource config from plugin configuration * @param defaultValue default value * @return resolved replica count */ - protected static int getReplicaCount(KubernetesListBuilder builder, ResourceConfig xmlResourceConfig, int defaultValue) { - if (xmlResourceConfig != null) { + protected static int getReplicaCount(KubernetesListBuilder builder, ControllerResourceConfig controllerResourceConfig, int defaultValue) { + if (controllerResourceConfig != null) { final List items = Optional.ofNullable(builder) .map(KubernetesListBuilder::buildItems).orElse(Collections.emptyList()); for (HasMetadata item : items) { @@ -212,7 +221,7 @@ protected static int getReplicaCount(KubernetesListBuilder builder, ResourceConf return ((DeploymentConfig)item).getSpec().getReplicas(); } } - return xmlResourceConfig.getReplicas() != null ? xmlResourceConfig.getReplicas() : defaultValue; + return controllerResourceConfig.getReplicas() != null ? controllerResourceConfig.getReplicas() : defaultValue; } return defaultValue; } diff --git a/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/api/util/InitContainerHandler.java b/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/api/util/InitContainerHandler.java deleted file mode 100644 index ecfc98c6be..0000000000 --- a/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/api/util/InitContainerHandler.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright (c) 2019 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at: - * - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.jkube.kit.enricher.api.util; - -import java.util.List; - -import io.fabric8.kubernetes.api.model.Container; -import io.fabric8.kubernetes.api.model.PodTemplateSpecBuilder; -import org.eclipse.jkube.kit.common.KitLogger; - -/** - * @author roland - * @since 07/02/17 - */ -public class InitContainerHandler { - - public static final String INIT_CONTAINER_ANNOTATION = "pod.alpha.kubernetes.io/init-containers"; - - KitLogger log; - - public InitContainerHandler(KitLogger log) { - this.log = log; - } - - public boolean hasInitContainer(PodTemplateSpecBuilder builder, String name) { - return getInitContainer(builder, name) != null; - } - - public Container getInitContainer(PodTemplateSpecBuilder builder, String name) { - if (builder.hasSpec()) { - List initContainerList = builder.buildSpec().getInitContainers(); - for(Container initContainer : initContainerList) { - if(initContainer.getName().equals(name)) { - return initContainer; - } - } - } - return null; - } - - public void removeInitContainer(PodTemplateSpecBuilder builder, String initContainerName) { - Container initContainer = getInitContainer(builder, initContainerName); - if (initContainer != null) { - List initContainers = builder.buildSpec().getInitContainers(); - initContainers.remove(initContainer); - builder.editSpec().withInitContainers(initContainers).endSpec(); - } - } - - public void appendInitContainer(PodTemplateSpecBuilder builder, Container initContainer) { - String name = initContainer.getName(); - Container existing = getInitContainer(builder, name); - if (existing != null) { - if (existing.equals(initContainer)) { - log.warn("Trying to add init-container %s a second time. Ignoring ....", name); - return; - } else { - throw new IllegalArgumentException( - String.format("PodSpec %s already contains a different init container with name %s but can not add a second one with the same name. " + - "Please choose a different name for the init container", - builder.build().getMetadata().getName(), name)); - } - } - - ensureSpec(builder); - builder.editSpec().addToInitContainers(initContainer).endSpec(); - } - - private void ensureSpec(PodTemplateSpecBuilder obj) { - if (obj.buildSpec() == null) { - obj.withNewSpec().endSpec(); - } - } -} diff --git a/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/api/util/KubernetesResourceUtil.java b/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/api/util/KubernetesResourceUtil.java index 0f36393aec..6c73094da9 100644 --- a/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/api/util/KubernetesResourceUtil.java +++ b/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/api/util/KubernetesResourceUtil.java @@ -34,7 +34,12 @@ import java.util.Objects; import java.util.Set; import java.util.regex.Matcher; +import java.util.stream.Collectors; +import io.fabric8.kubernetes.api.model.ContainerBuilder; +import io.fabric8.kubernetes.api.model.PodTemplateSpecBuilder; +import io.fabric8.kubernetes.api.model.VolumeMount; +import io.fabric8.kubernetes.api.model.VolumeMountBuilder; import io.fabric8.kubernetes.client.utils.Serialization; import org.eclipse.jkube.kit.common.KitLogger; import org.eclipse.jkube.kit.common.util.KindFilenameMapperUtil; @@ -42,7 +47,9 @@ import org.eclipse.jkube.kit.common.util.MapUtil; import org.eclipse.jkube.kit.config.image.ImageConfiguration; import org.eclipse.jkube.kit.config.image.ImageName; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; import org.eclipse.jkube.kit.config.resource.GroupArtifactVersion; +import org.eclipse.jkube.kit.config.resource.InitContainerConfig; import org.eclipse.jkube.kit.config.resource.MappingConfig; import org.eclipse.jkube.kit.config.resource.PlatformMode; import org.eclipse.jkube.kit.config.resource.ResourceVersioning; @@ -68,10 +75,12 @@ import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.openshift.api.model.Build; import org.apache.commons.lang3.StringUtils; +import org.eclipse.jkube.kit.config.resource.VolumeConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.eclipse.jkube.kit.common.util.KubernetesHelper.FILENAME_PATTERN; +import static org.eclipse.jkube.kit.common.util.KubernetesHelper.convertToEnvVarList; /** * Utility class for handling Kubernetes resource descriptors @@ -736,7 +745,117 @@ public static ObjectMeta removeLabel(ObjectMeta metadata, String labelKey, Strin return metadata; } + public static boolean hasInitContainer(PodTemplateSpecBuilder builder, String name) { + return getInitContainer(builder, name) != null; + } + + public static Container getInitContainer(PodTemplateSpecBuilder builder, String name) { + if (Boolean.TRUE.equals(builder.hasSpec())) { + List initContainerList = builder.buildSpec().getInitContainers(); + for(Container initContainer : initContainerList) { + if(initContainer.getName().equals(name)) { + return initContainer; + } + } + } + return null; + } + + public static void removeInitContainer(PodTemplateSpecBuilder builder, String initContainerName) { + Container initContainer = getInitContainer(builder, initContainerName); + if (initContainer != null) { + List initContainers = builder.buildSpec().getInitContainers(); + initContainers.remove(initContainer); + builder.editSpec().withInitContainers(initContainers).endSpec(); + } + } + + public static void appendInitContainer(PodTemplateSpecBuilder builder, Container initContainer, KitLogger log) { + String name = initContainer.getName(); + Container existing = getInitContainer(builder, name); + if (existing != null) { + if (existing.equals(initContainer)) { + log.warn("Trying to add init-container %s a second time. Ignoring ....", name); + return; + } else { + throw new IllegalArgumentException( + String.format("PodSpec %s already contains a different init container with name %s but can not add a second one with the same name. " + + "Please choose a different name for the init container", + builder.build().getMetadata().getName(), name)); + } + } + ensureSpec(builder); + builder.editSpec().addToInitContainers(initContainer).endSpec(); + } + + public static List createNewInitContainersFromConfig(List initContainerConfigs) { + List initContainers = new ArrayList<>(); + for (InitContainerConfig initContainerConfig : initContainerConfigs) { + initContainers.add(createNewInitContainerFromConfig(initContainerConfig)); + } + return initContainers; + } + + public static Container createNewInitContainerFromConfig(InitContainerConfig initContainerConfig) { + ContainerBuilder containerBuilder = new ContainerBuilder(); + if (StringUtils.isNotBlank(initContainerConfig.getName())) { + containerBuilder.withName(initContainerConfig.getName()); + } + if (StringUtils.isNotBlank(initContainerConfig.getImageName())) { + containerBuilder.withImage(initContainerConfig.getImageName()); + } + if (StringUtils.isNotBlank(initContainerConfig.getImagePullPolicy())) { + containerBuilder.withImagePullPolicy(initContainerConfig.getImagePullPolicy()); + } + if (initContainerConfig.getCmd() != null) { + containerBuilder.withCommand(initContainerConfig.getCmd().asStrings()); + } + if (initContainerConfig.getVolumes() != null && !initContainerConfig.getVolumes().isEmpty()) { + containerBuilder.withVolumeMounts(createVolumeMountsFromConfig(initContainerConfig.getVolumes())); + } + if (initContainerConfig.getEnv() != null && !initContainerConfig.getEnv().isEmpty()) { + containerBuilder.withEnv(convertToEnvVarList(initContainerConfig.getEnv())); + } + + return containerBuilder.build(); + } + + public static boolean isContainerImage(ImageConfiguration imageConfig, ControllerResourceConfig config) { + return imageConfig.getBuildConfiguration() != null && !isInitContainerImage(imageConfig, config); + } + + public static boolean isInitContainerImage(ImageConfiguration imageConfiguration, ControllerResourceConfig config) { + if (config.getInitContainers() != null && !config.getInitContainers().isEmpty()) { + return config.getInitContainers() + .stream() + .map(InitContainerConfig::getImageName) + .collect(Collectors.toSet()) + .contains(imageConfiguration.getName()); + } + return false; + } + + private static void ensureSpec(PodTemplateSpecBuilder obj) { + if (obj.buildSpec() == null) { + obj.withNewSpec().endSpec(); + } + } + + private static List createVolumeMountsFromConfig(List volumeConfigs) { + List volumeMounts = new ArrayList<>(); + for (VolumeConfig vc : volumeConfigs) { + VolumeMountBuilder volumeMountBuilder = new VolumeMountBuilder(); + if (StringUtils.isNotBlank(vc.getName())) { + volumeMountBuilder.withName(vc.getName()); + } + if (StringUtils.isNotBlank(vc.getPath())) { + volumeMountBuilder.withMountPath(vc.getPath()); + } + volumeMounts.add(volumeMountBuilder.build()); + } + return volumeMounts; + } protected static HasMetadata mergeConfigMaps(ConfigMap cm1, ConfigMap cm2, KitLogger log, boolean switchOnLocalCustomisation) { ConfigMap cm1OrCopy = cm1; @@ -878,3 +997,4 @@ private static String sanitizeName(String name) { return name.replaceAll("[^a-zA-Z0-9-]", "").replaceFirst("^-*(.*?)-*$","$1"); } } + diff --git a/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/ContainerHandler.java b/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/ContainerHandler.java index 2f382c4f87..9b594c6596 100644 --- a/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/ContainerHandler.java +++ b/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/ContainerHandler.java @@ -33,7 +33,7 @@ import org.eclipse.jkube.kit.config.image.ImageName; import org.eclipse.jkube.kit.config.image.build.BuildConfiguration; import org.eclipse.jkube.kit.config.resource.GroupArtifactVersion; -import org.eclipse.jkube.kit.config.resource.ResourceConfig; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; import org.eclipse.jkube.kit.config.resource.VolumeConfig; import org.eclipse.jkube.kit.enricher.api.util.KubernetesResourceUtil; import org.apache.commons.lang3.StringUtils; @@ -42,6 +42,8 @@ import java.util.List; import java.util.Properties; +import static org.eclipse.jkube.kit.enricher.api.util.KubernetesResourceUtil.isContainerImage; + /** * @author roland */ @@ -57,11 +59,11 @@ public ContainerHandler(Properties configurationProperties, GroupArtifactVersion this.groupArtifactVersion = groupArtifactVersion; } - List getContainers(ResourceConfig config, List images) { + List getContainers(ControllerResourceConfig config, List images) { List ret = new ArrayList<>(); for (ImageConfiguration imageConfig : images) { - if (imageConfig.getBuildConfiguration() != null) { + if (isContainerImage(imageConfig, config)) { Probe livenessProbe = probeHandler.getProbe(config.getLiveness()); Probe readinessProbe = probeHandler.getProbe(config.getReadiness()); Probe startupProbe = probeHandler.getProbe(config.getStartup()); @@ -84,7 +86,7 @@ List getContainers(ResourceConfig config, List im return ret; } - private List getEnvVars(ResourceConfig config) { + private List getEnvVars(ControllerResourceConfig config) { List envVars = KubernetesHelper.convertToEnvVarList(config.getEnv()); // TODO: This should go into an extra enricher so that this behaviour can be switched on / off @@ -102,8 +104,7 @@ private List getEnvVars(ResourceConfig config) { return envVars; } - - private String getImagePullPolicy(ResourceConfig config) { + private String getImagePullPolicy(ControllerResourceConfig config) { String pullPolicy = config.getImagePullPolicy(); if (StringUtils.isBlank(pullPolicy) && this.groupArtifactVersion.isSnapshot()) { @@ -136,14 +137,13 @@ private Properties getPropertiesWithSystemOverrides(Properties configurationProp return configurationProperties; } - private SecurityContext createSecurityContext(ResourceConfig config) { + private SecurityContext createSecurityContext(ControllerResourceConfig config) { return new SecurityContextBuilder() .withPrivileged(config.isContainerPrivileged()) .build(); } - - private List getVolumeMounts(ResourceConfig config) { + private List getVolumeMounts(ControllerResourceConfig config) { List volumeConfigs = config.getVolumes(); List ret = new ArrayList<>(); @@ -194,5 +194,4 @@ private ContainerPort extractContainerPort(JsonObject portSpec) { } return portBuilder.build(); } - } diff --git a/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/ControllerHandler.java b/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/ControllerHandler.java index da95d4e01f..2586390a6c 100644 --- a/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/ControllerHandler.java +++ b/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/ControllerHandler.java @@ -17,15 +17,15 @@ import io.fabric8.kubernetes.api.model.KubernetesListBuilder; import io.fabric8.kubernetes.api.model.PodTemplateSpec; import org.eclipse.jkube.kit.config.image.ImageConfiguration; -import org.eclipse.jkube.kit.config.resource.ResourceConfig; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; import java.util.List; public interface ControllerHandler { - T get(ResourceConfig config, List images); + T get(ControllerResourceConfig config, List images); - PodTemplateSpec getPodTemplateSpec(ResourceConfig config, List images); + PodTemplateSpec getPodTemplateSpec(ControllerResourceConfig config, List images); PodTemplateSpec getPodTemplate(T controller); diff --git a/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/DaemonSetHandler.java b/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/DaemonSetHandler.java index 3f879dd64e..d29c006dbd 100644 --- a/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/DaemonSetHandler.java +++ b/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/DaemonSetHandler.java @@ -22,7 +22,7 @@ import io.fabric8.kubernetes.api.model.apps.DaemonSetSpec; import io.fabric8.kubernetes.api.model.apps.DaemonSetSpecBuilder; import org.eclipse.jkube.kit.config.image.ImageConfiguration; -import org.eclipse.jkube.kit.config.resource.ResourceConfig; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; import org.eclipse.jkube.kit.common.util.KubernetesHelper; import java.util.List; @@ -39,7 +39,7 @@ public class DaemonSetHandler implements ControllerHandler { } @Override - public DaemonSet get(ResourceConfig config, List images) { + public DaemonSet get(ControllerResourceConfig config, List images) { return new DaemonSetBuilder() .withMetadata(createDaemonSetMetaData(config)) .withSpec(createDaemonSetSpec(config, images)) @@ -47,7 +47,7 @@ public DaemonSet get(ResourceConfig config, List images) { } @Override - public PodTemplateSpec getPodTemplateSpec(ResourceConfig config, List images) { + public PodTemplateSpec getPodTemplateSpec(ControllerResourceConfig config, List images) { return get(config, images).getSpec().getTemplate(); } @@ -61,13 +61,13 @@ public void overrideReplicas(KubernetesListBuilder resources, int replicas) { // NOOP } - private ObjectMeta createDaemonSetMetaData(ResourceConfig config) { + private ObjectMeta createDaemonSetMetaData(ControllerResourceConfig config) { return new ObjectMetaBuilder() .withName(KubernetesHelper.validateKubernetesId(config.getControllerName(), "controller name")) .build(); } - private DaemonSetSpec createDaemonSetSpec(ResourceConfig config, List images) { + private DaemonSetSpec createDaemonSetSpec(ControllerResourceConfig config, List images) { return new DaemonSetSpecBuilder() .withTemplate(podTemplateHandler.getPodTemplate(config, config.getRestartPolicy(), images)) .build(); diff --git a/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/DeploymentConfigHandler.java b/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/DeploymentConfigHandler.java index f22df51aba..e9ab460814 100644 --- a/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/DeploymentConfigHandler.java +++ b/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/DeploymentConfigHandler.java @@ -17,7 +17,7 @@ import org.eclipse.jkube.kit.common.util.KubernetesHelper; import org.eclipse.jkube.kit.config.image.ImageConfiguration; -import org.eclipse.jkube.kit.config.resource.ResourceConfig; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; import io.fabric8.kubernetes.api.builder.TypedVisitor; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; @@ -37,7 +37,7 @@ public class DeploymentConfigHandler implements ControllerHandler images) { + public DeploymentConfig get(ControllerResourceConfig config, List images) { return new DeploymentConfigBuilder() .withMetadata(createMetaData(config)) .withSpec(createDeploymentConfigSpec(config, images)) @@ -45,7 +45,7 @@ public DeploymentConfig get(ResourceConfig config, List imag } @Override - public PodTemplateSpec getPodTemplateSpec(ResourceConfig config, List images) { + public PodTemplateSpec getPodTemplateSpec(ControllerResourceConfig config, List images) { return get(config, images).getSpec().getTemplate(); } @@ -64,13 +64,13 @@ public void visit(DeploymentConfigBuilder builder) { }); } - private ObjectMeta createMetaData(ResourceConfig config) { + private ObjectMeta createMetaData(ControllerResourceConfig config) { return new ObjectMetaBuilder() .withName(KubernetesHelper.validateKubernetesId(config.getControllerName(), "controller name")) .build(); } - private DeploymentConfigSpec createDeploymentConfigSpec(ResourceConfig config, List images) { + private DeploymentConfigSpec createDeploymentConfigSpec(ControllerResourceConfig config, List images) { return new DeploymentConfigSpecBuilder() .withReplicas(config.getReplicas()) .withTemplate(podTemplateHandler.getPodTemplate(config, config.getRestartPolicy(), images)) diff --git a/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/DeploymentHandler.java b/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/DeploymentHandler.java index fd7d7db4ce..13b64455d6 100644 --- a/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/DeploymentHandler.java +++ b/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/DeploymentHandler.java @@ -17,7 +17,7 @@ import org.eclipse.jkube.kit.common.util.KubernetesHelper; import org.eclipse.jkube.kit.config.image.ImageConfiguration; -import org.eclipse.jkube.kit.config.resource.ResourceConfig; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; import io.fabric8.kubernetes.api.builder.TypedVisitor; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; @@ -37,7 +37,7 @@ public class DeploymentHandler implements ControllerHandler { } @Override - public Deployment get(ResourceConfig config, List images) { + public Deployment get(ControllerResourceConfig config, List images) { return new DeploymentBuilder() .withMetadata(createDeploymentMetaData(config)) .withSpec(createDeploymentSpec(config, images)) @@ -45,7 +45,7 @@ public Deployment get(ResourceConfig config, List images) { } @Override - public PodTemplateSpec getPodTemplateSpec(ResourceConfig config, List images) { + public PodTemplateSpec getPodTemplateSpec(ControllerResourceConfig config, List images) { return get(config, images).getSpec().getTemplate(); } @@ -64,13 +64,13 @@ public void visit(DeploymentBuilder builder) { }); } - private ObjectMeta createDeploymentMetaData(ResourceConfig config) { + private ObjectMeta createDeploymentMetaData(ControllerResourceConfig config) { return new ObjectMetaBuilder() .withName(KubernetesHelper.validateKubernetesId(config.getControllerName(), "controller name")) .build(); } - private DeploymentSpec createDeploymentSpec(ResourceConfig config, List images) { + private DeploymentSpec createDeploymentSpec(ControllerResourceConfig config, List images) { return new DeploymentSpecBuilder() .withReplicas(config.getReplicas()) .withTemplate(podTemplateHandler.getPodTemplate(config, config.getRestartPolicy(), images)) diff --git a/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/JobHandler.java b/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/JobHandler.java index fd3fb97b91..65097b9078 100644 --- a/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/JobHandler.java +++ b/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/JobHandler.java @@ -22,7 +22,7 @@ import io.fabric8.kubernetes.api.model.batch.v1.JobSpec; import io.fabric8.kubernetes.api.model.batch.v1.JobSpecBuilder; import org.eclipse.jkube.kit.config.image.ImageConfiguration; -import org.eclipse.jkube.kit.config.resource.ResourceConfig; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; import org.eclipse.jkube.kit.common.util.KubernetesHelper; import java.util.List; @@ -43,7 +43,7 @@ public class JobHandler implements ControllerHandler { } @Override - public Job get(ResourceConfig config, List images) { + public Job get(ControllerResourceConfig config, List images) { return new JobBuilder() .withMetadata(createJobSpecMetaData(config)) .withSpec(createJobSpec(config, images)) @@ -51,7 +51,7 @@ public Job get(ResourceConfig config, List images) { } @Override - public PodTemplateSpec getPodTemplateSpec(ResourceConfig config, List images) { + public PodTemplateSpec getPodTemplateSpec(ControllerResourceConfig config, List images) { return get(config, images).getSpec().getTemplate(); } @@ -65,13 +65,13 @@ public void overrideReplicas(KubernetesListBuilder resources, int replicas) { // NOOP } - private ObjectMeta createJobSpecMetaData(ResourceConfig config) { + private ObjectMeta createJobSpecMetaData(ControllerResourceConfig config) { return new ObjectMetaBuilder() .withName(KubernetesHelper.validateKubernetesId(config.getControllerName(), "controller name")) .build(); } - private JobSpec createJobSpec(ResourceConfig config, List images) { + private JobSpec createJobSpec(ControllerResourceConfig config, List images) { return new JobSpecBuilder() .withTemplate(podTemplateHandler.getPodTemplate(config, Optional.ofNullable(config.getRestartPolicy()).orElse(DEFAULT_JOB_RESTART_POLICY), images)) .build(); diff --git a/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/PodTemplateHandler.java b/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/PodTemplateHandler.java index 0dc67cd1a5..b3f09ef693 100644 --- a/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/PodTemplateHandler.java +++ b/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/PodTemplateHandler.java @@ -21,13 +21,15 @@ import io.fabric8.kubernetes.api.model.PodTemplateSpecBuilder; import io.fabric8.kubernetes.api.model.Volume; import org.eclipse.jkube.kit.config.image.ImageConfiguration; -import org.eclipse.jkube.kit.config.resource.ResourceConfig; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; import org.eclipse.jkube.kit.config.resource.VolumeConfig; import org.eclipse.jkube.kit.config.resource.VolumeType; import java.util.ArrayList; import java.util.List; +import static org.eclipse.jkube.kit.enricher.api.util.KubernetesResourceUtil.createNewInitContainersFromConfig; + /** * @author roland */ @@ -39,7 +41,7 @@ public PodTemplateHandler(ContainerHandler containerHandler) { this.containerHandler = containerHandler; } - public PodTemplateSpec getPodTemplate(ResourceConfig config, String restartPolicy, List images) { + public PodTemplateSpec getPodTemplate(ControllerResourceConfig config, String restartPolicy, List images) { return new PodTemplateSpecBuilder() .withMetadata(createPodMetaData()) .withSpec(createPodSpec(config, restartPolicy, images)) @@ -50,17 +52,17 @@ private ObjectMeta createPodMetaData() { return new ObjectMetaBuilder().build(); } - private PodSpec createPodSpec(ResourceConfig config, String restartPolicy, List images) { + private PodSpec createPodSpec(ControllerResourceConfig config, String restartPolicy, List images) { return new PodSpecBuilder() - .withServiceAccountName(config.getServiceAccount()) .withRestartPolicy(restartPolicy) .withContainers(containerHandler.getContainers(config,images)) + .withInitContainers(createNewInitContainersFromConfig(config.getInitContainers())) .withVolumes(getVolumes(config)) .build(); } - private List getVolumes(ResourceConfig config) { + private List getVolumes(ControllerResourceConfig config) { List volumeConfigs = config.getVolumes(); List ret = new ArrayList<>(); diff --git a/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/ReplicaSetHandler.java b/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/ReplicaSetHandler.java index adf17b40d3..e5aeab7495 100644 --- a/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/ReplicaSetHandler.java +++ b/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/ReplicaSetHandler.java @@ -17,7 +17,7 @@ import org.eclipse.jkube.kit.common.util.KubernetesHelper; import org.eclipse.jkube.kit.config.image.ImageConfiguration; -import org.eclipse.jkube.kit.config.resource.ResourceConfig; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; import io.fabric8.kubernetes.api.builder.TypedVisitor; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; @@ -41,7 +41,7 @@ public class ReplicaSetHandler implements ControllerHandler { } @Override - public ReplicaSet get(ResourceConfig config, List images) { + public ReplicaSet get(ControllerResourceConfig config, List images) { return new ReplicaSetBuilder() .withMetadata(createRsMetaData(config)) .withSpec(createSpec(config, images)) @@ -49,7 +49,7 @@ public ReplicaSet get(ResourceConfig config, List images) { } @Override - public PodTemplateSpec getPodTemplateSpec(ResourceConfig config, List images) { + public PodTemplateSpec getPodTemplateSpec(ControllerResourceConfig config, List images) { return get(config, images).getSpec().getTemplate(); } @@ -68,13 +68,13 @@ public void visit(ReplicaSetBuilder builder) { }); } - private ObjectMeta createRsMetaData(ResourceConfig config) { + private ObjectMeta createRsMetaData(ControllerResourceConfig config) { return new ObjectMetaBuilder() .withName(KubernetesHelper.validateKubernetesId(config.getControllerName(), "controller name")) .build(); } - private ReplicaSetSpec createSpec(ResourceConfig config, List images) { + private ReplicaSetSpec createSpec(ControllerResourceConfig config, List images) { return new ReplicaSetSpecBuilder() .withReplicas(config.getReplicas()) .withTemplate(podTemplateHandler.getPodTemplate(config, config.getRestartPolicy(), images)) diff --git a/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/ReplicationControllerHandler.java b/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/ReplicationControllerHandler.java index 8c3cf0127f..234664f4e8 100644 --- a/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/ReplicationControllerHandler.java +++ b/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/ReplicationControllerHandler.java @@ -17,7 +17,7 @@ import org.eclipse.jkube.kit.common.util.KubernetesHelper; import org.eclipse.jkube.kit.config.image.ImageConfiguration; -import org.eclipse.jkube.kit.config.resource.ResourceConfig; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; import io.fabric8.kubernetes.api.builder.TypedVisitor; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; @@ -41,7 +41,7 @@ public class ReplicationControllerHandler implements ControllerHandler images) { + public ReplicationController get(ControllerResourceConfig config, List images) { return new ReplicationControllerBuilder() .withMetadata(createRcMetaData(config)) .withSpec(createRcSpec(config, images)) @@ -49,7 +49,7 @@ public ReplicationController get(ResourceConfig config, List } @Override - public PodTemplateSpec getPodTemplateSpec(ResourceConfig config, List images) { + public PodTemplateSpec getPodTemplateSpec(ControllerResourceConfig config, List images) { return get(config, images).getSpec().getTemplate(); } @@ -70,13 +70,13 @@ public void visit(ReplicationControllerBuilder builder) { // =========================================================== // TODO: "replica set" config used - private ObjectMeta createRcMetaData(ResourceConfig config) { + private ObjectMeta createRcMetaData(ControllerResourceConfig config) { return new ObjectMetaBuilder() .withName(KubernetesHelper.validateKubernetesId(config.getControllerName(), "replication controller name")) .build(); } - private ReplicationControllerSpec createRcSpec(ResourceConfig config, List images) { + private ReplicationControllerSpec createRcSpec(ControllerResourceConfig config, List images) { return new ReplicationControllerSpecBuilder() .withReplicas(config.getReplicas()) .withTemplate(podTemplateHandler.getPodTemplate(config, config.getRestartPolicy(), images)) diff --git a/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/StatefulSetHandler.java b/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/StatefulSetHandler.java index d93bff6750..d5d860dd9c 100644 --- a/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/StatefulSetHandler.java +++ b/jkube-kit/enricher/api/src/main/java/org/eclipse/jkube/kit/enricher/handler/StatefulSetHandler.java @@ -17,7 +17,7 @@ import org.eclipse.jkube.kit.common.util.KubernetesHelper; import org.eclipse.jkube.kit.config.image.ImageConfiguration; -import org.eclipse.jkube.kit.config.resource.ResourceConfig; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; import io.fabric8.kubernetes.api.builder.TypedVisitor; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; @@ -43,7 +43,7 @@ public class StatefulSetHandler implements ControllerHandler { } @Override - public StatefulSet get(ResourceConfig config, List images) { + public StatefulSet get(ControllerResourceConfig config, List images) { return new StatefulSetBuilder() .withMetadata(createStatefulSetMetaData(config)) .withSpec(createStatefulSetSpec(config, images)) @@ -51,7 +51,7 @@ public StatefulSet get(ResourceConfig config, List images) { } @Override - public PodTemplateSpec getPodTemplateSpec(ResourceConfig config, List images) { + public PodTemplateSpec getPodTemplateSpec(ControllerResourceConfig config, List images) { return get(config, images).getSpec().getTemplate(); } @@ -70,13 +70,13 @@ public void visit(StatefulSetBuilder builder) { }); } - private ObjectMeta createStatefulSetMetaData(ResourceConfig config) { + private ObjectMeta createStatefulSetMetaData(ControllerResourceConfig config) { return new ObjectMetaBuilder() .withName(KubernetesHelper.validateKubernetesId(config.getControllerName(), "controller name")) .build(); } - private StatefulSetSpec createStatefulSetSpec(ResourceConfig config, List images) { + private StatefulSetSpec createStatefulSetSpec(ControllerResourceConfig config, List images) { return new StatefulSetSpecBuilder() .withReplicas(config.getReplicas()) .withServiceName(config.getControllerName()) diff --git a/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/api/BaseEnricherGetReplicaCountTest.java b/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/api/BaseEnricherGetReplicaCountTest.java index 02fb7ffd9f..830acd6677 100644 --- a/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/api/BaseEnricherGetReplicaCountTest.java +++ b/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/api/BaseEnricherGetReplicaCountTest.java @@ -15,7 +15,7 @@ import io.fabric8.kubernetes.api.model.apps.DeploymentBuilder; import io.fabric8.openshift.api.model.DeploymentConfigBuilder; -import org.eclipse.jkube.kit.config.resource.ResourceConfig; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; @@ -41,8 +41,8 @@ class BaseEnricherGetReplicaCountTest { class NoListBuilder { @Test - @DisplayName("no resource config, should return default value") - void nullResourceConfig() { + @DisplayName("no controller resource config, should return default value") + void nullControllerResourceConfig() { // When int result = getReplicaCount(null, null, 42); // Then @@ -54,7 +54,7 @@ void nullResourceConfig() { @MethodSource("getReplicaCountsData") void resourceConfig(Integer replicas, int expectedReplicas) { // Given - final ResourceConfig resourceConfig = ResourceConfig.builder().replicas(replicas).build(); + final ControllerResourceConfig resourceConfig = ControllerResourceConfig.builder().replicas(replicas).build(); // When int result = getReplicaCount(null, resourceConfig, 42); // Then @@ -71,19 +71,19 @@ Stream getReplicaCountsData() { @Test - void withEmptyListBuilderAndEmptyResourceConfig_shouldReturnDefault() { + void withEmptyListBuilderAndEmptyControllerResourceConfig_shouldReturnDefault() { // When - int result = getReplicaCount(new KubernetesListBuilder().addToItems(new ConfigMapBuilder()), new ResourceConfig(), 1337); + int result = getReplicaCount(new KubernetesListBuilder().addToItems(new ConfigMapBuilder()), new ControllerResourceConfig(), 1337); // Then assertThat(result).isEqualTo(1337); } @Test - void withDeploymentConfigInListBuilderAndEmptyResourceConfig_shouldReturnDeploymentConfig() { + void withDeploymentConfigInListBuilderAndEmptyControllerResourceConfig_shouldReturnDeploymentConfig() { // Given final KubernetesListBuilder klb = new KubernetesListBuilder() .addToItems(new DeploymentConfigBuilder().withNewSpec().withReplicas(1).endSpec()); - final ResourceConfig resourceConfig = ResourceConfig.builder().replicas(313373).build(); + final ControllerResourceConfig resourceConfig = ControllerResourceConfig.builder().replicas(313373).build(); // When final int result = getReplicaCount(klb, resourceConfig, 1337); // Then @@ -91,12 +91,12 @@ void withDeploymentConfigInListBuilderAndEmptyResourceConfig_shouldReturnDeploym } @Test - void withDeploymentAndDeploymentConfigInListBuilderAndEmptyResourceConfig_shouldReturnValueInFirstItem() { + void withDeploymentAndDeploymentConfigInListBuilderAndEmptyControllerResourceConfig_shouldReturnValueInFirstItem() { // Given final KubernetesListBuilder klb = new KubernetesListBuilder() .addToItems(new DeploymentBuilder().withNewSpec().withReplicas(2).endSpec()) .addToItems(new DeploymentConfigBuilder().withNewSpec().withReplicas(1).endSpec()); - final ResourceConfig resourceConfig = ResourceConfig.builder().replicas(313373).build(); + final ControllerResourceConfig resourceConfig = ControllerResourceConfig.builder().replicas(313373).build(); // When int result = getReplicaCount(klb, resourceConfig, 1337); // Then diff --git a/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/api/BaseEnricherTest.java b/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/api/BaseEnricherTest.java index 968efa35ad..6f3b096c18 100644 --- a/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/api/BaseEnricherTest.java +++ b/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/api/BaseEnricherTest.java @@ -13,25 +13,392 @@ */ package org.eclipse.jkube.kit.enricher.api; +import io.fabric8.kubernetes.api.model.KubernetesListBuilder; +import io.fabric8.kubernetes.api.model.apps.DeploymentBuilder; +import io.fabric8.openshift.api.model.DeploymentConfigBuilder; +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.eclipse.jkube.kit.common.Configs; +import org.eclipse.jkube.kit.common.KitLogger; +import org.eclipse.jkube.kit.common.PrefixedLogger; +import org.eclipse.jkube.kit.config.image.ImageConfiguration; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; +import org.eclipse.jkube.kit.config.resource.PlatformMode; import org.eclipse.jkube.kit.config.resource.ResourceConfig; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Properties; + import static org.assertj.core.api.Assertions.assertThat; +import static org.eclipse.jkube.kit.enricher.api.BaseEnricher.getNamespace; +import static org.eclipse.jkube.kit.enricher.api.BaseEnricher.getReplicaCount; import static org.mockito.Answers.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class BaseEnricherTest { private BaseEnricher baseEnricher; - private ResourceConfig resourceConfig; + private ControllerResourceConfig controllerResourceConfig; private JKubeEnricherContext context; + private KitLogger logger; + private Properties properties; + + private static class TestEnricher extends BaseEnricher { + @AllArgsConstructor + public enum Config implements Configs.Config { + TEST_PROPERTY("testProperty", null); + @Getter + private final String key; + @Getter + private final String defaultValue; + } + public TestEnricher(EnricherContext enricherContext) { + super(enricherContext, "test-enricher"); + } + } @BeforeEach void setup() { - resourceConfig = mock(ResourceConfig.class, RETURNS_DEEP_STUBS); + logger = new KitLogger.SilentLogger(); + controllerResourceConfig = mock(ControllerResourceConfig.class, RETURNS_DEEP_STUBS); context = mock(JKubeEnricherContext.class, RETURNS_DEEP_STUBS); - baseEnricher = new BaseEnricher(context, "base-enricher"); + properties = new Properties(); + when(context.getConfiguration().getImages()).thenReturn(Collections.emptyList()); + when(context.getLog()).thenReturn(logger); + when(context.getProperties()).thenReturn(properties); + baseEnricher = createNewBaseEnricher(); + } + + @Test + void getName_whenInvoked_shouldReturnEnricherName() { + assertThat(baseEnricher.getName()).isEqualTo("base-enricher"); + } + + @Test + void getLog_whenInvoked_shouldReturnPrefixedLogger() { + assertThat(baseEnricher.getLog()) + .isInstanceOf(PrefixedLogger.class) + .hasFieldOrPropertyWithValue("log", logger); + } + + @Test + void enrich_whenInvoked_shouldDoNothing() { + // Given + KubernetesListBuilder klb = new KubernetesListBuilder(); + // When + baseEnricher.enrich(PlatformMode.kubernetes, klb); + // Then + assertThat(klb.buildItems()).isEmpty(); + } + + @Test + void create_whenInvoked_shouldDoNothing() { + // Given + KubernetesListBuilder klb = new KubernetesListBuilder(); + // When + baseEnricher.create(PlatformMode.kubernetes, klb); + // Then + assertThat(klb.buildItems()).isEmpty(); + } + + @Test + void getImages_whenNoImageInConfiguration_thenReturnEmptyList() { + assertThat(baseEnricher.getImages()).isEmpty(); + } + + @Test + void getImages_whenImageInConfiguration_thenReturnImage() { + // Given + ImageConfiguration ic = ImageConfiguration.builder().name("foo/bar:latest").build(); + when(context.getConfiguration().getImages()).thenReturn(Collections.singletonList(ic)); + baseEnricher = createNewBaseEnricher(); + // When + List imageConfigurationList = baseEnricher.getImages(); + // then + assertThat(imageConfigurationList).hasSize(1).contains(ic); + } + + @Test + void hasImageConfiguration_whenNoImageInConfiguration_thenReturnFalse() { + assertThat(baseEnricher.hasImageConfiguration()).isFalse(); + } + + @Test + void hasImageConfiguration_whenImageInConfiguration_thenReturnTrue() { + // Given + ImageConfiguration ic = ImageConfiguration.builder().name("foo/bar:latest").build(); + when(context.getConfiguration().getImages()).thenReturn(Collections.singletonList(ic)); + baseEnricher = createNewBaseEnricher(); + // When + boolean result = baseEnricher.hasImageConfiguration(); + // then + assertThat(result).isTrue(); + } + + @Test + void getConfig_whenConfigProvided_thenReturnConfigValue() { + // Given + properties.put("jkube.enricher.test-enricher.testProperty", "testValue"); + TestEnricher testEnricher = new TestEnricher(context); + + // When + String result = testEnricher.getConfig(TestEnricher.Config.TEST_PROPERTY); + + // Then + assertThat(result).isEqualTo("testValue"); + } + + @Test + void getConfig_whenNoValueProvided_thenReturnDefaultValue() { + // Given + TestEnricher testEnricher = new TestEnricher(context); + + // When + String result = testEnricher.getConfig(TestEnricher.Config.TEST_PROPERTY, "defaultValue"); + + // Then + assertThat(result).isEqualTo("defaultValue"); + } + + @Test + void getConfigWithFallback_whenFallbackPropertyProvided_thenReturnFallbackValue() { + // Given + properties.put("fallback.property", "fallbackValue"); + TestEnricher testEnricher = new TestEnricher(context); + + // When + String result = testEnricher.getConfigWithFallback(TestEnricher.Config.TEST_PROPERTY, "fallback.property", "defaultValue"); + + // Then + assertThat(result).isEqualTo("fallbackValue"); + } + + @Test + void getConfigWithFallback_whenNothingProvided_thenReturnDefaultValue() { + // Given + TestEnricher testEnricher = new TestEnricher(context); + + // When + String result = testEnricher.getConfigWithFallback(TestEnricher.Config.TEST_PROPERTY, "fallback.property", "defaultValue"); + + // Then + assertThat(result).isEqualTo("defaultValue"); + } + + @Test + void isOpenShiftMode_ifOpenShiftPropertyPresent_thenReturnTrue() { + // Given + properties.put("jkube.internal.effective.platform.mode", "OPENSHIFT"); + // When + boolean result = baseEnricher.isOpenShiftMode(); + // Then + assertThat(result).isTrue(); + } + + @Test + void isOpenShiftMode_ifNoPropertyPresent_thenReturnTrue() { + // Given + When + when(context.getProperties()).thenReturn(null); + boolean result = baseEnricher.isOpenShiftMode(); + // Then + assertThat(result).isFalse(); + } + + @Test + void getProcessingInstructionViaKey_whenInstructionPresent_thenShouldReturnList() { + // Given + when(context.getProcessingInstructions()).thenReturn(Collections.singletonMap("pi1", "instruction1,instruction2")); + // When + List result = baseEnricher.getProcessingInstructionViaKey("pi1"); + // Then + assertThat(result).contains("instruction1", "instruction2"); + } + + @Test + void setProcessingInstruction_whenInstructionProvided_thenShouldAddItToProcessingInstructionMap() { + // Given + When + baseEnricher.setProcessingInstruction("pi1", Arrays.asList("c1", "c2", "c3")); + // Then + verify(context).setProcessingInstructions(Collections.singletonMap("pi1", "c1,c2,c3")); + } + + @Test + void getOpenshiftDeployTimeoutInSeconds_whenNothingProvided_thenReturnDefaultTimeout() { + // Given + When + long deployTimeout = baseEnricher.getOpenshiftDeployTimeoutInSeconds(10L); + // Then + assertThat(deployTimeout).isEqualTo(10L); + } + + @Test + void getOpenshiftDeployTimeoutInSeconds_whenTimeoutProvidedInProperty_thenReturnTimeout() { + // Given + when(context.getProperty("jkube.openshift.deployTimeoutSeconds")).thenReturn("3"); + // When + long deployTimeout = baseEnricher.getOpenshiftDeployTimeoutInSeconds(10L); + // Then + assertThat(deployTimeout).isEqualTo(3L); + } + + @Test + void getControllerName_whenNameProvidedInConfig_thenReturnControllerName() { + // Given + when(controllerResourceConfig.getControllerName()).thenReturn("name-from-config"); + // When + String controllerName = baseEnricher.getControllerName(controllerResourceConfig, "default-name"); + // Then + assertThat(controllerName).isEqualTo("name-from-config"); + } + + @Test + void getControllerName_whenNullConfig_thenReturnDefaultName() { + // Given + When + String controllerName = baseEnricher.getControllerName(controllerResourceConfig, "default-name"); + // Then + assertThat(controllerName).isEqualTo("default-name"); + } + + @Test + void getCreateExternalUrls_whenPropertyProvided_thenReturnValueFromProperty() { + // Given + when(context.getProperty("jkube.createExternalUrls")).thenReturn("true"); + // When + boolean createExternalUrls = baseEnricher.getCreateExternalUrls(); + // Then + assertThat(createExternalUrls).isTrue(); + } + + @Test + void getCreateExternalUrls_whenConfigProvided_thenReturnValueFromProperty() { + // Given + when(context.getConfiguration().getResource()).thenReturn(ResourceConfig.builder() + .createExternalUrls(true) + .build()); + // When + boolean createExternalUrls = baseEnricher.getCreateExternalUrls(); + // Then + assertThat(createExternalUrls).isTrue(); + } + + @Test + void getCreateExternalUrls_whenNothingProvided_thenReturnFalse() { + // Given + when(context.getConfiguration().getResource()).thenReturn(ResourceConfig.builder().build()); + // When + boolean createExternalUrls = baseEnricher.getCreateExternalUrls(); + // Then + assertThat(createExternalUrls).isFalse(); + } + + @Test + void getReplicaCount_whenReplicaProvidedInDeployment_thenReturnDeploymentReplica() { + // Given + KubernetesListBuilder klb = new KubernetesListBuilder(); + klb.addToItems(new DeploymentBuilder().withNewSpec().withReplicas(5).endSpec().build()); + + // When + int replicaCount = getReplicaCount(klb, controllerResourceConfig, 1); + + // Then + assertThat(replicaCount).isEqualTo(5); + } + + @Test + void getReplicaCount_whenReplicaProvidedInDeploymentConfig_thenReturnDeploymentConfigReplica() { + // Given + KubernetesListBuilder klb = new KubernetesListBuilder(); + klb.addToItems(new DeploymentConfigBuilder().withNewSpec().withReplicas(5).endSpec().build()); + + // When + int replicaCount = getReplicaCount(klb, controllerResourceConfig, 1); + + // Then + assertThat(replicaCount).isEqualTo(5); + } + + @Test + void getReplicaCount_whenReplicaProvidedInControllerConfig_thenReturnControllerConfigReplica() { + // Given + KubernetesListBuilder klb = new KubernetesListBuilder(); + when(controllerResourceConfig.getReplicas()).thenReturn(5); + // When + int replicaCount = getReplicaCount(klb, controllerResourceConfig, 1); + // Then + assertThat(replicaCount).isEqualTo(5); + } + + @Test + void getReplicaCount_whenNullReplicaProvidedInControllerConfig_thenReturnDefaultReplica() { + // Given + KubernetesListBuilder klb = new KubernetesListBuilder(); + when(controllerResourceConfig.getReplicas()).thenReturn(null); + // When + int replicaCount = getReplicaCount(klb, controllerResourceConfig, 1); + // Then + assertThat(replicaCount).isEqualTo(1); + } + + @Test + void getReplicaCount_whenNullControllerConfig_thenReturnDefaultReplica() { + // Given + KubernetesListBuilder klb = new KubernetesListBuilder(); + // When + int replicaCount = getReplicaCount(klb, null, 1); + // Then + assertThat(replicaCount).isEqualTo(1); + } + + @Test + void getNamespace_whenNamespaceInResourceConfig_thenReturnResourceConfigNamespace() { + // Given + ResourceConfig resourceConfig = ResourceConfig.builder() + .namespace("namespace-from-config") + .build(); + // When + String namespace = getNamespace(resourceConfig, "default-namespace"); + // Then + assertThat(namespace).isEqualTo("namespace-from-config"); + } + + @Test + void getNamespace_whenNothingProvided_thenReturnDefaultNamespace() { + // Given + When + String namespace = getNamespace(null, "default-namespace"); + // Then + assertThat(namespace).isEqualTo("default-namespace"); + } + + @Test + void getValueFromConfig_whenBooleanPropertyProvided_thenReturnPropertyValue() { + // Given + when(context.getProperty("test.property")).thenReturn("true"); + // When + boolean result = baseEnricher.getValueFromConfig("test.property", false); + // Then + assertThat(result).isTrue(); + } + + @Test + void useDeploymentForOpenShift_whenSwitchDeploymentEnabled_thenReturnTrue() { + // Given + when(context.getProperty("jkube.build.switchToDeployment")).thenReturn("true"); + // When + boolean result = baseEnricher.useDeploymentForOpenShift(); + // Then + assertThat(result).isTrue(); + } + + @Test + void useDeploymentForOpenShift_whenNoPropertyProvided_thenReturnFalse() { + // Given + When + boolean result = baseEnricher.useDeploymentForOpenShift(); + // Then + assertThat(result).isFalse(); } @Test @@ -44,12 +411,12 @@ void getImagePullPolicy_whenNoConfigPresent_shouldReturnDefaultImagePullPolicy() } @Test - void getImagePullPolicy_whenPullPolicySpecifiedInResourceConfig_shouldReturnPullPolicy() { + void getImagePullPolicy_whenPullPolicySpecifiedInControllerResourceConfig_shouldReturnPullPolicy() { // Given - when(resourceConfig.getImagePullPolicy()).thenReturn("Never"); + when(controllerResourceConfig.getImagePullPolicy()).thenReturn("Never"); // When - String value = baseEnricher.getImagePullPolicy(resourceConfig, null); + String value = baseEnricher.getImagePullPolicy(controllerResourceConfig, null); // Then assertThat(value).isEqualTo("Never"); @@ -61,9 +428,39 @@ void getImagePullPolicy_whenPullPolicySpecifiedViaProperty_shouldReturnPullPolic when(context.getProperty("jkube.imagePullPolicy")).thenReturn("Always"); // When - String value = baseEnricher.getImagePullPolicy(resourceConfig, null); + String value = baseEnricher.getImagePullPolicy(controllerResourceConfig, null); // Then assertThat(value).isEqualTo("Always"); } + + @Test + void getControllerResourceConfig_whenNullResourceProvided_thenReturnsEmptyControllerResourceConfig() { + // Given + when(context.getConfiguration().getResource()).thenReturn(null); + + // When + ControllerResourceConfig config = baseEnricher.getControllerResourceConfig(); + + // Then + assertThat(config).isNotNull(); + } + + @Test + void getControllerResourceConfig_whenValidControllerResourceProvided_thenReturnsControllerResourceConfig() { + // Given + when(context.getConfiguration().getResource()).thenReturn(ResourceConfig.builder() + .controller(controllerResourceConfig) + .build()); + + // When + ControllerResourceConfig config = baseEnricher.getControllerResourceConfig(); + + // Then + assertThat(config).isEqualTo(controllerResourceConfig); + } + + private BaseEnricher createNewBaseEnricher() { + return new BaseEnricher(context, "base-enricher"); + } } diff --git a/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/api/util/InitContainerHandlerTest.java b/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/api/util/InitContainerHandlerTest.java deleted file mode 100644 index 6a8a307ba4..0000000000 --- a/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/api/util/InitContainerHandlerTest.java +++ /dev/null @@ -1,144 +0,0 @@ -/** - * Copyright (c) 2019 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at: - * - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.jkube.kit.enricher.api.util; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import io.fabric8.kubernetes.api.model.Container; -import io.fabric8.kubernetes.api.model.ContainerBuilder; -import io.fabric8.kubernetes.api.model.PodTemplateSpec; -import io.fabric8.kubernetes.api.model.PodTemplateSpecBuilder; -import org.eclipse.jkube.kit.common.KitLogger; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.spy; - -/** - * @author roland - */ - -class InitContainerHandlerTest { - - private KitLogger log; - - private InitContainerHandler handler; - - @BeforeEach - void setUp() { - log = spy(new KitLogger.SilentLogger()); - handler = new InitContainerHandler(log); - } - - @Test - void simple() { - PodTemplateSpecBuilder builder = getPodTemplateBuilder(); - assertThat(handler.hasInitContainer(builder, "blub")).isFalse(); - Container initContainer = createInitContainer("blub", "foo/blub"); - handler.appendInitContainer(builder, initContainer); - assertThat(handler.hasInitContainer(builder, "blub")).isTrue(); - verifyBuilder(builder, Collections.singletonList(initContainer)); - } - - @Test - void append() { - PodTemplateSpecBuilder builder = getPodTemplateBuilder("bla", "foo/bla"); - assertThat(handler.hasInitContainer(builder, "blub")).isFalse(); - Container initContainer = createInitContainer("blub", "foo/blub"); - handler.appendInitContainer(builder, initContainer); - assertThat(handler.hasInitContainer(builder, "blub")).isTrue(); - verifyBuilder(builder, Arrays.asList(createInitContainer("bla", "foo/bla"), initContainer)); - } - - @Test - void removeAll() { - PodTemplateSpecBuilder builder = getPodTemplateBuilder("bla", "foo/bla"); - assertThat(handler.hasInitContainer(builder, "bla")).isTrue(); - handler.removeInitContainer(builder, "bla"); - assertThat(handler.hasInitContainer(builder, "bla")).isFalse(); - verifyBuilder(builder, null); - } - - @Test - void removeOne() { - PodTemplateSpecBuilder builder = getPodTemplateBuilder("bla", "foo/bla", "blub", "foo/blub"); - assertThat(handler.hasInitContainer(builder, "bla")).isTrue(); - assertThat(handler.hasInitContainer(builder, "blub")).isTrue(); - handler.removeInitContainer(builder, "bla"); - assertThat(handler.hasInitContainer(builder, "bla")).isFalse(); - assertThat(handler.hasInitContainer(builder, "blub")).isTrue(); - verifyBuilder(builder, Collections.singletonList(createInitContainer("blub", "foo/blub"))); - } - - @Test - void existingSame() { - PodTemplateSpecBuilder builder = getPodTemplateBuilder("blub", "foo/blub"); - assertThat(handler.hasInitContainer(builder, "blub")).isTrue(); - Container initContainer = createInitContainer("blub", "foo/blub"); - handler.appendInitContainer(builder, initContainer); - assertThat(handler.hasInitContainer(builder, "blub")).isTrue(); - verifyBuilder(builder, Collections.singletonList(initContainer)); - } - - @Test - void existingDifferent() { - PodTemplateSpecBuilder builder = getPodTemplateBuilder("blub", "foo/bla"); - assertThat(handler.hasInitContainer(builder, "blub")).isTrue(); - Container initContainer = createInitContainer("blub", "foo/blub"); - assertThatIllegalArgumentException() - .isThrownBy(() -> handler.appendInitContainer(builder, initContainer)) - .withMessageContaining("blub"); - } - - private void verifyBuilder(PodTemplateSpecBuilder builder, List initContainers) { - PodTemplateSpec spec = builder.build(); - List initContainersInSpec = spec.getSpec().getInitContainers(); - if (initContainersInSpec.size() == 0) { - assertThat(initContainers).isNull();; - } else { - assertThat(initContainers).hasSameSizeAs(initContainersInSpec); - for (int i = 0; i < initContainers.size(); i++) { - assertThat(initContainers.get(i)).isEqualTo(initContainersInSpec.get(i)); - } - } - } - - private PodTemplateSpecBuilder getPodTemplateBuilder(String ... definitions) { - PodTemplateSpecBuilder ret = new PodTemplateSpecBuilder(); - ret.withNewMetadata().withName("test-pod-templateSpec").endMetadata().withNewSpec().withInitContainers(getInitContainerList(definitions)).endSpec(); - return ret; - } - - private List getInitContainerList(String ... definitions) { - List ret = new ArrayList<>(); - for (int i = 0; i < definitions.length; i += 2 ) { - ret.add(createInitContainer(definitions[i], definitions[i+1])); - } - return ret; - } - - private Container createInitContainer(String name, String image) { - return new ContainerBuilder() - .withName(name) - .withImage(image) - .build(); - } -} diff --git a/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/api/util/KubernetesResourceUtilTest.java b/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/api/util/KubernetesResourceUtilTest.java index 646f0d60c9..61b9396202 100644 --- a/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/api/util/KubernetesResourceUtilTest.java +++ b/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/api/util/KubernetesResourceUtilTest.java @@ -13,19 +13,41 @@ */ package org.eclipse.jkube.kit.enricher.api.util; +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.ConfigMapBuilder; +import io.fabric8.kubernetes.api.model.Container; +import io.fabric8.kubernetes.api.model.ContainerBuilder; +import io.fabric8.kubernetes.api.model.EnvVarBuilder; import io.fabric8.kubernetes.api.model.GenericKubernetesResource; import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; +import io.fabric8.kubernetes.api.model.Pod; +import io.fabric8.kubernetes.api.model.PodBuilder; import io.fabric8.kubernetes.api.model.PodSpec; import io.fabric8.kubernetes.api.model.PodSpecBuilder; +import io.fabric8.kubernetes.api.model.PodTemplateSpec; +import io.fabric8.kubernetes.api.model.PodTemplateSpecBuilder; import io.fabric8.kubernetes.api.model.Quantity; import io.fabric8.kubernetes.api.model.ReplicationController; import io.fabric8.kubernetes.api.model.Service; +import io.fabric8.kubernetes.api.model.ServiceAccountBuilder; +import io.fabric8.kubernetes.api.model.VolumeMountBuilder; +import io.fabric8.kubernetes.api.model.apps.Deployment; +import io.fabric8.kubernetes.api.model.apps.DeploymentBuilder; +import io.fabric8.kubernetes.api.model.apps.DeploymentSpec; import io.fabric8.kubernetes.api.model.batch.v1.Job; import io.fabric8.kubernetes.api.model.networking.v1.Ingress; import io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicy; +import io.fabric8.kubernetes.client.KubernetesClientException; +import org.assertj.core.api.InstanceOfAssertFactories; +import org.eclipse.jkube.kit.common.KitLogger; import org.eclipse.jkube.kit.config.image.ImageConfiguration; +import org.eclipse.jkube.kit.config.image.build.BuildConfiguration; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; import org.eclipse.jkube.kit.config.resource.GroupArtifactVersion; +import org.eclipse.jkube.kit.config.resource.InitContainerConfig; +import org.eclipse.jkube.kit.config.resource.MappingConfig; +import org.eclipse.jkube.kit.config.resource.VolumeConfig; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -39,6 +61,11 @@ import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; @@ -48,18 +75,27 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIOException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.tuple; import static org.eclipse.jkube.kit.config.resource.PlatformMode.kubernetes; import static org.eclipse.jkube.kit.enricher.api.util.KubernetesResourceUtil.DEFAULT_RESOURCE_VERSIONING; import static org.eclipse.jkube.kit.enricher.api.util.KubernetesResourceUtil.FILENAME_TO_KIND_MAPPER; import static org.eclipse.jkube.kit.enricher.api.util.KubernetesResourceUtil.KIND_TO_FILENAME_MAPPER; +import static org.eclipse.jkube.kit.enricher.api.util.KubernetesResourceUtil.createNewInitContainersFromConfig; import static org.eclipse.jkube.kit.enricher.api.util.KubernetesResourceUtil.getNameWithSuffix; +import static org.eclipse.jkube.kit.enricher.api.util.KubernetesResourceUtil.handleKubernetesClientException; import static org.eclipse.jkube.kit.enricher.api.util.KubernetesResourceUtil.initializeKindFilenameMapper; +import static org.eclipse.jkube.kit.enricher.api.util.KubernetesResourceUtil.isContainerImage; +import static org.eclipse.jkube.kit.enricher.api.util.KubernetesResourceUtil.mergeResources; +import static org.eclipse.jkube.kit.enricher.api.util.KubernetesResourceUtil.validateKubernetesMasterUrl; import static org.junit.jupiter.params.provider.Arguments.arguments; +import static org.mockito.Mockito.spy; class KubernetesResourceUtilTest { private static File fragmentsDir; + private KitLogger log; + private ImageConfiguration imageConfiguration; @BeforeAll static void initPath() { @@ -72,6 +108,13 @@ void setUp() { FILENAME_TO_KIND_MAPPER.clear(); KIND_TO_FILENAME_MAPPER.clear(); initializeKindFilenameMapper(); + log = spy(new KitLogger.SilentLogger()); + imageConfiguration = ImageConfiguration.builder() + .name("foo/bar:latest") + .build(BuildConfiguration.builder() + .from("base:latest") + .build()) + .build(); } @Nested @@ -395,6 +438,519 @@ void updateKindFilenameMappings_whenAddsCronTabMapping_updatesKindToFileNameMapp assertThat(FILENAME_TO_KIND_MAPPER).containsKey("foo"); } + @Test + void remove_whenInvoked_shouldRemoveKindFilenameMappings() { + // Given + KubernetesResourceUtil.updateKindFilenameMapper(Collections.singletonMap("CronTab", Collections.singletonList("foo"))); + + // When + KubernetesResourceUtil.remove("CronTab", "foo"); + + // Then + assertThat(KIND_TO_FILENAME_MAPPER).doesNotContainKey("CronTab"); + assertThat(FILENAME_TO_KIND_MAPPER).doesNotContainKey("foo"); + } + + @Test + void updateKindFilenameMappings_whenProvidedMappingConfigs_thenShouldAddMappings() { + // Given + List mappingConfigs = Collections.singletonList(MappingConfig.builder() + .kind("CronTab") + .filenameTypes("crontab,cr") + .build()); + + // When + KubernetesResourceUtil.updateKindFilenameMappings(mappingConfigs); + + // Then + assertThat(KIND_TO_FILENAME_MAPPER).containsEntry("CronTab", "cr"); + assertThat(FILENAME_TO_KIND_MAPPER) + .containsEntry("crontab", "CronTab") + .containsEntry("cr", "CronTab"); + } + + @Test + void updateKindFilenameMappings_whenProvidedInvalidMappingConfigs_thenThrowException() { + // Given + List mappingConfigs = Collections.singletonList(MappingConfig.builder() + .kind("foo") + .build()); + + // When + Then + assertThatIllegalArgumentException() + .isThrownBy(() -> KubernetesResourceUtil.updateKindFilenameMappings(mappingConfigs)) + .withMessageContaining("Invalid mapping for Kind foo and Filename Types"); + } + + @Test + void removeItemFromKubernetesBuilder_whenInvoked_shouldRemoveItem() { + // Given + HasMetadata sa = new ServiceAccountBuilder().withNewMetadata().withName("sa1").endMetadata().build(); + HasMetadata pod = new PodBuilder().withNewMetadata().withName("p1").endMetadata().build(); + KubernetesListBuilder kubernetesListBuilder = new KubernetesListBuilder(); + kubernetesListBuilder.addToItems(sa); + kubernetesListBuilder.addToItems(pod); + + // When + KubernetesResourceUtil.removeItemFromKubernetesBuilder(kubernetesListBuilder, sa); + + // Then + assertThat(kubernetesListBuilder.buildItems()) + .hasSize(1) + .containsExactly(pod); + } + + @Test + void checkForKind_whenPresent_shouldReturnTrue() { + // Given + KubernetesListBuilder klb = new KubernetesListBuilder(); + klb.addToItems(new DeploymentBuilder().build()); + + // When + boolean result = KubernetesResourceUtil.checkForKind(klb, "Deployment"); + + // Then + assertThat(result).isTrue(); + } + + @Test + void checkForKind_whenNotPresent_shouldReturnFalse() { + // Given + KubernetesListBuilder klb = new KubernetesListBuilder(); + klb.addToItems(new DeploymentBuilder().build()); + + // When + boolean result = KubernetesResourceUtil.checkForKind(klb, "DeploymentConfig"); + + // Then + assertThat(result).isFalse(); + } + + @Test + void validateKubernetesMasterUrl_whenInvalidUrl_thenThrowsException() { + assertThatIllegalStateException() + .isThrownBy(() -> validateKubernetesMasterUrl(null)) + .withMessage("Cannot find Kubernetes master URL. Are you sure if you're connected to a remote cluster via `kubectl`?"); + } + + @Test + void handleKubernetesClientException_whenCauseNoHost_thenThrowExceptionWithMessage() { + // Given + KubernetesClientException exception = new KubernetesClientException("test", new UnknownHostException()); + + // When + Then + assertThatIllegalStateException() + .isThrownBy(() -> handleKubernetesClientException(exception, log)) + .withMessageContaining("Could not connect to kubernetes cluster. Are you sure if you're connected to a remote cluster via `kubectl`? Error: "); + } + + @Test + void handleKubernetesClientException_whenInvoked_thenThrowExceptionWithMessage() { + // Given + KubernetesClientException exception = new KubernetesClientException("kubernetes failure", new RuntimeException()); + + // When + Then + assertThatIllegalStateException() + .isThrownBy(() -> handleKubernetesClientException(exception, log)) + .withMessageContaining("kubernetes failure"); + } + + @Nested + @DisplayName("mergeResources tests with different inputs") + class MergeResourcesTest { + @Test + void mergeResources_whenDeploymentProvidedAndFirstDeploymentWithEmptySpec_thenShouldMergeBothObjects() { + // Given + Deployment d1 = new DeploymentBuilder() + .withNewMetadata() + .withName("test-deploy") + .endMetadata() + .build(); + Deployment d2 = new DeploymentBuilder() + .withNewSpec() + .withNewTemplate() + .withNewSpec() + .addNewContainer() + .withName("foo") + .endContainer() + .endSpec() + .endTemplate() + .endSpec() + .build(); + + // When + HasMetadata mergedDeployment = mergeResources(d1, d2, log, true); + + // Then + assertThat(mergedDeployment) + .isInstanceOf(Deployment.class) + .asInstanceOf(InstanceOfAssertFactories.type(Deployment.class)) + .hasFieldOrPropertyWithValue("metadata.name", "test-deploy") + .extracting(Deployment::getSpec) + .extracting(DeploymentSpec::getTemplate) + .extracting(PodTemplateSpec::getSpec) + .extracting(PodSpec::getContainers) + .asList() + .singleElement(InstanceOfAssertFactories.type(Container.class)) + .hasFieldOrPropertyWithValue("name", "foo"); + } + + @Test + void mergeResources_whenDeploymentProvidedAndSecondDeploymentWithEmptySpec_thenShouldMergeBothObjects() { + // Given + Deployment d1 = new DeploymentBuilder() + .withNewSpec() + .withNewTemplate() + .withNewSpec() + .addNewContainer() + .withName("foo") + .endContainer() + .endSpec() + .endTemplate() + .endSpec() + .build(); + Deployment d2 = new DeploymentBuilder() + .withNewMetadata() + .withName("test-deploy") + .endMetadata() + .build(); + + // When + HasMetadata mergedDeployment = mergeResources(d1, d2, log, true); + + // Then + assertThat(mergedDeployment) + .isInstanceOf(Deployment.class) + .asInstanceOf(InstanceOfAssertFactories.type(Deployment.class)) + .hasFieldOrPropertyWithValue("metadata.name", "test-deploy") + .extracting(Deployment::getSpec) + .extracting(DeploymentSpec::getTemplate) + .extracting(PodTemplateSpec::getSpec) + .extracting(PodSpec::getContainers) + .asList() + .singleElement(InstanceOfAssertFactories.type(Container.class)) + .hasFieldOrPropertyWithValue("name", "foo"); + } + + @Test + void mergeResources_whenBothDeploymentNonEmptySpec_thenShouldMergeBothObjects() { + // Given + Deployment d1 = new DeploymentBuilder() + .withNewMetadata() + .withName("test-deploy") + .endMetadata() + .withNewSpec() + .withNewTemplate() + .withNewMetadata() + .addToLabels("app1", "test-deploy1") + .endMetadata() + .withNewSpec() + .addNewContainer() + .withName("c1") + .endContainer() + .endSpec() + .endTemplate() + .endSpec() + .build(); + Deployment d2 = new DeploymentBuilder() + .withNewSpec() + .withNewTemplate() + .withNewMetadata() + .addToLabels("app2", "test-deploy2") + .endMetadata() + .withNewSpec() + .addNewContainer() + .withName("c2") + .withImage("img2:latest") + .endContainer() + .endSpec() + .endTemplate() + .endSpec() + .build(); + + // When + HasMetadata mergedDeployment = mergeResources(d1, d2, log, true); + + // Then + assertThat(mergedDeployment) + .isInstanceOf(Deployment.class) + .asInstanceOf(InstanceOfAssertFactories.type(Deployment.class)) + .hasFieldOrPropertyWithValue("metadata.name", "test-deploy") + .hasFieldOrPropertyWithValue("spec.template.metadata.labels.app1", "test-deploy1") + .hasFieldOrPropertyWithValue("spec.template.metadata.labels.app2", "test-deploy2") + .extracting(Deployment::getSpec) + .extracting(DeploymentSpec::getTemplate) + .extracting(PodTemplateSpec::getSpec) + .extracting(PodSpec::getContainers) + .asList() + .singleElement(InstanceOfAssertFactories.type(Container.class)) + .hasFieldOrPropertyWithValue("name", "c1"); + } + + @Test + void mergeResources_whenConfigMapsProvided_thenMergeBothConfigMaps() { + // Given + ConfigMap configMap1 = new ConfigMapBuilder() + .withNewMetadata().withName("c1").endMetadata() + .addToData("key1", "value1") + .build(); + ConfigMap configMap2 = new ConfigMapBuilder() + .withNewMetadata().withName("c2").endMetadata() + .addToData("key2", "value2") + .addToData("key3", "") + .build(); + + // When + HasMetadata mergedConfigMap = mergeResources(configMap1, configMap2, log, true); + // Then + assertThat(mergedConfigMap) + .isInstanceOf(ConfigMap.class) + .asInstanceOf(InstanceOfAssertFactories.type(ConfigMap.class)) + .hasFieldOrPropertyWithValue("metadata.name", "c1") + .hasFieldOrPropertyWithValue("data.key1", "value1") + .hasFieldOrPropertyWithValue("data.key2", "value2") + .extracting(ConfigMap::getData) + .asInstanceOf(InstanceOfAssertFactories.MAP) + .hasSize(2); + } + + @Test + void mergeResources_whenConfigMapsProvidedAndLocalCustomizationDisabled_thenMergeBothConfigMaps() { + // Given + ConfigMap configMap1 = new ConfigMapBuilder() + .withNewMetadata().withName("c1").addToLabels("l1", "v1").endMetadata() + .addToData("key1", "value1") + .build(); + ConfigMap configMap2 = new ConfigMapBuilder() + .withNewMetadata().withName("c2").addToLabels("l2", "v2").endMetadata() + .addToData("key2", "value2") + .build(); + + // When + HasMetadata mergedConfigMap = mergeResources(configMap1, configMap2, log, false); + // Then + assertThat(mergedConfigMap) + .isInstanceOf(ConfigMap.class) + .asInstanceOf(InstanceOfAssertFactories.type(ConfigMap.class)) + .hasFieldOrPropertyWithValue("metadata.name", "c1") + .hasFieldOrPropertyWithValue("metadata.labels.l1", "v1") + .hasFieldOrPropertyWithValue("metadata.labels.l2", "v2") + .hasFieldOrPropertyWithValue("data.key1", "value1") + .hasFieldOrPropertyWithValue("data.key2", "value2") + .extracting(ConfigMap::getData) + .asInstanceOf(InstanceOfAssertFactories.MAP) + .hasSize(2); + } + + @Test + void mergeResources_whenPodsProvided_thenMergeBothPodMetadataOnly() { + // Given + Pod p1 = new PodBuilder() + .withNewMetadata().withName("p1").addToLabels("l1", "v1").endMetadata() + .withNewSpec() + .addNewContainer() + .withName("c1") + .withImage("image1:latest") + .endContainer() + .endSpec() + .build(); + Pod p2 = new PodBuilder() + .withNewMetadata().withName("p2").addToLabels("l2", "v2").endMetadata() + .withNewSpec() + .addNewContainer() + .withName("c2") + .withImage("image2:latest") + .endContainer() + .endSpec() + .build(); + + // When + HasMetadata mergedConfigMap = mergeResources(p1, p2, log, true); + // Then + assertThat(mergedConfigMap) + .isInstanceOf(Pod.class) + .asInstanceOf(InstanceOfAssertFactories.type(Pod.class)) + .hasFieldOrPropertyWithValue("metadata.name", "p1") + .hasFieldOrPropertyWithValue("metadata.labels.l1", "v1") + .hasFieldOrPropertyWithValue("metadata.labels.l2", "v2") + .extracting(Pod::getSpec) + .extracting(PodSpec::getContainers) + .asList() + .singleElement(InstanceOfAssertFactories.type(Container.class)) + .hasFieldOrPropertyWithValue("name", "c1") + .hasFieldOrPropertyWithValue("image", "image1:latest"); + } + } + + @Nested + @DisplayName("tests related to initContainer manipulation") + class InitContainerTests { + + @Test + void simple() { + PodTemplateSpecBuilder builder = getPodTemplateBuilder(); + assertThat(KubernetesResourceUtil.hasInitContainer(builder, "blub")).isFalse(); + Container initContainer = createInitContainer("blub", "foo/blub"); + KubernetesResourceUtil.appendInitContainer(builder, initContainer, log); + assertThat(KubernetesResourceUtil.hasInitContainer(builder, "blub")).isTrue(); + verifyBuilder(builder, Collections.singletonList(initContainer)); + } + + @Test + void append() { + PodTemplateSpecBuilder builder = getPodTemplateBuilder("bla", "foo/bla"); + assertThat(KubernetesResourceUtil.hasInitContainer(builder, "blub")).isFalse(); + Container initContainer = createInitContainer("blub", "foo/blub"); + KubernetesResourceUtil.appendInitContainer(builder, initContainer, log); + assertThat(KubernetesResourceUtil.hasInitContainer(builder, "blub")).isTrue(); + verifyBuilder(builder, Arrays.asList(createInitContainer("bla", "foo/bla"), initContainer)); + } + + @Test + void appendAndEnsureSpec() { + PodTemplateSpecBuilder builder =new PodTemplateSpecBuilder(); + assertThat(KubernetesResourceUtil.hasInitContainer(builder, "blub")).isFalse(); + Container initContainer = createInitContainer("blub", "foo/blub"); + KubernetesResourceUtil.appendInitContainer(builder, initContainer, log); + assertThat(KubernetesResourceUtil.hasInitContainer(builder, "blub")).isTrue(); + verifyBuilder(builder, Collections.singletonList(initContainer)); + } + + @Test + void removeAll() { + PodTemplateSpecBuilder builder = getPodTemplateBuilder("bla", "foo/bla"); + assertThat(KubernetesResourceUtil.hasInitContainer(builder, "bla")).isTrue(); + KubernetesResourceUtil.removeInitContainer(builder, "bla"); + assertThat(KubernetesResourceUtil.hasInitContainer(builder, "bla")).isFalse(); + verifyBuilder(builder, null); + } + + @Test + void removeOne() { + PodTemplateSpecBuilder builder = getPodTemplateBuilder("bla", "foo/bla", "blub", "foo/blub"); + assertThat(KubernetesResourceUtil.hasInitContainer(builder, "bla")).isTrue(); + assertThat(KubernetesResourceUtil.hasInitContainer(builder, "blub")).isTrue(); + KubernetesResourceUtil.removeInitContainer(builder, "bla"); + assertThat(KubernetesResourceUtil.hasInitContainer(builder, "bla")).isFalse(); + assertThat(KubernetesResourceUtil.hasInitContainer(builder, "blub")).isTrue(); + verifyBuilder(builder, Collections.singletonList(createInitContainer("blub", "foo/blub"))); + } + + @Test + void existingSame() { + PodTemplateSpecBuilder builder = getPodTemplateBuilder("blub", "foo/blub"); + assertThat(KubernetesResourceUtil.hasInitContainer(builder, "blub")).isTrue(); + Container initContainer = createInitContainer("blub", "foo/blub"); + KubernetesResourceUtil.appendInitContainer(builder, initContainer, log); + assertThat(KubernetesResourceUtil.hasInitContainer(builder, "blub")).isTrue(); + verifyBuilder(builder, Collections.singletonList(initContainer)); + } + + @Test + void existingDifferent() { + PodTemplateSpecBuilder builder = getPodTemplateBuilder("blub", "foo/bla"); + assertThat(KubernetesResourceUtil.hasInitContainer(builder, "blub")).isTrue(); + Container initContainer = createInitContainer("blub", "foo/blub"); + assertThatIllegalArgumentException() + .isThrownBy(() -> KubernetesResourceUtil.appendInitContainer(builder, initContainer, log)) + .withMessageContaining("blub"); + } + + @Test + void createNewInitContainersFromConfig_whenConfigProvided_thenReturnsValidContainerList() { + // Given + List initContainerConfigs = new ArrayList<>(); + initContainerConfigs.add(InitContainerConfig.builder() + .env(Collections.singletonMap("FOO_ENV", "BAR")) + .imageName("foo/bar:latest") + .name("init1") + .imagePullPolicy("Always") + .cmd(org.eclipse.jkube.kit.common.Arguments.builder() + .exec(Arrays.asList("sleep", "10")) + .build()) + .volumes(Collections.singletonList(VolumeConfig.builder() + .name("workdir") + .path("/work-dir") + .build())) + .build()); + + // When + List initContainers = createNewInitContainersFromConfig(initContainerConfigs); + + // Then + assertThat(initContainers) + .singleElement() + .hasFieldOrPropertyWithValue("env", Collections.singletonList(new EnvVarBuilder().withName("FOO_ENV").withValue("BAR").build())) + .hasFieldOrPropertyWithValue("image", "foo/bar:latest") + .hasFieldOrPropertyWithValue("name", "init1") + .hasFieldOrPropertyWithValue("imagePullPolicy", "Always") + .hasFieldOrPropertyWithValue("command", Arrays.asList("sleep", "10")) + .hasFieldOrPropertyWithValue("volumeMounts", Collections.singletonList(new VolumeMountBuilder().withName("workdir").withMountPath("/work-dir").build())); + } + + @Test + void isContainerImage_whenImagePresentInInitContainerConfig_thenReturnFalse() { + // Given + ControllerResourceConfig controllerResourceConfig = ControllerResourceConfig.builder() + .initContainer(InitContainerConfig.builder().imageName("foo/bar:latest").build()) + .build(); + + // When + boolean result = isContainerImage(imageConfiguration, controllerResourceConfig); + + // Then + assertThat(result).isFalse(); + } + + @Test + void isContainerImage_whenImageAbsentInInitContainerConfig_thenReturnTrue() { + // Given + ControllerResourceConfig controllerResourceConfig = ControllerResourceConfig.builder() + .initContainers(Collections.emptyList()) + .build(); + + // When + boolean result = isContainerImage(imageConfiguration, controllerResourceConfig); + + // Then + assertThat(result).isTrue(); + } + } + + private void verifyBuilder(PodTemplateSpecBuilder builder, List initContainers) { + PodTemplateSpec spec = builder.build(); + List initContainersInSpec = spec.getSpec().getInitContainers(); + if (initContainersInSpec.size() == 0) { + assertThat(initContainers).isNull();; + } else { + assertThat(initContainers).hasSameSizeAs(initContainersInSpec); + for (int i = 0; i < initContainers.size(); i++) { + assertThat(initContainers.get(i)).isEqualTo(initContainersInSpec.get(i)); + } + } + } + + private PodTemplateSpecBuilder getPodTemplateBuilder(String ... definitions) { + PodTemplateSpecBuilder ret = new PodTemplateSpecBuilder(); + ret.withNewMetadata().withName("test-pod-templateSpec").endMetadata().withNewSpec().withInitContainers(getInitContainerList(definitions)).endSpec(); + return ret; + } + + private List getInitContainerList(String ... definitions) { + List ret = new ArrayList<>(); + for (int i = 0; i < definitions.length; i += 2 ) { + ret.add(createInitContainer(definitions[i], definitions[i+1])); + } + return ret; + } + + private Container createInitContainer(String name, String image) { + return new ContainerBuilder() + .withName(name) + .withImage(image) + .build(); + } + private static PodSpec defaultPodSpec() { return new PodSpecBuilder() .addNewContainer() diff --git a/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/ContainerHandlerTest.java b/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/ContainerHandlerTest.java index dc0b57fd65..d0b75d4eca 100644 --- a/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/ContainerHandlerTest.java +++ b/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/ContainerHandlerTest.java @@ -20,7 +20,8 @@ import org.eclipse.jkube.kit.config.image.ImageConfiguration; import org.eclipse.jkube.kit.common.JavaProject; import org.eclipse.jkube.kit.config.resource.GroupArtifactVersion; -import org.eclipse.jkube.kit.config.resource.ResourceConfig; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; +import org.eclipse.jkube.kit.config.resource.InitContainerConfig; import org.eclipse.jkube.kit.config.resource.VolumeConfig; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.BeforeEach; @@ -39,7 +40,7 @@ class ContainerHandlerTest { private ProbeHandler probeHandler; private JavaProject project; - private ResourceConfig config; + private ControllerResourceConfig config; private List ports; private List tags; private List images; @@ -54,7 +55,7 @@ class ContainerHandlerTest { void setUp() { probeHandler = mock(ProbeHandler.class); project = JavaProject.builder().properties(new Properties()).build(); - config = ResourceConfig.builder() + config = ControllerResourceConfig.builder() .imagePullPolicy("IfNotPresent") .controllerName("testing") .replicas(5) @@ -181,7 +182,7 @@ void withImageNames_shouldReturnContainersWithConfiguredImages() { ImageConfiguration imageConfigWithoutNameAndRegistry = ImageConfiguration.builder().alias("test-app") .build(buildImageConfiguration).registry("docker.io").build(); - ResourceConfig config1 = ResourceConfig.builder().imagePullPolicy("IfNotPresent").build(); + ControllerResourceConfig config1 = ControllerResourceConfig.builder().imagePullPolicy("IfNotPresent").build(); images.add(imageConfiguration); images.add(imageConfigWithNameAndWithoutRegistry); @@ -218,6 +219,32 @@ void withUserAndImageAndTagWithPeriodInImageUser_shouldReturnConfiguredImage() { assertThat(containers).singleElement() .hasFieldOrPropertyWithValue("image", "quay.io/roman.gordill/customer-service-cache:latest"); } + + @Test + @DisplayName("with initContainer config and image configuration, should not create new container") + void withInitContainerConfigAndImageConfiguration_shouldNotCreateNewContainer() { + // Given + ContainerHandler containerHandler = createContainerHandler(project); + List imageConfigurations = new ArrayList<>(); + imageConfigurations.add(ImageConfiguration.builder() + .name("foo:latest") + .build(BuildConfiguration.builder() + .from("basefoo:latest") + .build()) + .build()); + config = config.toBuilder() + .initContainer(InitContainerConfig.builder() + .name("init1") + .imageName("foo:latest") + .build()) + .build(); + + // When + List containers = containerHandler.getContainers(config, imageConfigurations); + + // Then + assertThat(containers).isEmpty(); + } } @Test @@ -302,7 +329,7 @@ void getImagePullPolicy_withPolicySet_shouldReturnSetPullPolicy() { ContainerHandler handler2 = new ContainerHandler(projectWithoutSnapshotVersion.getProperties(), new GroupArtifactVersion("g","a", "3.5-NEW"), probeHandler); images.add(imageConfiguration); - ResourceConfig config1 = ResourceConfig.builder().imagePullPolicy("IfNotPresent").build(); + ControllerResourceConfig config1 = ControllerResourceConfig.builder().imagePullPolicy("IfNotPresent").build(); String handler1ImagePullPolicy = handler1.getContainers(config1, images).get(0).getImagePullPolicy(); assertThat(handler1ImagePullPolicy).isEqualTo("IfNotPresent"); @@ -335,7 +362,7 @@ void getImagePullPolicy_withoutPolicySet_shouldBeEmpty(){ images.add(imageConfiguration); //check if policy is not set then both in case of version is set or not - ResourceConfig config1 = ResourceConfig.builder().imagePullPolicy("").build(); + ControllerResourceConfig config1 = ControllerResourceConfig.builder().imagePullPolicy("").build(); String handler1ImagePullPolicy = handler1.getContainers(config1, images).get(0).getImagePullPolicy(); assertThat(handler1ImagePullPolicy).isEqualTo("PullAlways"); @@ -350,7 +377,7 @@ void getImagePullPolicy_withoutPolicySet_shouldBeEmpty(){ @Test void getImage_withPullRegistry_shouldReturnImageWithConfiguredPullRegistry() { ContainerHandler handler = createContainerHandler(project); - ResourceConfig config1 = ResourceConfig.builder().imagePullPolicy("IfNotPresent").build(); + ControllerResourceConfig config1 = ControllerResourceConfig.builder().imagePullPolicy("IfNotPresent").build(); imageConfiguration = ImageConfiguration.builder() .name("test").alias("test-app").build(buildImageConfiguration).build(); @@ -378,7 +405,7 @@ void withoutMountPathAndWithName_shouldBeEmpty() { VolumeConfig volumeConfigWithoutMount = VolumeConfig.builder().name("first").build(); volumes.add(volumeConfigWithoutMount); - ResourceConfig config1 = ResourceConfig.builder().volumes(volumes).build(); + ControllerResourceConfig config1 = ControllerResourceConfig.builder().volumes(volumes).build(); List volumeMounts = handler.getContainers(config1, images).get(0) .getVolumeMounts(); assertThat(volumeMounts).isEmpty(); @@ -397,7 +424,7 @@ void withMountPathAndWithoutName_shouldReturnMountPath() { VolumeConfig volumeConfigWithoutNameAndWithMount = VolumeConfig.builder().mounts(mounts).build(); volumes.add(volumeConfigWithoutNameAndWithMount); - ResourceConfig config1 = ResourceConfig.builder().volumes(volumes).build(); + ControllerResourceConfig config1 = ControllerResourceConfig.builder().volumes(volumes).build(); List volumeMounts = handler.getContainers(config1, images).get(0) .getVolumeMounts(); assertThat(volumeMounts).singleElement() @@ -417,7 +444,7 @@ void withMountAndName_shouldReturnBoth() { VolumeConfig volumeConfigWithNameAndSingleMount = VolumeConfig.builder().name("third").mounts(mounts).build(); volumes.add(volumeConfigWithNameAndSingleMount); - ResourceConfig config1 = ResourceConfig.builder().volumes(volumes).build(); + ControllerResourceConfig config1 = ControllerResourceConfig.builder().volumes(volumes).build(); List volumeMounts = handler.getContainers(config1, images).get(0) .getVolumeMounts(); assertThat(volumeMounts).singleElement() @@ -439,7 +466,7 @@ void withMultipleMountPaths_shouldReturnName() { .mount("/path/sys") .build(); volumes.add(volumeConfigWithNameAndMultipleMounts); - ResourceConfig config1 = ResourceConfig.builder().volumes(volumes).build(); + ControllerResourceConfig config1 = ControllerResourceConfig.builder().volumes(volumes).build(); List volumeMounts = handler.getContainers(config1, images).get(0) .getVolumeMounts(); assertThat(volumeMounts).hasSize(3) @@ -462,7 +489,7 @@ void withEmptyVolume_shouldBeEmpty() { images.add(imageConfiguration); //empty volume - ResourceConfig config1 = ResourceConfig.builder().volumes(emptyVolumes).build(); + ControllerResourceConfig config1 = ControllerResourceConfig.builder().volumes(emptyVolumes).build(); List volumeMounts = handler.getContainers(config1, images).get(0) .getVolumeMounts(); assertThat(volumeMounts).isEmpty(); diff --git a/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/DaemonSetHandlerTest.java b/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/DaemonSetHandlerTest.java index bce9108157..6ea1dbaf22 100644 --- a/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/DaemonSetHandlerTest.java +++ b/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/DaemonSetHandlerTest.java @@ -22,8 +22,8 @@ import org.eclipse.jkube.kit.common.JavaProject; import org.eclipse.jkube.kit.config.image.ImageConfiguration; import org.eclipse.jkube.kit.config.image.build.BuildConfiguration; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; import org.eclipse.jkube.kit.config.resource.GroupArtifactVersion; -import org.eclipse.jkube.kit.config.resource.ResourceConfig; import org.eclipse.jkube.kit.config.resource.VolumeConfig; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; @@ -82,10 +82,9 @@ void before(){ @Test void get_withValidControllerName_shouldReturnConfigWithContainers() { - ResourceConfig config = ResourceConfig.builder() + ControllerResourceConfig config = ControllerResourceConfig.builder() .imagePullPolicy("IfNotPresent") .controllerName("testing") - .serviceAccount("test-account") .volumes(volumes) .build(); @@ -100,7 +99,6 @@ void get_withValidControllerName_shouldReturnConfigWithContainers() { .isNotNull() .extracting(DaemonSetSpec::getTemplate).isNotNull() .extracting(PodTemplateSpec::getSpec) - .hasFieldOrPropertyWithValue("serviceAccountName", "test-account") .extracting(PodSpec::getVolumes).isNotNull() .asList() .first() @@ -110,10 +108,9 @@ void get_withValidControllerName_shouldReturnConfigWithContainers() { @Test void get_withInvalidControllerName_shouldThrowException() { - ResourceConfig config = ResourceConfig.builder() + ControllerResourceConfig config = ControllerResourceConfig.builder() .imagePullPolicy("IfNotPresent") .controllerName("TesTing") - .serviceAccount("test-account") .volumes(volumes) .build(); @@ -125,9 +122,8 @@ void get_withInvalidControllerName_shouldThrowException() { @Test void get_withoutControllerName_shouldThrowException() { - ResourceConfig config = ResourceConfig.builder() + ControllerResourceConfig config = ControllerResourceConfig.builder() .imagePullPolicy("IfNotPresent") - .serviceAccount("test-account") .volumes(volumes) .build(); assertThatIllegalArgumentException() diff --git a/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/DeploymentConfigHandlerTest.java b/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/DeploymentConfigHandlerTest.java index a9d2d51f64..0be71b39ea 100644 --- a/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/DeploymentConfigHandlerTest.java +++ b/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/DeploymentConfigHandlerTest.java @@ -20,8 +20,8 @@ import org.eclipse.jkube.kit.config.image.ImageConfiguration; import org.eclipse.jkube.kit.config.image.build.BuildConfiguration; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; import org.eclipse.jkube.kit.config.resource.GroupArtifactVersion; -import org.eclipse.jkube.kit.config.resource.ResourceConfig; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; import io.fabric8.kubernetes.api.model.PodTemplateSpec; @@ -36,12 +36,12 @@ class DeploymentConfigHandlerTest { - private ResourceConfig.ResourceConfigBuilder resourceConfigBuilder; + private ControllerResourceConfig.ControllerResourceConfigBuilder controllerResourceConfigBuilder; private DeploymentConfigHandler deploymentConfigHandler; @BeforeEach - void before(){ - resourceConfigBuilder = ResourceConfig.builder(); + void before() { + controllerResourceConfigBuilder = ControllerResourceConfig.builder(); deploymentConfigHandler = new DeploymentConfigHandler(new PodTemplateHandler(new ContainerHandler(new Properties(), new GroupArtifactVersion("g", "a", "v"), new ProbeHandler()))); } @@ -49,21 +49,21 @@ void before(){ @Test void get_withNoImagesAndNoControllerName_shouldThrowException() { // Given - final ResourceConfig resourceConfig = resourceConfigBuilder.build(); + final ControllerResourceConfig controllerResourceConfig = controllerResourceConfigBuilder.build(); final List images = Collections.emptyList(); // When & Then assertThatIllegalArgumentException() - .isThrownBy(() -> deploymentConfigHandler.get(resourceConfig, images)) + .isThrownBy(() -> deploymentConfigHandler.get(controllerResourceConfig, images)) .withMessage("No controller name is specified!"); } @Test void get_withNoImages_shouldReturnConfigWithNoContainers() { // Given - final ResourceConfig resourceConfig = resourceConfigBuilder.controllerName("controller").build(); + final ControllerResourceConfig controllerResourceConfig = controllerResourceConfigBuilder.controllerName("controller").build(); final List images = Collections.emptyList(); // When - final DeploymentConfig result = deploymentConfigHandler.get(resourceConfig, images); + final DeploymentConfig result = deploymentConfigHandler.get(controllerResourceConfig, images); // Then assertThat(result) .hasFieldOrPropertyWithValue("metadata.name", "controller") @@ -73,13 +73,13 @@ void get_withNoImages_shouldReturnConfigWithNoContainers() { @Test void get_withImages_shouldReturnConfigWithContainers() { // Given - final ResourceConfig resourceConfig = resourceConfigBuilder.controllerName("controller").build(); + final ControllerResourceConfig controllerResourceConfig = controllerResourceConfigBuilder.controllerName("controller").build(); final List images = Arrays.asList( ImageConfiguration.builder().name("busybox").build(BuildConfiguration.builder().build()).build(), ImageConfiguration.builder().name("jkubeio/java:latest").build(BuildConfiguration.builder().build()).build() ); // When - final DeploymentConfig result = deploymentConfigHandler.get(resourceConfig, images); + final DeploymentConfig result = deploymentConfigHandler.get(controllerResourceConfig, images); // Then assertThat(result) .hasFieldOrPropertyWithValue("metadata.name", "controller") @@ -91,10 +91,10 @@ void get_withImages_shouldReturnConfigWithContainers() { @Test void getPodTemplateSpec_withNoImages_shouldReturnPodTemplateSpecWithNoContainers() { // Given - final ResourceConfig resourceConfig = resourceConfigBuilder.controllerName("controller").build(); + final ControllerResourceConfig controllerResourceConfig = controllerResourceConfigBuilder.controllerName("controller").build(); final List images = Collections.emptyList(); // When - final PodTemplateSpec result = deploymentConfigHandler.getPodTemplateSpec(resourceConfig, images); + final PodTemplateSpec result = deploymentConfigHandler.getPodTemplateSpec(controllerResourceConfig, images); // Then assertThat(result).extracting("spec.containers").asList().isEmpty(); } diff --git a/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/DeploymentHandlerTest.java b/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/DeploymentHandlerTest.java index 7b27a6d93d..6ab78fd2ad 100644 --- a/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/DeploymentHandlerTest.java +++ b/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/DeploymentHandlerTest.java @@ -23,7 +23,7 @@ import org.eclipse.jkube.kit.config.image.ImageConfiguration; import org.eclipse.jkube.kit.config.image.build.BuildConfiguration; import org.eclipse.jkube.kit.config.resource.GroupArtifactVersion; -import org.eclipse.jkube.kit.config.resource.ResourceConfig; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; import org.eclipse.jkube.kit.config.resource.VolumeConfig; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; @@ -82,10 +82,9 @@ void before(){ @Test void get_withValidControllerName_shouldReturnConfigWithContainers() { - ResourceConfig config = ResourceConfig.builder() + ControllerResourceConfig config = ControllerResourceConfig.builder() .imagePullPolicy("IfNotPresent") .controllerName("testing") - .serviceAccount("test-account") .replicas(5) .volumes(volumes1) .build(); @@ -102,7 +101,6 @@ void get_withValidControllerName_shouldReturnConfigWithContainers() { .hasFieldOrPropertyWithValue("replicas", 5) .extracting(DeploymentSpec::getTemplate).isNotNull() .extracting(PodTemplateSpec::getSpec) - .hasFieldOrPropertyWithValue("serviceAccountName", "test-account") .extracting(PodSpec::getVolumes).isNotNull() .asList() .first() @@ -113,10 +111,9 @@ void get_withValidControllerName_shouldReturnConfigWithContainers() { @Test void get_withInvalidControllerName_shouldThrowException() { - ResourceConfig config = ResourceConfig.builder() + ControllerResourceConfig config = ControllerResourceConfig.builder() .imagePullPolicy("IfNotPresent") .controllerName("TesTing") - .serviceAccount("test-account") .replicas(5) .volumes(volumes1) .build(); @@ -128,9 +125,8 @@ void get_withInvalidControllerName_shouldThrowException() { @Test void get_withoutControllerName_shouldThrowException() { - ResourceConfig config = ResourceConfig.builder() + ControllerResourceConfig config = ControllerResourceConfig.builder() .imagePullPolicy("IfNotPresent") - .serviceAccount("test-account") .replicas(5) .volumes(volumes1) .build(); diff --git a/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/JobHandlerTest.java b/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/JobHandlerTest.java index eb7c196ec2..f39d0c937b 100644 --- a/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/JobHandlerTest.java +++ b/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/JobHandlerTest.java @@ -22,8 +22,8 @@ import io.fabric8.kubernetes.api.model.batch.v1.JobSpec; import org.eclipse.jkube.kit.config.image.ImageConfiguration; import org.eclipse.jkube.kit.config.image.build.BuildConfiguration; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; import org.eclipse.jkube.kit.config.resource.GroupArtifactVersion; -import org.eclipse.jkube.kit.config.resource.ResourceConfig; import org.eclipse.jkube.kit.config.resource.VolumeConfig; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; @@ -78,15 +78,14 @@ void setUp(){ @Test void get_withValidControllerName_shouldReturnConfigWithContainers() { - ResourceConfig config = ResourceConfig.builder() + ControllerResourceConfig config = ControllerResourceConfig.builder() .imagePullPolicy("IfNotPresent") .controllerName("testing") - .serviceAccount("test-account") .restartPolicy("OnFailure") .volumes(volumes) .build(); - Job job = jobHandler.get(config,images); + Job job = jobHandler.get(config, images); assertThat(job.getSpec().getTemplate().getSpec().getContainers()).isNotNull(); assertThat(job) .satisfies(j -> assertThat(j.getMetadata()) @@ -97,7 +96,6 @@ void get_withValidControllerName_shouldReturnConfigWithContainers() { .isNotNull() .extracting(JobSpec::getTemplate).isNotNull() .extracting(PodTemplateSpec::getSpec) - .hasFieldOrPropertyWithValue("serviceAccountName", "test-account") .hasFieldOrPropertyWithValue("restartPolicy", "OnFailure") .extracting(PodSpec::getVolumes).asList() .first() @@ -108,10 +106,9 @@ void get_withValidControllerName_shouldReturnConfigWithContainers() { @Test void get_withInvalidControllerName_shouldThrowException() { - ResourceConfig config = ResourceConfig.builder() + ControllerResourceConfig config = ControllerResourceConfig.builder() .imagePullPolicy("IfNotPresent") .controllerName("TesTing") - .serviceAccount("test-account") .volumes(volumes) .build(); @@ -123,9 +120,8 @@ void get_withInvalidControllerName_shouldThrowException() { @Test void get_withoutControllerName_shouldThrowException() { - ResourceConfig config = ResourceConfig.builder() + ControllerResourceConfig config = ControllerResourceConfig.builder() .imagePullPolicy("IfNotPresent") - .serviceAccount("test-account") .volumes(volumes) .build(); diff --git a/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/PodTemplateHandlerTest.java b/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/PodTemplateHandlerTest.java index 2040f88665..14690da93b 100644 --- a/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/PodTemplateHandlerTest.java +++ b/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/PodTemplateHandlerTest.java @@ -19,7 +19,7 @@ import org.eclipse.jkube.kit.config.image.ImageConfiguration; import org.eclipse.jkube.kit.common.JavaProject; import org.eclipse.jkube.kit.config.resource.GroupArtifactVersion; -import org.eclipse.jkube.kit.config.resource.ResourceConfig; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; import org.eclipse.jkube.kit.config.resource.VolumeConfig; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -76,17 +76,15 @@ void setUp() { @Test void getPodTemplate_withoutVolumeConfig_shouldGeneratePodTemplateWithoutVolume() { - ResourceConfig config = ResourceConfig.builder() + ControllerResourceConfig config = ControllerResourceConfig.builder() .imagePullPolicy("IfNotPresent") .controllerName("testing") - .serviceAccount("test-account") .replicas(5) .build(); PodTemplateSpec podTemplateSpec = podTemplateHandler.getPodTemplate(config, null, images); assertThat(podTemplateSpec.getSpec().getVolumes()).isEmpty(); assertThat(podTemplateSpec.getSpec()) - .hasFieldOrPropertyWithValue("serviceAccountName", "test-account") .extracting(PodSpec::getContainers).isNotNull() .asList() .first() @@ -97,7 +95,7 @@ void getPodTemplate_withoutVolumeConfig_shouldGeneratePodTemplateWithoutVolume() @Test void getPodTemplate_withEmptyVolumeAndWithoutServiceAccount_shouldGeneratePodTemplateWithNoVolume(){ - ResourceConfig config = ResourceConfig.builder() + ControllerResourceConfig config = ControllerResourceConfig.builder() .imagePullPolicy("IfNotPresent") .controllerName("testing") .replicas(5) @@ -118,10 +116,9 @@ void getPodTemplate_withVolumeAndServiceAccount_shouldGeneratePodTemplateWithCon .mounts(mounts).type("hostPath").path("/test/path").build(); volumes.add(volumeConfig); - ResourceConfig config = ResourceConfig.builder() + ControllerResourceConfig config = ControllerResourceConfig.builder() .imagePullPolicy("IfNotPresent") .controllerName("testing") - .serviceAccount("test-account") .replicas(5) .volumes(volumes) .build(); @@ -130,7 +127,6 @@ void getPodTemplate_withVolumeAndServiceAccount_shouldGeneratePodTemplateWithCon assertThat(podTemplateSpec.getSpec().getContainers()).isNotNull(); assertThat(podTemplateSpec.getSpec()) - .hasFieldOrPropertyWithValue("serviceAccountName", "test-account") .extracting(PodSpec::getVolumes).asList() .isNotEmpty() .first() @@ -144,17 +140,15 @@ void getPodTemplate_withInvalidVolume_shouldGeneratePodTemplateWithNoVolume(){ .mounts(mounts).type("hoStPath").path("/test/path").build(); volumes.add(volumeConfig1); - ResourceConfig config = ResourceConfig.builder() + ControllerResourceConfig config = ControllerResourceConfig.builder() .imagePullPolicy("IfNotPresent") .controllerName("testing") - .serviceAccount("test-account") .replicas(5) .volumes(volumes) .build(); PodTemplateSpec podTemplateSpec = podTemplateHandler.getPodTemplate(config, null, images); assertThat(podTemplateSpec.getSpec()) - .hasFieldOrPropertyWithValue("serviceAccountName", "test-account") .returns(true, s -> s.getVolumes().isEmpty()) .extracting(PodSpec::getContainers) .isNotNull(); @@ -165,26 +159,24 @@ void getPodTemplate_withoutEmptyVolume_shouldGeneratePodTemplateWithNoVolume(){ VolumeConfig volumeConfig1 = VolumeConfig.builder().name("test").mounts(mounts).build(); volumes.add(volumeConfig1); - ResourceConfig config = ResourceConfig.builder() + ControllerResourceConfig config = ControllerResourceConfig.builder() .imagePullPolicy("IfNotPresent") .controllerName("testing") - .serviceAccount("test-account") .replicas(5) .volumes(volumes) .build(); PodTemplateSpec podTemplateSpec = podTemplateHandler.getPodTemplate(config, null, images); assertThat(podTemplateSpec.getSpec()) - .hasFieldOrPropertyWithValue("serviceAccountName", "test-account") .returns(true, s -> s.getVolumes().isEmpty()) .extracting(PodSpec::getContainers) .isNotNull(); } @Test - void getPodTemplate_withRestartPolicyAndResourceConfig_shouldGeneratePodTemplateWithConfiguredRestartPolicy() { + void getPodTemplate_withRestartPolicyAndControllerResourceConfig_shouldGeneratePodTemplateWithConfiguredRestartPolicy() { // Given - ResourceConfig config = ResourceConfig.builder().build(); + ControllerResourceConfig config = ControllerResourceConfig.builder().build(); // When PodTemplateSpec podTemplateSpec = podTemplateHandler.getPodTemplate(config, "Always", images); diff --git a/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/ReplicaSetHandlerTest.java b/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/ReplicaSetHandlerTest.java index a95bc56b8b..abe6e069e0 100644 --- a/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/ReplicaSetHandlerTest.java +++ b/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/ReplicaSetHandlerTest.java @@ -22,7 +22,7 @@ import org.eclipse.jkube.kit.config.image.ImageConfiguration; import org.eclipse.jkube.kit.config.image.build.BuildConfiguration; import org.eclipse.jkube.kit.config.resource.GroupArtifactVersion; -import org.eclipse.jkube.kit.config.resource.ResourceConfig; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; import org.eclipse.jkube.kit.config.resource.VolumeConfig; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -79,10 +79,9 @@ void setUp(){ @Test void get_withValidControllerName_shouldReturnConfigsWithContainers() { - ResourceConfig config = ResourceConfig.builder() + ControllerResourceConfig config = ControllerResourceConfig.builder() .imagePullPolicy("IfNotPresent") .controllerName("testing") - .serviceAccount("test-account") .replicas(5) .volumes(volumes) .build(); @@ -99,7 +98,6 @@ void get_withValidControllerName_shouldReturnConfigsWithContainers() { .hasFieldOrPropertyWithValue("replicas", 5) .extracting(ReplicaSetSpec::getTemplate).isNotNull() .extracting(PodTemplateSpec::getSpec) - .hasFieldOrPropertyWithValue("serviceAccountName", "test-account") .extracting(PodSpec::getVolumes).asList() .isNotEmpty() .first() @@ -109,10 +107,9 @@ void get_withValidControllerName_shouldReturnConfigsWithContainers() { @Test void get_withInvalidName_shouldThrowException() { - ResourceConfig config = ResourceConfig.builder() + ControllerResourceConfig config = ControllerResourceConfig.builder() .imagePullPolicy("IfNotPresent") .controllerName("TesTing") - .serviceAccount("test-account") .replicas(5) .volumes(volumes) .build(); @@ -124,9 +121,8 @@ void get_withInvalidName_shouldThrowException() { @Test void get_withoutControllerName_shouldThrowException() { - ResourceConfig config = ResourceConfig.builder() + ControllerResourceConfig config = ControllerResourceConfig.builder() .imagePullPolicy("IfNotPresent") - .serviceAccount("test-account") .replicas(5) .volumes(volumes) .build(); diff --git a/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/ReplicationControllerHandlerTest.java b/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/ReplicationControllerHandlerTest.java index d9375ad96f..f1e7de93b5 100644 --- a/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/ReplicationControllerHandlerTest.java +++ b/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/ReplicationControllerHandlerTest.java @@ -23,7 +23,7 @@ import org.eclipse.jkube.kit.config.image.ImageConfiguration; import org.eclipse.jkube.kit.config.image.build.BuildConfiguration; import org.eclipse.jkube.kit.config.resource.GroupArtifactVersion; -import org.eclipse.jkube.kit.config.resource.ResourceConfig; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; import org.eclipse.jkube.kit.config.resource.VolumeConfig; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; @@ -80,10 +80,9 @@ void setUp(){ @Test void get_withValidControllerName_shouldReturnConfigWithContainers() { - ResourceConfig config = ResourceConfig.builder() + ControllerResourceConfig config = ControllerResourceConfig.builder() .imagePullPolicy("IfNotPresent") .controllerName("testing") - .serviceAccount("test-account") .replicas(5) .volumes(volumes) .build(); @@ -100,7 +99,6 @@ void get_withValidControllerName_shouldReturnConfigWithContainers() { .hasFieldOrPropertyWithValue("replicas", 5) .extracting(ReplicationControllerSpec::getTemplate).isNotNull() .extracting(PodTemplateSpec::getSpec) - .hasFieldOrPropertyWithValue("serviceAccountName", "test-account") .extracting(PodSpec::getVolumes).asList() .isNotEmpty() .first() @@ -111,10 +109,9 @@ void get_withValidControllerName_shouldReturnConfigWithContainers() { @Test void get_withInvalidControllerName_shouldThrowException() { - ResourceConfig config = ResourceConfig.builder() + ControllerResourceConfig config = ControllerResourceConfig.builder() .imagePullPolicy("IfNotPresent") .controllerName("TesTing") - .serviceAccount("test-account") .replicas(5) .volumes(volumes) .build(); @@ -126,9 +123,8 @@ void get_withInvalidControllerName_shouldThrowException() { @Test void get_withoutControllerName_shouldThrowException() { - ResourceConfig config = ResourceConfig.builder() + ControllerResourceConfig config = ControllerResourceConfig.builder() .imagePullPolicy("IfNotPresent") - .serviceAccount("test-account") .replicas(5) .volumes(volumes) .build(); diff --git a/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/StatefulSetHandlerTest.java b/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/StatefulSetHandlerTest.java index 2e9e063587..19f98f4420 100644 --- a/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/StatefulSetHandlerTest.java +++ b/jkube-kit/enricher/api/src/test/java/org/eclipse/jkube/kit/enricher/handler/StatefulSetHandlerTest.java @@ -23,7 +23,7 @@ import org.eclipse.jkube.kit.config.image.ImageConfiguration; import org.eclipse.jkube.kit.config.image.build.BuildConfiguration; import org.eclipse.jkube.kit.config.resource.GroupArtifactVersion; -import org.eclipse.jkube.kit.config.resource.ResourceConfig; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; import org.eclipse.jkube.kit.config.resource.VolumeConfig; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; @@ -81,10 +81,9 @@ void setUp(){ @Test void get_withValidControllerName_shouldReturnConfigWithContainers() { - ResourceConfig config = ResourceConfig.builder() + ControllerResourceConfig config = ControllerResourceConfig.builder() .imagePullPolicy("IfNotPresent") .controllerName("testing") - .serviceAccount("test-account") .replicas(5) .volumes(volumes) .build(); @@ -102,7 +101,6 @@ void get_withValidControllerName_shouldReturnConfigWithContainers() { .hasFieldOrPropertyWithValue("serviceName", "testing") .extracting(StatefulSetSpec::getTemplate).isNotNull() .extracting(PodTemplateSpec::getSpec) - .hasFieldOrPropertyWithValue("serviceAccountName", "test-account") .extracting(PodSpec::getVolumes).asList() .isNotEmpty() .first() @@ -113,10 +111,9 @@ void get_withValidControllerName_shouldReturnConfigWithContainers() { @Test void get_withInvalidControllerName_shouldThrowException() { - ResourceConfig config = ResourceConfig.builder() + ControllerResourceConfig config = ControllerResourceConfig.builder() .imagePullPolicy("IfNotPresent") .controllerName("TesTing") - .serviceAccount("test-account") .replicas(5) .volumes(volumes) .build(); @@ -128,9 +125,8 @@ void get_withInvalidControllerName_shouldThrowException() { @Test void get_withoutControllerName_shouldThrowException() { - ResourceConfig config = ResourceConfig.builder() + ControllerResourceConfig config = ControllerResourceConfig.builder() .imagePullPolicy("IfNotPresent") - .serviceAccount("test-account") .replicas(5) .volumes(volumes) .build(); diff --git a/jkube-kit/enricher/generic/src/main/java/org/eclipse/jkube/enricher/generic/ControllerViaPluginConfigurationEnricher.java b/jkube-kit/enricher/generic/src/main/java/org/eclipse/jkube/enricher/generic/ControllerViaPluginConfigurationEnricher.java index 585a92777c..52b540bebc 100644 --- a/jkube-kit/enricher/generic/src/main/java/org/eclipse/jkube/enricher/generic/ControllerViaPluginConfigurationEnricher.java +++ b/jkube-kit/enricher/generic/src/main/java/org/eclipse/jkube/enricher/generic/ControllerViaPluginConfigurationEnricher.java @@ -15,10 +15,12 @@ import java.util.Collections; import java.util.List; +import java.util.Optional; import org.eclipse.jkube.kit.common.Configs; import org.eclipse.jkube.kit.common.util.JKubeProjectUtil; import org.eclipse.jkube.kit.config.image.ImageConfiguration; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; import org.eclipse.jkube.kit.config.resource.PlatformMode; import org.eclipse.jkube.kit.config.resource.ResourceConfig; import org.eclipse.jkube.kit.enricher.api.BaseEnricher; @@ -73,11 +75,12 @@ public ControllerViaPluginConfigurationEnricher(EnricherContext context) { @Override public void create(PlatformMode platformMode, KubernetesListBuilder builder) { final String name = getConfig(Config.NAME, JKubeProjectUtil.createDefaultResourceName(getContext().getGav().getSanitizedArtifactId())); - ResourceConfig xmlResourceConfig = getConfiguration().getResource(); - final ResourceConfig config = ResourceConfig.builder() + ControllerResourceConfig providedControllerResourceConfig = getControllerResourceConfig(); + final ControllerResourceConfig controllerResourceConfig = ControllerResourceConfig.builder() .controllerName(name) - .imagePullPolicy(getImagePullPolicy(xmlResourceConfig, Config.PULL_POLICY)) - .replicas(getReplicaCount(builder, xmlResourceConfig, Configs.asInt(getConfig(Config.REPLICA_COUNT)))) + .imagePullPolicy(getImagePullPolicy(providedControllerResourceConfig, Config.PULL_POLICY)) + .replicas(getReplicaCount(builder, providedControllerResourceConfig, Configs.asInt(getConfig(Config.REPLICA_COUNT)))) + .initContainers(Optional.ofNullable(providedControllerResourceConfig.getInitContainers()).orElse(Collections.emptyList())) .build(); final List images = getImages(); @@ -85,7 +88,7 @@ public void create(PlatformMode platformMode, KubernetesListBuilder builder) { if (KubernetesResourceUtil.checkForKind(builder, POD_CONTROLLER_KINDS)) { // At least one image must be present, otherwise the resulting config will be invalid if (KubernetesResourceUtil.checkForKind(builder, "StatefulSet")) { - final StatefulSetSpec spec = statefulSetHandler.get(config, images).getSpec(); + final StatefulSetSpec spec = statefulSetHandler.get(controllerResourceConfig, images).getSpec(); if (spec != null) { builder.accept(new TypedVisitor() { @Override @@ -112,7 +115,7 @@ public void visit(PodSpecBuilder builder) { } } } else { - final DeploymentSpec spec = deployHandler.get(config, images).getSpec(); + final DeploymentSpec spec = deployHandler.get(controllerResourceConfig, images).getSpec(); if (spec != null) { builder.accept(new TypedVisitor() { @Override diff --git a/jkube-kit/enricher/generic/src/main/java/org/eclipse/jkube/enricher/generic/DefaultControllerEnricher.java b/jkube-kit/enricher/generic/src/main/java/org/eclipse/jkube/enricher/generic/DefaultControllerEnricher.java index fdef3c9d5a..432533b51c 100644 --- a/jkube-kit/enricher/generic/src/main/java/org/eclipse/jkube/enricher/generic/DefaultControllerEnricher.java +++ b/jkube-kit/enricher/generic/src/main/java/org/eclipse/jkube/enricher/generic/DefaultControllerEnricher.java @@ -29,8 +29,8 @@ import org.eclipse.jkube.kit.common.Configs; import org.eclipse.jkube.kit.common.util.JKubeProjectUtil; import org.eclipse.jkube.kit.config.image.ImageConfiguration; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; import org.eclipse.jkube.kit.config.resource.PlatformMode; -import org.eclipse.jkube.kit.config.resource.ResourceConfig; import org.eclipse.jkube.kit.enricher.api.BaseEnricher; import org.eclipse.jkube.kit.enricher.api.EnricherContext; import org.eclipse.jkube.kit.enricher.api.util.KubernetesResourceUtil; @@ -101,13 +101,12 @@ public DefaultControllerEnricher(EnricherContext buildContext) { public void create(PlatformMode platformMode, KubernetesListBuilder builder) { final String name = getConfig(Config.NAME, JKubeProjectUtil.createDefaultResourceName(getContext().getGav().getSanitizedArtifactId())); - ResourceConfig providedResourceConfig = Optional.ofNullable(getConfiguration().getResource()) - .orElse(ResourceConfig.builder().build()); - ResourceConfig config = ResourceConfig.toBuilder(providedResourceConfig) - .controllerName(getControllerName(providedResourceConfig, name)) - .imagePullPolicy(getImagePullPolicy(providedResourceConfig, Config.PULL_POLICY)) - .replicas(getReplicaCount(builder, providedResourceConfig, Configs.asInt(getConfig(Config.REPLICA_COUNT)))) - .restartPolicy(providedResourceConfig.getRestartPolicy()) + ControllerResourceConfig providedControllerResourceConfig = getControllerResourceConfig(); + final ControllerResourceConfig controllerResourceConfig = providedControllerResourceConfig.toBuilder() + .controllerName(getControllerName(providedControllerResourceConfig, name)) + .imagePullPolicy(getImagePullPolicy(providedControllerResourceConfig, Config.PULL_POLICY)) + .replicas(getReplicaCount(builder, providedControllerResourceConfig, Configs.asInt(getConfig(Config.REPLICA_COUNT)))) + .restartPolicy(providedControllerResourceConfig.getRestartPolicy()) .build(); final List images = getImages(); @@ -117,11 +116,11 @@ public void create(PlatformMode platformMode, KubernetesListBuilder builder) { if (!KubernetesResourceUtil.checkForKind(builder, POD_CONTROLLER_KINDS) && !images.isEmpty()) { final ControllerHandler ch = getContext().getHandlerHub() .getHandlerFor(fromType(getConfig(Config.TYPE))); - final HasMetadata resource = ch.get(config, images); + final HasMetadata resource = ch.get(controllerResourceConfig, images); log.info("Adding a default %s", resource.getKind()); builder.addToItems(resource); setProcessingInstruction(FABRIC8_GENERATED_CONTAINERS, - getContainersFromPodSpec(ch.getPodTemplateSpec(config, images))); + getContainersFromPodSpec(ch.getPodTemplateSpec(controllerResourceConfig, images))); } } diff --git a/jkube-kit/enricher/generic/src/main/java/org/eclipse/jkube/enricher/generic/ImageEnricher.java b/jkube-kit/enricher/generic/src/main/java/org/eclipse/jkube/enricher/generic/ImageEnricher.java index 2aaf2f0f5e..41b9d6c62d 100644 --- a/jkube-kit/enricher/generic/src/main/java/org/eclipse/jkube/enricher/generic/ImageEnricher.java +++ b/jkube-kit/enricher/generic/src/main/java/org/eclipse/jkube/enricher/generic/ImageEnricher.java @@ -42,6 +42,7 @@ import lombok.Getter; import org.eclipse.jkube.kit.config.image.ImageConfiguration; import org.eclipse.jkube.kit.common.Configs; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; import org.eclipse.jkube.kit.config.resource.PlatformMode; import org.eclipse.jkube.kit.config.resource.ResourceConfig; import org.eclipse.jkube.kit.enricher.api.BaseEnricher; @@ -55,6 +56,7 @@ import java.util.Optional; import static org.eclipse.jkube.kit.enricher.api.util.KubernetesResourceUtil.extractContainerName; +import static org.eclipse.jkube.kit.enricher.api.util.KubernetesResourceUtil.isContainerImage; /** * Merge in image configuration like the image name into ReplicaSet and ReplicationController's @@ -215,12 +217,14 @@ public void visit(PodTemplateSpecBuilder templateBuilder) { private void mergeImageConfigurationWithContainerSpec(List containers) { int idx = 0; for (ImageConfiguration image : getImages()) { - Container container = getContainer(idx, containers); - mergeImagePullPolicy(image, container); - mergeImage(image, container); - mergeContainerName(image, container); - mergeEnvVariables(container); - idx++; + if (isContainerImage(image, getControllerResourceConfig())) { + Container container = getContainer(idx, containers); + mergeImagePullPolicy(image, container); + mergeImage(image, container); + mergeContainerName(image, container); + mergeEnvVariables(container); + idx++; + } } } @@ -270,7 +274,7 @@ private void mergeImagePullPolicy(ImageConfiguration imageConfiguration, Contain } private void mergeEnvVariables(Container container) { - Optional.ofNullable(getConfiguration().getResource()).map(ResourceConfig::getEnv).ifPresent(resourceEnv -> { + Optional.ofNullable(getControllerResourceConfig()).map(ControllerResourceConfig::getEnv).ifPresent(resourceEnv -> { List containerEnvVars = container.getEnv(); if (containerEnvVars == null) { containerEnvVars = new LinkedList<>(); diff --git a/jkube-kit/enricher/generic/src/main/java/org/eclipse/jkube/enricher/generic/VolumePermissionEnricher.java b/jkube-kit/enricher/generic/src/main/java/org/eclipse/jkube/enricher/generic/VolumePermissionEnricher.java index 84d6f8bf39..4a8dc3447b 100644 --- a/jkube-kit/enricher/generic/src/main/java/org/eclipse/jkube/enricher/generic/VolumePermissionEnricher.java +++ b/jkube-kit/enricher/generic/src/main/java/org/eclipse/jkube/enricher/generic/VolumePermissionEnricher.java @@ -24,7 +24,6 @@ import io.fabric8.kubernetes.api.model.PodSpec; import io.fabric8.kubernetes.api.model.PodTemplateSpecBuilder; import io.fabric8.kubernetes.api.model.Quantity; -import io.fabric8.kubernetes.api.model.ResourceRequirements; import io.fabric8.kubernetes.api.model.ResourceRequirementsBuilder; import io.fabric8.kubernetes.api.model.Volume; import io.fabric8.kubernetes.api.model.VolumeMount; @@ -35,8 +34,8 @@ import org.eclipse.jkube.kit.config.resource.PlatformMode; import org.eclipse.jkube.kit.enricher.api.BaseEnricher; import org.eclipse.jkube.kit.enricher.api.JKubeEnricherContext; -import org.eclipse.jkube.kit.enricher.api.util.InitContainerHandler; import org.apache.commons.lang3.StringUtils; +import org.eclipse.jkube.kit.enricher.api.util.KubernetesResourceUtil; import java.util.ArrayList; import java.util.HashMap; @@ -54,8 +53,6 @@ public class VolumePermissionEnricher extends BaseEnricher { public static final String ENRICHER_NAME = "jkube-volume-permission"; static final String VOLUME_STORAGE_CLASS_ANNOTATION = "volume.beta.kubernetes.io/storage-class"; - private final InitContainerHandler initContainerHandler; - @AllArgsConstructor enum Config implements Configs.Config { IMAGE_NAME("imageName", "busybox"), @@ -75,7 +72,6 @@ enum Config implements Configs.Config { public VolumePermissionEnricher(JKubeEnricherContext buildContext) { super(buildContext, ENRICHER_NAME); - initContainerHandler = new InitContainerHandler(buildContext.getLog()); } @Override @@ -100,8 +96,8 @@ public void visit(PodTemplateSpecBuilder builder) { log.verbose("Adding init container for changing persistent volumes access mode to %s", getConfig(Config.PERMISSION)); - if (!initContainerHandler.hasInitContainer(builder, ENRICHER_NAME)) { - initContainerHandler.appendInitContainer(builder, createPvInitContainer(podSpec)); + if (!KubernetesResourceUtil.hasInitContainer(builder, ENRICHER_NAME)) { + KubernetesResourceUtil.appendInitContainer(builder, createPvInitContainer(podSpec), log); } } diff --git a/jkube-kit/enricher/generic/src/main/java/org/eclipse/jkube/enricher/generic/openshift/AutoTLSEnricher.java b/jkube-kit/enricher/generic/src/main/java/org/eclipse/jkube/enricher/generic/openshift/AutoTLSEnricher.java index 66c8e16031..b6042647c3 100644 --- a/jkube-kit/enricher/generic/src/main/java/org/eclipse/jkube/enricher/generic/openshift/AutoTLSEnricher.java +++ b/jkube-kit/enricher/generic/src/main/java/org/eclipse/jkube/enricher/generic/openshift/AutoTLSEnricher.java @@ -29,7 +29,7 @@ import org.eclipse.jkube.kit.config.resource.PlatformMode; import org.eclipse.jkube.kit.enricher.api.BaseEnricher; import org.eclipse.jkube.kit.enricher.api.JKubeEnricherContext; -import org.eclipse.jkube.kit.enricher.api.util.InitContainerHandler; +import org.eclipse.jkube.kit.enricher.api.util.KubernetesResourceUtil; import java.util.ArrayList; import java.util.Arrays; @@ -48,8 +48,6 @@ public class AutoTLSEnricher extends BaseEnricher { private final String secretName; - private final InitContainerHandler initContainerHandler; - @AllArgsConstructor private enum Config implements Configs.Config { @@ -74,7 +72,6 @@ public AutoTLSEnricher(JKubeEnricherContext buildContext) { super(buildContext, ENRICHER_NAME); this.secretName = getConfig(Config.TLS_SECRET_NAME, getContext().getGav().getArtifactId() + "-tls"); - this.initContainerHandler = new InitContainerHandler(buildContext.getLog()); } @Override @@ -86,7 +83,7 @@ public void enrich(PlatformMode platformMode, KubernetesListBuilder builder) { builder.accept(new TypedVisitor() { @Override public void visit(PodTemplateSpecBuilder builder) { - initContainerHandler.appendInitContainer(builder, createInitContainer()); + KubernetesResourceUtil.appendInitContainer(builder, createInitContainer(), log); } private Container createInitContainer() { diff --git a/jkube-kit/enricher/generic/src/test/java/org/eclipse/jkube/enricher/generic/ControllerViaPluginConfigurationEnricherTest.java b/jkube-kit/enricher/generic/src/test/java/org/eclipse/jkube/enricher/generic/ControllerViaPluginConfigurationEnricherTest.java index 3bc533cc8d..910a1896c0 100644 --- a/jkube-kit/enricher/generic/src/test/java/org/eclipse/jkube/enricher/generic/ControllerViaPluginConfigurationEnricherTest.java +++ b/jkube-kit/enricher/generic/src/test/java/org/eclipse/jkube/enricher/generic/ControllerViaPluginConfigurationEnricherTest.java @@ -26,6 +26,7 @@ import io.fabric8.kubernetes.api.model.apps.StatefulSetBuilder; import io.fabric8.kubernetes.api.model.apps.StatefulSetSpec; import org.assertj.core.api.InstanceOfAssertFactories; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; import org.eclipse.jkube.kit.config.resource.PlatformMode; import org.eclipse.jkube.kit.config.resource.ResourceConfig; import org.eclipse.jkube.kit.enricher.api.EnricherContext; @@ -56,6 +57,8 @@ class ControllerViaPluginConfigurationEnricherTest { void setUp() { context = mock(JKubeEnricherContext.class, RETURNS_DEEP_STUBS); when(context.getGav().getSanitizedArtifactId()).thenReturn("test-project"); + when(context.getConfiguration().getResource()).thenReturn(ResourceConfig.builder() + .build()); kubernetesListBuilder = new KubernetesListBuilder(); } @@ -165,7 +168,7 @@ void create_withStatefulSetFragmentWithExistingNameAndConfiguredControllerName_s void create_withDeploymentFragmentAndImagePullPolicyPropertySet_shouldSendConfiguredPolicyToDeploymentHandler() { // Given mockDeploymentHandler(); - ArgumentCaptor resourceConfigArgumentCaptor = ArgumentCaptor.forClass(ResourceConfig.class); + ArgumentCaptor controllerResourceConfigArgumentCaptor = ArgumentCaptor.forClass(ControllerResourceConfig.class); controllerViaPluginConfigurationEnricher = new ControllerViaPluginConfigurationEnricher(context); when(context.getProperty("jkube.imagePullPolicy")).thenReturn("Never"); DeploymentBuilder deploymentFragment = createNewDeploymentBuilder().withNewMetadata() @@ -178,8 +181,8 @@ void create_withDeploymentFragmentAndImagePullPolicyPropertySet_shouldSendConfig // Then verify(mockedDeploymentHandler, times(1)) - .get(resourceConfigArgumentCaptor.capture(), any()); - assertThat(resourceConfigArgumentCaptor.getValue()) + .get(controllerResourceConfigArgumentCaptor.capture(), any()); + assertThat(controllerResourceConfigArgumentCaptor.getValue()) .hasFieldOrPropertyWithValue("imagePullPolicy", "Never"); } diff --git a/jkube-kit/enricher/generic/src/test/java/org/eclipse/jkube/enricher/generic/ImageEnricherTest.java b/jkube-kit/enricher/generic/src/test/java/org/eclipse/jkube/enricher/generic/ImageEnricherTest.java index 550f9c7e40..51198322c1 100644 --- a/jkube-kit/enricher/generic/src/test/java/org/eclipse/jkube/enricher/generic/ImageEnricherTest.java +++ b/jkube-kit/enricher/generic/src/test/java/org/eclipse/jkube/enricher/generic/ImageEnricherTest.java @@ -16,12 +16,15 @@ import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.api.model.KubernetesList; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; +import io.fabric8.kubernetes.api.model.ReplicationControllerBuilder; import io.fabric8.kubernetes.api.model.apps.DaemonSetBuilder; import io.fabric8.kubernetes.api.model.apps.DeploymentBuilder; import io.fabric8.kubernetes.api.model.apps.ReplicaSetBuilder; import io.fabric8.kubernetes.api.model.apps.StatefulSetBuilder; import io.fabric8.openshift.api.model.DeploymentConfigBuilder; +import org.eclipse.jkube.kit.common.PrefixedLogger; import org.eclipse.jkube.kit.config.image.ImageConfiguration; +import org.eclipse.jkube.kit.config.resource.ControllerResourceConfig; import org.eclipse.jkube.kit.config.resource.PlatformMode; import org.eclipse.jkube.kit.config.resource.ResourceConfig; import org.eclipse.jkube.kit.enricher.api.JKubeEnricherContext; @@ -32,14 +35,18 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.MockedConstruction; import java.util.Collections; import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; +import static org.eclipse.jkube.enricher.generic.ImageEnricher.containerImageName; import static org.junit.jupiter.params.provider.Arguments.arguments; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** @@ -77,6 +84,7 @@ static Stream resources() { return Stream.of( arguments(new DeploymentBuilder().build(), "Deployment"), arguments(new ReplicaSetBuilder().build(), "ReplicaSet"), + arguments(new ReplicationControllerBuilder().build(), "ReplicationController"), arguments(new DaemonSetBuilder().build(), "DaemonSet"), arguments(new StatefulSetBuilder().build(), "StatefulSet"), arguments(new DeploymentConfigBuilder().build(), "DeploymentConfig")); @@ -117,6 +125,34 @@ void create_whenEnvironmentVariablePresentWithDifferentValue_thenOldValueIsPrese assertCorrectlyGeneratedResources(builder.build(), "Deployment", "key", "valueOld"); } + @Test + void create_whenNoImageConfiguration_thenSkip() { + try (MockedConstruction prefixedLoggerMockedConstruction = mockConstruction(PrefixedLogger.class)) { + // Given + KubernetesListBuilder builder = new KubernetesListBuilder(); + when(context.getConfiguration()).thenReturn(Configuration.builder() + .images(Collections.emptyList()) + .build()); + imageEnricher = new ImageEnricher(context); + + // When + imageEnricher.create(PlatformMode.kubernetes, builder); + + // Then + assertThat(prefixedLoggerMockedConstruction.constructed()).hasSize(1); + verify(prefixedLoggerMockedConstruction.constructed().get(0)) + .verbose("No images resolved. Skipping ..."); + } + } + + @Test + void containerImageName_whenRegistryPresent_thenAddRegistryPrefixToImageName() { + assertThat(containerImageName(ImageConfiguration.builder() + .name("foo/bar:latest") + .registry("example.com") + .build())).isEqualTo("example.com/foo/bar:latest"); + } + private void assertCorrectlyGeneratedResources(KubernetesList list, String kind, String expectedKey, String expectedValue) { assertThat(list.getItems()) .satisfies(l -> assertThat(l).singleElement() @@ -133,8 +169,10 @@ private void assertCorrectlyGeneratedResources(KubernetesList list, String kind, private void givenResourceConfigWithEnvVar(String name, String value) { Configuration configuration = Configuration.builder() .resource(ResourceConfig.builder() + .controller(ControllerResourceConfig.builder() .env(Collections.singletonMap(name, value)) .build()) + .build()) .image(imageConfiguration) .build(); when(context.getConfiguration()).thenReturn(configuration); diff --git a/jkube-kit/enricher/generic/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker b/jkube-kit/enricher/generic/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker new file mode 100644 index 0000000000..ca6ee9cea8 --- /dev/null +++ b/jkube-kit/enricher/generic/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker @@ -0,0 +1 @@ +mock-maker-inline \ No newline at end of file diff --git a/jkube-kit/enricher/specific/src/test/java/org/eclipse/jkube/kit/enricher/specific/DockerHealthCheckEnricherTest.java b/jkube-kit/enricher/specific/src/test/java/org/eclipse/jkube/kit/enricher/specific/DockerHealthCheckEnricherTest.java index b407001af3..7f69e025df 100644 --- a/jkube-kit/enricher/specific/src/test/java/org/eclipse/jkube/kit/enricher/specific/DockerHealthCheckEnricherTest.java +++ b/jkube-kit/enricher/specific/src/test/java/org/eclipse/jkube/kit/enricher/specific/DockerHealthCheckEnricherTest.java @@ -23,7 +23,7 @@ import io.fabric8.kubernetes.api.model.apps.DeploymentBuilder; import org.eclipse.jkube.kit.config.image.build.BuildConfiguration; import org.eclipse.jkube.kit.config.image.ImageConfiguration; -import org.eclipse.jkube.kit.config.image.build.Arguments; +import org.eclipse.jkube.kit.common.Arguments; import org.eclipse.jkube.kit.config.image.build.HealthCheckConfiguration; import org.eclipse.jkube.kit.config.image.build.HealthCheckMode; import org.eclipse.jkube.kit.config.resource.PlatformMode; diff --git a/jkube-kit/generator/java-exec/src/main/java/org/eclipse/jkube/generator/javaexec/JavaExecGenerator.java b/jkube-kit/generator/java-exec/src/main/java/org/eclipse/jkube/generator/javaexec/JavaExecGenerator.java index 9f6f68b443..b0f80df741 100644 --- a/jkube-kit/generator/java-exec/src/main/java/org/eclipse/jkube/generator/javaexec/JavaExecGenerator.java +++ b/jkube-kit/generator/java-exec/src/main/java/org/eclipse/jkube/generator/javaexec/JavaExecGenerator.java @@ -23,7 +23,7 @@ import lombok.AllArgsConstructor; import lombok.Getter; import org.eclipse.jkube.kit.common.AssemblyConfiguration; -import org.eclipse.jkube.kit.config.image.build.Arguments; +import org.eclipse.jkube.kit.common.Arguments; import org.eclipse.jkube.kit.config.image.build.BuildConfiguration; import org.eclipse.jkube.kit.config.image.ImageConfiguration; import org.eclipse.jkube.kit.common.Configs; diff --git a/jkube-kit/generator/webapp/src/main/java/org/eclipse/jkube/generator/webapp/WebAppGenerator.java b/jkube-kit/generator/webapp/src/main/java/org/eclipse/jkube/generator/webapp/WebAppGenerator.java index d8b31b60df..f28cd8f93c 100644 --- a/jkube-kit/generator/webapp/src/main/java/org/eclipse/jkube/generator/webapp/WebAppGenerator.java +++ b/jkube-kit/generator/webapp/src/main/java/org/eclipse/jkube/generator/webapp/WebAppGenerator.java @@ -34,7 +34,7 @@ import org.eclipse.jkube.kit.config.image.ImageConfiguration; import org.eclipse.jkube.kit.common.Configs; import org.eclipse.jkube.kit.common.util.JKubeProjectUtil; -import org.eclipse.jkube.kit.config.image.build.Arguments; +import org.eclipse.jkube.kit.common.Arguments; import org.eclipse.jkube.kit.config.image.build.JKubeBuildStrategy; import org.eclipse.jkube.generator.api.GeneratorContext; import org.eclipse.jkube.generator.api.support.BaseGenerator; diff --git a/jkube-kit/jkube-kit-quarkus/src/main/java/org/eclipse/jkube/quarkus/generator/QuarkusGenerator.java b/jkube-kit/jkube-kit-quarkus/src/main/java/org/eclipse/jkube/quarkus/generator/QuarkusGenerator.java index 655c3240d3..443d46d8a4 100644 --- a/jkube-kit/jkube-kit-quarkus/src/main/java/org/eclipse/jkube/quarkus/generator/QuarkusGenerator.java +++ b/jkube-kit/jkube-kit-quarkus/src/main/java/org/eclipse/jkube/quarkus/generator/QuarkusGenerator.java @@ -13,7 +13,6 @@ */ package org.eclipse.jkube.quarkus.generator; -import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -24,9 +23,8 @@ import org.eclipse.jkube.generator.javaexec.JavaExecGenerator; import org.eclipse.jkube.kit.common.AssemblyConfiguration; import org.eclipse.jkube.kit.common.Configs; -import org.eclipse.jkube.kit.common.util.JKubeProjectUtil; import org.eclipse.jkube.kit.config.image.ImageConfiguration; -import org.eclipse.jkube.kit.config.image.build.Arguments; +import org.eclipse.jkube.kit.common.Arguments; import org.eclipse.jkube.kit.config.resource.RuntimeMode; import org.eclipse.jkube.quarkus.QuarkusMode;