Skip to content

Commit

Permalink
feat: Apply and Undeploy service use configured namespace
Browse files Browse the repository at this point in the history
As opposed to using a property that was read from Maven and passed on
as a System property.

Signed-off-by: Marc Nuri <marc@marcnuri.com>
  • Loading branch information
manusa committed Feb 24, 2021
1 parent f3c66d5 commit e0b4b4e
Show file tree
Hide file tree
Showing 18 changed files with 386 additions and 179 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ Usage:
* Fix #546: Use `java.util.function.Function` instead of Guava's `com.google.common.base.Function`
* Fix #545: Replace Boolean.valueOf with Boolean.parseBoolean for string to boolean conversion
* Fix #515: Properties now get resolved in CustomResource fragments
* Fix #586: Apply and Undeploy service use configured namespace

### 1.1.1 (2021-02-23)
* Fix #570: Disable namespace creation during k8s:resource with `jkube.namespace` flag
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.CountDownLatch;
Expand Down Expand Up @@ -114,8 +113,6 @@ public class KubernetesHelper {
public static final Pattern PROFILES_PATTERN = Pattern.compile(PROFILES_PATTERN_REGEX, Pattern.CASE_INSENSITIVE);
protected static final String[] POD_CONTROLLER_KINDS =
{ "ReplicationController", "ReplicaSet", "Deployment", "DeploymentConfig", "StatefulSet", "DaemonSet", "Job" };
public static final String JKUBE_NAMESPACE = "jkube.namespace";


private KubernetesHelper() {}

Expand Down Expand Up @@ -925,14 +922,6 @@ public static String getAnnotationValue(HasMetadata item, String annotationKey)
return null;
}

public static String getConfiguredNamespace(Properties properties, String defaultNamespaceFromConfig) {
String jkubeNamespace = (String) properties.get(JKUBE_NAMESPACE);
if (StringUtils.isNotEmpty(jkubeNamespace)) {
return jkubeNamespace;
}
return defaultNamespaceFromConfig;
}

