Skip to content
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
7 changes: 7 additions & 0 deletions docs/content/en/docs/documentation/reconciler.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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())
Expand All @@ -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 extends HasMetadata> 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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,15 @@ public class ErrorStatusUpdateControl<P extends HasMetadata>
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 <T> resource type
* @return ErrorStatusUpdateControl instance
*/
public static <T extends HasMetadata> ErrorStatusUpdateControl<T> patchStatus(T resource) {
return new ErrorStatusUpdateControl<>(resource);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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}.
*
* <p>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
Expand Down Expand Up @@ -901,7 +906,6 @@ public <R extends HasMetadata> R resourcePatch(R resource, UnaryOperator<R> upda
return resourcePatch(resource, updateOperation, Options.filterWithOptimisticLocking());
}

@SuppressWarnings({"rawtypes", "unchecked"})
private <R extends HasMetadata> R resourcePatch(
R desired, UnaryOperator<R> updateOperation, Options options) {
return resourcePatch(desired, null, updateOperation, options);
Expand Down Expand Up @@ -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;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<P extends HasMetadata> extends BaseControl<UpdateControl<P>> {

Expand All @@ -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.
*
* <p>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:
* <a href=
* <p>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.
*
* <p>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: <a href=
* "https://github.com/fabric8io/kubernetes-client/issues/4158">https://github.com/fabric8io/kubernetes-client/issues/4158</a>
*
* @param <T> resource type
Expand All @@ -57,6 +64,9 @@ public static <T extends HasMetadata> UpdateControl<T> 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 <T> resource type
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -385,20 +387,32 @@ public R patchResource(Context<R> context, R resource, R originalResource) {
public R patchStatus(Context<R> 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);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We do not send UID anymore, would be a bit safer to send it, so we do not patch a deleted - than -recreated primary

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added it. Small caveat: for CRs the API server throws it away on the status subresource (the status strategy copies the stored metadata before validating), so there the resourceVersion is what really guards against a recreated primary. It does help for built-in types, and it's what the old body sent anyway.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The resourceVersion could be omitted. Would be good to have a test if UID helps in that case.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked on minikube (1.37): status SSA on a recreated CR with the old uid and no resourceVersion goes through (200) and updates the status, the old uid is simply ignored.
With the old resourceVersion it's a 409. On a Deployment the stale uid is rejected with 422 (metadata.uid immutable).
So for CRs only the resourceVersion protects, the uid stays in for the built-in types. A test would just assert the server ignores the uid, so I'd skip it.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ahh ok, sorry I merged too quick then. Maybe a subsequent PR?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, no worries, all good, nothing's missing here, the uid made it into the merge.
Just as I said, that test would only assert the server ignores the uid, so nothing really worth doing.
Thanks for the quick review and approval

@csviri csviri Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, maybe we should then remove the unnecessary UID propagation.
Do you require an urgent patch release? If not would do it end of this or beginning next week

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, no rush for that. Next week is fine

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe I could also propose a PR for this #3728 as well, so it can make it?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, sure go for it, thx!

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));
Comment thread
afalhambra-hivemq marked this conversation as resolved.
Resolved
return statusOnly;
}

private R editStatus(Context<R> context, R resource, R originalResource) {
String resourceVersion = resource.getMetadata().getResourceVersion();
// the cached resource should not be changed in any circumstances
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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();
Expand Down
Loading