diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d807000e9..549119d423 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,7 @@ Usage: * Fix #237: Remove deprecated fields and method calls * Fix #192: Removed `@Deprecated` fields from ClusterAccess * Fix #190: Removed `@Deprecated` fields from AssemblyConfiguration +* Fix #189: Removed `@Deprecated` fields from BuildConfiguration ### 1.0.0-alpha-4 (2020-06-08) diff --git a/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/core/assembly/AssemblyConfigurationUtils.java b/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/core/assembly/AssemblyConfigurationUtils.java index 2692df68f5..4381f22dae 100644 --- a/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/core/assembly/AssemblyConfigurationUtils.java +++ b/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/core/assembly/AssemblyConfigurationUtils.java @@ -37,7 +37,7 @@ private AssemblyConfigurationUtils() {} static AssemblyConfiguration getAssemblyConfigurationOrCreateDefault(BuildConfiguration buildConfiguration) { final AssemblyConfiguration ac = Optional.ofNullable(buildConfiguration) - .map(BuildConfiguration::getAssemblyConfiguration) + .map(BuildConfiguration::getAssembly) .orElse(AssemblyConfiguration.builder().user(DEFAULT_USER).build()); final AssemblyConfiguration.AssemblyConfigurationBuilder builder = ac.toBuilder(); final String name; diff --git a/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/core/assembly/DockerAssemblyManager.java b/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/core/assembly/DockerAssemblyManager.java index 5182edc2fe..19d162dbca 100644 --- a/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/core/assembly/DockerAssemblyManager.java +++ b/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/core/assembly/DockerAssemblyManager.java @@ -147,7 +147,7 @@ private void interpolateDockerfile(File dockerFile, BuildDirs params, Properties // visible for testing void verifyGivenDockerfile(File dockerFile, BuildConfiguration buildConfig, Properties properties, KitLogger log) throws IOException { - AssemblyConfiguration assemblyConfig = buildConfig.getAssemblyConfiguration(); + AssemblyConfiguration assemblyConfig = buildConfig.getAssembly(); if (assemblyConfig == null) { return; } @@ -190,7 +190,7 @@ public AssemblyFiles getAssemblyFiles(String name, BuildConfiguration buildConfi BuildDirs buildDirs = createBuildDirs(name, jKubeConfiguration); - AssemblyConfiguration assemblyConfig = buildConfig.getAssemblyConfiguration(); + AssemblyConfiguration assemblyConfig = buildConfig.getAssembly(); String assemblyName = assemblyConfig.getName(); AssemblyFiles assemblyFiles = new AssemblyFiles(buildDirs.getOutputDirectory()); @@ -285,7 +285,7 @@ DockerFileBuilder createDockerFileBuilder(BuildConfiguration buildConfig, Assemb builder.workdir(buildConfig.getWorkdir()); } if (assemblyConfig != null) { - builder.add(assemblyConfig.getName(), "") + builder.add(assemblyConfig.getTargetDir(), "") .basedir(assemblyConfig.getTargetDir()) .assemblyUser(assemblyConfig.getUser()) .exportTargetDir(assemblyConfig.getExportTargetDir()); @@ -472,13 +472,13 @@ private File processAssemblyConfigToCreateTarball(BuildConfiguration buildConfig archiveCustomizers.add(archiver -> { File finalArtifactFile = JKubeProjectUtil.getFinalOutputArtifact(params.getProject()); if (finalArtifactFile != null) { - archiver.includeFile(finalArtifactFile, assemblyConfig.getName() + File.separator + finalArtifactFile.getName()); + archiver.includeFile(finalArtifactFile, assemblyConfig.getTargetDir() + File.separator + finalArtifactFile.getName()); } return archiver; }); } - List filesToExclude = getJKubeAssemblyFileSetsExcludes(buildConfig.getAssemblyConfiguration()); + List filesToExclude = getJKubeAssemblyFileSetsExcludes(buildConfig.getAssembly()); archiveCustomizers.add(archiver -> { filesToExclude.forEach(archiver::excludeFile); fileToPermissionsMap.forEach(archiver::setFilePermissions); diff --git a/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/BuildService.java b/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/BuildService.java index 72847674ba..156a6e3e8d 100644 --- a/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/BuildService.java +++ b/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/BuildService.java @@ -267,7 +267,7 @@ private String extractBaseFromConfiguration(BuildConfiguration buildConfig) { String fromImage; fromImage = buildConfig.getFrom(); if (fromImage == null) { - AssemblyConfiguration assemblyConfig = buildConfig.getAssemblyConfiguration(); + AssemblyConfiguration assemblyConfig = buildConfig.getAssembly(); if (assemblyConfig == null) { fromImage = DockerAssemblyManager.DEFAULT_DATA_BASE_IMAGE; } diff --git a/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/ImageConfiguration.java b/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/ImageConfiguration.java index 6d4db7c118..2552f55228 100644 --- a/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/ImageConfiguration.java +++ b/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/ImageConfiguration.java @@ -26,7 +26,6 @@ import org.eclipse.jkube.kit.build.service.docker.config.RunVolumeConfiguration; import org.eclipse.jkube.kit.build.service.docker.config.WatchImageConfiguration; import org.eclipse.jkube.kit.build.service.docker.helper.StartOrderResolver; -import org.eclipse.jkube.kit.common.KitLogger; import org.eclipse.jkube.kit.common.util.EnvUtil; import org.eclipse.jkube.kit.config.image.ImageName; @@ -156,11 +155,11 @@ public String getDescription() { return String.format("[%s] %s", new ImageName(name).getFullName(), (alias != null ? "\"" + alias + "\"" : "")).trim(); } - public String initAndValidate(ConfigHelper.NameFormatter nameFormatter, KitLogger log) { + public String initAndValidate(ConfigHelper.NameFormatter nameFormatter) { name = nameFormatter.format(name); String minimalApiVersion = null; if (build != null) { - minimalApiVersion = build.initAndValidate(log); + minimalApiVersion = build.initAndValidate(); } if (run != null) { minimalApiVersion = EnvUtil.extractLargerVersion(minimalApiVersion, run.initAndValidate()); diff --git a/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/WatchService.java b/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/WatchService.java index e195215d16..eaa17b782c 100644 --- a/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/WatchService.java +++ b/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/WatchService.java @@ -92,9 +92,9 @@ public synchronized void watch(WatchContext context, JKubeConfiguration buildCon ArrayList tasks = new ArrayList<>(); if (imageConfig.getBuildConfiguration() != null && - imageConfig.getBuildConfiguration().getAssemblyConfiguration() != null) { + imageConfig.getBuildConfiguration().getAssembly() != null) { if (watcher.isCopy()) { - String containerBaseDir = imageConfig.getBuildConfiguration().getAssemblyConfiguration().getTargetDir(); + String containerBaseDir = imageConfig.getBuildConfiguration().getAssembly().getTargetDir(); schedule(executor, createCopyWatchTask(watcher, context.getBuildContext(), containerBaseDir), interval); tasks.add("copying artifacts"); } diff --git a/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/config/ConfigHelper.java b/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/config/ConfigHelper.java index cec2ab6a46..20d6d694e2 100644 --- a/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/config/ConfigHelper.java +++ b/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/config/ConfigHelper.java @@ -115,14 +115,12 @@ public static String getExternalConfigActivationProperty(JavaProject project) { * @param images the images to check * @param apiVersion the original API version intended to use * @param nameFormatter formatter for image names - * @param log a logger for printing out diagnostic messages * @return the minimal API Docker API required to be used for the given configuration. */ - public static String initAndValidate(List images, String apiVersion, NameFormatter nameFormatter, - KitLogger log) { + public static String initAndValidate(List images, String apiVersion, NameFormatter nameFormatter) { // Init and validate configs. After this step, getResolvedImages() contains the valid configuration. for (ImageConfiguration imageConfiguration : images) { - apiVersion = EnvUtil.extractLargerVersion(apiVersion, imageConfiguration.initAndValidate(nameFormatter, log)); + apiVersion = EnvUtil.extractLargerVersion(apiVersion, imageConfiguration.initAndValidate(nameFormatter)); } return apiVersion; } diff --git a/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/config/handler/property/ConfigKey.java b/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/config/handler/property/ConfigKey.java index ebde900963..c3f920c78b 100644 --- a/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/config/handler/property/ConfigKey.java +++ b/jkube-kit/build/service/docker/src/main/java/org/eclipse/jkube/kit/build/service/docker/config/handler/property/ConfigKey.java @@ -52,7 +52,6 @@ public enum ConfigKey { DNS_SEARCH, DOCKER_ARCHIVE, DOCKER_FILE, - DOCKER_FILE_DIR, ENTRYPOINT, ENV, ENV_PROPERTY_FILE, 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 382df5ffe2..e6fa19f96b 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 @@ -69,7 +69,6 @@ import static org.eclipse.jkube.kit.build.service.docker.config.handler.property.ConfigKey.DNS_SEARCH; import static org.eclipse.jkube.kit.build.service.docker.config.handler.property.ConfigKey.DOCKER_ARCHIVE; import static org.eclipse.jkube.kit.build.service.docker.config.handler.property.ConfigKey.DOCKER_FILE; -import static org.eclipse.jkube.kit.build.service.docker.config.handler.property.ConfigKey.DOCKER_FILE_DIR; import static org.eclipse.jkube.kit.build.service.docker.config.handler.property.ConfigKey.DOMAINNAME; import static org.eclipse.jkube.kit.build.service.docker.config.handler.property.ConfigKey.ENTRYPOINT; import static org.eclipse.jkube.kit.build.service.docker.config.handler.property.ConfigKey.ENV; @@ -114,7 +113,6 @@ import static org.eclipse.jkube.kit.build.service.docker.config.handler.property.ConfigKey.PORT_PROPERTY_FILE; import static org.eclipse.jkube.kit.build.service.docker.config.handler.property.ConfigKey.PRIVILEGED; import static org.eclipse.jkube.kit.build.service.docker.config.handler.property.ConfigKey.READ_ONLY; -import static org.eclipse.jkube.kit.build.service.docker.config.handler.property.ConfigKey.REGISTRY; import static org.eclipse.jkube.kit.build.service.docker.config.handler.property.ConfigKey.RESTART_POLICY_NAME; import static org.eclipse.jkube.kit.build.service.docker.config.handler.property.ConfigKey.RESTART_POLICY_RETRY; import static org.eclipse.jkube.kit.build.service.docker.config.handler.property.ConfigKey.RUN; @@ -195,10 +193,9 @@ private static boolean isStringValueNull(ValueProvider valueProvider, BuildConfi return valueProvider.getString(key, config == null ? null : supplier.get()) != null; } - // Enable build config only when a `.from.`, `.dockerFile.`, or `.dockerFileDir.` is configured + // Enable build config only when a `.from.`, or `.dockerFile.` is configured private boolean buildConfigured(BuildConfiguration config, ValueProvider valueProvider, JavaProject project) { - if (isStringValueNull(valueProvider, config, FROM, config::getFrom)) { return true; } @@ -206,18 +203,14 @@ private boolean buildConfigured(BuildConfiguration config, ValueProvider valuePr if (valueProvider.getMap(FROM_EXT, config == null ? null : config.getFromExt()) != null) { return true; } - if (isStringValueNull(valueProvider, config, DOCKER_FILE, () -> config.getDockerFileRaw() )) { - return true; - } - if (isStringValueNull(valueProvider, config, DOCKER_ARCHIVE, () -> config.getDockerArchiveRaw())) { + if (isStringValueNull(valueProvider, config, DOCKER_FILE, config::getDockerFileRaw)) { return true; } - - if (isStringValueNull(valueProvider, config, CONTEXT_DIR, () -> config.getContextDirRaw())) { + if (isStringValueNull(valueProvider, config, DOCKER_ARCHIVE, config::getDockerArchiveRaw)) { return true; } - if (isStringValueNull(valueProvider, config, DOCKER_FILE_DIR, () -> config.getDockerFileDirRaw())) { + if (isStringValueNull(valueProvider, config, CONTEXT_DIR, config::getContextDirRaw)) { return true; } @@ -237,10 +230,10 @@ private BuildConfiguration extractBuildConfiguration(ImageConfiguration fromConf return BuildConfiguration.builder() .cmd(extractArguments(valueProvider, CMD, valueOrNull(config, BuildConfiguration::getCmd))) .cleanup(valueProvider.getString(CLEANUP, valueOrNull(config, BuildConfiguration::getCleanup))) - .nocache(valueProvider.getBoolean(NOCACHE, valueOrNull(config, BuildConfiguration::getNoCache))) + .nocache(valueProvider.getBoolean(NOCACHE, valueOrNull(config, BuildConfiguration::getNocache))) .optimise(valueProvider.getBoolean(OPTIMISE, valueOrNull(config, BuildConfiguration::getOptimise))) .entryPoint(extractArguments(valueProvider, ENTRYPOINT, valueOrNull(config, BuildConfiguration::getEntryPoint))) - .assembly(extractAssembly(valueOrNull(config, BuildConfiguration::getAssemblyConfiguration), valueProvider)) + .assembly(extractAssembly(valueOrNull(config, BuildConfiguration::getAssembly), valueProvider)) .env(MapUtil.mergeMaps( valueProvider.getMap(ENV_BUILD, valueOrNull(config, BuildConfiguration::getEnv)), valueProvider.getMap(ENV, Collections.emptyMap()) @@ -252,7 +245,6 @@ private BuildConfiguration extractBuildConfiguration(ImageConfiguration fromConf .runCmds(valueProvider.getList(RUN, valueOrNull(config, BuildConfiguration::getRunCmds))) .from(valueProvider.getString(FROM, valueOrNull(config, BuildConfiguration::getFrom))) .fromExt(valueProvider.getMap(FROM_EXT, valueOrNull(config, BuildConfiguration::getFromExt))) - .registry(valueProvider.getString(REGISTRY, valueOrNull(config, BuildConfiguration::getRegistry))) .volumes(valueProvider.getList(VOLUMES, valueOrNull(config, BuildConfiguration::getVolumes))) .tags(valueProvider.getList(TAGS, valueOrNull(config, BuildConfiguration::getTags))) .maintainer(valueProvider.getString(MAINTAINER, valueOrNull(config, BuildConfiguration::getMaintainer))) @@ -262,9 +254,8 @@ private BuildConfiguration extractBuildConfiguration(ImageConfiguration fromConf .contextDir(valueProvider.getString(CONTEXT_DIR, valueOrNull(config, BuildConfiguration::getContextDirRaw))) .dockerArchive(valueProvider.getString(DOCKER_ARCHIVE, valueOrNull(config, BuildConfiguration::getDockerArchiveRaw))) .dockerFile(valueProvider.getString(DOCKER_FILE, valueOrNull(config, BuildConfiguration::getDockerFileRaw))) - .dockerFileDir(valueProvider.getString(DOCKER_FILE_DIR, valueOrNull(config, BuildConfiguration::getDockerFileDirRaw))) .buildOptions(valueProvider.getMap(BUILD_OPTIONS, valueOrNull(config, BuildConfiguration::getBuildOptions))) - .filter(valueProvider.getString(FILTER, valueOrNull(config, BuildConfiguration::getFilterRaw))) + .filter(valueProvider.getString(FILTER, valueOrNull(config, BuildConfiguration::getFilter))) .user(valueProvider.getString(USER, valueOrNull(config, BuildConfiguration::getUser))) .healthCheck(extractHealthCheck(valueOrNull(config, BuildConfiguration::getHealthCheck), valueProvider)) .build(); diff --git a/jkube-kit/build/service/docker/src/test/java/org/eclipse/jkube/kit/build/core/assembly/AssemblyConfigurationUtilsTest.java b/jkube-kit/build/service/docker/src/test/java/org/eclipse/jkube/kit/build/core/assembly/AssemblyConfigurationUtilsTest.java index 2cd47131ac..57556de6e9 100644 --- a/jkube-kit/build/service/docker/src/test/java/org/eclipse/jkube/kit/build/core/assembly/AssemblyConfigurationUtilsTest.java +++ b/jkube-kit/build/service/docker/src/test/java/org/eclipse/jkube/kit/build/core/assembly/AssemblyConfigurationUtilsTest.java @@ -45,7 +45,7 @@ public void getAssemblyConfigurationOrCreateDefaultNoConfigurationShouldReturnDe // Given new Expectations() {{ - buildConfiguration.getAssemblyConfiguration(); + buildConfiguration.getAssembly(); result = null; }}; // When @@ -63,7 +63,7 @@ public void getAssemblyConfigurationOrCreateDefaultWithConfigurationShouldReturn // Given final AssemblyConfiguration configuration = AssemblyConfiguration.builder().user("OtherUser").name("ImageName").build(); new Expectations() {{ - buildConfiguration.getAssemblyConfiguration(); + buildConfiguration.getAssembly(); result = configuration; }}; // When diff --git a/jkube-kit/build/service/docker/src/test/java/org/eclipse/jkube/kit/build/core/assembly/DockerAssemblyManagerTest.java b/jkube-kit/build/service/docker/src/test/java/org/eclipse/jkube/kit/build/core/assembly/DockerAssemblyManagerTest.java index a05b74ebaf..0e0a30da9d 100644 --- a/jkube-kit/build/service/docker/src/test/java/org/eclipse/jkube/kit/build/core/assembly/DockerAssemblyManagerTest.java +++ b/jkube-kit/build/service/docker/src/test/java/org/eclipse/jkube/kit/build/core/assembly/DockerAssemblyManagerTest.java @@ -57,7 +57,7 @@ public class DockerAssemblyManagerTest { @Test public void testNoAssembly() { BuildConfiguration buildConfig = BuildConfiguration.builder().build(); - AssemblyConfiguration assemblyConfig = buildConfig.getAssemblyConfiguration(); + AssemblyConfiguration assemblyConfig = buildConfig.getAssembly(); DockerFileBuilder builder = assemblyManager.createDockerFileBuilder(buildConfig, assemblyConfig); String content = builder.content(); @@ -253,7 +253,7 @@ public void testCreateDockerTarArchiveWithDockerfile() throws IOException { File dockerDirectory = new File(targetDirectory, "docker"); - final JKubeConfiguration jKubeBuildContext = JKubeConfiguration.builder() + final JKubeConfiguration configuration = JKubeConfiguration.builder() .project(JavaProject.builder() .groupId("org.eclipse.jkube") .artifactId("test") @@ -269,14 +269,13 @@ public void testCreateDockerTarArchiveWithDockerfile() throws IOException { .sourceDirectory(baseProjectDir.getPath() + "/src/main/docker") .build(); final BuildConfiguration jKubeBuildConfiguration = BuildConfiguration.builder() - .dockerFileDir(baseProjectDir.getPath()) .dockerFile(dockerFile.getPath()) .dockerFileFile(dockerFile) .build(); // When - File dockerArchiveFile = assemblyManager.createDockerTarArchive("test-image", jKubeBuildContext, jKubeBuildConfiguration, prefixedLogger, null); + File dockerArchiveFile = assemblyManager.createDockerTarArchive("test-image", configuration, jKubeBuildConfiguration, prefixedLogger, null); // Then assertNotNull(dockerArchiveFile); diff --git a/jkube-kit/build/service/docker/src/test/java/org/eclipse/jkube/kit/build/service/docker/ImageConfigurationTest.java b/jkube-kit/build/service/docker/src/test/java/org/eclipse/jkube/kit/build/service/docker/ImageConfigurationTest.java new file mode 100644 index 0000000000..52ec6c5ad6 --- /dev/null +++ b/jkube-kit/build/service/docker/src/test/java/org/eclipse/jkube/kit/build/service/docker/ImageConfigurationTest.java @@ -0,0 +1,50 @@ +/** + * 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.build.service.docker; + +import mockit.Expectations; +import org.eclipse.jkube.kit.build.service.docker.config.ConfigHelper; +import org.eclipse.jkube.kit.build.service.docker.config.RunImageConfiguration; +import org.eclipse.jkube.kit.config.image.build.BuildConfiguration; + +import mockit.Mocked; +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +public class ImageConfigurationTest { + + @Test + public void initAndValidateWithBuildAndRun( + @Mocked ConfigHelper.NameFormatter nameFormatter, @Mocked BuildConfiguration buildConfiguration, + @Mocked RunImageConfiguration runImageConfiguration) { + + // Given + final ImageConfiguration imageConfiguration = ImageConfiguration.builder() + .build(buildConfiguration) + .run(runImageConfiguration) + .build(); + // @formatter:off + new Expectations() {{ + buildConfiguration.initAndValidate(); result = "1.337"; + runImageConfiguration.initAndValidate(); result = "13.37"; + }}; + // @formatter:on + // When + final String result = imageConfiguration.initAndValidate(nameFormatter); + // Then + assertThat(result, is("13.37")); + } +} diff --git a/jkube-kit/common/src/main/java/org/eclipse/jkube/kit/common/archive/AssemblyFileSetUtils.java b/jkube-kit/common/src/main/java/org/eclipse/jkube/kit/common/archive/AssemblyFileSetUtils.java index 250c703504..9dc12f458c 100644 --- a/jkube-kit/common/src/main/java/org/eclipse/jkube/kit/common/archive/AssemblyFileSetUtils.java +++ b/jkube-kit/common/src/main/java/org/eclipse/jkube/kit/common/archive/AssemblyFileSetUtils.java @@ -74,9 +74,8 @@ public static Map processAssemblyFileSet( final Map fileToPermissionsMap = new HashMap<>(); final File sourceDirectory = resolveSourceDirectory(baseDirectory, assemblyFileSet); - final File targetDirectory = outputDirectory.toPath() - .resolve(Objects.requireNonNull(assemblyConfiguration.getName(), "Assembly Configuration name is required")) - .toFile(); + final File targetDirectory = new File(outputDirectory, Objects.requireNonNull( + assemblyConfiguration.getTargetDir(), "Assembly Configuration target dir is required")); final File destinationDirectory; if (assemblyFileSet.getOutputDirectory() == null) { destinationDirectory = new File(targetDirectory, sourceDirectory.getName()); diff --git a/jkube-kit/common/src/main/java/org/eclipse/jkube/kit/common/archive/AssemblyFileUtils.java b/jkube-kit/common/src/main/java/org/eclipse/jkube/kit/common/archive/AssemblyFileUtils.java index 79cdf08ba7..a568d01477 100644 --- a/jkube-kit/common/src/main/java/org/eclipse/jkube/kit/common/archive/AssemblyFileUtils.java +++ b/jkube-kit/common/src/main/java/org/eclipse/jkube/kit/common/archive/AssemblyFileUtils.java @@ -29,10 +29,10 @@ public static File getAssemblyFileOutputDirectory( if (assemblyFile.getOutputDirectory().isAbsolute()) { outputDirectory = assemblyFile.getOutputDirectory(); } else { - outputDirectory = outputDirectoryForRelativePaths.toPath() - .resolve(Objects.requireNonNull(assemblyConfiguration.getName(), "Assembly Configuration name is required")) - .resolve(assemblyFile.getOutputDirectory().toPath()) - .toFile(); + outputDirectory = new File(outputDirectoryForRelativePaths, Objects.requireNonNull( + assemblyConfiguration.getTargetDir(), "Assembly Configuration target dir is required")).toPath() + .resolve(assemblyFile.getOutputDirectory().toPath()) + .toFile(); } return outputDirectory; } diff --git a/jkube-kit/common/src/test/java/org/eclipse/jkube/kit/common/archive/AssemblyFileSetUtilsProcessAssemblyFileSetTest.java b/jkube-kit/common/src/test/java/org/eclipse/jkube/kit/common/archive/AssemblyFileSetUtilsProcessAssemblyFileSetTest.java index 1bdb08bc41..453dee8b7b 100644 --- a/jkube-kit/common/src/test/java/org/eclipse/jkube/kit/common/archive/AssemblyFileSetUtilsProcessAssemblyFileSetTest.java +++ b/jkube-kit/common/src/test/java/org/eclipse/jkube/kit/common/archive/AssemblyFileSetUtilsProcessAssemblyFileSetTest.java @@ -120,7 +120,7 @@ public void assemblyFileSetHasNoDirectoryShouldThrowException() { } @Test - public void assemblyConfigurationHasNoNameShouldThrowException() { + public void assemblyConfigurationHasNoTargetDirShouldThrowException() { // Given final AssemblyFileSet afs = AssemblyFileSet.builder() .directory(sourceDirectory) @@ -131,13 +131,13 @@ public void assemblyConfigurationHasNoNameShouldThrowException() { AssemblyFileSetUtils.processAssemblyFileSet(baseDirectory, outputDirectory, afs, ac) ); // Then - assertThat(result.getMessage(), equalTo("Assembly Configuration name is required")); + assertThat(result.getMessage(), equalTo("Assembly Configuration target dir is required")); } /** - * Has AssemblyFileSet#directory and AssemblyConfiguration#name options. + * Has AssemblyFileSet#directory and AssemblyConfiguration#targetDir options. * - * Should copy the AssemblyFileSet#directory to the outputDirectory in a subdirectory named as the AssemblyConfiguration#name. + * Should copy the AssemblyFileSet#directory to the outputDirectory in a subdirectory named as the AssemblyConfiguration#targetDir. * * n.b. this is the only case where the source directory and not its contents is copied. */ @@ -148,7 +148,7 @@ public void minimumRequiredFields() throws Exception { .directory(sourceDirectory) .build(); final AssemblyConfiguration ac = AssemblyConfiguration.builder() - .name("deployments") + .targetDir("deployments") .build(); // When final Map permissions = AssemblyFileSetUtils.processAssemblyFileSet(baseDirectory, outputDirectory, afs, ac); @@ -165,7 +165,7 @@ public void minimumRequiredFields() throws Exception { } /** - * Has AssemblyFileSet#directory and AssemblyConfiguration#name options. + * Has AssemblyFileSet#directory and AssemblyConfiguration#targetDir options. * * Source directory doesn't exist * @@ -178,7 +178,7 @@ public void sourceDoesNotExist() throws Exception { .directory(new File(sourceDirectory, "non-existent")) .build(); final AssemblyConfiguration ac = AssemblyConfiguration.builder() - .name("deployments") + .targetDir("deployments") .build(); // When final Map permissions = AssemblyFileSetUtils.processAssemblyFileSet(baseDirectory, outputDirectory, afs, ac); @@ -190,9 +190,10 @@ public void sourceDoesNotExist() throws Exception { /** * Has AssemblyFileSet with directory and outputDirectory relative path resolving to self. - * Has AssemblyConfiguration name. + * Has AssemblyConfiguration targetDir. * - * Should copy contents of AssemblyFileSet#directory to the outputDirectory in a subdirectory named as the AssemblyConfiguration#name. + * Should copy contents of AssemblyFileSet#directory to the outputDirectory in a subdirectory named as the + * AssemblyConfiguration#targetDir. */ @Test public void fileSetDirectoryAndOutputDirectoryResolvingToSelf() throws Exception { @@ -202,7 +203,8 @@ public void fileSetDirectoryAndOutputDirectoryResolvingToSelf() throws Exception .outputDirectory(new File(".")) .build(); final AssemblyConfiguration ac = AssemblyConfiguration.builder() - .name("deployments") + .name("NotImportant") + .targetDir("deployments") .build(); // When final Map permissions = AssemblyFileSetUtils.processAssemblyFileSet(baseDirectory, outputDirectory, afs, ac); @@ -217,7 +219,7 @@ public void fileSetDirectoryAndOutputDirectoryResolvingToSelf() throws Exception /** * Has AssemblyFileSet directory and absolute outputDirectory. - * Has AssemblyConfiguration name. + * Has AssemblyConfiguration targetDir. * * Should copy contents of AssemblyFileSet#directory to the absoluteOutputDirectory. */ @@ -231,7 +233,7 @@ public void fileSetDirectoryAndAbsoluteOutputDirectory() throws Exception { .outputDirectory(absoluteOutputDirectory) .build(); final AssemblyConfiguration ac = AssemblyConfiguration.builder() - .name("deployments") + .targetDir("/deployments") .build(); // When final Map permissions = AssemblyFileSetUtils.processAssemblyFileSet(baseDirectory, outputDirectory, afs, ac); @@ -243,10 +245,10 @@ public void fileSetDirectoryAndAbsoluteOutputDirectory() throws Exception { } /** - * No options provided except of the AssemblyFileSet#directory, relative outputDirectory and AssemblyConfiguration#name. + * No options provided except of the AssemblyFileSet#directory, relative outputDirectory and AssemblyConfiguration#targetDir. * * Should copy contents of AssemblyFileSet#directory to the outputDirectory in a relative subdirectory with path - * composed of AssemblyConfiguration#name and the relative outputDirectory. + * composed of AssemblyConfiguration#targetDir and the relative outputDirectory. */ @Test public void fileSetDirectoryAndRelativeOutputDirectory() throws Exception { @@ -257,7 +259,8 @@ public void fileSetDirectoryAndRelativeOutputDirectory() throws Exception { .outputDirectory(relativeOutputDirectory) .build(); final AssemblyConfiguration ac = AssemblyConfiguration.builder() - .name("deployments") + .name("MyNameIsAl") + .targetDir("/deployments/") .build(); // When final Map permissions = AssemblyFileSetUtils.processAssemblyFileSet(baseDirectory, outputDirectory, afs, ac); @@ -275,9 +278,9 @@ public void fileSetDirectoryAndRelativeOutputDirectory() throws Exception { /** * Has AssemblyFileSet#directory and includes for files in several hierarchic levels. - * Has AssemblyConfiguration name. + * Has AssemblyConfiguration targetDir. * - * Should copy contents of AssemblyFileSet#directory to the outputDirectory in a subdirectory named as the AssemblyConfiguration#name. + * Should copy contents of AssemblyFileSet#directory to the outputDirectory in a subdirectory named as the AssemblyConfiguration#targetDir. */ @Test public void hierarchicalInclude() throws Exception { @@ -290,6 +293,7 @@ public void hierarchicalInclude() throws Exception { .build(); final AssemblyConfiguration ac = AssemblyConfiguration.builder() .name("deployments") + .targetDir("/deployments") .build(); // When final Map permissions = AssemblyFileSetUtils.processAssemblyFileSet(baseDirectory, outputDirectory, afs, ac); @@ -309,9 +313,9 @@ public void hierarchicalInclude() throws Exception { /** * AssemblyFileSet#directory, relative outputDirectory and includes for files in several hierarchic levels. - * Has AssemblyConfiguration name. + * Has AssemblyConfiguration targetDir. * - * Should copy contents of AssemblyFileSet#directory to the outputDirectory in a subdirectory named as the AssemblyConfiguration#name. + * Should copy contents of AssemblyFileSet#directory to the outputDirectory in a subdirectory named as the AssemblyConfiguration#targetDir. */ @Test public void hierarchicalIncludeInRelativeDirectory() throws Exception { @@ -324,7 +328,7 @@ public void hierarchicalIncludeInRelativeDirectory() throws Exception { .include("three") .build(); final AssemblyConfiguration ac = AssemblyConfiguration.builder() - .name("maven") + .targetDir("maven") .build(); // When final Map permissions = AssemblyFileSetUtils.processAssemblyFileSet(baseDirectory, outputDirectory, afs, ac); diff --git a/jkube-kit/common/src/test/java/org/eclipse/jkube/kit/common/archive/AssemblyFileUtilsTest.java b/jkube-kit/common/src/test/java/org/eclipse/jkube/kit/common/archive/AssemblyFileUtilsTest.java index 0ceacac10c..59d97dab13 100644 --- a/jkube-kit/common/src/test/java/org/eclipse/jkube/kit/common/archive/AssemblyFileUtilsTest.java +++ b/jkube-kit/common/src/test/java/org/eclipse/jkube/kit/common/archive/AssemblyFileUtilsTest.java @@ -46,7 +46,7 @@ public void getAssemblyFileOutputDirectoryWithRelativeDirectoryShouldReturnCompu // Given final AssemblyFile af = AssemblyFile.builder().outputDirectory(new File("target")).build(); final File outputDirectoryForRelativePaths = temporaryFolder.newFolder("output"); - final AssemblyConfiguration ac = AssemblyConfiguration.builder().name("project").build(); + final AssemblyConfiguration ac = AssemblyConfiguration.builder().targetDir("/project").build(); // When final File result = AssemblyFileUtils.getAssemblyFileOutputDirectory(af, outputDirectoryForRelativePaths, ac); // Then 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 0de95b613e..237f6df594 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 @@ -24,17 +24,21 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; +import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; +import lombok.Setter; import lombok.Singular; import org.eclipse.jkube.kit.common.AssemblyConfiguration; -import org.eclipse.jkube.kit.common.KitLogger; import org.eclipse.jkube.kit.common.archive.ArchiveCompression; import org.eclipse.jkube.kit.common.util.EnvUtil; +import static org.eclipse.jkube.kit.common.util.EnvUtil.isWindows; + + /** * @author roland */ @@ -45,349 +49,404 @@ @EqualsAndHashCode(doNotUseGetters = true) public class BuildConfiguration implements Serializable { - private static final long serialVersionUID = 3904939784596208966L; - - public static final String DEFAULT_FILTER = "${*}"; - public static final String DEFAULT_CLEANUP = "try"; - - /** - * Directory used as the context directory, e.g. for a docker build. - */ - private String contextDir; - /** - * Path to a dockerfile to use. Its parent directory is used as build context (i.e. as dockerFileDir). - * Multiple different Dockerfiles can be specified that way. If set overwrites a possibly given. - * contextDir - */ - private String dockerFile; - /** - * Path to a docker archive to load an image instead of building from scratch. - * Note only either dockerFile/dockerFileDir or - * dockerArchive can be used. - */ - private String dockerArchive; - /** - * How interpolation of a dockerfile should be performed. - */ - private String filter; - /** - * Base Image - */ - private String from; - /** - * Extended version for ;<from;> - */ - private Map fromExt; - private String registry; - private String maintainer; - @Singular - private List ports; - private Arguments shell; - /** - * Policy for pulling the base images - */ - private String imagePullPolicy; - /** - * RUN Commands within Build/Image - */ - @Singular - private List runCmds; - private String cleanup; - private Boolean nocache; - private Boolean optimise; - @Singular - private List volumes; - @Singular - private List tags; - @Singular("putEnv") - private Map env; - @Singular - private Map labels; - private Map args; - private Arguments entryPoint; - private String workdir; - private Arguments cmd; - private String user; - private HealthCheckConfiguration healthCheck; - private AssemblyConfiguration assembly; - private Boolean skip; - private ArchiveCompression compression; - private Map buildOptions; - /** - * Directory holding an external Dockerfile which is used to build the - * image. This Dockerfile will be enriched by the addition build configuration - */ - @Deprecated - private String dockerFileDir; - /** - * Path to Dockerfile to use, initialized lazily. - */ - private File dockerFileFile; - private File dockerArchiveFile; - - public boolean isDockerFileMode() { - return dockerFile != null || contextDir != null; - } - - public File getDockerFile() { - return dockerFileFile; - } - - public String getDockerFileRaw() { - return dockerFile; - } - - public File getDockerArchive() { - return dockerArchiveFile; - } - - public String getDockerArchiveRaw() { - return dockerArchive; + private static final long serialVersionUID = 3904939784596208966L; + + public static final String DEFAULT_FILTER = "${*}"; + public static final String DEFAULT_CLEANUP = "try"; + + /** + * Path to a directory used for the build's context. You can specify the Dockerfile to use with dockerFile, which by + * default is the Dockerfile found in the contextDir. + * The Dockerfile can be also located outside of the contextDir, if provided with an absolute file path. + */ + private String contextDir; + /** + * Path to a Dockerfile which also triggers Dockerfile mode. + * The Docker build context directory is set to contextDir if given. + * If not the directory by default is the directory in which the Dockerfile is stored. + */ + private String dockerFile; + /** + * Path to a docker archive to load an image instead of building from scratch. + * If a dockerArchive is provided, no {@link BuildConfiguration#dockerFile} must be given. + */ + private String dockerArchive; + /** + * Enable and set the delimiters for property replacements. + * + *

