diff --git a/docs/content/en/docs/documentation/reconciler.md b/docs/content/en/docs/documentation/reconciler.md index 86e701d801..be1afd9a63 100644 --- a/docs/content/en/docs/documentation/reconciler.md +++ b/docs/content/en/docs/documentation/reconciler.md @@ -78,6 +78,13 @@ in Kubernetes parlance), thus usually using a resource created from scratch, see [sample](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourcewithssa). To contrast, see the same sample, this time [without SSA](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourceandstatusnossa/PatchResourceAndStatusNoSSAReconciler.java). +The status is an exception: for `UpdateControl.patchStatus` and `ErrorStatusUpdateControl.patchStatus`, JOSDK derives +the fully specified intent itself from the resource you return, keeping only the fields identifying it (name, namespace +and the resource version, if set) and the status. Your controller thus never takes ownership of labels, annotations or +the spec through the `status` subresource, which Kubernetes up to 1.35 would otherwise record and which makes other SSA +appliers of those fields conflict with the controller (see +[#3721](https://github.com/operator-framework/java-operator-sdk/issues/3721)). + Non-SSA based patch is still supported. You can control whether or not to use SSA using [`ConfigurationServcice.useSSAToPatchPrimaryResource()`](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java#L385-L385) diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/ReconcilerUtilsInternal.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/ReconcilerUtilsInternal.java index a969f52c9b..6c52f9b338 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/ReconcilerUtilsInternal.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/ReconcilerUtilsInternal.java @@ -29,6 +29,7 @@ import io.fabric8.kubernetes.client.CustomResource; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.utils.Serialization; +import io.javaoperatorsdk.operator.api.config.Utils; import io.javaoperatorsdk.operator.api.reconciler.Constants; import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; import io.javaoperatorsdk.operator.api.reconciler.NonComparableResourceVersionException; @@ -176,7 +177,7 @@ private static Object setSpecOrStatus( // if given spec is null, find the method just using its name Method setMethod; if (spec != null) { - setMethod = resourceClass.getMethod(setterMethodName, spec.getClass()); + setMethod = findSetter(resourceClass, setterMethodName, spec.getClass()); } else { setMethod = Arrays.stream(resourceClass.getMethods()) @@ -191,6 +192,40 @@ private static Object setSpecOrStatus( } } + // the value may be a subclass of the setter's parameter type, then there is no exact match + private static Method findSetter( + Class resourceClass, String setterMethodName, Class valueClass) + throws NoSuchMethodException { + try { + return resourceClass.getMethod(setterMethodName, valueClass); + } catch (NoSuchMethodException e) { + return Arrays.stream(resourceClass.getMethods()) + .filter( + method -> + setterMethodName.equals(method.getName()) + && method.getParameterCount() == 1 + && method.getParameterTypes()[0].isAssignableFrom(valueClass)) + .findFirst() + .orElseThrow(() -> e); + } + } + + /** + * Creates a new, empty instance of the given resource's class through its no-arg constructor, as + * a starting point for a server-side apply body that carries only selected fields. + */ + @SuppressWarnings("unchecked") + public static R newEmptyInstanceOf(R resource) { + try { + return (R) Utils.getConstructor(resource.getClass()).newInstance(); + } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException( + "Issue with creating custom resource instance with reflection. Class: " + + resource.getClass().getName(), + e); + } + } + private static IllegalStateException noMethodException( HasMetadata resource, ReflectiveOperationException e, String methodName) { return new IllegalStateException( diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/ErrorStatusUpdateControl.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/ErrorStatusUpdateControl.java index 2636fea879..0562056bc8 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/ErrorStatusUpdateControl.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/ErrorStatusUpdateControl.java @@ -27,6 +27,15 @@ public class ErrorStatusUpdateControl

private boolean noRetry = false; private final boolean defaultErrorProcessing; + /** + * Patches the status of the resource, the same way {@link UpdateControl#patchStatus(HasMetadata)} + * does: with Server-Side Apply only the fields identifying the resource and the status are + * applied. + * + * @param resource the resource with the target status + * @param resource type + * @return ErrorStatusUpdateControl instance + */ public static ErrorStatusUpdateControl patchStatus(T resource) { return new ErrorStatusUpdateControl<>(resource); } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/ResourceOperations.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/ResourceOperations.java index 93bbe7fa7b..b8eedf3bfc 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/ResourceOperations.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/ResourceOperations.java @@ -15,7 +15,6 @@ */ package io.javaoperatorsdk.operator.api.reconciler; -import java.lang.reflect.InvocationTargetException; import java.net.HttpURLConnection; import java.util.Optional; import java.util.function.IntPredicate; @@ -30,6 +29,7 @@ import io.fabric8.kubernetes.client.dsl.base.PatchContext; import io.fabric8.kubernetes.client.dsl.base.PatchType; import io.javaoperatorsdk.operator.OperatorException; +import io.javaoperatorsdk.operator.ReconcilerUtilsInternal; import io.javaoperatorsdk.operator.api.reconciler.matcher.Matcher; import io.javaoperatorsdk.operator.processing.event.ResourceID; import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; @@ -309,6 +309,11 @@ public P serverSideApplyPrimaryStatus(P desired) { * Server-Side Applies the primary resource {@code status} subresource, caching and filtering the * own event through the controller's own event source and using the given {@link Options}. * + *

The desired resource is applied as given. Unlike {@link + * UpdateControl#patchStatus(HasMetadata)}, which derives such a body from any resource, it should + * carry only the fields identifying the resource and the status, otherwise the controller takes + * ownership of the other fields as well. + * * @param desired the desired primary resource (with the status to apply) * @param options controls caching and own-event filtering; see {@link Options} * @return the applied resource as returned by the API server @@ -901,7 +906,6 @@ public R resourcePatch(R resource, UnaryOperator upda return resourcePatch(resource, updateOperation, Options.filterWithOptimisticLocking()); } - @SuppressWarnings({"rawtypes", "unchecked"}) private R resourcePatch( R desired, UnaryOperator updateOperation, Options options) { return resourcePatch(desired, null, updateOperation, options); @@ -1299,23 +1303,11 @@ public P addFinalizerWithSSA(String finalizerName) { } private P finalizerApplyFor(P actualResource, String finalizerName) { - try { - @SuppressWarnings("unchecked") - P resource = (P) actualResource.getClass().getConstructor().newInstance(); - resource.initNameAndNamespaceFrom(actualResource); - resource.getMetadata().setUid(actualResource.getMetadata().getUid()); - resource.addFinalizer(finalizerName); - return resource; - } catch (InstantiationException - | IllegalAccessException - | InvocationTargetException - | NoSuchMethodException e) { - throw new RuntimeException( - "Issue with creating custom resource instance with reflection." - + " Custom Resources must provide a no-arg constructor. Class: " - + actualResource.getClass().getName(), - e); - } + P resource = ReconcilerUtilsInternal.newEmptyInstanceOf(actualResource); + resource.initNameAndNamespaceFrom(actualResource); + resource.getMetadata().setUid(actualResource.getMetadata().getUid()); + resource.addFinalizer(finalizerName); + return resource; } /** diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/UpdateControl.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/UpdateControl.java index 08611ff06f..9f2a867909 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/UpdateControl.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/UpdateControl.java @@ -18,7 +18,7 @@ import java.util.Optional; import io.fabric8.kubernetes.api.model.HasMetadata; -import io.fabric8.kubernetes.client.CustomResource; +import io.javaoperatorsdk.operator.api.config.ConfigurationService; public class UpdateControl

extends BaseControl> { @@ -36,12 +36,19 @@ private UpdateControl(P resource, boolean patchResource, boolean patchStatus) { } /** - * Preferred way to update the status. Uses JSON Patch to patch the resource. + * Preferred way to update the status. * - *

Note that this does not work, if the {@link CustomResource#initStatus()} is implemented, - * since it breaks the diffing process. Don't implement it if using this method. There is also an - * issue with setting value to {@code null} with older Kubernetes versions (1.19 and below). See: - * By default the status is patched with Server-Side Apply, see {@link + * ConfigurationService#useSSAToPatchPrimaryResource()}. The framework builds the applied body + * from the given resource: it carries only the fields identifying the resource (name, namespace + * and the resource version when set, which keeps optimistic locking) and the status, so the + * controller does not take ownership of any other field, such as labels or the spec, through the + * status subresource. The given resource itself is not modified. + * + *

Without Server-Side Apply, a JSON Patch is used. Note that this does not work, if the {@code + * CustomResource#initStatus()} is implemented, since it breaks the diffing process. Don't + * implement it if using this method. There is also an issue with setting value to {@code null} + * with older Kubernetes versions (1.19 and below). See: https://github.com/fabric8io/kubernetes-client/issues/4158 * * @param resource type @@ -57,6 +64,9 @@ public static UpdateControl patchResource(T customRes } /** + * Patches the resource first and then the status, with two separate requests. The status is + * patched the same way as with {@link #patchStatus(HasMetadata)}. + * * @param customResource to update * @return UpdateControl instance * @param resource type diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/ReconciliationDispatcher.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/ReconciliationDispatcher.java index e65a611c19..61ebfeea4c 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/ReconciliationDispatcher.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/ReconciliationDispatcher.java @@ -22,6 +22,8 @@ import org.slf4j.event.Level; import io.fabric8.kubernetes.api.model.HasMetadata; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.fabric8.kubernetes.client.CustomResource; import io.fabric8.kubernetes.client.KubernetesClientException; import io.javaoperatorsdk.operator.OperatorException; import io.javaoperatorsdk.operator.ReconcilerUtilsInternal; @@ -385,20 +387,32 @@ public R patchResource(Context context, R resource, R originalResource) { public R patchStatus(Context context, R resource, R originalResource) { log.trace("Patching status for resource: {} with ssa: {}", resource, useSSA); if (useSSA) { - var managedFields = resource.getMetadata().getManagedFields(); - try { - resource.getMetadata().setManagedFields(null); - return context - .resourceOperations() - .serverSideApplyPrimaryStatus(resource, ResourceOperations.Options.cacheOnly()); - } finally { - resource.getMetadata().setManagedFields(managedFields); - } + return context + .resourceOperations() + .serverSideApplyPrimaryStatus( + statusApplyFor(resource), ResourceOperations.Options.cacheOnly()); } else { return editStatus(context, resource, originalResource); } } + private R statusApplyFor(R resource) { + var statusOnly = ReconcilerUtilsInternal.newEmptyInstanceOf(resource); + statusOnly.setMetadata( + new ObjectMetaBuilder() + .withName(resource.getMetadata().getName()) + .withNamespace(resource.getMetadata().getNamespace()) + .withUid(resource.getMetadata().getUid()) + .withResourceVersion(resource.getMetadata().getResourceVersion()) + .build()); + if (statusOnly instanceof CustomResource customResource) { + // a subclass may pre-populate the spec through CustomResource#initSpec() + customResource.setSpec(null); + } + ReconcilerUtilsInternal.setStatus(statusOnly, ReconcilerUtilsInternal.getStatus(resource)); + return statusOnly; + } + private R editStatus(Context context, R resource, R originalResource) { String resourceVersion = resource.getMetadata().getResourceVersion(); // the cached resource should not be changed in any circumstances diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/ReconcilerUtilsInternalTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/ReconcilerUtilsInternalTest.java index bd64333c6b..b329056ce8 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/ReconcilerUtilsInternalTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/ReconcilerUtilsInternalTest.java @@ -26,6 +26,7 @@ import io.fabric8.kubernetes.api.model.apps.Deployment; import io.fabric8.kubernetes.api.model.apps.DeploymentBuilder; import io.fabric8.kubernetes.api.model.apps.DeploymentSpec; +import io.fabric8.kubernetes.api.model.apps.DeploymentStatus; import io.fabric8.kubernetes.client.CustomResource; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.http.HttpRequest; @@ -121,6 +122,18 @@ void setsSpecWithReflection() { assertThat(deployment.getSpec().getReplicas()).isEqualTo(1); } + @Test + void setsStatusSubclassWithReflection() { + var deployment = new Deployment(); + var status = new ExtendedDeploymentStatus(); + + ReconcilerUtilsInternal.setStatus(deployment, status); + + assertThat(deployment.getStatus()).isSameAs(status); + } + + private static class ExtendedDeploymentStatus extends DeploymentStatus {} + @Test void setsSpecCustomResourceWithReflection() { Tomcat tomcat = new Tomcat(); diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/CustomResourceFacadeTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/CustomResourceFacadeTest.java new file mode 100644 index 0000000000..8adfe36492 --- /dev/null +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/CustomResourceFacadeTest.java @@ -0,0 +1,166 @@ +/* + * Copyright Java Operator SDK Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.javaoperatorsdk.operator.processing.event; + +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.fabric8.kubernetes.api.model.ManagedFieldsEntry; +import io.fabric8.kubernetes.api.model.apps.DeploymentBuilder; +import io.javaoperatorsdk.operator.TestUtils; +import io.javaoperatorsdk.operator.api.config.BaseConfigurationService; +import io.javaoperatorsdk.operator.api.config.ConfigurationService; +import io.javaoperatorsdk.operator.api.config.MockControllerConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.ResourceOperations; +import io.javaoperatorsdk.operator.processing.event.ReconciliationDispatcher.CustomResourceFacade; +import io.javaoperatorsdk.operator.sample.simple.TestCustomResource; +import io.javaoperatorsdk.operator.sample.simple.TestCustomResourceStatus; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@SuppressWarnings("unchecked") +class CustomResourceFacadeTest { + + private static final String FINALIZER = "test.javaoperatorsdk.io/finalizer"; + + @Test + void ssaStatusPatchAppliesOnlyIdentityResourceVersionAndStatus() { + var resource = testResourceWithMetadataAndStatus(); + + var applied = ssaPatchStatus(resource); + + assertThat(applied).isNotSameAs(resource); + assertThat(applied.getApiVersion()).isEqualTo(resource.getApiVersion()); + assertThat(applied.getKind()).isEqualTo(resource.getKind()); + assertThat(applied.getMetadata().getName()).isEqualTo(resource.getMetadata().getName()); + assertThat(applied.getMetadata().getNamespace()) + .isEqualTo(resource.getMetadata().getNamespace()); + assertThat(applied.getMetadata().getResourceVersion()).isEqualTo("1"); + assertThat(applied.getStatus()).isEqualTo(resource.getStatus()); + assertThat(applied.getSpec()).isNull(); + assertThat(applied.getMetadata().getLabels()).isNullOrEmpty(); + assertThat(applied.getMetadata().getAnnotations()).isNullOrEmpty(); + assertThat(applied.getMetadata().getFinalizers()).isNullOrEmpty(); + assertThat(applied.getMetadata().getManagedFields()).isNullOrEmpty(); + assertThat(applied.getMetadata().getGeneration()).isNull(); + assertThat(applied.getMetadata().getUid()).isEqualTo("uid-1"); + } + + @Test + void ssaStatusPatchOmitsResourceVersionWhenNotSet() { + var resource = testResourceWithMetadataAndStatus(); + resource.getMetadata().setResourceVersion(null); + + var applied = ssaPatchStatus(resource); + + assertThat(applied.getMetadata().getResourceVersion()).isNull(); + } + + @Test + void ssaStatusPatchAppliesNullStatusWhenResourceHasNone() { + var resource = testResourceWithMetadataAndStatus(); + resource.setStatus(null); + + var applied = ssaPatchStatus(resource); + + assertThat(applied.getStatus()).isNull(); + } + + @Test + void ssaStatusPatchLeavesPassedResourceUntouched() { + var resource = testResourceWithMetadataAndStatus(); + + ssaPatchStatus(resource); + + assertThat(resource.getMetadata().getLabels()).containsEntry("app", "test"); + assertThat(resource.getMetadata().getFinalizers()).containsExactly(FINALIZER); + assertThat(resource.getMetadata().getManagedFields()).hasSize(1); + assertThat(resource.getSpec()).isNotNull(); + } + + @Test + void ssaStatusPatchTrimsNonCustomResourcePrimaryToo() { + var deployment = + new DeploymentBuilder() + .withNewMetadata() + .withName("test") + .withNamespace("default") + .withResourceVersion("7") + .withLabels(Map.of("app", "test")) + .endMetadata() + .withNewSpec() + .withReplicas(3) + .endSpec() + .withNewStatus() + .withReadyReplicas(3) + .endStatus() + .build(); + + var applied = ssaPatchStatus(deployment); + + assertThat(applied.getApiVersion()).isEqualTo("apps/v1"); + assertThat(applied.getKind()).isEqualTo("Deployment"); + assertThat(applied.getMetadata().getName()).isEqualTo("test"); + assertThat(applied.getMetadata().getNamespace()).isEqualTo("default"); + assertThat(applied.getMetadata().getResourceVersion()).isEqualTo("7"); + assertThat(applied.getMetadata().getLabels()).isNullOrEmpty(); + assertThat(applied.getSpec()).isNull(); + assertThat(applied.getStatus().getReadyReplicas()).isEqualTo(3); + } + + private static TestCustomResource testResourceWithMetadataAndStatus() { + var resource = TestUtils.testCustomResource(); + resource.getMetadata().setUid("uid-1"); + resource.getMetadata().setLabels(Map.of("app", "test")); + resource.getMetadata().setAnnotations(Map.of("note", "value")); + resource.getMetadata().setFinalizers(List.of(FINALIZER)); + resource.getMetadata().setManagedFields(List.of(new ManagedFieldsEntry())); + var status = new TestCustomResourceStatus(); + status.setConfigMapStatus("created"); + resource.setStatus(status); + return resource; + } + + private static R ssaPatchStatus(R resource) { + var configurationService = + ConfigurationService.newOverriddenConfigurationService( + new BaseConfigurationService(), + overrider -> overrider.withUseSSAToPatchPrimaryResource(true)); + var configuration = + MockControllerConfiguration.forResource( + (Class) resource.getClass(), configurationService); + var facade = + new CustomResourceFacade<>(configuration, configurationService.getResourceCloner()); + Context context = mock(Context.class); + ResourceOperations resourceOperations = mock(ResourceOperations.class); + when(context.resourceOperations()).thenReturn(resourceOperations); + + facade.patchStatus(context, resource, resource); + + ArgumentCaptor captor = ArgumentCaptor.forClass((Class) resource.getClass()); + verify(resourceOperations).serverSideApplyPrimaryStatus(captor.capture(), any()); + return captor.getValue(); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchssaownership/StatusPatchSSAOwnershipCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchssaownership/StatusPatchSSAOwnershipCustomResource.java new file mode 100644 index 0000000000..14d8674a66 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchssaownership/StatusPatchSSAOwnershipCustomResource.java @@ -0,0 +1,29 @@ +/* + * Copyright Java Operator SDK Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.javaoperatorsdk.operator.baseapi.statuspatchssaownership; + +import io.fabric8.kubernetes.api.model.Namespaced; +import io.fabric8.kubernetes.client.CustomResource; +import io.fabric8.kubernetes.model.annotation.Group; +import io.fabric8.kubernetes.model.annotation.ShortNames; +import io.fabric8.kubernetes.model.annotation.Version; + +@Group("sample.javaoperatorsdk") +@Version("v1") +@ShortNames("spso") +public class StatusPatchSSAOwnershipCustomResource + extends CustomResource + implements Namespaced {} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchssaownership/StatusPatchSSAOwnershipIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchssaownership/StatusPatchSSAOwnershipIT.java new file mode 100644 index 0000000000..973f7d2155 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchssaownership/StatusPatchSSAOwnershipIT.java @@ -0,0 +1,103 @@ +/* + * Copyright Java Operator SDK Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.javaoperatorsdk.operator.baseapi.statuspatchssaownership; + +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.fabric8.kubernetes.client.dsl.base.PatchContext; +import io.fabric8.kubernetes.client.dsl.base.PatchType; +import io.javaoperatorsdk.annotation.Sample; +import io.javaoperatorsdk.operator.ReconcilerUtilsInternal; +import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; + +import static io.javaoperatorsdk.operator.baseapi.statuspatchssaownership.StatusPatchSSAOwnershipReconciler.MESSAGE; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +@Sample( + tldr = "Status Patching with SSA Owns Only the Status", + description = + """ + Verifies that patching the status with Server-Side Apply through UpdateControl, even when \ + the reconciler returns the reconciled resource itself with its labels and spec, leaves the \ + controller as owner of the status only. Up to Kubernetes 1.35 the API server records the \ + controller as owner of every field in the status apply body, so another applier of the \ + labels would otherwise conflict with the controller. + """) +class StatusPatchSSAOwnershipIT { + + static final String RESOURCE_NAME = "test"; + static final String LABEL = "app.kubernetes.io/version"; + static final String OTHER_MANAGER = "other-manager"; + + @RegisterExtension + LocallyRunOperatorExtension extension = + LocallyRunOperatorExtension.builder() + .withReconciler(new StatusPatchSSAOwnershipReconciler()) + .build(); + + @Test + void statusPatchOwnsOnlyTheStatus() { + applyWithLabelAsOtherManager("1"); + + await() + .untilAsserted( + () -> { + var actual = + extension.get(StatusPatchSSAOwnershipCustomResource.class, RESOURCE_NAME); + assertThat(actual.getStatus()).isNotNull(); + assertThat(actual.getStatus().getMessage()).isEqualTo(MESSAGE); + }); + + var actual = extension.get(StatusPatchSSAOwnershipCustomResource.class, RESOURCE_NAME); + var controllerStatusEntry = + actual.getMetadata().getManagedFields().stream() + .filter(entry -> "status".equals(entry.getSubresource())) + .findFirst() + .orElseThrow(); + assertThat(controllerStatusEntry.getManager()) + .isEqualTo( + ReconcilerUtilsInternal.getDefaultNameFor(StatusPatchSSAOwnershipReconciler.class)); + assertThat(controllerStatusEntry.getFieldsV1().getAdditionalProperties()) + .containsOnlyKeys("f:status"); + + var relabelled = applyWithLabelAsOtherManager("2"); + assertThat(relabelled.getMetadata().getLabels()).containsEntry(LABEL, "2"); + } + + private StatusPatchSSAOwnershipCustomResource applyWithLabelAsOtherManager(String version) { + var resource = new StatusPatchSSAOwnershipCustomResource(); + resource.setMetadata( + new ObjectMetaBuilder() + .withName(RESOURCE_NAME) + .withNamespace(extension.getNamespace()) + .withLabels(Map.of(LABEL, version)) + .build()); + resource.setSpec(new StatusPatchSSAOwnershipSpec().setValue("value")); + return extension + .getKubernetesClient() + .resource(resource) + .patch( + new PatchContext.Builder() + .withFieldManager(OTHER_MANAGER) + .withPatchType(PatchType.SERVER_SIDE_APPLY) + .build()); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchssaownership/StatusPatchSSAOwnershipReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchssaownership/StatusPatchSSAOwnershipReconciler.java new file mode 100644 index 0000000000..8c55dd178a --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchssaownership/StatusPatchSSAOwnershipReconciler.java @@ -0,0 +1,39 @@ +/* + * Copyright Java Operator SDK Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.javaoperatorsdk.operator.baseapi.statuspatchssaownership; + +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.Reconciler; +import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; + +@ControllerConfiguration +public class StatusPatchSSAOwnershipReconciler + implements Reconciler { + + public static final String MESSAGE = "reconciled"; + + @Override + public UpdateControl reconcile( + StatusPatchSSAOwnershipCustomResource resource, + Context context) { + if (resource.getStatus() == null) { + resource.setStatus(new StatusPatchSSAOwnershipStatus()); + } + resource.getStatus().setMessage(MESSAGE); + return UpdateControl.patchStatus(resource); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchssaownership/StatusPatchSSAOwnershipSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchssaownership/StatusPatchSSAOwnershipSpec.java new file mode 100644 index 0000000000..8dca8971df --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchssaownership/StatusPatchSSAOwnershipSpec.java @@ -0,0 +1,30 @@ +/* + * Copyright Java Operator SDK Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.javaoperatorsdk.operator.baseapi.statuspatchssaownership; + +public class StatusPatchSSAOwnershipSpec { + + private String value; + + public String getValue() { + return value; + } + + public StatusPatchSSAOwnershipSpec setValue(String value) { + this.value = value; + return this; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchssaownership/StatusPatchSSAOwnershipStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchssaownership/StatusPatchSSAOwnershipStatus.java new file mode 100644 index 0000000000..621076d7ac --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchssaownership/StatusPatchSSAOwnershipStatus.java @@ -0,0 +1,30 @@ +/* + * Copyright Java Operator SDK Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.javaoperatorsdk.operator.baseapi.statuspatchssaownership; + +public class StatusPatchSSAOwnershipStatus { + + private String message; + + public String getMessage() { + return message; + } + + public StatusPatchSSAOwnershipStatus setMessage(String message) { + this.message = message; + return this; + } +}