Skip to content

feature: update preserves metadata #960

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,15 @@ public static Object getSpec(HasMetadata resource) {
}
}

public static Object setSpec(HasMetadata resource, Object spec) {
try {
Method setSpecMethod = resource.getClass().getMethod("setSpec", spec.getClass());
return setSpecMethod.invoke(resource, spec);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
throw new IllegalStateException("No spec found on resource", e);
}
}

public static <T> T loadYaml(Class<T> clazz, Class loader, String yaml) {
try (InputStream is = loader.getResourceAsStream(yaml)) {
return Serialization.unmarshal(is, clazz);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ public abstract class KubernetesDependentResource<R extends HasMetadata, P exten
private InformerEventSource<R, P> informerEventSource;
private boolean addOwnerReference;
protected ResourceMatcher resourceMatcher;
protected ResourceUpdatePreProcessor<R> resourceUpdatePreProcessor;

@Override
public void configureWith(KubernetesDependentResourceConfig config) {
Expand Down Expand Up @@ -74,10 +75,10 @@ public void configureWith(ConfigurationService configurationService,
boolean addOwnerReference) {
this.informerEventSource = informerEventSource;
this.addOwnerReference = addOwnerReference;
initResourceMatcherIfNotSet(configurationService);
initResourceMatcherAndUpdatePreProcessorIfNotSet(configurationService);
}

protected void beforeCreateOrUpdate(R desired, P primary) {
protected void beforeCreate(R desired, P primary) {
if (addOwnerReference) {
desired.addOwnerReference(primary);
}
Expand All @@ -93,7 +94,7 @@ protected boolean match(R actualResource, R desiredResource, Context context) {
protected R create(R target, P primary, Context context) {
log.debug("Creating target resource with type: " +
"{}, with id: {}", target.getClass(), ResourceID.fromResource(target));
beforeCreateOrUpdate(target, primary);
beforeCreate(target, primary);
Class<R> targetClass = (Class<R>) target.getClass();
return client.resources(targetClass).inNamespace(target.getMetadata().getNamespace())
.create(target);
Expand All @@ -104,15 +105,15 @@ protected R create(R target, P primary, Context context) {
protected R update(R actual, R target, P primary, Context context) {
log.debug("Updating target resource with type: {}, with id: {}", target.getClass(),
ResourceID.fromResource(target));
beforeCreateOrUpdate(target, primary);
Class<R> targetClass = (Class<R>) target.getClass();
var updatedActual = resourceUpdatePreProcessor.replaceSpecOnActual(actual, target);
return client.resources(targetClass).inNamespace(target.getMetadata().getNamespace())
.replace(target);
.replace(updatedActual);
}

@Override
public EventSource eventSource(EventSourceContext<P> context) {
initResourceMatcherIfNotSet(context.getConfigurationService());
initResourceMatcherAndUpdatePreProcessorIfNotSet(context.getConfigurationService());
if (informerEventSource == null) {
configureWith(context.getConfigurationService(), null, null,
KubernetesDependent.ADD_OWNER_REFERENCE_DEFAULT);
Expand Down Expand Up @@ -156,10 +157,25 @@ public void setKubernetesClient(KubernetesClient kubernetesClient) {
*
* @param configurationService config service to mainly access object mapper
*/
protected void initResourceMatcherIfNotSet(ConfigurationService configurationService) {
protected void initResourceMatcherAndUpdatePreProcessorIfNotSet(
ConfigurationService configurationService) {
if (resourceMatcher == null) {
resourceMatcher = new DesiredValueMatcher(configurationService.getObjectMapper());
}
if (resourceUpdatePreProcessor == null) {
resourceUpdatePreProcessor =
new ResourceUpdatePreProcessor<>(configurationService.getResourceCloner());
}
}

public KubernetesDependentResource<R, P> setResourceMatcher(ResourceMatcher resourceMatcher) {
this.resourceMatcher = resourceMatcher;
return this;
}

public KubernetesDependentResource<R, P> setResourceUpdatePreProcessor(
ResourceUpdatePreProcessor<R> resourceUpdatePreProcessor) {
this.resourceUpdatePreProcessor = resourceUpdatePreProcessor;
return this;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package io.javaoperatorsdk.operator.processing.dependent.kubernetes;

import io.fabric8.kubernetes.api.model.ConfigMap;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.Secret;
import io.javaoperatorsdk.operator.ReconcilerUtils;
import io.javaoperatorsdk.operator.api.config.Cloner;

public class ResourceUpdatePreProcessor<R extends HasMetadata> {

private final Cloner cloner;

public ResourceUpdatePreProcessor(Cloner cloner) {
this.cloner = cloner;
}

public R replaceSpecOnActual(R actual, R desired) {
var clonedActual = cloner.clone(actual);
if (desired instanceof ConfigMap) {
((ConfigMap) clonedActual).setData(((ConfigMap) desired).getData());
((ConfigMap) clonedActual).setBinaryData((((ConfigMap) desired).getBinaryData()));
return clonedActual;
} else if (desired instanceof Secret) {
((Secret) clonedActual).setData(((Secret) desired).getData());
((Secret) clonedActual).setStringData(((Secret) desired).getStringData());
return clonedActual;
} else {
var desiredSpec = ReconcilerUtils.getSpec(desired);
ReconcilerUtils.setSpec(clonedActual, desiredSpec);
return clonedActual;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,19 @@ void getsSpecWithReflection() {
assertThat(spec.getReplicas()).isEqualTo(5);
}

@Test
void setsSpecWithReflection() {
Deployment deployment = new Deployment();
deployment.setSpec(new DeploymentSpec());
deployment.getSpec().setReplicas(5);
DeploymentSpec newSpec = new DeploymentSpec();
newSpec.setReplicas(1);

ReconcilerUtils.setSpec(deployment, newSpec);

assertThat(deployment.getSpec().getReplicas()).isEqualTo(1);
}

private Deployment createTestDeployment() {
Deployment deployment = new Deployment();
deployment.setSpec(new DeploymentSpec());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package io.javaoperatorsdk.operator.processing.dependent.kubernetes;

import java.util.HashMap;

import org.junit.jupiter.api.Test;

import io.fabric8.kubernetes.api.model.apps.Deployment;
import io.javaoperatorsdk.operator.ReconcilerUtils;
import io.javaoperatorsdk.operator.api.config.ConfigurationService;

import static org.assertj.core.api.Assertions.assertThat;

class ResourceUpdatePreProcessorTest {

ResourceUpdatePreProcessor<Deployment> resourceUpdatePreProcessor =
new ResourceUpdatePreProcessor<>(ConfigurationService.DEFAULT_CLONER);

@Test
void preservesValues() {
var desired = createDeployment();
var actual = createDeployment();
actual.getMetadata().setLabels(new HashMap<>());
actual.getMetadata().getLabels().put("additionalActualKey", "value");
actual.getMetadata().setResourceVersion("1234");
actual.getSpec().setRevisionHistoryLimit(5);

var result = resourceUpdatePreProcessor.replaceSpecOnActual(actual, desired);

assertThat(result.getMetadata().getLabels().get("additionalActualKey")).isEqualTo("value");
assertThat(result.getMetadata().getResourceVersion()).isEqualTo("1234");
assertThat(result.getSpec().getRevisionHistoryLimit()).isEqualTo(10);
}

Deployment createDeployment() {
Deployment deployment =
ReconcilerUtils.loadYaml(
Deployment.class, ResourceUpdatePreProcessorTest.class, "nginx-deployment.yaml");
return deployment;
}

}