By default properties in the format ${..} are replaced with Maven properties. + * When using a single char like @ then this is used as a delimiter (e.g @…​@). + */ + private String filter; + /** + * The base image which should be used for this image. + * + *

If not given this default to busybox:latest and is suitable for a pure data image. + */ + private String from; + /** + * Extended definition for a base image. This field holds a map of defined in key:value format. + *

The known keys are: + *

    + *
  • name: Name of the base image
  • + *
+ *

A provided {@link BuildConfiguration#from} takes precedence over the name given here. + * This tag is useful for extensions of this plugin. + */ + private Map fromExt; + /** + * The author (MAINTAINER) field for the generated image + */ + private String maintainer; + /** + * The exposed ports which is a list of <port> elements, one for each port to expose. + * Whitespace is trimmed from each element and empty elements are ignored. + * + *

The format can be either pure numerical (8080) or with the protocol attached (8080/tcp). + */ + @Singular + private List ports; + /** + * Shell to be used for the {@link BuildConfiguration#runCmds}. It contains arg elements which are defining the + * executable and its params. + */ + private Arguments shell; + /** + * Specific pull policy for the base image. This overrides any global image pull policy. + */ + private String imagePullPolicy; + /** + * Commands to be run during the build process. + * + *

It contains <run> elements which are passed to the shell. + * Whitespace is trimmed from each element and empty elements are ignored. + * + *

The run commands are inserted right after the assembly and after {@link BuildConfiguration#workdir} into the + * Dockerfile. + * + *

This setting is not to be confused with the <run> section for this image which specifies the runtime + * behaviour when starting containers. + */ + @Singular + private List runCmds; + /** + * Cleanup dangling (untagged) images after each build (including any containers created from them) + *

    + *
  • try: tries to remove the old image but doesn't fail the build if this is not possible
  • + *
  • remove: removes old image or fails if it doesn't
  • + *
  • none: No cleanup is requested
  • + *
+ */ + private String cleanup; + /** + * Don't use Docker’s build cache. + */ + private Boolean nocache; + /** + * If set to true then it will compress all the {@link BuildConfiguration#runCmds} into a single RUN directive so that + * only one image layer is created. + */ + private Boolean optimise; + /** + * List of <volume%gt; elements to create a container volume. + * Whitespace is trimmed from each element and empty elements are ignored. + */ + @Singular + private List volumes; + /** + * List of additional tag elements with which an image is to be tagged after the build. + * Whitespace is trimmed from each element and empty elements are ignored. + */ + @Singular + private List tags; + /** + * Environment variables. + */ + @Singular("putEnv") + private Map env; + /** + * Labels. + */ + @Singular + private Map labels; + /** + * Map specifying the value of Docker build args which should be used when building the image with an external + * Dockerfile which uses build arguments. + * + *

The key-value syntax is the same as when defining Maven properties (or labels or env). This argument is + * ignored when no external Dockerfile is used. + */ + @Singular + private Map args; + /** + * An entrypoint allows you to configure a container that will run as an executable. + */ + private Arguments entryPoint; + /** + * Directory to change to when starting the container. + */ + private String workdir; + /** + * A command to execute by default. + */ + private Arguments cmd; + /** + * User to which the Dockerfile should switch to the end (corresponds to the USER Dockerfile directive). + */ + private String user; + /** + * Health check configuration. + */ + private HealthCheckConfiguration healthCheck; + /** + * Specifies the assembly configuration. + */ + private AssemblyConfiguration assembly; + /** + * If set to true disables building of the image. + */ + private Boolean skip; + /** + * The compression mode how the build archive is transmitted to the docker daemon and how docker build archives are + * attached to this build as sources. + */ + private ArchiveCompression compression; + /** + * Map specifying the build options to provide to the docker daemon when building the image. + * + *

These options map to the ones listed as query parameters in the Docker Remote API and are restricted to + * simple options (e.g.: memory, shmsize). + * + * @see Docker Engine API v1.40 + */ + private Map buildOptions; + /** + * Path to Dockerfile to use, initialized lazily. + */ + @Setter(AccessLevel.PRIVATE) + private File dockerFileFile; + @Setter(AccessLevel.PRIVATE) + private File dockerArchiveFile; + + public boolean isDockerFileMode() { + return dockerFile != null || contextDir != null; + } + + public File getDockerFile() { + return dockerFileFile; + } + + public String getDockerFileRaw() { + return dockerFile; + } + + public File getDockerArchive() { + return dockerArchiveFile; + } + + public String getDockerArchiveRaw() { + return dockerArchive; + } + + public File getContextDir() { + return contextDir != null ? new File(contextDir) : getDockerFile().getParentFile(); + } + + public String getContextDirRaw() { + return contextDir; + } + + public String getFrom() { + if (from == null && getFromExt() != null) { + return getFromExt().get("name"); + } + return from; + } + + public List getPorts() { + return removeEmptyEntries(ports); + } + + public List getVolumes() { + return removeEmptyEntries(volumes); + } + + public List getTags() { + return removeEmptyEntries(tags); + } + + public Boolean getSkip() { + return Optional.ofNullable(skip).orElse(false); + } + + public ArchiveCompression getCompression() { + return Optional.ofNullable(compression).orElse(ArchiveCompression.none); + } + + public List getRunCmds() { + return removeEmptyEntries(runCmds); + } + + + public boolean optimise() { + return Optional.ofNullable(optimise).orElse(false); + } + + public boolean nocache() { + return Optional.ofNullable(nocache).orElse(false); + } + + public CleanupMode cleanupMode() { + return CleanupMode.parse(cleanup != null ? cleanup : DEFAULT_CLEANUP); + } + + public File getAbsoluteContextDirPath(String sourceDirectory, String projectBaseDir) { + return EnvUtil.prepareAbsoluteSourceDirPath(sourceDirectory, projectBaseDir, getContextDir().getPath()); + } + + public File getAbsoluteDockerFilePath(String sourceDirectory, String projectBaseDir) { + return EnvUtil.prepareAbsoluteSourceDirPath(sourceDirectory, projectBaseDir, getDockerFile().getPath()); + } + + public File getAbsoluteDockerTarPath(String sourceDirectory, String projectBaseDir) { + return EnvUtil.prepareAbsoluteSourceDirPath(sourceDirectory, projectBaseDir, getDockerArchive().getPath()); + } + + public String initAndValidate() { + if (entryPoint != null) { + entryPoint.validate(); + } + if (cmd != null) { + cmd.validate(); } - - public File getContextDir() { - return contextDir != null ? new File(contextDir) : getDockerFile().getParentFile(); + if (healthCheck != null) { + healthCheck.validate(); } + initDockerFileFile(); - public String getContextDirRaw() { - return contextDir; + if (healthCheck != null) { + // HEALTHCHECK support added later + return "1.24"; + } else if (args != null && !args.isEmpty()) { + // ARG support came in later + return "1.21"; + } else { + return null; } + } - - public String getDockerFileDirRaw() { - return dockerFileDir; + // Initialize the dockerfile location and the build mode + private void initDockerFileFile() { + if (dockerFile != null && dockerArchive != null) { + throw new IllegalArgumentException("Both and are set. " + + "Only one of them can be specified."); } + dockerFileFile = findDockerFileFile(); - public String getFilterRaw() { - return filter; + if (dockerArchive != null) { + dockerArchiveFile = new File(dockerArchive); } + } - public String getFrom() { - if (from == null && getFromExt() != null) { - return getFromExt().get("name"); + private File findDockerFileFile() { + if (dockerFile != null) { + File dFile = new File(dockerFile); + if (contextDir == null) { + return dFile; + } else { + if (dFile.isAbsolute()) { + return dFile; } - return from; - } - - - public AssemblyConfiguration getAssemblyConfiguration() { - return assembly; - } - - public List getPorts() { - return removeEmptyEntries(ports); - } - - public List getVolumes() { - return removeEmptyEntries(volumes); - } - - public List getTags() { - return removeEmptyEntries(tags); - } - - public String getCleanupMode() { - return cleanup; - } - - public Boolean getNoCache() { - return nocache; - } - - - public Boolean getSkip() { - return Optional.ofNullable(skip).orElse(false); - } - - public ArchiveCompression getCompression() { - return Optional.ofNullable(compression).orElse(ArchiveCompression.none); - } - - public List getRunCmds() { - return removeEmptyEntries(runCmds); - } - - - public boolean optimise() { - return Optional.ofNullable(optimise).orElse(false); - } - - public boolean nocache() { - return Optional.ofNullable(nocache).orElse(false); + return new File(contextDir, dockerFile); + } } - public CleanupMode cleanupMode() { - return CleanupMode.parse(cleanup != null ? cleanup : DEFAULT_CLEANUP); + if (contextDir != null) { + return new File(contextDir, "Dockerfile"); } + // No dockerfile mode + return null; + } - public File getAbsoluteContextDirPath(String sourceDirectory, String projectBaseDir) { - return EnvUtil.prepareAbsoluteSourceDirPath(sourceDirectory, projectBaseDir, getContextDir().getPath()); + public String validate() { + if (entryPoint != null) { + entryPoint.validate(); } - - public File getAbsoluteDockerFilePath(String sourceDirectory, String projectBaseDir) { - return EnvUtil.prepareAbsoluteSourceDirPath(sourceDirectory, projectBaseDir, getDockerFile().getPath()); + if (cmd != null) { + cmd.validate(); } - - public File getAbsoluteDockerTarPath(String sourceDirectory, String projectBaseDir) { - return EnvUtil.prepareAbsoluteSourceDirPath(sourceDirectory, projectBaseDir, getDockerArchive().getPath()); + if (healthCheck != null) { + healthCheck.validate(); } - public String initAndValidate(KitLogger log) { - if (entryPoint != null) { - entryPoint.validate(); - } - if (cmd != null) { - cmd.validate(); - } - if (healthCheck != null) { - healthCheck.validate(); - } - - initDockerFileFile(log); - - if (healthCheck != null) { - // HEALTHCHECK support added later - return "1.24"; - } else if (args != null) { - // ARG support came in later - return "1.21"; - } else { - return null; - } + if ((dockerFile != null || contextDir != null) && dockerArchive != null) { + throw new IllegalArgumentException("Both () and are set. " + + "Only one of them can be specified."); } - // Initialize the dockerfile location and the build mode - private void initDockerFileFile(KitLogger log) { - // can't have dockerFile/dockerFileDir and dockerArchive - if ((dockerFile != null || dockerFileDir != null) && dockerArchive != null) { - throw new IllegalArgumentException("Both () and are set. " + - "Only one of them can be specified."); - } - dockerFileFile = findDockerFileFile(log); - - if (dockerArchive != null) { - dockerArchiveFile = new File(dockerArchive); - } + if (healthCheck != null) { + // HEALTHCHECK support added later + return "1.24"; + } else if (args != null) { + // ARG support came in later + return "1.21"; + } else { + return null; } + } - private File findDockerFileFile(KitLogger log) { - if(dockerFileDir != null && contextDir != null) { - log.warn("Both contextDir (%s) and deprecated dockerFileDir (%s) are configured. Using contextDir.", contextDir, dockerFileDir); - } - - if (dockerFile != null) { - File dFile = new File(dockerFile); - if (dockerFileDir == null && contextDir == null) { - return dFile; - } else { - if(contextDir != null) { - if (dFile.isAbsolute()) { - return dFile; - } - return new File(contextDir, dockerFile); - } - if (dFile.isAbsolute()) { - throw new IllegalArgumentException(" can not be absolute path if also set."); - } - log.warn("dockerFileDir parameter is deprecated, please migrate to contextDir"); - return new File(dockerFileDir, dockerFile); - } - } - - - if (contextDir != null) { - return new File(contextDir, "Dockerfile"); - } - - if (dockerFileDir != null) { - return new File(dockerFileDir, "Dockerfile"); - } - - // No dockerfile mode - return null; + public File calculateDockerFilePath() { + if (dockerFile != null) { + File dFile = new File(dockerFile); + if (contextDir == null) { + return dFile; + } + if (dFile.isAbsolute()) { + return dFile; + } + if (isWindows() && !isValidWindowsFileName(dockerFile)) { + throw new IllegalArgumentException(String.format("Invalid Windows file name %s for ", dockerFile)); + } + return new File(contextDir, dFile.getPath()); } - public String validate() throws IllegalArgumentException { - if (entryPoint != null) { - entryPoint.validate(); - } - if (cmd != null) { - cmd.validate(); - } - if (healthCheck != null) { - healthCheck.validate(); - } - - // can't have dockerFile/dockerFileDir and dockerArchive - if ((dockerFile != null || contextDir != null) && dockerArchive != null) { - throw new IllegalArgumentException("Both () and are set. " + - "Only one of them can be specified."); - } - - if (healthCheck != null) { - // HEALTHCHECK support added later - return "1.24"; - } else if (args != null) { - // ARG support came in later - return "1.21"; - } else { - return null; - } + if (contextDir != null) { + return new File(contextDir, "Dockerfile"); } - public File calculateDockerFilePath() { - if (dockerFile != null) { - File dFile = new File(dockerFile); - if (contextDir == null) { - return dFile; - } - if (dFile.isAbsolute()) { - return dFile; - } - if (System.getProperty("os.name").toLowerCase().contains("windows") && - !isValidWindowsFileName(dockerFile)) { - throw new IllegalArgumentException(String.format("Invalid Windows file name %s for ", dockerFile)); - } - return new File(contextDir, dFile.getPath()); - } + // No dockerfile mode + throw new IllegalArgumentException("Can't calculate a docker file path if neither dockerFile nor contextDir is specified"); + } - if (contextDir != null) { - return new File(contextDir, "Dockerfile"); - } - - // No dockerfile mode - throw new IllegalArgumentException("Can't calculate a docker file path if neither dockerFile nor contextDir is specified"); + public static class BuildConfigurationBuilder { + public BuildConfigurationBuilder compressionString(String compressionString) { + compression = Optional.ofNullable(compressionString).map(ArchiveCompression::valueOf).orElse(null); + return this; } + } - public static class BuildConfigurationBuilder { - public BuildConfigurationBuilder compressionString(String compressionString) { - compression = Optional.ofNullable(compressionString).map(ArchiveCompression::valueOf).orElse(null); - return this; - } - } - - private static List removeEmptyEntries(List list) { - return Optional.ofNullable(list).orElse(Collections.emptyList()).stream() - .filter(Objects::nonNull) - .map(String::trim) - .filter(s -> !s.isEmpty()) - .collect(Collectors.toList()); - } + private static List removeEmptyEntries(List list) { + return Optional.ofNullable(list).orElse(Collections.emptyList()).stream() + .filter(Objects::nonNull) + .map(String::trim) + .filter(s -> !s.isEmpty()) + .collect(Collectors.toList()); + } - /** - * Validate that the provided filename is a valid Windows filename. - * - * The validation of the Windows filename is copied from stackoverflow: https://stackoverflow.com/a/6804755 - * - * @param filename the filename - * @return filename is a valid Windows filename - */ - static boolean isValidWindowsFileName(String filename) { - Pattern pattern = Pattern.compile( - "# Match a valid Windows filename (unspecified file system). \n" + + /** + * Validate that the provided filename is a valid Windows filename. + * + * The validation of the Windows filename is copied from stackoverflow: https://stackoverflow.com/a/6804755 + * + * @param filename the filename + * @return filename is a valid Windows filename + */ + static boolean isValidWindowsFileName(String filename) { + Pattern pattern = Pattern.compile( + "# Match a valid Windows filename (unspecified file system). \n" + "^ # Anchor to start of string. \n" + "(?! # Assert filename is not: CON, PRN, \n" + " (?: # AUX, NUL, COM1, COM2, COM3, COM4, \n" + @@ -400,9 +459,9 @@ static boolean isValidWindowsFileName(String filename) { "[^<>:\"/\\\\|?*\\x00-\\x1F]* # Zero or more valid filename chars.\n" + "[^<>:\"/\\\\|?*\\x00-\\x1F .] # Last char is not a space or dot. \n" + "$ # Anchor to end of string. ", - Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.COMMENTS); - Matcher matcher = pattern.matcher(filename); - return matcher.matches(); - } + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.COMMENTS); + Matcher matcher = pattern.matcher(filename); + return matcher.matches(); + } } 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 4c219ee967..fc7d6912ea 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 @@ -39,6 +39,8 @@ */ public class DockerFileBuilder { + private static final String DEFAULT_BASE_IMAGE = "busybox"; + // Base image to use as from private String baseImage; @@ -110,7 +112,7 @@ public String content() { StringBuilder b = new StringBuilder(); - DockerFileKeyword.FROM.addTo(b, baseImage != null ? baseImage : "busybox"); + DockerFileKeyword.FROM.addTo(b, baseImage != null ? baseImage : DEFAULT_BASE_IMAGE); if (maintainer != null) { DockerFileKeyword.MAINTAINER.addTo(b, maintainer); } @@ -239,7 +241,7 @@ private void addLabels(StringBuilder b) { private void addMap(StringBuilder b, DockerFileKeyword keyword, Map map) { if (map != null && map.size() > 0) { - String entries[] = new String[map.size()]; + final String[] entries = new String[map.size()]; int i = 0; for (Map.Entry entry : map.entrySet()) { entries[i++] = createKeyValue(entry.getKey(), entry.getValue()); diff --git a/jkube-kit/config/image/src/test/java/org/eclipse/jkube/kit/config/image/build/BuildConfigurationTest.java b/jkube-kit/config/image/src/test/java/org/eclipse/jkube/kit/config/image/build/BuildConfigurationTest.java index 07d43577f9..55fbd8d286 100644 --- a/jkube-kit/config/image/src/test/java/org/eclipse/jkube/kit/config/image/build/BuildConfigurationTest.java +++ b/jkube-kit/config/image/src/test/java/org/eclipse/jkube/kit/config/image/build/BuildConfigurationTest.java @@ -14,136 +14,208 @@ package org.eclipse.jkube.kit.config.image.build; import java.io.File; +import java.io.IOException; +import java.util.Collections; -import mockit.Expectations; import org.eclipse.jkube.kit.common.AssemblyConfiguration; -import org.eclipse.jkube.kit.common.KitLogger; + +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import mockit.Expectations; import mockit.Mocked; import org.junit.Test; import static org.eclipse.jkube.kit.common.archive.ArchiveCompression.bzip2; import static org.eclipse.jkube.kit.common.archive.ArchiveCompression.gzip; import static org.eclipse.jkube.kit.common.archive.ArchiveCompression.none; +import static org.hamcrest.CoreMatchers.allOf; +import static org.hamcrest.CoreMatchers.endsWith; import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.CoreMatchers.startsWith; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * @author roland */ - public class BuildConfigurationTest { - @Mocked - KitLogger logger; - - @Test - public void empty() { - BuildConfiguration config = new BuildConfiguration(); - config.validate(); - assertFalse(config.isDockerFileMode()); - } - - @Test - public void simpleDockerfile() { - BuildConfiguration config = BuildConfiguration.builder() - .dockerFile("src/docker/Dockerfile").build(); - config.validate(); - assertTrue(config.isDockerFileMode()); - assertEquals(config.calculateDockerFilePath(),new File("src/docker/Dockerfile")); - } - - @Test - public void simpleDockerfileDir() { - BuildConfiguration config = BuildConfiguration.builder() - .contextDir("src/docker/").build(); - config.validate(); - assertTrue(config.isDockerFileMode()); - assertEquals(config.calculateDockerFilePath(),new File("src/docker/Dockerfile")); - } - - @Test - public void DockerfileDirAndDockerfileAlsoSet() { - BuildConfiguration config = BuildConfiguration.builder() - .contextDir("/tmp/") - .dockerFile("Dockerfile").build(); - config.validate(); - assertTrue(config.isDockerFileMode()); - assertEquals(config.calculateDockerFilePath(),new File("/tmp/Dockerfile")); - } - - @Test - public void dockerFileAndArchive() { - BuildConfiguration config = BuildConfiguration.builder() - .dockerArchive("this") - .dockerFile("that").build(); - - try { - config.validate(); - } catch (IllegalArgumentException expected) { - return; - } - fail("Should have failed."); - } - - @Test - public void dockerArchive() { - BuildConfiguration config = BuildConfiguration.builder() - .dockerArchive("this").build(); - config.initAndValidate(logger); - - assertFalse(config.isDockerFileMode()); - assertEquals(new File("this"), config.getDockerArchive()); - } - - @Test - public void compression() { - BuildConfiguration config = BuildConfiguration.builder() - .compressionString("gzip").build(); - assertEquals(gzip, config.getCompression()); - - config = BuildConfiguration.builder().build(); - assertEquals(none, config.getCompression()); - - config = BuildConfiguration.builder() - .compressionString("bzip2").build(); - assertEquals(bzip2, config.getCompression()); - - try { - BuildConfiguration.builder() - .compressionString("bzip").build(); - fail(); - } catch (Exception exp) { - assertTrue(exp.getMessage().contains("bzip")); - } - } - - - @Test - public void isValidWindowsFileName() { - assertFalse(BuildConfiguration.isValidWindowsFileName("/Dockerfile")); - assertTrue(BuildConfiguration.isValidWindowsFileName("Dockerfile")); - assertFalse(BuildConfiguration.isValidWindowsFileName("Dockerfile/")); - } - - @Test - public void testBuilder(@Mocked AssemblyConfiguration mockAssemblyConfiguration) { - // Given - new Expectations() {{ - mockAssemblyConfiguration.getName(); - result = "1337"; - }}; - // When - final BuildConfiguration result = BuildConfiguration.builder() - .assembly(mockAssemblyConfiguration) - .user("super-user") - .build(); - // Then - assertThat(result.getUser(), equalTo("super-user")); - assertThat(result.getAssemblyConfiguration().getName(), equalTo("1337")); - } - + @Test + public void emptyConfigurationShouldBeValidNonDockerfileWithDefaults() { + BuildConfiguration config = new BuildConfiguration(); + config.validate(); + assertFalse(config.isDockerFileMode()); + assertThat(config.getDockerFile(), nullValue()); + assertThat(config.getCompression(), is(none)); + assertThat(config.cleanupMode(), is(CleanupMode.TRY_TO_REMOVE)); + assertThat(config.optimise(), is(false)); + assertThat(config.nocache(), is(false)); + } + + @Test + public void dockerFileShouldBeValidDockerfile() { + BuildConfiguration config = BuildConfiguration.builder() + .dockerFile("src/docker/Dockerfile").build(); + config.validate(); + assertTrue(config.isDockerFileMode()); + assertEquals(config.calculateDockerFilePath(),new File("src/docker/Dockerfile")); + } + + @Test + public void contextDirShouldBeValidDockerfile() { + BuildConfiguration config = BuildConfiguration.builder() + .contextDir("src/docker/").build(); + config.validate(); + assertTrue(config.isDockerFileMode()); + assertEquals(config.calculateDockerFilePath(), new File("src/docker/Dockerfile")); + } + + @Test + public void contextDirAndDockerFileShouldBeValidDockerfile() { + BuildConfiguration config = BuildConfiguration.builder() + .contextDir("/tmp/") + .dockerFile("Docker-file").build(); + config.validate(); + config.initAndValidate(); + assertTrue(config.isDockerFileMode()); + assertEquals(config.getDockerFile(), new File("/tmp/Docker-file")); + assertEquals(config.calculateDockerFilePath(), new File("/tmp/Docker-file")); + } + + @Test(expected = IllegalArgumentException.class) + public void dockerFileAndDockerArchiveShouldBeInvalid() { + BuildConfiguration config = BuildConfiguration.builder() + .dockerArchive("this") + .dockerFile("that").build(); + + config.validate(); + + fail("Should have failed."); + } + + @Test + public void dockerArchiveShouldBeValidNonDockerfile() { + BuildConfiguration config = BuildConfiguration.builder() + .dockerArchive("docker-archive.tar").build(); + config.validate(); + config.initAndValidate(); + + assertFalse(config.isDockerFileMode()); + assertEquals(new File("docker-archive.tar"), config.getDockerArchive()); + } + + @Test + public void compressionStringGzip() { + BuildConfiguration config = BuildConfiguration.builder() + .compressionString("gzip").build(); + assertEquals(gzip, config.getCompression()); + } + + @Test + public void compressionStringNone() { + BuildConfiguration config = BuildConfiguration.builder().build(); + assertEquals(none, config.getCompression()); + } + + @Test + public void compressionStringBzip2() { + BuildConfiguration config = BuildConfiguration.builder() + .compressionString("bzip2").build(); + assertEquals(bzip2, config.getCompression()); + } + + @Test + public void compressionStringInvalid() { + final BuildConfiguration.BuildConfigurationBuilder builder = BuildConfiguration.builder(); + final IllegalArgumentException result = assertThrows(IllegalArgumentException.class, () -> builder.compressionString("bzip")); + assertThat(result.getMessage(), allOf(startsWith("No enum constant"), endsWith("ArchiveCompression.bzip"))); + } + + + @Test + public void isValidWindowsFileName() { + assertFalse(BuildConfiguration.isValidWindowsFileName("/Dockerfile")); + assertTrue(BuildConfiguration.isValidWindowsFileName("Dockerfile")); + assertFalse(BuildConfiguration.isValidWindowsFileName("Dockerfile/")); + } + + @Test + public void testBuilder(@Mocked AssemblyConfiguration mockAssemblyConfiguration) { + // Given + // @formatter:off + new Expectations() {{ + mockAssemblyConfiguration.getName(); + result = "1337"; + }}; + // @formatter:on + // When + final BuildConfiguration result = BuildConfiguration.builder() + .assembly(mockAssemblyConfiguration) + .user("super-user") + .build(); + // Then + assertThat(result.getUser(), equalTo("super-user")); + assertThat(result.getAssembly().getName(), equalTo("1337")); + } + + /** + * Verifies that deserialization works for raw deserialization (Maven-Plexus) disregarding annotations. + * + * Especially designed to catch problems if Enum names are changed. + */ + @Test + public void rawDeserialization() throws IOException { + // Given + final ObjectMapper mapper = new ObjectMapper(); + mapper.configure(MapperFeature.USE_ANNOTATIONS, false); + // When + final BuildConfiguration result = mapper.readValue( + BuildConfigurationTest.class.getResourceAsStream("/build-configuration.json"), + BuildConfiguration.class + ); + // Then + assertThat(result, notNullValue()); + assertThat(result.getContextDirRaw(), is("context")); + assertThat(result.getContextDir(), is(new File("context"))); + assertThat(result.getDockerFileRaw(), is("Dockerfile.jvm")); + assertThat(result.getDockerArchiveRaw(), is("docker-archive.tar")); + assertThat(result.getFilter(), is("@")); + assertThat(result.getFrom(), is("jkube-images/image:1337")); + assertThat(result.getFromExt().values(), hasSize(1)); + assertThat(result.getFromExt(), hasEntry("name", "jkube-images/image:ext")); + assertThat(result.getMaintainer(), is("A-Team")); + assertThat(result.getPorts(), is(Collections.singletonList("8080"))); + assertThat(result.getShell().getShell(), is("java -version")); + assertThat(result.getImagePullPolicy(), is("Always")); + assertThat(result.getRunCmds(), contains("ls -la", "sleep 1", "echo done")); + assertThat(result.getCleanup(), is("none")); + assertThat(result.cleanupMode(), is(CleanupMode.NONE)); + assertThat(result.getNocache(), is(true)); + assertThat(result.getOptimise(), is(false)); + assertThat(result.getVolumes(), contains("volume 1")); + assertThat(result.getTags(), contains("latest", "1337")); + assertThat(result.getEnv().values(), hasSize(1)); + assertThat(result.getEnv(), hasEntry("JAVA_OPTS", "-Xmx1337m")); + assertThat(result.getLabels(), hasEntry("label-1", "label")); + assertThat(result.getArgs(), hasEntry("CODE_VERSION", "latest")); + assertThat(result.getEntryPoint().getExec(), contains("java -version")); + assertThat(result.getWorkdir(), is("/tmp")); + assertThat(result.getCmd().getExec(), contains("sh", "-c")); + assertThat(result.getUser(), is("root")); + assertThat(result.getHealthCheck(), notNullValue()); + assertThat(result.getAssembly(), notNullValue()); + assertThat(result.getSkip(), is(false)); + assertThat(result.getCompression(), is(gzip)); + assertThat(result.getBuildOptions(), hasEntry("NetworkMode", "bridge")); + } } diff --git a/jkube-kit/config/image/src/test/resources/build-configuration.json b/jkube-kit/config/image/src/test/resources/build-configuration.json new file mode 100644 index 0000000000..57663473af --- /dev/null +++ b/jkube-kit/config/image/src/test/resources/build-configuration.json @@ -0,0 +1,46 @@ +{ + "contextDir": "context", + "dockerFile": "Dockerfile.jvm", + "dockerArchive": "docker-archive.tar", + "filter": "@", + "from": "jkube-images/image:1337", + "fromExt": { + "name": "jkube-images/image:ext" + }, + "maintainer": "A-Team", + "ports": ["8080"], + "shell": { + "shell": "java -version" + }, + "imagePullPolicy": "Always", + "runCmds": ["ls -la", "sleep 1", "echo done"], + "cleanup": "none", + "nocache": true, + "optimise": false, + "volumes": ["volume 1"], + "tags": ["latest", "1337"], + "env":{ + "JAVA_OPTS": "-Xmx1337m" + }, + "labels":{ + "label-1": "label" + }, + "args":{ + "CODE_VERSION": "latest" + }, + "entryPoint": { + "exec": ["java -version"] + }, + "workdir": "/tmp", + "cmd": { + "exec": ["sh", "-c"] + }, + "user": "root", + "healthCheck": {}, + "assembly": {}, + "skip": false, + "compression": "gzip", + "buildOptions": { + "NetworkMode": "bridge" + } +} \ No newline at end of file diff --git a/jkube-kit/config/service/src/main/java/org/eclipse/jkube/kit/config/service/openshift/OpenshiftBuildService.java b/jkube-kit/config/service/src/main/java/org/eclipse/jkube/kit/config/service/openshift/OpenshiftBuildService.java index 44195bc899..d05d77ccb6 100644 --- a/jkube-kit/config/service/src/main/java/org/eclipse/jkube/kit/config/service/openshift/OpenshiftBuildService.java +++ b/jkube-kit/config/service/src/main/java/org/eclipse/jkube/kit/config/service/openshift/OpenshiftBuildService.java @@ -381,10 +381,10 @@ private BuildStrategy createBuildStrategy(ImageConfiguration imageConfig, OpenSh private Boolean checkForNocache(ImageConfiguration imageConfig) { String nocache = System.getProperty("docker.nocache"); if (nocache != null) { - return nocache.length() == 0 || Boolean.valueOf(nocache); + return nocache.length() == 0 || Boolean.parseBoolean(nocache); } else { BuildConfiguration buildConfig = imageConfig.getBuildConfiguration(); - return buildConfig.getNoCache(); + return buildConfig.nocache(); } } @@ -474,7 +474,7 @@ private String extractBaseFromConfiguration(BuildConfiguration buildConfig) { String fromImage; fromImage = buildConfig.getFrom(); if (fromImage == null) { - AssemblyConfiguration assemblyConfig = buildConfig.getAssemblyConfiguration(); + AssemblyConfiguration assemblyConfig = buildConfig.getAssembly(); if (assemblyConfig == null) { fromImage = DockerAssemblyManager.DEFAULT_DATA_BASE_IMAGE; } diff --git a/jkube-kit/config/service/src/test/java/org/eclipse/jkube/kit/config/service/openshift/OpenshiftBuildServiceTest.java b/jkube-kit/config/service/src/test/java/org/eclipse/jkube/kit/config/service/openshift/OpenshiftBuildServiceTest.java index f77ddb5055..09cac1162b 100644 --- a/jkube-kit/config/service/src/test/java/org/eclipse/jkube/kit/config/service/openshift/OpenshiftBuildServiceTest.java +++ b/jkube-kit/config/service/src/test/java/org/eclipse/jkube/kit/config/service/openshift/OpenshiftBuildServiceTest.java @@ -228,7 +228,7 @@ public void testDockerBuild() throws Exception { assertTrue(mockServer.getRequestCount() > 8); collector.assertEventsRecordedInOrder("build-config-check", "new-build-config", "pushed"); - assertEquals("{\"apiVersion\":\"build.openshift.io/v1\",\"kind\":\"BuildConfig\",\"metadata\":{\"name\":\"myapp-docker\"},\"spec\":{\"output\":{\"to\":{\"kind\":\"ImageStreamTag\",\"name\":\"myapp:latest\"}},\"source\":{\"type\":\"Binary\"},\"strategy\":{\"dockerStrategy\":{\"from\":{\"kind\":\"DockerImage\",\"name\":\"myapp\"}},\"type\":\"Docker\"}}}", collector.getBodies().get(1)); + assertEquals("{\"apiVersion\":\"build.openshift.io/v1\",\"kind\":\"BuildConfig\",\"metadata\":{\"name\":\"myapp-docker\"},\"spec\":{\"output\":{\"to\":{\"kind\":\"ImageStreamTag\",\"name\":\"myapp:latest\"}},\"source\":{\"type\":\"Binary\"},\"strategy\":{\"dockerStrategy\":{\"from\":{\"kind\":\"DockerImage\",\"name\":\"myapp\"},\"noCache\":false},\"type\":\"Docker\"}}}", collector.getBodies().get(1)); collector.assertEventsNotRecorded("patch-build-config"); }); } @@ -256,7 +256,7 @@ public void testDockerBuildNoS2iSuffix() throws Exception { assertTrue(mockServer.getRequestCount() > 8); collector.assertEventsRecordedInOrder("build-config-check", "new-build-config", "pushed"); - assertEquals("{\"apiVersion\":\"build.openshift.io/v1\",\"kind\":\"BuildConfig\",\"metadata\":{\"name\":\"myapp\"},\"spec\":{\"output\":{\"to\":{\"kind\":\"ImageStreamTag\",\"name\":\"myapp:latest\"}},\"source\":{\"type\":\"Binary\"},\"strategy\":{\"dockerStrategy\":{\"from\":{\"kind\":\"DockerImage\",\"name\":\"myapp\"}},\"type\":\"Docker\"}}}", collector.getBodies().get(1)); + assertEquals("{\"apiVersion\":\"build.openshift.io/v1\",\"kind\":\"BuildConfig\",\"metadata\":{\"name\":\"myapp\"},\"spec\":{\"output\":{\"to\":{\"kind\":\"ImageStreamTag\",\"name\":\"myapp:latest\"}},\"source\":{\"type\":\"Binary\"},\"strategy\":{\"dockerStrategy\":{\"from\":{\"kind\":\"DockerImage\",\"name\":\"myapp\"},\"noCache\":false},\"type\":\"Docker\"}}}", collector.getBodies().get(1)); collector.assertEventsNotRecorded("patch-build-config"); }); } 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 52def53193..a1e45e4789 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 @@ -210,7 +210,7 @@ public void getContainerWithGroupArtifactTest() { //container name with group id and aritact id without alias and user final BuildConfiguration buildImageConfiguration = BuildConfiguration.builder() .ports(ports).from("fabric8/").cleanup("try").tags(tags) - .compressionString("gzip").dockerFile("testFile").dockerFileDir("/demo").build(); + .compressionString("gzip").dockerFile("testFile").build(); ImageConfiguration imageConfiguration = ImageConfiguration.builder() .name("test").build(buildImageConfiguration).registry("docker.io").build(); @@ -240,7 +240,7 @@ public void getContainerTestWithUser(){ final BuildConfiguration buildImageConfiguration = BuildConfiguration.builder() .ports(ports).from("fabric8/").cleanup("try").tags(tags) - .compressionString("gzip").dockerFile("testFile").dockerFileDir("/demo").build(); + .compressionString("gzip").dockerFile("testFile").build(); ImageConfiguration imageConfiguration = ImageConfiguration.builder() .name("user/test:latest").build(buildImageConfiguration).registry("docker.io").build(); diff --git a/jkube-kit/generator/karaf/src/test/java/org/eclipse/jkube/generator/karaf/KarafGeneratorTest.java b/jkube-kit/generator/karaf/src/test/java/org/eclipse/jkube/generator/karaf/KarafGeneratorTest.java index eb49b67e23..dbc47db356 100644 --- a/jkube-kit/generator/karaf/src/test/java/org/eclipse/jkube/generator/karaf/KarafGeneratorTest.java +++ b/jkube-kit/generator/karaf/src/test/java/org/eclipse/jkube/generator/karaf/KarafGeneratorTest.java @@ -107,7 +107,7 @@ public void customizeWithKarafMavenPluginShouldAddImageConfiguration(@Mocked Plu assertThat(bc.getPorts(), contains("8181")); assertThat(bc.getEnv(), hasEntry("DEPLOYMENTS_DIR", "/deployments")); assertThat(bc.getEnv(), hasEntry("KARAF_HOME", "/deployments/karaf")); - final AssemblyConfiguration ac = bc.getAssemblyConfiguration(); + final AssemblyConfiguration ac = bc.getAssembly(); assertThat(ac.getName(), equalTo("deployments")); assertThat(ac.isExcludeFinalOutputArtifact(), equalTo(false)); assertThat(ac.getInline().getFileSets(), contains( diff --git a/jkube-kit/generator/webapp/src/main/java/org/eclipse/jkube/generator/webapp/handler/WildFlyAppSeverHandler.java b/jkube-kit/generator/webapp/src/main/java/org/eclipse/jkube/generator/webapp/handler/WildFlyAppSeverHandler.java index d348304c93..9855418b4b 100644 --- a/jkube-kit/generator/webapp/src/main/java/org/eclipse/jkube/generator/webapp/handler/WildFlyAppSeverHandler.java +++ b/jkube-kit/generator/webapp/src/main/java/org/eclipse/jkube/generator/webapp/handler/WildFlyAppSeverHandler.java @@ -86,7 +86,10 @@ public String getFrom() { @Override public String getDeploymentDir() { - // Applicable for Docker image - ignored for s2i + if (generatorContext.getRuntimeMode() == RuntimeMode.openshift + && generatorContext.getStrategy() == OpenShiftBuildStrategy.s2i) { + return "/deployments"; + } return "/opt/jboss/wildfly/standalone/deployments"; } diff --git a/jkube-kit/generator/webapp/src/test/java/org/eclipse/jkube/generator/webapp/WebAppGeneratorTest.java b/jkube-kit/generator/webapp/src/test/java/org/eclipse/jkube/generator/webapp/WebAppGeneratorTest.java index c40803365d..c882f9d823 100644 --- a/jkube-kit/generator/webapp/src/test/java/org/eclipse/jkube/generator/webapp/WebAppGeneratorTest.java +++ b/jkube-kit/generator/webapp/src/test/java/org/eclipse/jkube/generator/webapp/WebAppGeneratorTest.java @@ -108,7 +108,7 @@ public void customizeWithDefaultHandlerShouldAddImageConfiguration() throws IOEx assertThat(imageConfiguration.getName(), equalTo("%g/%a:%l")); assertThat(imageConfiguration.getAlias(), equalTo("webapp")); assertThat(imageConfiguration.getBuildConfiguration().getTags(), contains("latest")); - assertThat(imageConfiguration.getBuildConfiguration().getAssemblyConfiguration().isExcludeFinalOutputArtifact(), + assertThat(imageConfiguration.getBuildConfiguration().getAssembly().isExcludeFinalOutputArtifact(), equalTo(true)); } } diff --git a/jkube-kit/generator/webapp/src/test/java/org/eclipse/jkube/generator/webapp/handler/WildFlyAppSeverHandlerTest.java b/jkube-kit/generator/webapp/src/test/java/org/eclipse/jkube/generator/webapp/handler/WildFlyAppSeverHandlerTest.java index 24461cd43c..f924aabddb 100644 --- a/jkube-kit/generator/webapp/src/test/java/org/eclipse/jkube/generator/webapp/handler/WildFlyAppSeverHandlerTest.java +++ b/jkube-kit/generator/webapp/src/test/java/org/eclipse/jkube/generator/webapp/handler/WildFlyAppSeverHandlerTest.java @@ -120,6 +120,7 @@ public void kubernetes() { // Then assertCommonValues(handler); assertEquals("jboss/wildfly:19.0.0.Final", handler.getFrom()); + assertEquals("/opt/jboss/wildfly/standalone/deployments", handler.getDeploymentDir()); assertTrue(handler.runCmds().isEmpty()); } @@ -137,6 +138,7 @@ public void openShiftDockerStrategy() { // Then assertCommonValues(handler); assertEquals("jboss/wildfly:19.0.0.Final", handler.getFrom()); + assertEquals("/opt/jboss/wildfly/standalone/deployments", handler.getDeploymentDir()); assertEquals(Collections.singletonList("chmod -R a+rw /opt/jboss/wildfly/standalone/"), handler.runCmds()); } @@ -154,13 +156,13 @@ public void openShiftSourceStrategy() { // Then assertCommonValues(handler); assertEquals("quay.io/wildfly/wildfly-centos7:19.0", handler.getFrom()); + assertEquals("/deployments", handler.getDeploymentDir()); assertTrue(handler.runCmds().isEmpty()); } private static void assertCommonValues(WildFlyAppSeverHandler handler) { assertTrue(handler.supportsS2iBuild()); assertEquals("deployments", handler.getAssemblyName()); - assertEquals("/opt/jboss/wildfly/standalone/deployments", handler.getDeploymentDir()); assertEquals("/opt/jboss/wildfly/bin/standalone.sh -b 0.0.0.0", handler.getCommand()); assertEquals("jboss:jboss:jboss", handler.getUser()); assertEquals(Collections.singletonMap("GALLEON_PROVISION_LAYERS", "cloud-server,web-clustering"), handler.getEnv()); diff --git a/jkube-kit/jkube-kit-spring-boot/src/main/java/org/eclipse/jkube/springboot/generator/SpringBootGenerator.java b/jkube-kit/jkube-kit-spring-boot/src/main/java/org/eclipse/jkube/springboot/generator/SpringBootGenerator.java index d1b6294228..ff66c0a496 100644 --- a/jkube-kit/jkube-kit-spring-boot/src/main/java/org/eclipse/jkube/springboot/generator/SpringBootGenerator.java +++ b/jkube-kit/jkube-kit-spring-boot/src/main/java/org/eclipse/jkube/springboot/generator/SpringBootGenerator.java @@ -258,7 +258,7 @@ private void addSecretTokenToApplicationProperties() { appendSecretTokenToFile("src/main/resources/application.properties", newToken); } - private void appendSecretTokenToFile(String path, String token) throws IllegalStateException { + private void appendSecretTokenToFile(String path, String token) { File file = new File(getProject().getBaseDirectory(), path); file.getParentFile().mkdirs(); String text = String.format("%s" + diff --git a/kubernetes-maven-plugin/doc/src/main/asciidoc/inc/build/_configuration.adoc b/kubernetes-maven-plugin/doc/src/main/asciidoc/inc/build/_configuration.adoc index 1fa1933a61..4cb5888ff5 100644 --- a/kubernetes-maven-plugin/doc/src/main/asciidoc/inc/build/_configuration.adoc +++ b/kubernetes-maven-plugin/doc/src/main/asciidoc/inc/build/_configuration.adoc @@ -9,7 +9,7 @@ of an image configuration. The following configuration options are supported: | Element | Description | <> -| specifies the assembly configuration as described in <> +| Specifies the assembly configuration as described in <> | <> | Map specifying the value of https://docs.docker.com/engine/reference/commandline/build/#set-build-time-variables-build-arg[Docker build args] @@ -37,9 +37,6 @@ https://docs.docker.com/engine/reference/api/docker_remote_api_v1.24/#build-imag | *dockerFile* | Path to a `Dockerfile` which also triggers _Dockerfile mode_. See <> for details. -| *dockerFileDir* (_deprecated_ in favor of *<>*) -| Path to a directory holding a `Dockerfile` and switch on _Dockerfile mode_. See <> for details. _This option is deprecated in favor of _contextDir_ and will be removed for the next major release_. - | *dockerArchive* | Path to a saved image archive which is then imported. See <> for details. @@ -75,7 +72,7 @@ A provided `` takes precedence over the name given here. This tag is usefu | Definition of a health check as described in <> | *imagePullPolicy* -| Specific pull policy for the base image. This overwrites any global pull policy. See the globale configuration option <> for the possible values and the default. +| Specific pull policy for the base image. This overwrites any global pull policy. See the global configuration option <> for the possible values and the default. | *loadNamePattern* a| Scan the images in the archive specified in `dockerArchive` and match the associated repository and tag information against this pattern. When a matching repository and tag is found, create a tag linking the `name` for this image to the repository and tag that matched the pattern. diff --git a/kubernetes-maven-plugin/doc/src/main/asciidoc/inc/build/_overview.adoc b/kubernetes-maven-plugin/doc/src/main/asciidoc/inc/build/_overview.adoc index ad046f35ad..0d7a800e66 100644 --- a/kubernetes-maven-plugin/doc/src/main/asciidoc/inc/build/_overview.adoc +++ b/kubernetes-maven-plugin/doc/src/main/asciidoc/inc/build/_overview.adoc @@ -13,13 +13,11 @@ Alternatively an external Dockerfile template or Docker archive can be used. Thi * *contextDir* specifies docker build context if an external dockerfile is located outside of Docker build context. If not specified, Dockerfile's parent directory is used as build context. * *dockerFile* specifies a specific Dockerfile path. The Docker build context directory is set to `contextDir` if given. If not the directory by default is the directory in which the Dockerfile is stored. -* *dockerArchive* specifies a previously saved image archive to load directly. If a `dockerArchive` is provided, no `dockerFile` or `dockerFileDir` must be given. -* *dockerFileDir* (_deprecated_, use *contextDir*) specifies a directory containing a Dockerfile that will be used to create the image. The name of the Dockerfile is `Dockerfile` by default but can be also set with the option `dockerFile` (see below). +* *dockerArchive* specifies a previously saved image archive to load directly. If a `dockerArchive` is provided, no `dockerFile` must be given. -All paths can be either absolute or relative paths (except when both `dockerFileDir` and `dockerFile` are provided in which case `dockerFile` must not be absolute). A relative path is looked up in `${project.basedir}/src/main/docker` by default. You can make it easily an absolute path by using `${project.basedir}` in your configuration. +All paths can be either absolute or relative paths. A relative path is looked up in `${project.basedir}/src/main/docker` by default. You can make it easily an absolute path by using `${project.basedir}` in your configuration. .Adding assemblies in Dockerfile mode -Any additional files located in the `dockerFileDir` directory will also be added to the build context as well. You can also use an assembly if specified in an <>. However, you need to add the files on your own in the Dockerfile with an `ADD` or `COPY` command. The files of the assembly are stored in a build context relative directory `maven/` but can be changed by changing the assembly name with the option `` in the assembly configuration. @@ -92,8 +90,7 @@ This form of property replacement works for Dockerfile only. For replacing other data in other files targeted for the Docker image, please use the `maven-resource-plugin` or an <> with filtering to make them available in the docker build context. .Example -The following example uses a Dockerfile in the directory -`src/main/docker/demo` and replaces all properties in the format `@property@` within the Dockerfile. +The following example replaces all properties in the format `@property@` within the Dockerfile. [source,xml,indent=0,subs="verbatim,quotes,attributes"] ---- @@ -102,7 +99,6 @@ The following example uses a Dockerfile in the directory user/demo - demo @ diff --git a/kubernetes-maven-plugin/plugin/src/main/java/org/eclipse/jkube/maven/plugin/mojo/build/AbstractDockerMojo.java b/kubernetes-maven-plugin/plugin/src/main/java/org/eclipse/jkube/maven/plugin/mojo/build/AbstractDockerMojo.java index 71820e07db..ed46631a4c 100644 --- a/kubernetes-maven-plugin/plugin/src/main/java/org/eclipse/jkube/maven/plugin/mojo/build/AbstractDockerMojo.java +++ b/kubernetes-maven-plugin/plugin/src/main/java/org/eclipse/jkube/maven/plugin/mojo/build/AbstractDockerMojo.java @@ -799,7 +799,7 @@ protected String initImageConfiguration(Date buildTimeStamp) throws DependencyRe } // Initialize configuration and detect minimal API version - return ConfigHelper.initAndValidate(resolvedImages, apiVersion, new ImageNameFormatter(MavenUtil.convertMavenProjectToJKubeProject(project, session), buildTimeStamp), log); + return ConfigHelper.initAndValidate(resolvedImages, apiVersion, new ImageNameFormatter(MavenUtil.convertMavenProjectToJKubeProject(project, session), buildTimeStamp)); } /** @@ -825,7 +825,7 @@ protected String showLogs() { } protected boolean follow() { - return Boolean.valueOf(System.getProperty("docker.follow", "false")); + return Boolean.parseBoolean(System.getProperty("docker.follow", "false")); } protected LogDispatcher getLogDispatcher(ServiceHub hub) { diff --git a/kubernetes-maven-plugin/plugin/src/main/java/org/eclipse/jkube/maven/plugin/mojo/build/ResourceMojo.java b/kubernetes-maven-plugin/plugin/src/main/java/org/eclipse/jkube/maven/plugin/mojo/build/ResourceMojo.java index 725313692e..a41c50e2a6 100644 --- a/kubernetes-maven-plugin/plugin/src/main/java/org/eclipse/jkube/maven/plugin/mojo/build/ResourceMojo.java +++ b/kubernetes-maven-plugin/plugin/src/main/java/org/eclipse/jkube/maven/plugin/mojo/build/ResourceMojo.java @@ -585,7 +585,7 @@ private List getResolvedImages(List imag } } String minimalApiVersion = ConfigHelper.initAndValidate(ret, null /* no minimal api version */, - new ImageNameFormatter(MavenUtil.convertMavenProjectToJKubeProject(project, session), now), log); + new ImageNameFormatter(MavenUtil.convertMavenProjectToJKubeProject(project, session), now)); return ret; }