public static boolean containsPort(List<ContainerPort> ports, String portValue) {
for (ContainerPort port : ports) {
Integer containerPort = port.getContainerPort();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -414,32 +414,6 @@ public void testIsControllerResource() {
assertFalse(KubernetesHelper.isControllerResource(new ConfigMapBuilder().build()));
}

@Test
public void testGetNamespaceFromKubernetesListReturnsValidNamespace() {
// Given
Properties properties = new Properties();
properties.put("jkube.namespace", "ns1");

// When
String namespace = KubernetesHelper.getConfiguredNamespace(properties, "default");

// Then
assertNotNull(namespace);
assertEquals("ns1", namespace);
}

@Test
public void testGetNamespaceFromKubernetesListReturnsNull() {
// Given
Properties properties = new Properties();

// When
String namespace = KubernetesHelper.getConfiguredNamespace(properties, "default");

// Then
assertEquals("default", namespace);
}

@Test
public void loadResourcesWithNestedTemplateAndDuplicateResources() throws IOException {
// Given
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
import io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext;

import static org.eclipse.jkube.kit.common.util.KubernetesHelper.getCrdContext;
import static org.eclipse.jkube.kit.common.util.KubernetesHelper.getConfiguredNamespace;
import static org.eclipse.jkube.kit.common.util.KubernetesHelper.loadResources;
import static org.eclipse.jkube.kit.config.service.ApplyService.getK8sListWithNamespaceFirst;

Expand Down Expand Up @@ -68,10 +67,8 @@ public void undeploy(File resourceDir, ResourceConfig resourceConfig, File... ma
}
List<HasMetadata> undeployEntities = getK8sListWithNamespaceFirst(entities);
Collections.reverse(undeployEntities);
final String currentNamespace = getConfiguredNamespace(jKubeServiceHub.getConfiguration().getProperties(),
jKubeServiceHub.getClusterAccess().getNamespace());
undeployCustomResources(currentNamespace, undeployEntities);
undeployResources(currentNamespace, undeployEntities);
undeployCustomResources(resourceConfig.getNamespace(), undeployEntities);
undeployResources(resourceConfig.getNamespace(), undeployEntities);
}

private void undeployCustomResources(String currentNamespace, List<HasMetadata> entities) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Properties;

import io.fabric8.kubernetes.api.model.ObjectMetaBuilder;
import io.fabric8.kubernetes.api.model.apiextensions.v1beta1.CustomResourceDefinitionListBuilder;
Expand Down Expand Up @@ -67,7 +66,7 @@ public void undeployWithNonexistentManifestShouldDoNothing() throws Exception {
// Given
final File nonexistent = new File("I don't exist");
// When
kubernetesUndeployService.undeploy(null, null, nonexistent, null);
kubernetesUndeployService.undeploy(null, ResourceConfig.builder().build(), nonexistent, null);
// Then
// @formatter:off
new Verifications() {{
Expand All @@ -79,6 +78,7 @@ public void undeployWithNonexistentManifestShouldDoNothing() throws Exception {
@Test
public void undeployWithManifestShouldDeleteAllEntities(@Mocked File file) throws Exception {
// Given
final ResourceConfig resourceConfig = ResourceConfig.builder().namespace("default").build();
final Namespace namespace = new NamespaceBuilder().withNewMetadata().withName("default").endMetadata().build();
final Pod pod = new PodBuilder().withNewMetadata().withName("MrPoddington").endMetadata().build();
final Service service = new Service();
Expand All @@ -88,12 +88,10 @@ public void undeployWithManifestShouldDeleteAllEntities(@Mocked File file) throw
file.isFile(); result = true;
kubernetesHelper.loadResources(file);
result = new HashSet<>(Arrays.asList(namespace, pod, service));
kubernetesHelper.getConfiguredNamespace((Properties) any, anyString);
result = "default";
}};
// @formatter:on
// When
kubernetesUndeployService.undeploy(null, null, file);
kubernetesUndeployService.undeploy(null, resourceConfig, file);
// Then
// @formatter:off
new Verifications() {{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import org.eclipse.jkube.kit.common.KitLogger;
import org.eclipse.jkube.kit.common.util.KubernetesHelper;
import org.eclipse.jkube.kit.config.resource.ResourceConfig;
import org.eclipse.jkube.kit.config.service.JKubeServiceHub;

import io.fabric8.kubernetes.api.model.DeletionPropagation;
Expand Down Expand Up @@ -130,7 +131,7 @@ public void deleteWithKubernetesClientShouldOnlyDeleteProvidedEntity() throws Ex
}};
// @formatter:on
// When
openshiftUndeployService.undeploy(null, null, temporaryFolder.newFile());
openshiftUndeployService.undeploy(null, ResourceConfig.builder().build(), temporaryFolder.newFile());
// Then
assertDeleteCount(1);
assertDeleted(entity);
Expand All @@ -142,7 +143,7 @@ public void deleteWithOpenShiftClientAndNoImageStreamShouldOnlyDeleteProvidedEnt
final Pod entity = new Pod();
withLoadedEntities(entity);
// When
openshiftUndeployService.undeploy(null, null, temporaryFolder.newFile());
openshiftUndeployService.undeploy(null, ResourceConfig.builder().build(), temporaryFolder.newFile());
// Then
assertDeleteCount(1);
assertDeleted(entity);
Expand All @@ -157,7 +158,7 @@ public void deleteWithOpenShiftClientAndImageStreamShouldDeleteProvidedImageStre
.build();
withLoadedEntities(entity);
// When
openshiftUndeployService.undeploy(null, null, temporaryFolder.newFile());
openshiftUndeployService.undeploy(null, ResourceConfig.builder().build(), temporaryFolder.newFile());
// Then
assertDeleteCount(1);
assertDeleted(entity);
Expand All @@ -179,7 +180,7 @@ public void deleteWithOpenShiftClientAndImageStreamShouldDeleteProvidedImageStre
.build();
withLoadedEntities(entity);
// When
openshiftUndeployService.undeploy(null, null, temporaryFolder.newFile());
openshiftUndeployService.undeploy(null, ResourceConfig.builder().build(), temporaryFolder.newFile());
// Then
assertDeleteCount(3);
assertDeleted(entity);
Expand Down Expand Up @@ -213,7 +214,7 @@ public void deleteWithOpenShiftClientAndDeploymentConfigShouldDeleteProvidedDepl
.endSpec().build();
withLoadedEntities(entity);
// When
openshiftUndeployService.undeploy(null, null, temporaryFolder.newFile());
openshiftUndeployService.undeploy(null, ResourceConfig.builder().build(), temporaryFolder.newFile());
// Then
assertDeleteCount(3);
assertDeleted(entity);
Expand Down Expand Up @@ -248,7 +249,7 @@ public void deleteWithOpenShiftClientAndDeploymentConfigNoMatchingLabelShouldDel
.endSpec().build();
withLoadedEntities(entity);
// When
openshiftUndeployService.undeploy(null, null, temporaryFolder.newFile());
openshiftUndeployService.undeploy(null, ResourceConfig.builder().build(), temporaryFolder.newFile());
// Then
assertDeleteCount(1);
assertDeleted(entity);
Expand Down Expand Up @@ -283,7 +284,7 @@ public void deleteWithOpenShiftClientAndDeploymentConfigShouldDeleteProvidedDepl
.endSpec().build();
withLoadedEntities(entity);
// When
openshiftUndeployService.undeploy(null, null, temporaryFolder.newFile());
openshiftUndeployService.undeploy(null, ResourceConfig.builder().build(), temporaryFolder.newFile());
// Then
assertDeleteCount(2);
assertDeleted(entity);
Expand Down
1 change: 0 additions & 1 deletion jkube-kit/parent/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@

<version.asciidoctor-maven-plugin>1.5.5</version.asciidoctor-maven-plugin>
<version.asciidoctorj>1.5.4</version.asciidoctorj>
<version.assertj-core>3.18.0</version.assertj-core>
<version.bouncycastle.bcpkix>1.61</version.bouncycastle.bcpkix>
<version.commons-codec>1.15</version.commons-codec>
<version.commons-compress>1.19</version.commons-compress>
Expand Down
4 changes: 4 additions & 0 deletions kubernetes-maven-plugin/plugin/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,10 @@
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
import org.eclipse.jkube.kit.common.util.KubernetesHelper;
import org.eclipse.jkube.kit.common.util.MavenUtil;
import org.eclipse.jkube.kit.common.util.OpenshiftHelper;
import org.eclipse.jkube.kit.config.resource.ResourceConfig;
import org.eclipse.jkube.kit.config.service.ApplyService;
import org.eclipse.jkube.kit.enricher.api.util.KubernetesResourceUtil;
import org.apache.maven.plugin.MojoExecutionException;
Expand All @@ -34,10 +33,9 @@

import java.io.File;
import java.net.URL;
import java.util.Optional;
import java.util.Set;

import static org.eclipse.jkube.kit.common.util.KubernetesHelper.getConfiguredNamespace;

/**
* Base class for goals which deploy the generated artifacts into the Kubernetes cluster
*/
Expand Down Expand Up @@ -124,9 +122,6 @@ public class ApplyMojo extends AbstractJKubeMojo implements ManifestProvider {
@Parameter(property = "jkube.serviceUrl.waitSeconds", defaultValue = "5")
protected long serviceUrlWaitTimeSeconds;

@Parameter
protected ResourceConfig resources;

/**
* Folder where to find project specific files
*/
Expand All @@ -140,6 +135,12 @@ public class ApplyMojo extends AbstractJKubeMojo implements ManifestProvider {
@Parameter(property = "jkube.environment")
private String environment;

/**
* Namespace to use when accessing Kubernetes or OpenShift
*/
@Parameter(property = "jkube.namespace")
protected String namespace;

@Parameter(property = "jkube.skip.apply", defaultValue = "false")
protected boolean skipApply;

Expand Down Expand Up @@ -183,18 +184,16 @@ public void executeInternal() throws MojoExecutionException {
configureApplyService(kubernetes);

// Apply rest of the entities present in manifest
applyEntities(kubernetes, getConfiguredNamespace(project.getProperties(), clusterAccess.getNamespace()), manifest.getName(), entities);
applyEntities(kubernetes, manifest.getName(), entities);
log.info("[[B]]HINT:[[B]] Use the command `%s get pods -w` to watch your pods start up", clusterAccess.isOpenShift() ? "oc" : "kubectl");
} catch (KubernetesClientException e) {
KubernetesResourceUtil.handleKubernetesClientException(e, this.log);
} catch (MojoExecutionException e) {
throw e;
} catch (Exception e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}

protected void applyEntities(final KubernetesClient kubernetes, final String namespace, String fileName, final Set<HasMetadata> entities) throws Exception {
protected void applyEntities(final KubernetesClient kubernetes, String fileName, final Set<HasMetadata> entities) throws InterruptedException {
KitLogger serviceLogger = createLogger("[[G]][SVC][[G]] [[s]]");
applyService.applyEntities(fileName, entities, serviceLogger, serviceUrlWaitTimeSeconds);
}
Expand Down Expand Up @@ -233,7 +232,12 @@ private void configureApplyService(KubernetesClient kubernetes) {
applyService.setRollingUpgrade(rollingUpgrades);
applyService.setRollingUpgradePreserveScale(isRollingUpgradePreserveScale());
applyService.setRecreateMode(recreate);
applyService.setNamespace(getConfiguredNamespace(project.getProperties(), clusterAccess.getNamespace()));
applyService.setNamespace(
Optional.ofNullable(namespace)
.map(String::trim)
.filter(s -> !s.isEmpty())
.orElse(clusterAccess.getNamespace())
);

boolean openShift = OpenshiftHelper.isOpenShift(kubernetes);
if (openShift) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@

import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.client.KubernetesClient;
import org.apache.maven.plugin.MojoExecutionException;
import org.eclipse.jkube.maven.plugin.mojo.build.ApplyMojo;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
Expand All @@ -31,21 +30,17 @@
@Mojo(name = "debug", requiresDependencyResolution = ResolutionScope.COMPILE, defaultPhase = LifecyclePhase.PACKAGE)
public class DebugMojo extends ApplyMojo {

@Parameter(property = "jkube.debug.port", defaultValue = "5005")
private String localDebugPort;
@Parameter(property = "jkube.debug.port", defaultValue = "5005")
private String localDebugPort;

@Parameter(property = "jkube.debug.suspend", defaultValue = "false")
private boolean debugSuspend;
@Parameter(property = "jkube.debug.suspend", defaultValue = "false")
private boolean debugSuspend;

@Override
protected void applyEntities(KubernetesClient kubernetes, String namespace, String fileName, Set<HasMetadata> entities) throws Exception {
try {
jkubeServiceHub.getDebugService().debug(namespace, fileName, entities, localDebugPort, debugSuspend, createLogger("[[Y]][W][[Y]] [[s]]"));
} catch (Exception exp) {
throw new MojoExecutionException(exp.getMessage());
}
}
@Override
protected void applyEntities(KubernetesClient kubernetes, String fileName, Set<HasMetadata> entities) {
jkubeServiceHub.getDebugService().debug(
applyService.getNamespace(), fileName, entities, localDebugPort, debugSuspend, createLogger("[[Y]][W][[Y]] [[s]]"));
}

}


Loading

0 comments on commit e0b4b4e

Please sign in to comment.