From 8288b3d1b38f1d34bd8422755323208b083c9e2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Attila=20M=C3=A9sz=C3=A1ros?= Date: Fri, 4 Sep 2026 12:31:56 +0200 Subject: [PATCH 01/23] chore: bump version for 999-SNAPSHOT for next MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Attila Mészáros --- bootstrapper-maven-plugin/pom.xml | 2 +- caffeine-bounded-cache-support/pom.xml | 2 +- micrometer-support/pom.xml | 2 +- migration/pom.xml | 2 +- operator-framework-bom/pom.xml | 2 +- operator-framework-core/pom.xml | 4 ++-- operator-framework-junit/pom.xml | 2 +- operator-framework/pom.xml | 2 +- pom.xml | 4 ++-- sample-operators/controller-namespace-deletion/pom.xml | 2 +- sample-operators/kotlin-operator/pom.xml | 2 +- sample-operators/leader-election/pom.xml | 2 +- sample-operators/mysql-schema/pom.xml | 2 +- sample-operators/operations/pom.xml | 4 ++-- sample-operators/pom.xml | 2 +- sample-operators/tomcat-operator/pom.xml | 2 +- sample-operators/webpage/pom.xml | 2 +- test-index-processor/pom.xml | 2 +- 18 files changed, 21 insertions(+), 21 deletions(-) diff --git a/bootstrapper-maven-plugin/pom.xml b/bootstrapper-maven-plugin/pom.xml index 90407d169b..b0d36eaf70 100644 --- a/bootstrapper-maven-plugin/pom.xml +++ b/bootstrapper-maven-plugin/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk java-operator-sdk - 5.6.5-SNAPSHOT + 999-SNAPSHOT bootstrapper diff --git a/caffeine-bounded-cache-support/pom.xml b/caffeine-bounded-cache-support/pom.xml index 0ccc983162..be70ab9a2e 100644 --- a/caffeine-bounded-cache-support/pom.xml +++ b/caffeine-bounded-cache-support/pom.xml @@ -21,7 +21,7 @@ io.javaoperatorsdk java-operator-sdk - 5.6.5-SNAPSHOT + 999-SNAPSHOT caffeine-bounded-cache-support diff --git a/micrometer-support/pom.xml b/micrometer-support/pom.xml index 650a24074c..ae3c4d0be1 100644 --- a/micrometer-support/pom.xml +++ b/micrometer-support/pom.xml @@ -21,7 +21,7 @@ io.javaoperatorsdk java-operator-sdk - 5.6.5-SNAPSHOT + 999-SNAPSHOT micrometer-support diff --git a/migration/pom.xml b/migration/pom.xml index 785f489728..cf5143c925 100644 --- a/migration/pom.xml +++ b/migration/pom.xml @@ -21,7 +21,7 @@ io.javaoperatorsdk java-operator-sdk - 5.6.5-SNAPSHOT + 999-SNAPSHOT migration diff --git a/operator-framework-bom/pom.xml b/operator-framework-bom/pom.xml index 712cfa769a..7ce5b2530b 100644 --- a/operator-framework-bom/pom.xml +++ b/operator-framework-bom/pom.xml @@ -21,7 +21,7 @@ io.javaoperatorsdk operator-framework-bom - 5.6.5-SNAPSHOT + 999-SNAPSHOT pom Operator SDK - Bill of Materials Java SDK for implementing Kubernetes operators diff --git a/operator-framework-core/pom.xml b/operator-framework-core/pom.xml index 7cf71de625..ea27b31466 100644 --- a/operator-framework-core/pom.xml +++ b/operator-framework-core/pom.xml @@ -21,7 +21,7 @@ io.javaoperatorsdk java-operator-sdk - 5.6.5-SNAPSHOT + 999-SNAPSHOT ../pom.xml @@ -149,7 +149,7 @@ org.codehaus.mojo templating-maven-plugin - 3.2.0 + 3.1.1 filtering-java-templates diff --git a/operator-framework-junit/pom.xml b/operator-framework-junit/pom.xml index 9a1d4e1116..aa18d5c778 100644 --- a/operator-framework-junit/pom.xml +++ b/operator-framework-junit/pom.xml @@ -21,7 +21,7 @@ io.javaoperatorsdk java-operator-sdk - 5.6.5-SNAPSHOT + 999-SNAPSHOT operator-framework-junit diff --git a/operator-framework/pom.xml b/operator-framework/pom.xml index cac8c16242..6d314d4687 100644 --- a/operator-framework/pom.xml +++ b/operator-framework/pom.xml @@ -21,7 +21,7 @@ io.javaoperatorsdk java-operator-sdk - 5.6.5-SNAPSHOT + 999-SNAPSHOT operator-framework diff --git a/pom.xml b/pom.xml index 46d8d2ac24..2a96fc40e9 100644 --- a/pom.xml +++ b/pom.xml @@ -21,7 +21,7 @@ io.javaoperatorsdk java-operator-sdk - 5.6.5-SNAPSHOT + 999-SNAPSHOT pom Operator SDK for Java Java SDK for implementing Kubernetes operators @@ -75,7 +75,7 @@ 2.0.20 2.26.1 5.24.0 - 3.22.0 + 3.21.0 0.24.0 1.13.0 3.27.7 diff --git a/sample-operators/controller-namespace-deletion/pom.xml b/sample-operators/controller-namespace-deletion/pom.xml index d56e6fe132..af4be01972 100644 --- a/sample-operators/controller-namespace-deletion/pom.xml +++ b/sample-operators/controller-namespace-deletion/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk sample-operators - 5.6.5-SNAPSHOT + 999-SNAPSHOT sample-controller-namespace-deletion diff --git a/sample-operators/kotlin-operator/pom.xml b/sample-operators/kotlin-operator/pom.xml index b954cda79d..02e345f22c 100644 --- a/sample-operators/kotlin-operator/pom.xml +++ b/sample-operators/kotlin-operator/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk sample-operators - 5.6.5-SNAPSHOT + 999-SNAPSHOT sample-kotlin-operator diff --git a/sample-operators/leader-election/pom.xml b/sample-operators/leader-election/pom.xml index 668aec1388..4f896485d1 100644 --- a/sample-operators/leader-election/pom.xml +++ b/sample-operators/leader-election/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk sample-operators - 5.6.5-SNAPSHOT + 999-SNAPSHOT sample-leader-election diff --git a/sample-operators/mysql-schema/pom.xml b/sample-operators/mysql-schema/pom.xml index b4456b2cd2..d2872c921a 100644 --- a/sample-operators/mysql-schema/pom.xml +++ b/sample-operators/mysql-schema/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk sample-operators - 5.6.5-SNAPSHOT + 999-SNAPSHOT sample-mysql-schema-operator diff --git a/sample-operators/operations/pom.xml b/sample-operators/operations/pom.xml index a91d6e8359..d9eddd1fee 100644 --- a/sample-operators/operations/pom.xml +++ b/sample-operators/operations/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk sample-operators - 5.6.5-SNAPSHOT + 999-SNAPSHOT sample-operations @@ -85,7 +85,7 @@ org.eclipse.jetty jetty-server - 12.1.15 + 12.1.14 io.javaoperatorsdk diff --git a/sample-operators/pom.xml b/sample-operators/pom.xml index 556935eb21..704007c076 100644 --- a/sample-operators/pom.xml +++ b/sample-operators/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk java-operator-sdk - 5.6.5-SNAPSHOT + 999-SNAPSHOT sample-operators diff --git a/sample-operators/tomcat-operator/pom.xml b/sample-operators/tomcat-operator/pom.xml index c67acac824..ea964a2b07 100644 --- a/sample-operators/tomcat-operator/pom.xml +++ b/sample-operators/tomcat-operator/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk sample-operators - 5.6.5-SNAPSHOT + 999-SNAPSHOT sample-tomcat-operator diff --git a/sample-operators/webpage/pom.xml b/sample-operators/webpage/pom.xml index 21af885ac3..d50e5ef03c 100644 --- a/sample-operators/webpage/pom.xml +++ b/sample-operators/webpage/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk sample-operators - 5.6.5-SNAPSHOT + 999-SNAPSHOT sample-webpage-operator diff --git a/test-index-processor/pom.xml b/test-index-processor/pom.xml index 1c9c63acb1..2ae7c5f454 100644 --- a/test-index-processor/pom.xml +++ b/test-index-processor/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk java-operator-sdk - 5.6.5-SNAPSHOT + 999-SNAPSHOT test-index-processor From 237e30590c75848621f07e22fda5489bde92be14 Mon Sep 17 00:00:00 2001 From: Martin Stefanko Date: Mon, 7 Sep 2026 13:31:04 +0200 Subject: [PATCH 02/23] feat: add a desired state aspect (#3598) Signed-off-by: xstefank --- .../dependent-resources.md | 28 +++++ .../api/config/ConfigurationService.java | 16 +++ .../config/ConfigurationServiceOverrider.java | 42 +++++++ .../api/reconciler/DefaultContext.java | 22 +++- .../dependent/DesiredStateAspect.java | 55 ++++++++ .../BulkDependentResourceReconciler.java | 5 +- .../ConfigurationServiceOverriderTest.java | 34 +++++ .../AbstractDependentResourceTest.java | 47 ++++++- .../GenericKubernetesResourceMatcherTest.java | 18 ++- .../DesiredStateAspectCustomResource.java | 26 ++++ .../DesiredStateAspectIT.java | 117 ++++++++++++++++++ .../DesiredStateAspectReconciler.java | 59 +++++++++ 12 files changed, 465 insertions(+), 4 deletions(-) create mode 100644 operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/DesiredStateAspect.java create mode 100644 operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/desiredstateaspect/DesiredStateAspectCustomResource.java create mode 100644 operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/desiredstateaspect/DesiredStateAspectIT.java create mode 100644 operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/desiredstateaspect/DesiredStateAspectReconciler.java diff --git a/docs/content/en/docs/documentation/dependent-resource-and-workflows/dependent-resources.md b/docs/content/en/docs/documentation/dependent-resource-and-workflows/dependent-resources.md index 538c52c00c..3ac1e88e71 100644 --- a/docs/content/en/docs/documentation/dependent-resource-and-workflows/dependent-resources.md +++ b/docs/content/en/docs/documentation/dependent-resource-and-workflows/dependent-resources.md @@ -531,6 +531,34 @@ samples [here](https://github.com/java-operator-sdk/java-operator-sdk/tree/main/ in [related integration test](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/orderedmanageddependent/ConfigMapDependentResource2.java) . +### Adding Common Metadata to All Managed Resources (Desired State Aspects) + +Operators often need to mark every resource they manage in a uniform way, for example with a +`app.kubernetes.io/managed-by` label, so that these resources can easily be identified, selected or +garbage-collected later on. Instead of repeating that logic in every `desired()` implementation, a +`DesiredStateAspect` can be registered once, at the operator level, and is then applied to the +desired state of every Kubernetes dependent resource managed by the operator: + +```java +Operator operator = new Operator(overrider -> overrider + .withDesiredStateAspects(List.of( + (desired, dependentResource, context) -> desired.getMetadata().getLabels() + .put("app.kubernetes.io/managed-by", "my-operator")))); +``` + +Aspects are applied, in registration order, right after the desired state has been computed and +before the desired state is matched against the actual resource, created or updated. As a +consequence, the metadata added by an aspect is part of the desired state proper: if it is removed +from the actual resource, or if the aspect itself changes, the associated secondary resources are +updated accordingly on the next reconciliation. + +Since the desired state is computed at most once per reconciliation and cached in the `Context`, +aspects are called at most once per dependent resource and reconciliation. They are only called for +dependent resources whose desired state is a `HasMetadata`, meaning that external (non-Kubernetes) +dependent resources are left untouched. Implementations are expected to modify the provided desired +state in place and need to be thread-safe as they can be called concurrently for different primary +resources. + ## "Read-only" Dependent Resources vs. Event Source See Integration test for a read-only diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java index db1b9a5fa5..35f46e5019 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java @@ -16,6 +16,7 @@ package io.javaoperatorsdk.operator.api.config; import java.time.Duration; +import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.ExecutorService; @@ -41,6 +42,7 @@ import io.javaoperatorsdk.operator.api.reconciler.Experimental; import io.javaoperatorsdk.operator.api.reconciler.Reconciler; import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResourceFactory; +import io.javaoperatorsdk.operator.api.reconciler.dependent.DesiredStateAspect; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResource; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResourceConfig; @@ -539,4 +541,18 @@ default InformerPool informerPool() { pool.setConfigurationService(this); return pool; } + + /** + * Retrieves the {@link DesiredStateAspect}s applied to the desired state of all the Kubernetes + * dependent resources managed by the operator. Aspects are applied in the order in which they are + * returned, right after the desired state has been computed, and are typically used to add common + * metadata (such as a label identifying the operator managing the resource) to all the resources + * the operator creates or updates. + * + * @return the list of aspects to apply to computed desired states, empty by default + * @since 5.6.0 + */ + default List desiredStateAspects() { + return List.of(); + } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverrider.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverrider.java index 18a2e3fc38..2cf6540af0 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverrider.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverrider.java @@ -16,6 +16,8 @@ package io.javaoperatorsdk.operator.api.config; import java.time.Duration; +import java.util.ArrayList; +import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.ExecutorService; @@ -31,6 +33,7 @@ import io.javaoperatorsdk.operator.api.monitoring.Metrics; import io.javaoperatorsdk.operator.api.reconciler.Experimental; import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResourceFactory; +import io.javaoperatorsdk.operator.api.reconciler.dependent.DesiredStateAspect; import io.javaoperatorsdk.operator.processing.event.source.informer.pool.InformerPool; @SuppressWarnings({"unused", "UnusedReturnValue"}) @@ -59,6 +62,7 @@ public class ConfigurationServiceOverrider { private Boolean useSSAToPatchPrimaryResource; private Boolean cloneSecondaryResourcesWhenGettingFromCache; private InformerPool informerPool; + private List desiredStateAspects; @SuppressWarnings("rawtypes") private DependentResourceFactory dependentResourceFactory; @@ -229,6 +233,38 @@ public ConfigurationServiceOverrider withInformerPool(InformerPool informerPool) return this; } + /** + * Replaces the {@link DesiredStateAspect}s applied to the desired state of all the Kubernetes + * dependent resources managed by the operator by the specified ones. + * + * @param desiredStateAspects the aspects to apply, in the order in which they should be applied + * @return this {@link ConfigurationServiceOverrider} for chained customization + * @since 5.6.0 + */ + public ConfigurationServiceOverrider withDesiredStateAspects( + List desiredStateAspects) { + this.desiredStateAspects = new ArrayList<>(desiredStateAspects); + return this; + } + + /** + * Appends the specified {@link DesiredStateAspect}s to the already configured ones, which are the + * ones configured on the overridden {@link ConfigurationService} unless {@link + * #withDesiredStateAspects(List)} was called on this overrider first. + * + * @param desiredStateAspects the aspects to append, in the order in which they should be applied + * @return this {@link ConfigurationServiceOverrider} for chained customization + * @since 5.6.0 + */ + public ConfigurationServiceOverrider addDesiredStateAspects( + DesiredStateAspect... desiredStateAspects) { + if (this.desiredStateAspects == null) { + this.desiredStateAspects = new ArrayList<>(original.desiredStateAspects()); + } + this.desiredStateAspects.addAll(List.of(desiredStateAspects)); + return this; + } + public ConfigurationService build() { return new BaseConfigurationService(original.getVersion(), cloner, client) { @Override @@ -383,6 +419,12 @@ public synchronized InformerPool informerPool() { informerPool.setConfigurationService(this); return informerPool; } + + @Override + public List desiredStateAspects() { + return overriddenValueOrDefault( + desiredStateAspects, ConfigurationService::desiredStateAspects); + } }; } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/DefaultContext.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/DefaultContext.java index e399f7fdfd..50e61526c4 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/DefaultContext.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/DefaultContext.java @@ -31,6 +31,7 @@ import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; import io.javaoperatorsdk.operator.api.event.ResourceEventRecorder; import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; +import io.javaoperatorsdk.operator.api.reconciler.dependent.DesiredStateAspect; import io.javaoperatorsdk.operator.api.reconciler.dependent.managed.DefaultManagedWorkflowAndDependentResourceContext; import io.javaoperatorsdk.operator.api.reconciler.dependent.managed.ManagedWorkflowAndDependentResourceContext; import io.javaoperatorsdk.operator.processing.Controller; @@ -258,6 +259,25 @@ public R getOrComputeDesiredStateFor( DependentResource dependentResource, Function desiredStateComputer) { return (R) desiredStates.computeIfAbsent( - dependentResource, ignored -> desiredStateComputer.apply(getPrimaryResource())); + dependentResource, + ignored -> { + final var desired = desiredStateComputer.apply(getPrimaryResource()); + applyDesiredStateAspects(desired, dependentResource); + return desired; + }); + } + + /** + * Applies the globally configured {@link DesiredStateAspect}s, in configuration order, to the + * freshly computed desired state. Aspects only apply to Kubernetes resources, external dependent + * resources are therefore left untouched. + */ + private void applyDesiredStateAspects(Object desired, DependentResource dependentResource) { + if (desired instanceof HasMetadata hasMetadata) { + controllerConfiguration + .getConfigurationService() + .desiredStateAspects() + .forEach(aspect -> aspect.apply(hasMetadata, dependentResource, this)); + } } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/DesiredStateAspect.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/DesiredStateAspect.java new file mode 100644 index 0000000000..826a15cb66 --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/DesiredStateAspect.java @@ -0,0 +1,55 @@ +/* + * 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.api.reconciler.dependent; + +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.javaoperatorsdk.operator.api.config.ConfigurationService; +import io.javaoperatorsdk.operator.api.reconciler.Context; + +/** + * A cross-cutting hook applied to the desired state of every Kubernetes {@link DependentResource} + * managed by the operator, typically used to add common metadata (labels or annotations) marking + * the resources the operator manages. + * + *

Aspects are registered globally on the {@link ConfigurationService} and are applied, in + * registration order, right after the desired state has been computed and before it is matched + * against, created or updated. This means modifications performed by an aspect are taken into + * account when determining whether the actual resource matches its desired state, so that changing + * an aspect triggers an update of the associated secondary resources. + * + *

The desired state is computed at most once per reconciliation and cached in the {@link + * Context}, so aspects are also called at most once per dependent resource and reconciliation. + * Aspects are only applied to dependent resources whose desired state is a {@link HasMetadata}, + * i.e. they are not called for external (non-Kubernetes) dependent resources. + * + *

Implementations are expected to mutate the provided desired state in place and must be + * thread-safe as they can be called concurrently for different primary resources. + * + * @see ConfigurationService#desiredStateAspects() + */ +@FunctionalInterface +public interface DesiredStateAspect { + + /** + * Applies this aspect to the specified, freshly computed desired state. + * + * @param desired the desired state to modify in place + * @param dependentResource the {@link DependentResource} the desired state was computed for + * @param context the {@link Context} of the current reconciliation, from which the primary + * resource can be retrieved using {@link Context#getPrimaryResource()} + */ + void apply(HasMetadata desired, DependentResource dependentResource, Context context); +} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/BulkDependentResourceReconciler.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/BulkDependentResourceReconciler.java index 827961b77f..2428eeba96 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/BulkDependentResourceReconciler.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/BulkDependentResourceReconciler.java @@ -117,7 +117,10 @@ public R update(R actual, R desired, P primary, Context

context) { @Override public Result match(R resource, P primary, Context

context) { - return bulkDependentResource.match(resource, desired, primary, context); + // retrieve the desired state via the context so that it is processed the same way as for + // non-bulk dependents, in particular so that configured DesiredStateAspects are applied + // before matching + return bulkDependentResource.match(resource, getOrComputeDesired(context), primary, context); } @Override diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverriderTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverriderTest.java index 4356395618..aec8381135 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverriderTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverriderTest.java @@ -16,6 +16,7 @@ package io.javaoperatorsdk.operator.api.config; import java.time.Duration; +import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.Executors; @@ -33,6 +34,7 @@ import io.javaoperatorsdk.operator.api.monitoring.Metrics; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResourceFactory; +import io.javaoperatorsdk.operator.api.reconciler.dependent.DesiredStateAspect; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertNotEquals; @@ -187,4 +189,36 @@ void clusterScopedEventNamespaceDefaultsToTheDefaultNamespaceAndCanBeOverridden( .clusterScopedEventNamespace()) .isEqualTo("operator-ns"); } + + @Test + void desiredStateAspectsAreEmptyByDefaultAndCanBeOverridden() { + assertThat(config.desiredStateAspects()).isEmpty(); + + final DesiredStateAspect first = (desired, dependentResource, context) -> {}; + final DesiredStateAspect second = (desired, dependentResource, context) -> {}; + + assertThat( + new ConfigurationServiceOverrider(config) + .withDesiredStateAspects(List.of(first, second)) + .build() + .desiredStateAspects()) + .containsExactly(first, second); + } + + @Test + void desiredStateAspectsCanBeAppendedToAlreadyConfiguredOnes() { + final DesiredStateAspect first = (desired, dependentResource, context) -> {}; + final DesiredStateAspect second = (desired, dependentResource, context) -> {}; + final DesiredStateAspect third = (desired, dependentResource, context) -> {}; + + final var configWithAspect = + new ConfigurationServiceOverrider(config).withDesiredStateAspects(List.of(first)).build(); + + assertThat( + new ConfigurationServiceOverrider(configWithAspect) + .addDesiredStateAspects(second, third) + .build() + .desiredStateAspects()) + .containsExactly(first, second, third); + } } diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/AbstractDependentResourceTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/AbstractDependentResourceTest.java index 1db69a1f9e..7c36aabe66 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/AbstractDependentResourceTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/AbstractDependentResourceTest.java @@ -15,6 +15,7 @@ */ package io.javaoperatorsdk.operator.processing.dependent; +import java.util.List; import java.util.Optional; import java.util.Set; @@ -23,8 +24,12 @@ import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.api.config.ConfigurationService; +import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.DefaultContext; +import io.javaoperatorsdk.operator.api.reconciler.dependent.DesiredStateAspect; +import io.javaoperatorsdk.operator.processing.Controller; import io.javaoperatorsdk.operator.sample.simple.TestCustomResource; import static org.junit.jupiter.api.Assertions.*; @@ -37,7 +42,18 @@ class AbstractDependentResourceTest { private static final DefaultContext CONTEXT = createContext(PRIMARY); private static DefaultContext createContext(TestCustomResource primary) { - return new DefaultContext<>(mock(), mock(), primary, false, false); + return createContext(primary, List.of()); + } + + private static DefaultContext createContext( + TestCustomResource primary, List aspects) { + final ConfigurationService configurationService = mock(); + when(configurationService.desiredStateAspects()).thenReturn(aspects); + final ControllerConfiguration controllerConfiguration = mock(); + when(controllerConfiguration.getConfigurationService()).thenReturn(configurationService); + final Controller controller = mock(); + when(controller.getConfiguration()).thenReturn(controllerConfiguration); + return new DefaultContext<>(mock(), controller, primary, false, false); } @Test @@ -101,6 +117,35 @@ void checkThatDesiredIsOnlyCalledOnce() { assertEquals(1, testDependentResource.desiredCallCount); } + @Test + void appliesConfiguredDesiredStateAspectsInOrderAndOnlyOnce() { + final var testDependentResource = new DesiredCallCountCheckingDR(); + final var primary = new TestCustomResource(); + final var spec = primary.getSpec(); + spec.setConfigMapName("foo"); + spec.setKey("key"); + spec.setValue("value"); + final var context = + createContext( + primary, + List.of( + (desired, dependentResource, ctx) -> { + assertSame(testDependentResource, dependentResource); + assertSame(primary, ctx.getPrimaryResource()); + desired.getMetadata().getLabels().put("aspect", "first"); + }, + (desired, dependentResource, ctx) -> + desired.getMetadata().getLabels().put("aspect", "second"))); + + final var created = testDependentResource.reconcile(primary, context).getSingleResource(); + assertEquals("second", created.orElseThrow().getMetadata().getLabels().get("aspect")); + + // desired state is cached, aspects should therefore not be applied again + created.orElseThrow().getMetadata().getLabels().remove("aspect"); + testDependentResource.reconcile(primary, context); + assertNull(created.orElseThrow().getMetadata().getLabels().get("aspect")); + } + private ConfigMap configMap() { ConfigMap configMap = new ConfigMap(); configMap.setMetadata( diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericKubernetesResourceMatcherTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericKubernetesResourceMatcherTest.java index 529b76425e..af91ccc393 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericKubernetesResourceMatcherTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericKubernetesResourceMatcherTest.java @@ -15,6 +15,7 @@ */ package io.javaoperatorsdk.operator.processing.dependent.kubernetes; +import java.util.List; import java.util.Map; import java.util.Optional; @@ -27,12 +28,16 @@ import io.fabric8.kubernetes.client.KubernetesClient; import io.javaoperatorsdk.operator.MockKubernetesClient; import io.javaoperatorsdk.operator.ReconcilerUtilsInternal; +import io.javaoperatorsdk.operator.api.config.ConfigurationService; +import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.DefaultContext; +import io.javaoperatorsdk.operator.processing.Controller; import static io.javaoperatorsdk.operator.processing.dependent.kubernetes.GenericKubernetesResourceMatcher.match; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; @SuppressWarnings({"unchecked"}) class GenericKubernetesResourceMatcherTest { @@ -47,7 +52,18 @@ public TestContext() { } public TestContext(HasMetadata primary) { - super(mock(), mock(), primary, false, false); + super(mock(), mockController(), primary, false, false); + } + + @SuppressWarnings("rawtypes") + private static Controller mockController() { + final ConfigurationService configurationService = mock(); + when(configurationService.desiredStateAspects()).thenReturn(List.of()); + final ControllerConfiguration controllerConfiguration = mock(); + when(controllerConfiguration.getConfigurationService()).thenReturn(configurationService); + final Controller controller = mock(); + when(controller.getConfiguration()).thenReturn(controllerConfiguration); + return controller; } @Override diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/desiredstateaspect/DesiredStateAspectCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/desiredstateaspect/DesiredStateAspectCustomResource.java new file mode 100644 index 0000000000..e5be695160 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/desiredstateaspect/DesiredStateAspectCustomResource.java @@ -0,0 +1,26 @@ +/* + * 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.dependent.desiredstateaspect; + +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.Version; + +@Group("sample.javaoperatorsdk") +@Version("v1") +public class DesiredStateAspectCustomResource extends CustomResource + implements Namespaced {} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/desiredstateaspect/DesiredStateAspectIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/desiredstateaspect/DesiredStateAspectIT.java new file mode 100644 index 0000000000..ef8048b47d --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/desiredstateaspect/DesiredStateAspectIT.java @@ -0,0 +1,117 @@ +/* + * 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.dependent.desiredstateaspect; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.annotation.Sample; +import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +@Sample( + tldr = "Common metadata on all managed resources using desired state aspects", + description = + """ + Demonstrates how to register a global DesiredStateAspect on the ConfigurationService in \ + order to add common metadata, here labels identifying the operator and the dependent \ + resource the secondary resource originates from, to every Kubernetes resource managed by \ + the operator. Aspects are applied to the desired state right after it is computed, so the \ + added metadata is also taken into account when matching the actual resource against its \ + desired state. + """) +class DesiredStateAspectIT { + + public static final String TEST_RESOURCE_NAME = "test1"; + public static final String MANAGED_BY_LABEL_KEY = "app.kubernetes.io/managed-by"; + public static final String MANAGED_BY_LABEL_VALUE = "desired-state-aspect-operator"; + public static final String DEPENDENT_LABEL_KEY = "javaoperatorsdk.io/dependent"; + public static final String DEPENDENT_LABEL_VALUE = + DesiredStateAspectReconciler.ConfigMapDependentResource.class.getSimpleName().toLowerCase(); + + @RegisterExtension + LocallyRunOperatorExtension operator = + LocallyRunOperatorExtension.builder() + .withReconciler(DesiredStateAspectReconciler.class) + .withConfigurationService( + o -> + o.addDesiredStateAspects( + (desired, dependentResource, context) -> + desired + .getMetadata() + .getLabels() + .put(MANAGED_BY_LABEL_KEY, MANAGED_BY_LABEL_VALUE), + (desired, dependentResource, context) -> + desired + .getMetadata() + .getLabels() + .put( + DEPENDENT_LABEL_KEY, + dependentResource.getClass().getSimpleName().toLowerCase()))) + .build(); + + @Test + void aspectsAreAppliedToAllManagedResources() { + operator.create(testResource()); + + await() + .untilAsserted( + () -> { + var configMap = operator.get(ConfigMap.class, TEST_RESOURCE_NAME); + assertThat(configMap).isNotNull(); + assertThat(configMap.getMetadata().getLabels()) + .containsEntry(MANAGED_BY_LABEL_KEY, MANAGED_BY_LABEL_VALUE) + .containsEntry(DEPENDENT_LABEL_KEY, DEPENDENT_LABEL_VALUE); + }); + } + + @Test + void metadataAddedByAspectsIsRestoredIfRemoved() { + operator.create(testResource()); + + await() + .untilAsserted( + () -> + assertThat(operator.get(ConfigMap.class, TEST_RESOURCE_NAME)) + .isNotNull() + .extracting(cm -> cm.getMetadata().getLabels()) + .satisfies( + labels -> + assertThat(labels) + .containsEntry(MANAGED_BY_LABEL_KEY, MANAGED_BY_LABEL_VALUE))); + + var configMap = operator.get(ConfigMap.class, TEST_RESOURCE_NAME); + configMap.getMetadata().getLabels().remove(MANAGED_BY_LABEL_KEY); + operator.replace(configMap); + + await() + .untilAsserted( + () -> + assertThat( + operator.get(ConfigMap.class, TEST_RESOURCE_NAME).getMetadata().getLabels()) + .containsEntry(MANAGED_BY_LABEL_KEY, MANAGED_BY_LABEL_VALUE)); + } + + DesiredStateAspectCustomResource testResource() { + var res = new DesiredStateAspectCustomResource(); + res.setMetadata(new ObjectMetaBuilder().withName(TEST_RESOURCE_NAME).build()); + return res; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/desiredstateaspect/DesiredStateAspectReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/desiredstateaspect/DesiredStateAspectReconciler.java new file mode 100644 index 0000000000..bdb34435e3 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/desiredstateaspect/DesiredStateAspectReconciler.java @@ -0,0 +1,59 @@ +/* + * 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.dependent.desiredstateaspect; + +import java.util.Map; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +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; +import io.javaoperatorsdk.operator.api.reconciler.Workflow; +import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; + +@Workflow( + dependents = @Dependent(type = DesiredStateAspectReconciler.ConfigMapDependentResource.class)) +@ControllerConfiguration +public class DesiredStateAspectReconciler implements Reconciler { + + @Override + public UpdateControl reconcile( + DesiredStateAspectCustomResource resource, + Context context) { + return UpdateControl.noUpdate(); + } + + public static class ConfigMapDependentResource + extends CRUDKubernetesDependentResource { + + @Override + protected ConfigMap desired( + DesiredStateAspectCustomResource primary, + Context context) { + ConfigMap configMap = new ConfigMap(); + configMap.setMetadata( + new ObjectMetaBuilder() + .withName(primary.getMetadata().getName()) + .withNamespace(primary.getMetadata().getNamespace()) + .build()); + configMap.setData(Map.of("data", primary.getMetadata().getName())); + return configMap; + } + } +} From 32a7c6beb8f705376065bb73f09fb91bdc9ec9c6 Mon Sep 17 00:00:00 2001 From: Antonio <122279781+afalhambra-hivemq@users.noreply.github.com> Date: Wed, 9 Sep 2026 13:59:45 +0200 Subject: [PATCH 03/23] feat: configurable aggregation, owner references and naming for the event recorder (#3604) Signed-off-by: Antonio Fernandez Alhambra --- .../api/event/DefaultEventRecorder.java | 155 +++++++++- .../operator/api/event/EventKeyStrategy.java | 55 ++++ .../api/event/EventNamingStrategy.java | 51 ++++ .../operator/api/event/EventRecord.java | 41 +++ .../api/event/DefaultEventRecorderTest.java | 271 +++++++++++++++++- ...ConfiguredEventRecorderCustomResource.java | 30 ++ .../ConfiguredEventRecorderIT.java | 168 +++++++++++ .../ConfiguredEventRecorderReconciler.java | 49 ++++ 8 files changed, 808 insertions(+), 12 deletions(-) create mode 100644 operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventKeyStrategy.java create mode 100644 operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventNamingStrategy.java create mode 100644 operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorderconfigured/ConfiguredEventRecorderCustomResource.java create mode 100644 operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorderconfigured/ConfiguredEventRecorderIT.java create mode 100644 operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorderconfigured/ConfiguredEventRecorderReconciler.java diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorder.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorder.java index 2e7023623d..67764b7146 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorder.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorder.java @@ -24,6 +24,7 @@ import java.time.temporal.ChronoUnit; import java.util.HexFormat; import java.util.Objects; +import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -48,10 +49,11 @@ * can be overridden, see {@link * io.javaoperatorsdk.operator.api.config.ConfigurationService#clusterScopedEventNamespace()}. * - *

Events are named deterministically, after the object they are about plus a hash of everything - * that identifies the event, so that recording the same event again resolves to the event already - * recorded for it. Repeat occurrences are then counted on that event rather than recorded as copies - * of it, see {@link DefaultEventSink}. + *

By default, events are named deterministically, after the object they are about plus a hash of + * everything that identifies the event, so that recording the same event again resolves to the + * event already recorded for it. Repeat occurrences are then counted on that event rather than + * recorded as copies of it, see {@link DefaultEventSink}. How events aggregate, how they are named + * and whether they carry an owner reference can be configured, see {@link #builder(EventSink)}. */ public class DefaultEventRecorder implements EventRecorder { @@ -73,10 +75,79 @@ public class DefaultEventRecorder implements EventRecorder { private static final int IDENTITY_HASH_LENGTH = 32; + /** What the API server accepts as an object name, see RFC 1123 on DNS subdomains. */ + private static final Pattern RFC_1123_SUBDOMAIN = + Pattern.compile("[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*"); + private final EventSink sink; + private final EventNamingStrategy namingStrategy; + private final EventKeyStrategy keyStrategy; + private final boolean ownerReference; public DefaultEventRecorder(EventSink sink) { + this(sink, EventNamingStrategy.none(), EventKeyStrategy.none(), false); + } + + private DefaultEventRecorder( + EventSink sink, + EventNamingStrategy namingStrategy, + EventKeyStrategy keyStrategy, + boolean ownerReference) { this.sink = sink; + this.namingStrategy = namingStrategy; + this.keyStrategy = keyStrategy; + this.ownerReference = ownerReference; + } + + public static Builder builder(EventSink sink) { + return new Builder(sink); + } + + /** Builder for {@link DefaultEventRecorder}. */ + public static final class Builder { + + private final EventSink sink; + private EventNamingStrategy namingStrategy = EventNamingStrategy.none(); + private EventKeyStrategy keyStrategy = EventKeyStrategy.none(); + private boolean ownerReference = false; + + private Builder(EventSink sink) { + this.sink = Objects.requireNonNull(sink, "sink must not be null"); + } + + /** The strategy naming recorded events, see {@link EventNamingStrategy}. */ + public Builder namingStrategy(EventNamingStrategy namingStrategy) { + this.namingStrategy = + Objects.requireNonNull(namingStrategy, "namingStrategy must not be null"); + return this; + } + + /** + * The strategy deriving the default aggregation key of records that do not set one, see {@link + * EventKeyStrategy}. The key is ignored for events whose name is set by the record or resolved + * by the naming strategy, see {@link EventNamingStrategy}. + */ + public Builder keyStrategy(EventKeyStrategy keyStrategy) { + this.keyStrategy = Objects.requireNonNull(keyStrategy, "keyStrategy must not be null"); + return this; + } + + /** + * When set, recorded events carry an {@code ownerReference} to the object they are about. The + * reference expresses ownership for tooling that reads it; note that the Kubernetes garbage + * collector ignores events, so it does not cause cascade deletion, events expire through the + * event TTL either way. Records can override this per event via {@link + * EventRecord.Builder#ownedByRegarding(boolean)}. The reference is only set when the object + * already has a uid. + */ + public Builder ownerReference(boolean ownerReference) { + this.ownerReference = ownerReference; + return this; + } + + public DefaultEventRecorder build() { + return new DefaultEventRecorder(sink, namingStrategy, keyStrategy, ownerReference); + } } /** @@ -111,14 +182,17 @@ private static String resolve() { public void record(EventRecord event, Context context) { Objects.requireNonNull(context, "the context of the reconciliation must not be null"); Objects.requireNonNull(event, "event must not be null"); + Event assembled = null; try { - sink.emit(toEvent(context, event), context); + assembled = toEvent(context, event); + sink.emit(assembled, context); } catch (Exception e) { // recording an event must never break the caller: a controller that fails to reconcile // because it could not write an event is strictly worse than one that records nothing log.warn( - "Could not record {} event with reason {} for resource {} in namespace {}", + "Could not record {} event named {} with reason {} for resource {} in namespace {}", event.type(), + assembled != null ? assembled.getMetadata().getName() : "unknown", event.reason(), context.getPrimaryResource().getMetadata().getName(), context.getPrimaryResource().getMetadata().getNamespace(), @@ -164,6 +238,23 @@ protected Event toEvent(Context context, EventRecord record) { .withNewSource() .withComponent(record.reportingComponent().orElse(controllerName)) .endSource(); + boolean ownedByRegarding = record.ownedByRegarding().orElse(ownerReference); + if (ownedByRegarding && regarding.getMetadata().getUid() == null) { + log.debug( + "Not setting the owner reference on the event about {}: the object has no uid yet", + regarding.getMetadata().getName()); + } + if (ownedByRegarding && regarding.getMetadata().getUid() != null) { + builder + .editMetadata() + .addNewOwnerReference() + .withApiVersion(regarding.getApiVersion()) + .withKind(regarding.getKind()) + .withName(regarding.getMetadata().getName()) + .withUid(regarding.getMetadata().getUid()) + .endOwnerReference() + .endMetadata(); + } record.action().ifPresent(builder::withAction); return builder.build(); } @@ -181,17 +272,56 @@ private String eventNamespace(HasMetadata regarding, Context context) { CLUSTER_SCOPED_EVENT_NAMESPACE); } + private String eventName(HasMetadata regarding, EventRecord record, String reportingController) { + return record + .name() + .filter(name -> !name.isBlank()) + .or(() -> namingStrategy.nameFor(regarding, record).filter(name -> !name.isBlank())) + .map(DefaultEventRecorder::truncateToMaxNameLength) + .filter(DefaultEventRecorder::isValidEventName) + .orElseGet(() -> identityHashName(regarding, record, reportingController)); + } + + private static boolean isValidEventName(String name) { + if (RFC_1123_SUBDOMAIN.matcher(name).matches()) { + return true; + } + log.warn( + "Falling back to the default event name: {} is not a valid RFC 1123 DNS subdomain", name); + return false; + } + + private static String truncateToMaxNameLength(String name) { + if (name.length() <= MAX_NAME_LENGTH) { + return name; + } + var truncated = name.substring(0, MAX_NAME_LENGTH); + while (truncated.endsWith("-") || truncated.endsWith(".")) { + truncated = truncated.substring(0, truncated.length() - 1); + } + log.warn( + "Truncated the name of event {} to {} to stay within the Kubernetes name limit", + name, + truncated); + return truncated; + } + /** * Names events {@code .}, following the convention of the Go client, hashing * everything that makes two events the same event: the object, the type, the reason, the - * reporting component and, unless the record sets a {@link EventRecord#key()}, the message. The - * name is therefore stable across occurrences, which is what lets the sink recognise a repeat, - * and stays so across operator restarts and between replicas, unlike a name remembered in memory. + * reporting component and, unless the record sets a {@link EventRecord#key()} or the recorder is + * built with a default {@link EventKeyStrategy}, the message. The name is therefore stable across + * occurrences, which is what lets the sink recognise a repeat, and stays so across operator + * restarts and between replicas, unlike a name remembered in memory. * *

The object is identified by its uid, with the kind as a fallback for objects that do not * have one yet, such as a dependent resource that has only been built so far. + * + *

This is the fallback when the record does not set a name and the naming strategy resolves to + * nothing, see {@link EventNamingStrategy}. */ - private String eventName(HasMetadata regarding, EventRecord record, String reportingController) { + private String identityHashName( + HasMetadata regarding, EventRecord record, String reportingController) { var metadata = regarding.getMetadata(); var identity = String.join( @@ -201,7 +331,10 @@ private String eventName(HasMetadata regarding, EventRecord record, String repor record.type().value(), record.reason(), record.reportingComponent().orElse(reportingController), - record.key().orElseGet(() -> requireNonNullElse(record.message(), ""))); + record + .key() + .or(() -> keyStrategy.keyFor(regarding, record)) + .orElseGet(() -> requireNonNullElse(record.message(), ""))); var suffix = "." + identityDigest(identity); var prefix = metadata.getName(); diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventKeyStrategy.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventKeyStrategy.java new file mode 100644 index 0000000000..632ff6ea6a --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventKeyStrategy.java @@ -0,0 +1,55 @@ +/* + * 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.api.event; + +import java.util.Optional; + +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.javaoperatorsdk.operator.api.reconciler.Experimental; + +import static io.javaoperatorsdk.operator.api.reconciler.Experimental.API_MIGHT_CHANGE; + +/** + * Derives the default aggregation key of an event, used when the {@link EventRecord} does not set + * one explicitly. The key identifies an event among the events about the same object, so that + * repeated occurrences resolve to the same event rather than to one event each, see {@link + * EventRecord#key()}. + * + *

An empty result leaves the record without a default key, which keeps the message part of the + * event identity. + * + *

Implementations are called from concurrent reconciliations and must be thread safe. + */ +@Experimental(API_MIGHT_CHANGE) +@FunctionalInterface +public interface EventKeyStrategy { + + Optional keyFor(HasMetadata regarding, EventRecord record); + + /** No default key: the message stays part of the event identity. */ + static EventKeyStrategy none() { + return (regarding, record) -> Optional.empty(); + } + + /** + * Aggregates by event type and reason: all occurrences of a reason resolve to one event whose + * count grows and whose message is replaced with the latest one. The right choice for events that + * report a current state rather than individual occurrences. + */ + static EventKeyStrategy byReason() { + return (regarding, record) -> Optional.of(record.type().value() + "/" + record.reason()); + } +} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventNamingStrategy.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventNamingStrategy.java new file mode 100644 index 0000000000..80f6f33e82 --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventNamingStrategy.java @@ -0,0 +1,51 @@ +/* + * 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.api.event; + +import java.util.Optional; + +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.javaoperatorsdk.operator.api.reconciler.Experimental; + +import static io.javaoperatorsdk.operator.api.reconciler.Experimental.API_MIGHT_CHANGE; + +/** + * Names the event recorded about an object. The name is what the sink looks a recorded event up by, + * so it is also the aggregation identity: two records resolving to the same name are counted as + * occurrences of one event. A name must therefore be unique among the events it should not + * aggregate with, and stable across operator restarts and replicas. + * + *

A name must be a valid RFC 1123 DNS subdomain: at most 253 lowercase alphanumeric characters, + * {@code -} or {@code .}, starting and ending with an alphanumeric character. Names longer than the + * limit are truncated. A name derived from the object and a fixed lowercase suffix (such as {@code + * -status-report}) satisfies all of this by construction. + * + *

An empty result or an invalid name falls back to the default {@code .} + * name, rather than the event being lost to the API server rejecting the name. + * + *

Implementations are called from concurrent reconciliations and must be thread safe. + */ +@Experimental(API_MIGHT_CHANGE) +@FunctionalInterface +public interface EventNamingStrategy { + + Optional nameFor(HasMetadata regarding, EventRecord record); + + /** No custom naming: every event gets the default {@code .} name. */ + static EventNamingStrategy none() { + return (regarding, record) -> Optional.empty(); + } +} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventRecord.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventRecord.java index e7b736abc0..6d98b7f1fe 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventRecord.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventRecord.java @@ -32,7 +32,9 @@ public final class EventRecord { private final EventType type; private final String reason; private final String message; + private final String name; private final String key; + private final Boolean ownedByRegarding; private final String action; private final String reportingComponent; private final Map labels; @@ -42,11 +44,13 @@ private EventRecord(Builder builder) { this.type = builder.type; this.reason = builder.reason; this.message = builder.message; + this.name = builder.name; this.key = builder.key; this.action = builder.action; this.reportingComponent = builder.reportingComponent; this.labels = Map.copyOf(builder.labels); this.annotations = Map.copyOf(builder.annotations); + this.ownedByRegarding = builder.ownedByRegarding; } public static Builder builder() { @@ -75,14 +79,34 @@ public String message() { return message; } + /** + * The name of the recorded event, overriding the recorder's naming. The name is the aggregation + * identity and must be a valid RFC 1123 DNS subdomain, see {@link EventNamingStrategy}; an + * invalid name falls back to the default name. A blank name is treated as unset. + */ + public Optional name() { + return Optional.ofNullable(name); + } + /** * Identifies this event among the events about the same object, so that repeated occurrences * resolve to the same event rather than to one event each. + * + *

The key is ignored when the record sets a {@link #name()} or the recorder's naming strategy + * resolves one: the name is then the aggregation identity on its own. */ public Optional key() { return Optional.ofNullable(key); } + /** + * Whether the recorded event carries an {@code ownerReference} to the object it is about. When + * empty, the recorder's own setting applies. + */ + public Optional ownedByRegarding() { + return Optional.ofNullable(ownedByRegarding); + } + /** * The action taken or failed regarding the involved object, if any. Optional, and only meaningful * for consumers that read the {@code action} field of the event. @@ -119,7 +143,9 @@ public static final class Builder { private EventType type = EventType.NORMAL; private String reason; private String message; + private String name; private String key; + private Boolean ownedByRegarding; private String action; private String reportingComponent; private final Map labels = new HashMap<>(); @@ -142,12 +168,27 @@ public Builder message(String message) { return this; } + /** Sets the name of the recorded event, see {@link EventRecord#name()}. */ + public Builder name(String name) { + this.name = name; + return this; + } + /** Sets the key identifying this event, see {@link EventRecord#key()}. */ public Builder key(String key) { this.key = key; return this; } + /** + * Sets whether this event is owned by the object it is about, see {@link + * EventRecord#ownedByRegarding()}. + */ + public Builder ownedByRegarding(boolean ownedByRegarding) { + this.ownedByRegarding = ownedByRegarding; + return this; + } + public Builder action(String action) { this.action = action; return this; diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorderTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorderTest.java index eb713e5d74..388217b9be 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorderTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorderTest.java @@ -226,6 +226,14 @@ void reasonIsRequired() { .isThrownBy(() -> EventRecord.builder().message("no reason given").build()); } + @Test + void alwaysDerivesTheSameDefaultNameForTheSameEvent() { + recorder.record(EventRecord.normal("Created", "created"), context(configMap())); + + assertThat(emitted.get(0).getMetadata().getName()) + .isEqualTo("test1.3c699548f37ff9cd6d2a786f64a27228"); + } + @Test void namesEventsWithADnsSafeHashSuffix() { recorder.record(EventRecord.normal("Created", "created"), context(configMap())); @@ -249,6 +257,267 @@ void givesEventsWhoseMessagesCollideUnderStringHashCodeDistinctNames() { .isNotEqualTo(emitted.get(1).getMetadata().getName()); } + @Test + void takesTheMessageOutOfTheEventIdentityWithADefaultKeyStrategy() { + var recorder = + DefaultEventRecorder.builder((event, context) -> emitted.add(event)) + .keyStrategy(EventKeyStrategy.byReason()) + .build(); + var context = context(configMap()); + + recorder.record(EventRecord.warning("Failed", "first message"), context); + recorder.record(EventRecord.warning("Failed", "second message"), context); + + assertThat(emitted.get(0).getMetadata().getName()) + .isEqualTo(emitted.get(1).getMetadata().getName()); + } + + @Test + void prefersThePerRecordKeyOverTheDefaultKeyStrategy() { + var recorder = + DefaultEventRecorder.builder((event, context) -> emitted.add(event)) + .keyStrategy(EventKeyStrategy.byReason()) + .build(); + var context = context(configMap()); + + recorder.record(EventRecord.warning("Failed", "message"), context); + recorder.record( + EventRecord.builder() + .type(EventType.WARNING) + .reason("Failed") + .message("message") + .key("another aggregate") + .build(), + context); + + assertThat(emitted.get(0).getMetadata().getName()) + .isNotEqualTo(emitted.get(1).getMetadata().getName()); + } + + @Test + void keepsTheMessageInTheEventIdentityWithoutADefaultKeyStrategy() { + var context = context(configMap()); + + recorder.record(EventRecord.warning("Failed", "first message"), context); + recorder.record(EventRecord.warning("Failed", "second message"), context); + + assertThat(emitted.get(0).getMetadata().getName()) + .isNotEqualTo(emitted.get(1).getMetadata().getName()); + } + + @Test + void keepsEventsWithTheSameReasonButDifferentTypesApartUnderByReason() { + var recorder = + DefaultEventRecorder.builder((event, context) -> emitted.add(event)) + .keyStrategy(EventKeyStrategy.byReason()) + .build(); + var context = context(configMap()); + + recorder.record(EventRecord.normal("Flipped", "message"), context); + recorder.record(EventRecord.warning("Flipped", "message"), context); + + assertThat(emitted.get(0).getMetadata().getName()) + .isNotEqualTo(emitted.get(1).getMetadata().getName()); + } + + @Test + void setsTheOwnerReferenceToTheInvolvedObjectWhenOwningEventsByRegarding() { + var recorder = + DefaultEventRecorder.builder((event, context) -> emitted.add(event)) + .ownerReference(true) + .build(); + + recorder.record(EventRecord.normal("Created", "created"), context(configMap())); + + assertThat(emitted.get(0).getMetadata().getOwnerReferences()) + .singleElement() + .satisfies( + owner -> { + assertThat(owner.getApiVersion()).isEqualTo("v1"); + assertThat(owner.getKind()).isEqualTo("ConfigMap"); + assertThat(owner.getName()).isEqualTo("test1"); + assertThat(owner.getUid()).isEqualTo("uid-1"); + }); + } + + @Test + void carriesNoOwnerReferenceByDefault() { + recorder.record(EventRecord.normal("Created", "created"), context(configMap())); + + assertThat(emitted.get(0).getMetadata().getOwnerReferences()).isEmpty(); + } + + @Test + void letsARecordOptOutOfTheRecorderLevelOwnerReference() { + var recorder = + DefaultEventRecorder.builder((event, context) -> emitted.add(event)) + .ownerReference(true) + .build(); + + recorder.record( + EventRecord.builder().reason("Created").message("created").ownedByRegarding(false).build(), + context(configMap())); + + assertThat(emitted.get(0).getMetadata().getOwnerReferences()).isEmpty(); + } + + @Test + void letsARecordOptIntoTheOwnerReferenceOnItsOwn() { + recorder.record( + EventRecord.builder().reason("Created").message("created").ownedByRegarding(true).build(), + context(configMap())); + + assertThat(emitted.get(0).getMetadata().getOwnerReferences()).hasSize(1); + } + + @Test + void setsNoOwnerReferenceWhenTheRegardingObjectHasNoUidYet() { + var withoutUid = configMap(); + withoutUid.getMetadata().setUid(null); + + recorder.record( + EventRecord.builder().reason("Created").message("created").ownedByRegarding(true).build(), + context(withoutUid)); + + assertThat(emitted.get(0).getMetadata().getOwnerReferences()).isEmpty(); + } + + @Test + void namesTheEventAfterThePerRecordNameWhenOneIsSet() { + recorder.record( + EventRecord.builder().reason("Created").message("created").name("my-event-name").build(), + context(configMap())); + + assertThat(emitted.get(0).getMetadata().getName()).isEqualTo("my-event-name"); + } + + @Test + void namesEventsThroughTheNamingStrategy() { + var recorder = + DefaultEventRecorder.builder((event, context) -> emitted.add(event)) + .namingStrategy( + (regarding, record) -> + Optional.of(regarding.getMetadata().getName() + "-" + record.reason())) + .build(); + + recorder.record(EventRecord.warning("failed", "first"), context(configMap())); + recorder.record(EventRecord.warning("failed", "second"), context(configMap())); + + assertThat(emitted) + .allSatisfy(event -> assertThat(event.getMetadata().getName()).isEqualTo("test1-failed")); + } + + @Test + void fallsBackToTheIdentityHashNameWhenTheNamingStrategyResolvesNothing() { + var recorder = + DefaultEventRecorder.builder((event, context) -> emitted.add(event)) + .namingStrategy((regarding, record) -> Optional.empty()) + .build(); + + recorder.record(EventRecord.warning("Failed", "message"), context(configMap())); + + assertThat(emitted.get(0).getMetadata().getName()) + .startsWith("test1.") + .hasSize("test1.".length() + 32); + } + + @Test + void truncatesSuppliedNamesToTheKubernetesNameLengthLimit() { + recorder.record( + EventRecord.builder().reason("Created").message("created").name("a".repeat(300)).build(), + context(configMap())); + + assertThat(emitted.get(0).getMetadata().getName()).hasSize(253); + } + + @Test + void stripsTrailingSeparatorsFromTruncatedNames() { + recorder.record( + EventRecord.builder() + .reason("Created") + .message("created") + .name("a".repeat(252) + "." + "b".repeat(47)) + .build(), + context(configMap())); + recorder.record( + EventRecord.builder() + .reason("Created") + .message("created") + .name("b".repeat(252) + "-" + "c".repeat(47)) + .build(), + context(configMap())); + + assertThat(emitted.get(0).getMetadata().getName()).isEqualTo("a".repeat(252)); + assertThat(emitted.get(1).getMetadata().getName()).isEqualTo("b".repeat(252)); + } + + @Test + void treatsABlankNameAsUnset() { + var recorder = + DefaultEventRecorder.builder((event, context) -> emitted.add(event)) + .namingStrategy((regarding, record) -> Optional.of("strategy-name")) + .build(); + + recorder.record( + EventRecord.builder().reason("Created").message("created").name("").build(), + context(configMap())); + + assertThat(emitted.get(0).getMetadata().getName()).isEqualTo("strategy-name"); + } + + @Test + void fallsBackToTheIdentityHashNameWhenEveryNameIsBlank() { + var recorder = + DefaultEventRecorder.builder((event, context) -> emitted.add(event)) + .namingStrategy((regarding, record) -> Optional.of(" ")) + .build(); + + recorder.record( + EventRecord.builder().reason("Created").message("created").name("").build(), + context(configMap())); + + assertThat(emitted.get(0).getMetadata().getName()).matches("test1\\.[0-9a-f]{32}"); + } + + @Test + void fallsBackToTheIdentityHashNameWhenTruncationLeavesNothing() { + recorder.record( + EventRecord.builder().reason("Created").message("created").name(".".repeat(300)).build(), + context(configMap())); + + assertThat(emitted.get(0).getMetadata().getName()).matches("test1\\.[0-9a-f]{32}"); + } + + @Test + void fallsBackToTheIdentityHashNameWhenTheSuppliedNameIsInvalid() { + recorder.record( + EventRecord.builder().reason("Created").message("created").name("Status").build(), + context(configMap())); + recorder.record( + EventRecord.builder().reason("Created").message("created").name("status_name").build(), + context(configMap())); + + assertThat(emitted) + .allSatisfy( + event -> assertThat(event.getMetadata().getName()).matches("test1\\.[0-9a-f]{32}")); + } + + @Test + void aFailingNamingStrategyNeverFailsTheCaller() { + var recorder = + DefaultEventRecorder.builder((event, context) -> emitted.add(event)) + .namingStrategy( + (regarding, record) -> { + throw new RuntimeException("cannot derive a name"); + }) + .build(); + + assertThatCode( + () -> recorder.record(EventRecord.normal("Created", "created"), context(configMap()))) + .doesNotThrowAnyException(); + assertThat(emitted).isEmpty(); + } + Context context(HasMetadata primaryResource) { return context(primaryResource, DefaultEventRecorder.CLUSTER_SCOPED_EVENT_NAMESPACE); } @@ -259,7 +528,7 @@ Context context(HasMetadata primaryResource) { * the configuration service the reporting instance and the cluster scoped event namespace come * from. */ - @SuppressWarnings({"unchecked", "rawtypes"}) + @SuppressWarnings("rawtypes") Context context(HasMetadata primaryResource, String clusterScopedEventNamespace) { var configurationService = mock(ConfigurationService.class); when(configurationService.getLeaderElectionConfiguration()) diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorderconfigured/ConfiguredEventRecorderCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorderconfigured/ConfiguredEventRecorderCustomResource.java new file mode 100644 index 0000000000..0e0e3cab5d --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorderconfigured/ConfiguredEventRecorderCustomResource.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.eventrecorderconfigured; + +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.Kind; +import io.fabric8.kubernetes.model.annotation.ShortNames; +import io.fabric8.kubernetes.model.annotation.Version; + +@Group("sample.javaoperatorsdk") +@Version("v1") +@Kind("ConfiguredEventRecorderCustomResource") +@ShortNames("cerc") +public class ConfiguredEventRecorderCustomResource extends CustomResource + implements Namespaced {} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorderconfigured/ConfiguredEventRecorderIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorderconfigured/ConfiguredEventRecorderIT.java new file mode 100644 index 0000000000..537aa38f8d --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorderconfigured/ConfiguredEventRecorderIT.java @@ -0,0 +1,168 @@ +/* + * 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.eventrecorderconfigured; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import io.fabric8.kubernetes.api.model.Event; +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.fabric8.kubernetes.api.model.OwnerReference; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.KubernetesClientBuilder; +import io.javaoperatorsdk.annotation.Sample; +import io.javaoperatorsdk.operator.api.event.DefaultEventRecorder; +import io.javaoperatorsdk.operator.api.event.DefaultEventSink; +import io.javaoperatorsdk.operator.api.event.EventKeyStrategy; +import io.javaoperatorsdk.operator.api.event.EventRecord; +import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; + +import static io.javaoperatorsdk.operator.baseapi.eventrecorderconfigured.ConfiguredEventRecorderReconciler.AGGREGATED_REASON; +import static io.javaoperatorsdk.operator.baseapi.eventrecorderconfigured.ConfiguredEventRecorderReconciler.NAMED_REASON; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +@Sample( + tldr = "Configuring how the event recorder aggregates, names and owns events", + description = + """ + Demonstrates configuring the event recorder with a default aggregation key strategy, a \ + naming strategy and owner references. Aggregating by reason resolves repeated occurrences \ + with changing messages to one event whose count grows and whose message is replaced with \ + the latest one. A naming strategy gives events predictable names instead of the default \ + identity hash. Owner references relate the events to the object they are about. + """) +class ConfiguredEventRecorderIT { + + private static final String TEST_RESOURCE_NAME = "test1"; + + private final KubernetesClient sinkClient = new KubernetesClientBuilder().build(); + + private final ConfiguredEventRecorderReconciler reconciler = + new ConfiguredEventRecorderReconciler(); + + @RegisterExtension + LocallyRunOperatorExtension extension = + LocallyRunOperatorExtension.builder() + .withReconciler(reconciler) + .withConfigurationService(o -> o.withEventRecorder(configuredEventRecorder())) + .build(); + + @AfterEach + void closeSinkClient() { + sinkClient.close(); + } + + @Test + void aggregatesOccurrencesWithChangingMessagesOntoOneEvent() { + var resource = extension.create(testResource()); + await().untilAsserted(() -> assertThat(reconciler.getNumberOfExecutions()).isPositive()); + + // reconcile once more: aggregating by reason resolves the new messages to the same events + resource.getMetadata().setAnnotations(Map.of("reconcile", "again")); + extension.replace(resource); + + await() + .untilAsserted( + () -> { + assertThat(reconciler.getNumberOfExecutions()).isGreaterThanOrEqualTo(2); + + assertThat(eventsWithReason(AGGREGATED_REASON)) + .singleElement() + .satisfies( + event -> { + assertThat(event.getCount()).isGreaterThanOrEqualTo(2); + assertThat(event.getMessage()) + .isEqualTo("something changed in execution " + event.getCount()); + }); + }); + } + + @Test + void namesEventsThroughTheConfiguredNamingStrategy() { + extension.create(testResource()); + + await() + .untilAsserted( + () -> + assertThat(eventsWithReason(NAMED_REASON)) + .singleElement() + .extracting(event -> event.getMetadata().getName()) + .isEqualTo(TEST_RESOURCE_NAME + "-status-report")); + } + + @Test + void setsOwnerReferencesOnTheEventsItRecords() { + var resource = extension.create(testResource()); + + await() + .untilAsserted( + () -> { + var events = eventsForTestResource(); + assertThat(events).isNotEmpty(); + assertThat(events) + .allSatisfy( + event -> + assertThat(event.getMetadata().getOwnerReferences()) + .singleElement() + .returns( + "ConfiguredEventRecorderCustomResource", OwnerReference::getKind) + .returns(resource.getMetadata().getUid(), OwnerReference::getUid)); + }); + } + + private List eventsWithReason(String reason) { + return eventsForTestResource().stream().filter(e -> reason.equals(e.getReason())).toList(); + } + + @SuppressWarnings("resource") + private List eventsForTestResource() { + return extension + .getKubernetesClient() + .v1() + .events() + .inNamespace(extension.getNamespace()) + .withField("involvedObject.name", TEST_RESOURCE_NAME) + .list() + .getItems(); + } + + private ConfiguredEventRecorderCustomResource testResource() { + var resource = new ConfiguredEventRecorderCustomResource(); + resource.setMetadata(new ObjectMetaBuilder().withName(TEST_RESOURCE_NAME).build()); + return resource; + } + + private DefaultEventRecorder configuredEventRecorder() { + return DefaultEventRecorder.builder(new DefaultEventSink(sinkClient)) + .namingStrategy(ConfiguredEventRecorderIT::statusReportName) + .keyStrategy(EventKeyStrategy.byReason()) + .ownerReference(true) + .build(); + } + + private static Optional statusReportName(HasMetadata regarding, EventRecord record) { + return NAMED_REASON.equals(record.reason()) + ? Optional.of(regarding.getMetadata().getName() + "-status-report") + : Optional.empty(); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorderconfigured/ConfiguredEventRecorderReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorderconfigured/ConfiguredEventRecorderReconciler.java new file mode 100644 index 0000000000..af4d136a4d --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorderconfigured/ConfiguredEventRecorderReconciler.java @@ -0,0 +1,49 @@ +/* + * 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.eventrecorderconfigured; + +import java.util.concurrent.atomic.AtomicInteger; + +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(generationAwareEventProcessing = false) +public class ConfiguredEventRecorderReconciler + implements Reconciler { + + public static final String NAMED_REASON = "StatusReport"; + public static final String AGGREGATED_REASON = "SomethingChanged"; + + private final AtomicInteger numberOfExecutions = new AtomicInteger(); + + @Override + public UpdateControl reconcile( + ConfiguredEventRecorderCustomResource resource, + Context context) { + var execution = numberOfExecutions.incrementAndGet(); + context.eventRecorder().warn(NAMED_REASON, "status after execution " + execution); + context + .eventRecorder() + .normal(AGGREGATED_REASON, "something changed in execution " + execution); + return UpdateControl.noUpdate(); + } + + public int getNumberOfExecutions() { + return numberOfExecutions.get(); + } +} From 94b0170d2ac23966af0ff4dbe496845b2939da76 Mon Sep 17 00:00:00 2001 From: Antonio <122279781+afalhambra-hivemq@users.noreply.github.com> Date: Fri, 18 Sep 2026 08:04:27 +0200 Subject: [PATCH 04/23] fix: keep comparableResourceVersions when copying a dependent resource's informer configuration (#3625) Signed-off-by: Antonio Fernandez Alhambra --- .../InformerEventSourceConfiguration.java | 1 + .../InformerEventSourceConfigurationTest.java | 42 +++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/InformerEventSourceConfigurationTest.java diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/InformerEventSourceConfiguration.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/InformerEventSourceConfiguration.java index 9bd6f84d06..a4ca2f63d4 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/InformerEventSourceConfiguration.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/InformerEventSourceConfiguration.java @@ -316,6 +316,7 @@ public void updateFrom(InformerConfiguration informerConfig) { .withOnDeleteFilter(informerConfig.getOnDeleteFilter()) .withGenericFilter(informerConfig.getGenericFilter()) .withInformerListLimit(informerConfig.getInformerListLimit()) + .withComparableResourceVersions(informerConfig.isComparableResourceVersions()) .withFieldSelector(informerConfig.getFieldSelector()); } } diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/InformerEventSourceConfigurationTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/InformerEventSourceConfigurationTest.java new file mode 100644 index 0000000000..9e43b288cc --- /dev/null +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/InformerEventSourceConfigurationTest.java @@ -0,0 +1,42 @@ +/* + * 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.api.config; + +import org.junit.jupiter.api.Test; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.Secret; +import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; + +import static org.junit.jupiter.api.Assertions.assertFalse; + +class InformerEventSourceConfigurationTest { + + @Test + void updateFromKeepsComparableResourceVersions() { + // the only caller is KubernetesDependentResource#createEventSource, so dropping it here means + // the setting silently has no effect on a dependent resource + var builder = InformerEventSourceConfiguration.from(ConfigMap.class, Secret.class); + + builder.updateFrom( + InformerConfiguration.builder(ConfigMap.class) + .withComparableResourceVersions(false) + .build()); + + assertFalse(builder.build().getInformerConfig().isComparableResourceVersions()); + } +} From 41e1a8ea8a53fea24da69bed6603bf21db49cecf Mon Sep 17 00:00:00 2001 From: Antonio <122279781+afalhambra-hivemq@users.noreply.github.com> Date: Fri, 18 Sep 2026 14:04:37 +0200 Subject: [PATCH 05/23] fix: rename version.properties to a unique name to avoid resource collisions (#3628) Signed-off-by: Antonio Fernandez Alhambra --- operator-framework-core/pom.xml | 2 +- .../io/javaoperatorsdk/operator/api/config/Utils.java | 10 ++++++++-- .../operator/api/config/VersionTest.java | 11 +++++++++++ 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/operator-framework-core/pom.xml b/operator-framework-core/pom.xml index ea27b31466..641a240426 100644 --- a/operator-framework-core/pom.xml +++ b/operator-framework-core/pom.xml @@ -128,7 +128,7 @@ ${git-commit-id-maven-plugin.version} true - ${project.build.outputDirectory}/version.properties + ${project.build.outputDirectory}/operator-sdk-version.properties ^git.build.time$ ^git.commit.id.(abbrev|full)$ diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/Utils.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/Utils.java index 6ad4928c86..4613d9645d 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/Utils.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/Utils.java @@ -42,6 +42,8 @@ public class Utils { public static final String GENERIC_PARAMETER_TYPE_ERROR_PREFIX = "Couldn't retrieve generic parameter type from "; + public static final String VERSION_PROPERTIES_FILE_NAME = "operator-sdk-version.properties"; + public static final Version VERSION = loadFromProperties(); /** @@ -52,7 +54,9 @@ public class Utils { */ private static Version loadFromProperties() { final var is = - Thread.currentThread().getContextClassLoader().getResourceAsStream("version.properties"); + Thread.currentThread() + .getContextClassLoader() + .getResourceAsStream(VERSION_PROPERTIES_FILE_NAME); final var properties = new Properties(); if (is != null) { @@ -62,7 +66,9 @@ private static Version loadFromProperties() { log.warn("Couldn't load version information: {}", e.getMessage()); } } else { - log.warn("Couldn't find version.properties file. Default version information will be used."); + log.warn( + "Couldn't find {} file. Default version information will be used.", + VERSION_PROPERTIES_FILE_NAME); } Date builtTime; diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/VersionTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/VersionTest.java index a8202dd0b3..7fff961ff7 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/VersionTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/VersionTest.java @@ -18,6 +18,8 @@ import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; class VersionTest { @@ -28,4 +30,13 @@ void versionShouldReturnTheSameResultFromMavenAndProperties() { assertEquals(versionFromProperties, versionFromMaven); } + + @Test + void versionShouldBeLoadedFromTheGeneratedPropertiesFile() { + assertNotNull( + Thread.currentThread() + .getContextClassLoader() + .getResource(Utils.VERSION_PROPERTIES_FILE_NAME)); + assertNotEquals(Version.UNKNOWN.getCommit(), Utils.VERSION.getCommit()); + } } From 233a4537a809d8fc23895d2223f1e364b15d3eab Mon Sep 17 00:00:00 2001 From: Antonio <122279781+afalhambra-hivemq@users.noreply.github.com> Date: Fri, 18 Sep 2026 14:30:18 +0200 Subject: [PATCH 06/23] feat: allow removing the default namespace index of an informer (#3623) Signed-off-by: Antonio Fernandez Alhambra --- .../content/en/docs/documentation/eventing.md | 29 ++++- .../documentation/operations/configuration.md | 1 + .../ControllerConfigurationOverrider.java | 12 ++ .../api/config/informer/Informer.java | 18 +++ .../informer/InformerConfiguration.java | 30 +++++ .../InformerEventSourceConfiguration.java | 6 + .../operator/api/reconciler/Constants.java | 1 + .../source/informer/InformerManager.java | 3 +- .../informer/pool/AbstractInformerPool.java | 7 +- .../informer/pool/DefaultInformerPool.java | 8 ++ .../informer/pool/InformerClassifier.java | 31 ++++- .../api/config/InformerConfigurationTest.java | 22 ++++ .../InformerManagerConcurrentReleaseTest.java | 10 +- .../source/informer/InformerWrapperTest.java | 2 +- .../pool/AbstractInformerPoolTest.java | 76 ++++++++++++ .../pool/DefaultInformerPoolTest.java | 6 +- .../informer/pool/InformerClassifierTest.java | 115 +++++++++++++++--- .../pool/NonSharingInformerPoolTest.java | 2 +- .../operator/config/loader/ConfigLoader.java | 8 +- .../WithoutNamespaceIndexIT.java | 76 ++++++++++++ .../WithoutNamespaceIndexTestReconciler.java | 86 +++++++++++++ .../config/loader/ConfigLoaderTest.java | 26 +++- 22 files changed, 539 insertions(+), 36 deletions(-) create mode 100644 operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/AbstractInformerPoolTest.java create mode 100644 operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/withoutnamespaceindex/WithoutNamespaceIndexIT.java create mode 100644 operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/withoutnamespaceindex/WithoutNamespaceIndexTestReconciler.java diff --git a/docs/content/en/docs/documentation/eventing.md b/docs/content/en/docs/documentation/eventing.md index e7aea6b065..4b890407e4 100644 --- a/docs/content/en/docs/documentation/eventing.md +++ b/docs/content/en/docs/documentation/eventing.md @@ -348,6 +348,30 @@ See also [CaffeineBoundedItemStores](https://github.com/operator-framework/java-operator-sdk/blob/main/caffeine-bounded-cache-support/src/main/java/io/javaoperatorsdk/operator/processing/event/source/cache/CaffeineBoundedItemStores.java) for more details. +### Removing the Namespace Index + +Informers keep an index from namespace to the resources cached for it. JOSDK never reads that index, +only the ones registered explicitly through `IndexerResourceCache.addIndexers(..)`, so it can be +removed to save an entry per cached resource: + +```java +@ControllerConfiguration(informer = @Informer(withoutNamespaceIndex = true)) +public class MyReconciler implements Reconciler { } +``` + +The same option is available on `InformerEventSourceConfiguration.Builder` for event sources, and on +`InformerConfiguration.Builder`. + +This matters most for informers that cache a large number of resources, and in particular together +with a custom [item store](#bounded-caches-for-informers) that keeps only a reduced form of each +resource: the index is keyed independently of what the store does with the resource itself, so +shrinking what is cached does not shrink the index. + +Note that this takes part in the informer pool identity described below: an event source that +removes the index does not share an informer with one that keeps it. If two event sources watch the +same resource type and only one of them sets the option, they end up with two informers, and two +caches of that resource type, which can cost far more memory than the index ever did. + ### Sharing Informers Between Controllers (Informer Pool) {{% alert title="Experimental" color="warning" %}} @@ -374,7 +398,10 @@ Two event sources share an informer when their effective informer configuration - the resource type (or the group/version/kind for generic resources), - the watched namespace, - the label, field and shard selectors, -- the configured [item store](#bounded-caches-for-informers). +- the configured [item store](#bounded-caches-for-informers), +- whether the [namespace index is removed](#removing-the-namespace-index): it cannot be present for + one event source and absent for another on one shared informer, so event sources that disagree on + it are backed by separate informers. The `informerListLimit` is intentionally *not* part of this identity: if two otherwise-equivalent event sources request a different list limit, the existing informer is reused (a warning is logged diff --git a/docs/content/en/docs/documentation/operations/configuration.md b/docs/content/en/docs/documentation/operations/configuration.md index cee9f65efa..182fd19555 100644 --- a/docs/content/en/docs/documentation/operations/configuration.md +++ b/docs/content/en/docs/documentation/operations/configuration.md @@ -385,6 +385,7 @@ josdk.controller.mycontroller.namespaces=team-a,team-b | `josdk.controller..informer.shard-selector` | `String` | Shard selector for the primary resource informer (alias for `shard-selector`) | | `josdk.controller..informer.list-limit` | `Long` | Page size for paginated informer list requests; omit for no pagination | | `josdk.controller..informer.comparable-resource-versions` | `Boolean` | Whether the resource versions of the primary resource can be treated as integers and thus compared | +| `josdk.controller..informer.without-namespace-index` | `Boolean` | Removes the namespace index the informer maintains; defaults to `false`. See [Removing the Namespace Index](../eventing#removing-the-namespace-index) | #### Retry diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ControllerConfigurationOverrider.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ControllerConfigurationOverrider.java index bf0f54e41a..816e5659fa 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ControllerConfigurationOverrider.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ControllerConfigurationOverrider.java @@ -222,6 +222,18 @@ public ControllerConfigurationOverrider withInformerListLimit(Long informerLi return this; } + /** + * Whether to remove the namespace index the underlying informer maintains by default. Note that + * event sources that disagree on this setting do not share an informer. + * + * @param withoutNamespaceIndex true to remove the namespace index, false (the default) to keep it + * @see io.javaoperatorsdk.operator.api.config.informer.Informer#withoutNamespaceIndex() + */ + public ControllerConfigurationOverrider withoutNamespaceIndex(boolean withoutNamespaceIndex) { + config.withoutNamespaceIndex(withoutNamespaceIndex); + return this; + } + public ControllerConfigurationOverrider replacingNamedDependentResourceConfig( String name, Object dependentResourceConfig) { diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/Informer.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/Informer.java index 04f97902d3..69999ef04f 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/Informer.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/Informer.java @@ -31,6 +31,7 @@ import static io.javaoperatorsdk.operator.api.reconciler.Constants.DEFAULT_COMPARABLE_RESOURCE_VERSION; import static io.javaoperatorsdk.operator.api.reconciler.Constants.DEFAULT_FOLLOW_CONTROLLER_NAMESPACE_CHANGES; import static io.javaoperatorsdk.operator.api.reconciler.Constants.DEFAULT_GHOST_RESOURCE_CHECK_INTERVAL_MILLIS; +import static io.javaoperatorsdk.operator.api.reconciler.Constants.DEFAULT_WITHOUT_NAMESPACE_INDEX; import static io.javaoperatorsdk.operator.api.reconciler.Constants.NO_LONG_VALUE_SET; import static io.javaoperatorsdk.operator.api.reconciler.Constants.NO_VALUE_SET; @@ -153,6 +154,23 @@ */ boolean comparableResourceVersions() default DEFAULT_COMPARABLE_RESOURCE_VERSION; + /** + * Whether to remove the namespace index that the underlying informer maintains by default. + * + *

The framework never reads that index, it only reads the indexes registered through {@link + * io.javaoperatorsdk.operator.processing.event.source.IndexerResourceCache#addIndexers}, so + * dropping it saves an entry per cached resource. It is worth setting when the informer caches a + * large number of resources and nothing looks them up by namespace, in particular together with a + * custom {@link #itemStore()} that keeps only a reduced form of each resource. + * + *

Note that this makes the informer a distinct one for pooling purposes: event sources that + * disagree on this setting do not share an informer, because the index cannot be present for one + * of them and absent for the other. + * + * @since 5.7.0 + */ + boolean withoutNamespaceIndex() default DEFAULT_WITHOUT_NAMESPACE_INDEX; + /** * @deprecated Ghost resource checking is now triggered by the informer's onList callback. This * setting is no longer used. diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/InformerConfiguration.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/InformerConfiguration.java index 9fe25c999d..106f5898c5 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/InformerConfiguration.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/InformerConfiguration.java @@ -58,6 +58,7 @@ public class InformerConfiguration { private Long informerListLimit; private FieldSelector fieldSelector; private Boolean comparableResourceVersions; + private Boolean withoutNamespaceIndex; protected InformerConfiguration( Class resourceClass, @@ -75,6 +76,7 @@ protected InformerConfiguration( Long informerListLimit, FieldSelector fieldSelector, Boolean comparableResourceVersions, + Boolean withoutNamespaceIndex, // TODO for removal in major release Duration ghostResourceCacheCheckInterval) { this(resourceClass, resourceGroupVersionKind); @@ -91,6 +93,7 @@ protected InformerConfiguration( this.informerListLimit = informerListLimit; this.fieldSelector = fieldSelector; this.comparableResourceVersions = comparableResourceVersions; + this.withoutNamespaceIndex = withoutNamespaceIndex; } private InformerConfiguration(Class resourceClass, GroupVersionKind resourceGroupVersionKind) { @@ -140,6 +143,7 @@ public static InformerConfiguration.Builder builder( original.informerListLimit, original.fieldSelector, original.comparableResourceVersions, + original.withoutNamespaceIndex, null) .builder; } @@ -332,6 +336,15 @@ public boolean isComparableResourceVersions() { return comparableResourceVersions; } + /** + * Whether the namespace index the underlying informer maintains by default is removed. + * + * @see Informer#withoutNamespaceIndex() + */ + public boolean isWithoutNamespaceIndex() { + return withoutNamespaceIndex; + } + @SuppressWarnings("UnusedReturnValue") public class Builder { @@ -349,6 +362,9 @@ public InformerConfiguration buildForController() { if (comparableResourceVersions == null) { comparableResourceVersions = DEFAULT_COMPARABLE_RESOURCE_VERSION; } + if (withoutNamespaceIndex == null) { + withoutNamespaceIndex = DEFAULT_WITHOUT_NAMESPACE_INDEX; + } return InformerConfiguration.this; } @@ -364,6 +380,9 @@ public InformerConfiguration build() { if (comparableResourceVersions == null) { comparableResourceVersions = DEFAULT_COMPARABLE_RESOURCE_VERSION; } + if (withoutNamespaceIndex == null) { + withoutNamespaceIndex = DEFAULT_WITHOUT_NAMESPACE_INDEX; + } return InformerConfiguration.this; } @@ -417,6 +436,7 @@ public InformerConfiguration.Builder initFromAnnotation( .map(f -> new FieldSelector.Field(f.path(), f.value(), f.negated())) .toList())); withComparableResourceVersions(informerConfig.comparableResourceVersions()); + withoutNamespaceIndex(informerConfig.withoutNamespaceIndex()); } return this; } @@ -533,6 +553,16 @@ private static boolean isEmpty(FieldSelector fieldSelector) { || fieldSelector.getFields().isEmpty(); } + /** + * Whether to remove the namespace index the underlying informer maintains by default. + * + * @see Informer#withoutNamespaceIndex() + */ + public Builder withoutNamespaceIndex(boolean withoutNamespaceIndex) { + InformerConfiguration.this.withoutNamespaceIndex = withoutNamespaceIndex; + return this; + } + public Builder withComparableResourceVersions(boolean comparableResourceVersions) { InformerConfiguration.this.comparableResourceVersions = comparableResourceVersions; return this; diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/InformerEventSourceConfiguration.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/InformerEventSourceConfiguration.java index a4ca2f63d4..d40469de4c 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/InformerEventSourceConfiguration.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/InformerEventSourceConfiguration.java @@ -292,6 +292,11 @@ public Builder withComparableResourceVersion(boolean comparableResourceVersio return this; } + public Builder withoutNamespaceIndex(boolean withoutNamespaceIndex) { + config.withoutNamespaceIndex(withoutNamespaceIndex); + return this; + } + @Deprecated(forRemoval = true) public Builder withGhostResourceCacheCheckInterval( Duration ghostResourceCacheCheckInterval) { @@ -317,6 +322,7 @@ public void updateFrom(InformerConfiguration informerConfig) { .withGenericFilter(informerConfig.getGenericFilter()) .withInformerListLimit(informerConfig.getInformerListLimit()) .withComparableResourceVersions(informerConfig.isComparableResourceVersions()) + .withoutNamespaceIndex(informerConfig.isWithoutNamespaceIndex()) .withFieldSelector(informerConfig.getFieldSelector()); } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/Constants.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/Constants.java index fad19d2021..2ae2de8b4f 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/Constants.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/Constants.java @@ -43,6 +43,7 @@ public final class Constants { public static final String CONTROLLER_NAME = "controller.name"; public static final boolean DEFAULT_FOLLOW_CONTROLLER_NAMESPACE_CHANGES = true; public static final boolean DEFAULT_COMPARABLE_RESOURCE_VERSION = true; + public static final boolean DEFAULT_WITHOUT_NAMESPACE_INDEX = false; @Deprecated(forRemoval = true) public static final long DEFAULT_GHOST_RESOURCE_CHECK_INTERVAL_MILLIS = 3 * 60 * 1000; diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerManager.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerManager.java index d53b65920e..a66e2c89a2 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerManager.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerManager.java @@ -181,7 +181,8 @@ private InformerClassifier getClassifier(String namespaceIdentifier) { configuration.getInformerConfig().getResourceGroupVersionKind(), configuration.getInformerConfig().getFieldSelector(), configuration.getInformerConfig().getInformerListLimit(), - configuration.getInformerConfig().getItemStore()); + configuration.getInformerConfig().getItemStore(), + configuration.getInformerConfig().isWithoutNamespaceIndex()); } private KubernetesClient getTargetClient() { diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/AbstractInformerPool.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/AbstractInformerPool.java index 4dc1920955..21464b378b 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/AbstractInformerPool.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/AbstractInformerPool.java @@ -71,7 +71,7 @@ public void setConfigurationService(ConfigurationService configurationService) { */ public abstract long numberOfInformersForResource(Class resourceClass); - @SuppressWarnings({"rawtypes", "unchecked"}) + @SuppressWarnings({"rawtypes", "unchecked", "resource"}) protected SharedIndexInformer createInformer(InformerClassifier classifier) { var client = classifier.client(); @@ -116,6 +116,11 @@ protected SharedIndexInformer createInformer(InformerClassifier classifier) { Optional.ofNullable(classifier.itemStore()).ifPresent(informer::itemStore); + if (classifier.withoutNamespaceIndex()) { + // the framework only reads the indexes registered through the resource cache, never this one + informer.removeNamespaceIndex(); + } + configurationService .getInformerStoppedHandler() .ifPresent( diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/DefaultInformerPool.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/DefaultInformerPool.java index b85b7d9f0b..24dcdba4c8 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/DefaultInformerPool.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/DefaultInformerPool.java @@ -43,6 +43,14 @@ public SharedIndexInformer getInformer( synchronized (this) { var pooled = informers.get(classifier); if (pooled == null) { + if (informers.keySet().stream() + .anyMatch(existing -> existing.differsOnlyByNamespaceIndex(classifier))) { + log.warn( + "Creating a second informer for classifier {} that differs from an existing one only" + + " by withoutNamespaceIndex, so the resource type is cached twice. Set the" + + " option the same way on both to share one informer.", + classifier); + } informer = createInformer(classifier); informers.put(classifier, new PooledInformer(informer, new AtomicInteger(1))); log.debug( diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/InformerClassifier.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/InformerClassifier.java index e4023a93e9..5f4cfae87f 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/InformerClassifier.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/InformerClassifier.java @@ -36,6 +36,9 @@ * limit still share an informer; the limit of whichever classifier created the informer is * kept (a pool is expected to warn about this, see {@link * #differsOnlyByInformerListLimit(InformerClassifier)}). + *

  • {@link #withoutNamespaceIndex()} on the other hand is part of the + * identity: the namespace index cannot be present for one event source and absent for another + * that shares the same informer, so event sources disagreeing on it get separate informers. *
  • Indexers are not part of the classifier at all: they are registered on the informer under a * name qualified with the event source that added them, so those of different event sources * can live side by side on a shared informer without colliding. @@ -61,7 +64,8 @@ public record InformerClassifier( GroupVersionKind groupVersionKind, FieldSelector fieldSelector, Long informerListLimit, - ItemStore itemStore) { + ItemStore itemStore, + boolean withoutNamespaceIndex) { @Override public boolean equals(Object o) { @@ -71,6 +75,16 @@ public boolean equals(Object o) { if (!(o instanceof InformerClassifier that)) { return false; } + return equalsIgnoringNamespaceIndex(that) + && withoutNamespaceIndex == that.withoutNamespaceIndex; + } + + /** + * Equality of everything the identity is made of except {@link #withoutNamespaceIndex()}, so that + * {@link #equals(Object)} and {@link #differsOnlyByNamespaceIndex(InformerClassifier)} cannot + * drift apart when a component is added. + */ + private boolean equalsIgnoringNamespaceIndex(InformerClassifier that) { return client == that.client && Objects.equals(labelSelector, that.labelSelector) && Objects.equals(shardSelector, that.shardSelector) @@ -91,7 +105,8 @@ public int hashCode() { resourceClass, groupVersionKind, fieldSelector, - itemStore); + itemStore, + withoutNamespaceIndex); } /** @@ -123,6 +138,8 @@ public String toString() { + informerListLimit + ", itemStore=" + itemStore + + ", withoutNamespaceIndex=" + + withoutNamespaceIndex + "]"; } @@ -140,4 +157,14 @@ private String masterUrl() { public boolean differsOnlyByInformerListLimit(InformerClassifier other) { return equals(other) && !Objects.equals(informerListLimit, other.informerListLimit); } + + /** + * Checks whether this classifier and the other are equal in every attribute except for {@link + * #withoutNamespaceIndex()}, which differs between them. Unlike the list limit, that setting is + * part of the identity, so such a pair is served by two informers rather than one. + */ + public boolean differsOnlyByNamespaceIndex(InformerClassifier other) { + return equalsIgnoringNamespaceIndex(other) + && withoutNamespaceIndex != other.withoutNamespaceIndex; + } } diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/InformerConfigurationTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/InformerConfigurationTest.java index 16e5ab578b..ef1bfafd24 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/InformerConfigurationTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/InformerConfigurationTest.java @@ -75,6 +75,28 @@ void nullLabelSelectorByDefault() { assertNull(informerConfig.getLabelSelector()); } + @Test + void keepsTheNamespaceIndexByDefault() { + final var informerConfig = InformerConfiguration.builder(ConfigMap.class).build(); + assertFalse(informerConfig.isWithoutNamespaceIndex()); + } + + @Test + void keepsTheNamespaceIndexByDefaultForController() { + final var informerConfig = InformerConfiguration.builder(ConfigMap.class).buildForController(); + assertFalse(informerConfig.isWithoutNamespaceIndex()); + } + + @Test + void withoutNamespaceIndexIsCarriedOverWhenCopyingTheConfiguration() { + final var original = + InformerConfiguration.builder(ConfigMap.class).withoutNamespaceIndex(true).build(); + + final var copy = InformerConfiguration.builder(original).build(); + + assertTrue(copy.isWithoutNamespaceIndex()); + } + @Test void nullShardSelectorByDefault() { final var informerConfig = InformerConfiguration.builder(ConfigMap.class).build(); diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerManagerConcurrentReleaseTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerManagerConcurrentReleaseTest.java index e8801781db..6fe3b3734e 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerManagerConcurrentReleaseTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerManagerConcurrentReleaseTest.java @@ -52,7 +52,7 @@ * InformerManager#changeNamespaces(Set)} can run concurrently, so removing the source from the * manager has to be what claims the right to release it. */ -@SuppressWarnings({"rawtypes", "unchecked"}) +@SuppressWarnings("unchecked") class InformerManagerConcurrentReleaseTest { private static final String NAMESPACE = "ns1"; @@ -94,6 +94,9 @@ void concurrentStopAndNamespaceChangeReleaseTheInformerOnlyOnce() throws Excepti pool.proceed.countDown(); namespaceChange.join(TimeUnit.SECONDS.toMillis(5)); + assertThat(pool.proceededInTime) + .as("the blocked release must be let through, otherwise the paths never interleaved") + .isTrue(); assertThat(pool.releaseCount.get()) .as("the same namespace must not be released twice") .isEqualTo(1); @@ -114,7 +117,7 @@ private ControllerConfiguration controllerConfiguration() { /** Has to match what the manager builds for {@link #NAMESPACE} so it hits the same pool entry. */ private InformerClassifier classifier() { return new InformerClassifier<>( - clientMock, null, null, NAMESPACE, Deployment.class, null, null, null, null); + clientMock, null, null, NAMESPACE, Deployment.class, null, null, null, null, false); } /** Blocks inside the first release so the two teardown paths can be interleaved on purpose. */ @@ -124,6 +127,7 @@ private static class LatchingInformerPool extends DefaultInformerPool { private final CountDownLatch proceed = new CountDownLatch(1); private final AtomicInteger releaseCount = new AtomicInteger(); private final AtomicBoolean blockNextRelease = new AtomicBoolean(true); + private final AtomicBoolean proceededInTime = new AtomicBoolean(); @Override public Optional> releaseInformer( @@ -134,7 +138,7 @@ public Optional> releaseInformer( if (blockNextRelease.compareAndSet(true, false)) { enteredRelease.countDown(); try { - proceed.await(5, TimeUnit.SECONDS); + proceededInTime.set(proceed.await(5, TimeUnit.SECONDS)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerWrapperTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerWrapperTest.java index c42264c061..c64ea51b3f 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerWrapperTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerWrapperTest.java @@ -124,7 +124,7 @@ private InformerWrapper wrapper(String controller, String ev informer, "default", new InformerClassifier<>( - null, null, null, "default", TestCustomResource.class, null, null, null, null), + null, null, null, "default", TestCustomResource.class, null, null, null, null, false), controller, eventSource); } diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/AbstractInformerPoolTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/AbstractInformerPoolTest.java new file mode 100644 index 0000000000..e5a1208f06 --- /dev/null +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/AbstractInformerPoolTest.java @@ -0,0 +1,76 @@ +/* + * 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.source.informer.pool; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import io.fabric8.kubernetes.client.KubernetesClient; +import io.javaoperatorsdk.operator.MockKubernetesClient; +import io.javaoperatorsdk.operator.api.config.BaseConfigurationService; +import io.javaoperatorsdk.operator.sample.simple.TestCustomResource; + +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +/** + * Unit tests for the informer creation that {@link AbstractInformerPool} performs for every pool, + * as opposed to the sharing strategy a concrete pool adds on top (covered by {@link + * DefaultInformerPoolTest} and {@link NonSharingInformerPoolTest}). {@link NonSharingInformerPool} + * is used merely as the simplest concrete subclass to reach that inherited behavior through. + */ +class AbstractInformerPoolTest { + + private static final String CONTROLLER = "controller"; + private static final String ES_NAME = "event-source"; + private static final String NAMESPACE = "default"; + + private final KubernetesClient client = MockKubernetesClient.client(TestCustomResource.class); + private final NonSharingInformerPool pool = new NonSharingInformerPool(); + + @BeforeEach + void setUp() { + pool.setConfigurationService(new BaseConfigurationService()); + } + + @Test + void keepsTheNamespaceIndexWhenTheClassifierDoesNotAskForIt() { + var informer = pool.getInformer(CONTROLLER, ES_NAME, classifier(false)); + + verify(informer, never()).removeNamespaceIndex(); + } + + @Test + void removesTheNamespaceIndexWhenTheClassifierAsksForIt() { + var informer = pool.getInformer(CONTROLLER, ES_NAME, classifier(true)); + + verify(informer).removeNamespaceIndex(); + } + + private InformerClassifier classifier(boolean withoutNamespaceIndex) { + return new InformerClassifier<>( + client, + null, + null, + NAMESPACE, + TestCustomResource.class, + null, + null, + null, + null, + withoutNamespaceIndex); + } +} diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/DefaultInformerPoolTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/DefaultInformerPoolTest.java index 4ca4db22bd..744dbdccee 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/DefaultInformerPoolTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/DefaultInformerPoolTest.java @@ -89,10 +89,10 @@ void createsSeparateInformersForDifferentClientsWithTheSameApiServerUrl() { void sharesInformerWhenClassifiersDifferOnlyByListLimit() { var withLimit100 = new InformerClassifier<>( - client, null, null, "default", TestCustomResource.class, null, null, 100L, null); + client, null, null, "default", TestCustomResource.class, null, null, 100L, null, false); var withLimit200 = new InformerClassifier<>( - client, null, null, "default", TestCustomResource.class, null, null, 200L, null); + client, null, null, "default", TestCustomResource.class, null, null, 200L, null, false); var first = pool.getInformer(CONTROLLER, ES_NAME, withLimit100); var second = pool.getInformer("other-controller", "other-es", withLimit200); @@ -149,6 +149,6 @@ private InformerClassifier classifier(String namespace) { private InformerClassifier classifier( KubernetesClient forClient, String namespace) { return new InformerClassifier<>( - forClient, null, null, namespace, TestCustomResource.class, null, null, null, null); + forClient, null, null, namespace, TestCustomResource.class, null, null, null, null, false); } } diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/InformerClassifierTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/InformerClassifierTest.java index 47f359a3f3..9025158918 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/InformerClassifierTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/InformerClassifierTest.java @@ -45,7 +45,7 @@ class InformerClassifierTest { private static final FieldSelector FIELD_SELECTOR = new FieldSelector(new FieldSelector.Field("status.phase", "Running")); private static final Long LIMIT = 100L; - private static final ItemStore ITEM_STORE = mock(ItemStore.class); + private static final ItemStore ITEM_STORE = mock(); private static InformerClassifier base() { return new InformerClassifier<>( @@ -57,7 +57,8 @@ private static InformerClassifier base() { GVK, FIELD_SELECTOR, LIMIT, - ITEM_STORE); + ITEM_STORE, + false); } @Test @@ -78,7 +79,8 @@ void informerListLimitIsExcludedFromEqualityAndHashCode() { GVK, FIELD_SELECTOR, 999L, - ITEM_STORE); + ITEM_STORE, + false); assertThat(base()).isEqualTo(withOtherLimit); assertThat(base()).hasSameHashCodeAs(withOtherLimit); @@ -103,7 +105,8 @@ void toStringContainsTheApiServerUrlDerivedFromTheClient() { GVK, FIELD_SELECTOR, LIMIT, - ITEM_STORE); + ITEM_STORE, + false); assertThat(classifier.toString()) .contains("https://localhost:8443/") @@ -124,7 +127,8 @@ void toStringDoesNotFailWithoutAClient() { GVK, FIELD_SELECTOR, LIMIT, - ITEM_STORE); + ITEM_STORE, + false); assertThat(classifier.toString()).contains(NAMESPACE); } @@ -144,7 +148,8 @@ void differsWhenClientDiffers() { GVK, FIELD_SELECTOR, LIMIT, - ITEM_STORE)); + ITEM_STORE, + false)); } @Test @@ -160,7 +165,8 @@ void differsWhenLabelSelectorDiffers() { GVK, FIELD_SELECTOR, LIMIT, - ITEM_STORE)); + ITEM_STORE, + false)); } @Test @@ -176,7 +182,8 @@ void differsWhenShardSelectorDiffers() { GVK, FIELD_SELECTOR, LIMIT, - ITEM_STORE)); + ITEM_STORE, + false)); } @Test @@ -192,14 +199,16 @@ void differsWhenNamespaceDiffers() { GVK, FIELD_SELECTOR, LIMIT, - ITEM_STORE)); + ITEM_STORE, + false)); } @Test void differsWhenResourceClassDiffers() { - // item stores are null here because their generic type is tied to the resource class, which is - // exactly the field under test; this keeps the resource class the only difference. - var forTestResource = + // the resource class is the field under test, so everything tied to it follows: the item stores + // are null to keep it the only difference, and both are declared as wildcards since their type + // argument differs with it + InformerClassifier forTestResource = new InformerClassifier<>( CLIENT, LABEL, @@ -209,8 +218,9 @@ void differsWhenResourceClassDiffers() { GVK, FIELD_SELECTOR, LIMIT, - null); - var forOtherResource = + null, + false); + InformerClassifier forOtherResource = new InformerClassifier<>( CLIENT, LABEL, @@ -220,7 +230,8 @@ void differsWhenResourceClassDiffers() { GVK, FIELD_SELECTOR, LIMIT, - null); + null, + false); assertThat(forTestResource).isNotEqualTo(forOtherResource); } @@ -238,7 +249,8 @@ void differsWhenGroupVersionKindDiffers() { new GroupVersionKind("sample.io/v1", "Bar"), FIELD_SELECTOR, LIMIT, - ITEM_STORE)); + ITEM_STORE, + false)); } @Test @@ -254,7 +266,8 @@ void differsWhenFieldSelectorDiffers() { GVK, new FieldSelector(new FieldSelector.Field("status.phase", "Pending")), LIMIT, - ITEM_STORE)); + ITEM_STORE, + false)); } @Test @@ -270,7 +283,25 @@ void differsWhenItemStoreDiffers() { GVK, FIELD_SELECTOR, LIMIT, - mock(ItemStore.class))); + mock(), + false)); + } + + @Test + void differsWhenWithoutNamespaceIndexDiffers() { + assertThat(base()) + .isNotEqualTo( + new InformerClassifier<>( + CLIENT, + LABEL, + SHARD, + NAMESPACE, + TestCustomResource.class, + GVK, + FIELD_SELECTOR, + LIMIT, + ITEM_STORE, + true)); } @Test @@ -285,7 +316,8 @@ void differsOnlyByInformerListLimitIsTrueWhenOnlyLimitDiffers() { GVK, FIELD_SELECTOR, 999L, - ITEM_STORE); + ITEM_STORE, + false); assertThat(base().differsOnlyByInformerListLimit(withOtherLimit)).isTrue(); } @@ -308,8 +340,51 @@ void differsOnlyByInformerListLimitIsFalseWhenAnotherFieldDiffers() { GVK, FIELD_SELECTOR, 999L, - ITEM_STORE); + ITEM_STORE, + false); assertThat(base().differsOnlyByInformerListLimit(differentNamespaceAndLimit)).isFalse(); } + + @Test + void differsOnlyByNamespaceIndexIsTrueWhenOnlyIndexDiffers() { + var withoutIndex = + new InformerClassifier<>( + CLIENT, + LABEL, + SHARD, + NAMESPACE, + TestCustomResource.class, + GVK, + FIELD_SELECTOR, + LIMIT, + ITEM_STORE, + true); + + assertThat(base().differsOnlyByNamespaceIndex(withoutIndex)).isTrue(); + } + + @Test + void differsOnlyByNamespaceIndexIsFalseWhenFullyEqual() { + assertThat(base().differsOnlyByNamespaceIndex(base())).isFalse(); + } + + @Test + void differsOnlyByNamespaceIndexIsFalseWhenAnotherFieldDiffers() { + // different namespace AND different index setting: not "only by namespace index" + var differentNamespaceAndIndex = + new InformerClassifier<>( + CLIENT, + LABEL, + SHARD, + "other-ns", + TestCustomResource.class, + GVK, + FIELD_SELECTOR, + LIMIT, + ITEM_STORE, + true); + + assertThat(base().differsOnlyByNamespaceIndex(differentNamespaceAndIndex)).isFalse(); + } } diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/NonSharingInformerPoolTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/NonSharingInformerPoolTest.java index 364103849e..939905f065 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/NonSharingInformerPoolTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/NonSharingInformerPoolTest.java @@ -138,6 +138,6 @@ void releaseOfUnknownInformerReturnsEmptyAndDoesNotThrow() { private InformerClassifier classifier(String namespace) { return new InformerClassifier<>( - client, null, null, namespace, TestCustomResource.class, null, null, null, null); + client, null, null, namespace, TestCustomResource.class, null, null, null, null, false); } } diff --git a/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/loader/ConfigLoader.java b/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/loader/ConfigLoader.java index df9e2e7a6c..1a221fb76c 100644 --- a/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/loader/ConfigLoader.java +++ b/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/loader/ConfigLoader.java @@ -190,7 +190,11 @@ public static ConfigLoader getDefault() { new ConfigBinding<>( "informer.comparable-resource-versions", Boolean.class, - ControllerConfigurationOverrider::withComparableResourceVersions)); + ControllerConfigurationOverrider::withComparableResourceVersions), + new ConfigBinding<>( + "informer.without-namespace-index", + Boolean.class, + ControllerConfigurationOverrider::withoutNamespaceIndex)); private final ConfigProvider configProvider; @@ -252,7 +256,7 @@ Consumer> applyControllerConfigs(String cont } Consumer> retryStep = buildRetryConsumer(prefix); if (retryStep != null) { - consumer = consumer == null ? retryStep : consumer.andThen(retryStep); + consumer = consumer.andThen(retryStep); } Consumer> rateLimiterStep = buildRateLimiterConsumer(prefix); diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/withoutnamespaceindex/WithoutNamespaceIndexIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/withoutnamespaceindex/WithoutNamespaceIndexIT.java new file mode 100644 index 0000000000..bd68813608 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/withoutnamespaceindex/WithoutNamespaceIndexIT.java @@ -0,0 +1,76 @@ +/* + * 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.withoutnamespaceindex; + +import java.time.Duration; +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import io.fabric8.kubernetes.api.model.ConfigMapBuilder; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.fabric8.kubernetes.api.model.SecretBuilder; +import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +class WithoutNamespaceIndexIT { + + private static final String TEST_RESOURCE_NAME = "test1"; + + @RegisterExtension + LocallyRunOperatorExtension extension = + LocallyRunOperatorExtension.builder() + .withReconciler(new WithoutNamespaceIndexTestReconciler()) + .build(); + + @Test + void reconcilesAndResolvesSecondariesWithoutTheNamespaceIndex() { + var configMap = + extension.create( + new ConfigMapBuilder() + .withMetadata(new ObjectMetaBuilder().withName(TEST_RESOURCE_NAME).build()) + .withData(Map.of("key", "value")) + .build()); + extension.create( + new SecretBuilder() + .withMetadata(new ObjectMetaBuilder().withName(TEST_RESOURCE_NAME).build()) + .build()); + + var reconciler = extension.getReconcilerOfType(WithoutNamespaceIndexTestReconciler.class); + await() + .pollDelay(Duration.ofMillis(150)) + .untilAsserted( + () -> { + assertThat(reconciler.getNumberOfExecutions()).isPositive(); + assertThat(reconciler.getSecondariesFound()).contains(TEST_RESOURCE_NAME); + }); + + // an update has to reach the reconciler too: the informer keeps serving events and cache reads + // with the index gone, it is not just the initial sync that works + var executionsBeforeUpdate = reconciler.getNumberOfExecutions(); + configMap.setData(Map.of("key", "updated")); + extension.update(configMap); + + await() + .untilAsserted( + () -> + assertThat(reconciler.getNumberOfExecutions()) + .isGreaterThan(executionsBeforeUpdate)); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/withoutnamespaceindex/WithoutNamespaceIndexTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/withoutnamespaceindex/WithoutNamespaceIndexTestReconciler.java new file mode 100644 index 0000000000..930e41480a --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/withoutnamespaceindex/WithoutNamespaceIndexTestReconciler.java @@ -0,0 +1,86 @@ +/* + * 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.withoutnamespaceindex; + +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.Secret; +import io.javaoperatorsdk.operator.api.config.informer.Informer; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; +import io.javaoperatorsdk.operator.api.reconciler.Reconciler; +import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; +import io.javaoperatorsdk.operator.processing.event.ResourceID; +import io.javaoperatorsdk.operator.processing.event.source.EventSource; +import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; +import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; + +/** + * Both informers drop the namespace index: the primary one through the annotation, the secondary + * one through the builder. Reconciling and resolving the secondary resource have to keep working, + * since neither reads that index. + */ +@ControllerConfiguration(informer = @Informer(withoutNamespaceIndex = true)) +public class WithoutNamespaceIndexTestReconciler + implements Reconciler, TestExecutionInfoProvider { + + private final AtomicInteger numberOfExecutions = new AtomicInteger(0); + private final Set secondariesFound = Collections.synchronizedSet(new HashSet<>()); + + @Override + public UpdateControl reconcile(Secret resource, Context context) { + numberOfExecutions.addAndGet(1); + // reads through the secondary informer's cache, the part that would break if the framework + // relied on the index it just removed + context + .getSecondaryResource(ConfigMap.class) + .ifPresent(configMap -> secondariesFound.add(configMap.getMetadata().getName())); + return UpdateControl.noUpdate(); + } + + @Override + public List> prepareEventSources(EventSourceContext context) { + return List.of( + new InformerEventSource<>( + InformerEventSourceConfiguration.from(ConfigMap.class, Secret.class) + .withNamespacesInheritedFromController() + .withoutNamespaceIndex(true) + // the ConfigMap of a Secret is the one sharing its name + .withSecondaryToPrimaryMapper( + configMap -> + Set.of( + new ResourceID( + configMap.getMetadata().getName(), + configMap.getMetadata().getNamespace()))) + .build())); + } + + @Override + public int getNumberOfExecutions() { + return numberOfExecutions.get(); + } + + public Set getSecondariesFound() { + return secondariesFound; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/loader/ConfigLoaderTest.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/loader/ConfigLoaderTest.java index 1714a2b038..cbec1f2a3c 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/loader/ConfigLoaderTest.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/loader/ConfigLoaderTest.java @@ -26,6 +26,7 @@ import org.junit.jupiter.api.Test; +import io.fabric8.kubernetes.api.model.ConfigMap; import io.javaoperatorsdk.operator.api.config.BaseConfigurationService; import io.javaoperatorsdk.operator.api.config.ConfigurationService; import io.javaoperatorsdk.operator.api.config.ConfigurationServiceOverrider; @@ -222,10 +223,23 @@ public Optional getValue(String key, Class type) { "josdk.controller.ctrl.informer.list-limit", "josdk.controller.ctrl.informer.comparable-resource-versions", "josdk.controller.ctrl.namespaces", + "josdk.controller.ctrl.informer.without-namespace-index", "josdk.controller.ctrl.rate-limiter.refresh-period", "josdk.controller.ctrl.rate-limiter.limit-for-period"); } + @Test + void applyControllerConfigsAppliesInformerWithoutNamespaceIndex() { + var loader = + new ConfigLoader( + mapProvider(Map.of("josdk.controller.ctrl.informer.without-namespace-index", true))); + var overrider = ControllerConfigurationOverrider.override(baseControllerConfig()); + + loader.applyControllerConfigs("ctrl").accept(overrider); + + assertThat(overrider.build().getInformerConfig().isWithoutNamespaceIndex()).isTrue(); + } + @Test void operatorKeyPrefixIsJosdkDot() { assertThat(ConfigLoader.DEFAULT_OPERATOR_KEY_PREFIX).isEqualTo("josdk."); @@ -626,8 +640,18 @@ void retryIsIsolatedPerControllerName() { assertThat(betaRetry.getMaxAttempts()).isEqualTo(9); } + private static boolean isTypeCompatible(Class methodParam, Class bindingType) { + if (methodParam == bindingType) return true; + if (methodParam == boolean.class && bindingType == Boolean.class) return true; + if (methodParam == Boolean.class && bindingType == boolean.class) return true; + if (methodParam == int.class && bindingType == Integer.class) return true; + if (methodParam == Integer.class && bindingType == int.class) return true; + if (methodParam == long.class && bindingType == Long.class) return true; + if (methodParam == Long.class && bindingType == long.class) return true; + if (methodParam == double.class && bindingType == Double.class) return true; + return methodParam == Double.class && bindingType == double.class; // -- watched namespaces ----------------------------------------------------- - + } private static Set applyAndGetNamespaces( java.util.function.Consumer< ControllerConfigurationOverrider> From bb7a642132b18b0175e5c3699e91692db1a22521 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Attila=20M=C3=A9sz=C3=A1ros?= Date: Tue, 27 Oct 2026 13:04:49 +0100 Subject: [PATCH 07/23] feat!: upgrade to fabric8 kubernetes client 8.0.0 (#3661) The client moved to Jackson 3, so the direct Jackson usages are migrated to the tools.jackson packages. YamlConfigProvider keeps throwing UncheckedIOException for malformed YAML. Tests calling the now ambiguous withShardSelector(null) cast the argument to String, and a v5.7 migration guide describes the changes for users. --- .github/workflows/build.yml | 2 +- .../en/docs/migration/v5-7-migration.md | 43 +++++++++++++++++++ operator-framework-core/pom.xml | 7 ++- .../api/config/ConfigurationService.java | 10 ++--- .../GenericKubernetesResourceMatcher.java | 6 +-- .../processing/matcher/MatcherUtils.java | 12 +++--- ...nformerEventSourceNamespaceChangeTest.java | 10 ++--- ...edInformerEventSourcePoolIdentityTest.java | 2 +- ...edInformerEventSourceStartFailureTest.java | 2 +- .../loader/provider/YamlConfigProvider.java | 12 ++++-- .../multiversioncrd/MultiVersionCRDIT.java | 8 ++-- pom.xml | 7 ++- 12 files changed, 88 insertions(+), 33 deletions(-) create mode 100644 docs/content/en/docs/migration/v5-7-migration.md diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 6441364993..26c3322fbd 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -23,7 +23,7 @@ jobs: httpclient-tests: strategy: matrix: - httpclient: [ 'vertx', 'jdk', 'jetty' ] + httpclient: [ 'vertx-5', 'jdk', 'jetty' ] uses: ./.github/workflows/integration-tests.yml with: java-version: 25 diff --git a/docs/content/en/docs/migration/v5-7-migration.md b/docs/content/en/docs/migration/v5-7-migration.md new file mode 100644 index 0000000000..a5fb257fd3 --- /dev/null +++ b/docs/content/en/docs/migration/v5-7-migration.md @@ -0,0 +1,43 @@ +--- +title: Migrating from v5.6 to v5.7 +description: Migrating from v5.6 to v5.7 +--- + +## Fabric8 Kubernetes Client upgraded to v8.0.0 + +v5.7 uses version 8.0.0 of the +[Fabric8 Kubernetes Client](https://github.com/fabric8io/kubernetes-client). Please consult the +client's own release notes and migration guide for the complete list of changes. The ones that are +most likely to affect operators built with JOSDK are described below. + +### Jackson 3 + +The client moved from Jackson 2 to Jackson 3. The packages changed from `com.fasterxml.jackson` to +`tools.jackson` (the annotations from `jackson-annotations` are the exception and remain in +`com.fasterxml.jackson.annotation`). If your operator uses Jackson types directly, for example +`JsonNode` obtained from the client's `KubernetesSerialization`, update the imports and the +dependencies accordingly: + +```java +// before +import com.fasterxml.jackson.databind.JsonNode; + +// after +import tools.jackson.databind.JsonNode; +``` + +Other notable Jackson 3 differences: + +- `JsonProcessingException` was replaced by `JacksonException`, which is unchecked. +- `JsonNode.fields()` was replaced by `properties()`, `fieldNames()` by `propertyNames()` and + `asText()` by `asString()`. +- `ObjectMapper` instances are created using builders, for example `YAMLMapper.builder().build()`. + +### Ambiguous `withShardSelector(null)` + +`Filterable` now has an additional `withShardSelector(ShardSelector)` overload next to +`withShardSelector(String)`. Calls passing a bare `null` no longer compile, cast the argument: + +```java +client.pods().withShardSelector((String) null); +``` diff --git a/operator-framework-core/pom.xml b/operator-framework-core/pom.xml index 641a240426..755536add7 100644 --- a/operator-framework-core/pom.xml +++ b/operator-framework-core/pom.xml @@ -46,7 +46,7 @@ io.fabric8 - kubernetes-httpclient-okhttp + kubernetes-httpclient-vertx-5 @@ -54,6 +54,11 @@ org.slf4j slf4j-api + + io.fabric8 + kubernetes-httpclient-${fabric8-httpclient-impl.name} + test + org.apache.logging.log4j log4j-slf4j2-impl diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java index 35f46e5019..336af9e2a8 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java @@ -147,11 +147,11 @@ public R clone(R object) { * you do not need to worry about setting the namespace information in most cases). * *

    Previous versions of this class provided direct access to the serialization mechanism (via - * {@link com.fasterxml.jackson.databind.ObjectMapper}) or the client's configuration. This was - * somewhat confusing, in particular with respect to changes made in the Fabric8 client - * serialization architecture made in 6.7. The proper way to configure these aspects is now to - * configure the Kubernetes client accordingly and the SDK will extract the information it needs - * from this instance. The recommended way to do so is to create your operator with {@link + * {@link tools.jackson.databind.ObjectMapper}) or the client's configuration. This was somewhat + * confusing, in particular with respect to changes made in the Fabric8 client serialization + * architecture made in 6.7. The proper way to configure these aspects is now to configure the + * Kubernetes client accordingly and the SDK will extract the information it needs from this + * instance. The recommended way to do so is to create your operator with {@link * io.javaoperatorsdk.operator.Operator#Operator(Consumer)}, passing your custom instance with * {@link ConfigurationServiceOverrider#withKubernetesClient(KubernetesClient)}. * diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericKubernetesResourceMatcher.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericKubernetesResourceMatcher.java index 668ed409ab..e6b5787df7 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericKubernetesResourceMatcher.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericKubernetesResourceMatcher.java @@ -25,7 +25,7 @@ import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.processing.dependent.Matcher; -import com.fasterxml.jackson.databind.JsonNode; +import tools.jackson.databind.JsonNode; public class GenericKubernetesResourceMatcher { @@ -264,7 +264,7 @@ private static boolean match(boolean equality, JsonNode diff, final List if (!ignoreList.isEmpty()) { return nodeIsChildOf(diff, ignoreList); } - return ADD.equals(diff.get(OP).asText()); + return ADD.equals(diff.get(OP).asString()); } static boolean nodeIsChildOf(JsonNode n, List prefixes) { @@ -278,6 +278,6 @@ static boolean nodeIsChildOf(JsonNode n, List prefixes) { } static String getPath(JsonNode n) { - return n.get(PATH).asText(); + return n.get(PATH).asString(); } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/matcher/MatcherUtils.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/matcher/MatcherUtils.java index 413a1c4acc..9bd6994fb2 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/matcher/MatcherUtils.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/matcher/MatcherUtils.java @@ -20,10 +20,10 @@ import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.matcher.Matcher; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.JsonNodeFactory; -import com.fasterxml.jackson.databind.node.NullNode; -import com.fasterxml.jackson.databind.node.ObjectNode; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.node.JsonNodeFactory; +import tools.jackson.databind.node.NullNode; +import tools.jackson.databind.node.ObjectNode; /** Shared helpers for the client-side patch based {@link Matcher} implementations. */ final class MatcherUtils { @@ -66,9 +66,7 @@ private static JsonNode applyMergePatch(JsonNode target, JsonNode patch) { } var targetObject = target.isObject() ? (ObjectNode) target : JsonNodeFactory.instance.objectNode(); - var fields = patch.fields(); - while (fields.hasNext()) { - var entry = fields.next(); + for (var entry : patch.properties()) { if (entry.getValue().isNull()) { targetObject.remove(entry.getKey()); } else { diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/ManagedInformerEventSourceNamespaceChangeTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/ManagedInformerEventSourceNamespaceChangeTest.java index 7a2ee4ee16..0a00723800 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/ManagedInformerEventSourceNamespaceChangeTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/ManagedInformerEventSourceNamespaceChangeTest.java @@ -158,11 +158,11 @@ private void stubInformerStore() { /** The mock client hands out the very same informer for every namespace. */ private SharedIndexInformer informer() { return clientMock - .resources(Deployment.class) - .inNamespace("ns1") - .withLabelSelector((String) null) - .withShardSelector(null) - .runnableInformer(0); + .resources(Deployment.class) + .inNamespace("ns1") + .withLabelSelector((String) null) + .withShardSelector(null) + .runnableInformer(0); } private InformerEventSource buildEventSource() { diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/ManagedInformerEventSourcePoolIdentityTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/ManagedInformerEventSourcePoolIdentityTest.java index a2d0759fbc..5ee911de1f 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/ManagedInformerEventSourcePoolIdentityTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/ManagedInformerEventSourcePoolIdentityTest.java @@ -70,7 +70,7 @@ void setup() { .resources(Deployment.class) .inNamespace(NAMESPACE) .withLabelSelector((String) null) - .withShardSelector(null) + .withShardSelector((String) null) .runnableInformer(0); when(informer.getStore()).thenReturn(mock(Cache.class)); } diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/ManagedInformerEventSourceStartFailureTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/ManagedInformerEventSourceStartFailureTest.java index a4d78ace74..17ff0f38b6 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/ManagedInformerEventSourceStartFailureTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/ManagedInformerEventSourceStartFailureTest.java @@ -88,7 +88,7 @@ private void stubInformerStore() { .resources(Deployment.class) .inNamespace("ns1") .withLabelSelector((String) null) - .withShardSelector(null) + .withShardSelector((String) null) .runnableInformer(0); when(informer.getStore()).thenReturn(mock(Cache.class)); } diff --git a/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/loader/provider/YamlConfigProvider.java b/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/loader/provider/YamlConfigProvider.java index fc80e46a43..872391fd45 100644 --- a/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/loader/provider/YamlConfigProvider.java +++ b/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/loader/provider/YamlConfigProvider.java @@ -28,8 +28,10 @@ import io.javaoperatorsdk.operator.config.loader.ConfigProvider; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import tools.jackson.core.JacksonException; +import tools.jackson.core.JsonParser; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.dataformat.yaml.YAMLMapper; /** * A {@link ConfigProvider} that resolves configuration values from a YAML file. @@ -44,7 +46,7 @@ public class YamlConfigProvider implements ConfigProvider { private static final Logger log = LoggerFactory.getLogger(YamlConfigProvider.class); - private static final ObjectMapper MAPPER = new ObjectMapper(new YAMLFactory()); + private static final ObjectMapper MAPPER = YAMLMapper.builder().build(); private final Map data; @@ -101,7 +103,7 @@ private static Map load(Path path) { } try (InputStream in = Files.newInputStream(path); - com.fasterxml.jackson.core.JsonParser parser = MAPPER.getFactory().createParser(in)) { + JsonParser parser = MAPPER.createParser(in)) { if (parser.nextToken() == null) { log.debug( "YAML file contains no mappings (possibly empty or comments only). " @@ -113,6 +115,8 @@ private static Map load(Path path) { return result != null ? result : Map.of(); } catch (IOException e) { throw new UncheckedIOException("Failed to load config YAML from " + path, e); + } catch (JacksonException e) { + throw new UncheckedIOException("Failed to load config YAML from " + path, new IOException(e)); } } } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDIT.java index b2606ad740..c4f2ca8df3 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDIT.java @@ -32,7 +32,7 @@ import io.javaoperatorsdk.operator.api.config.InformerStoppedHandler; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import com.fasterxml.jackson.core.JsonProcessingException; +import tools.jackson.core.JacksonException; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; @@ -93,7 +93,7 @@ public void onStop(SharedIndexInformer informer, Throwable ex) { final var object = unmarshal.get("object"); resourceCreateAsVersion = acceptOnlyIfUnsetOrEqualToAlreadySet( - resourceCreateAsVersion, object.get("apiVersion").asText()); + resourceCreateAsVersion, object.get("apiVersion").asString()); // extract the asked resource version failedResourceVersion = acceptOnlyIfUnsetOrEqualToAlreadySet( @@ -103,8 +103,8 @@ public void onStop(SharedIndexInformer informer, Throwable ex) { .get("managedFields") .get(0) .get("apiVersion") - .asText()); - } catch (JsonProcessingException e) { + .asString()); + } catch (JacksonException e) { throw new RuntimeException(e); } }); diff --git a/pom.xml b/pom.xml index 2a96fc40e9..d160549315 100644 --- a/pom.xml +++ b/pom.xml @@ -71,7 +71,7 @@ https://sonarcloud.io jdk 6.1.3 - 7.9.0 + 8.0.0 2.0.20 2.26.1 5.24.0 @@ -236,6 +236,11 @@ kubernetes-httpclient-vertx ${fabric8-client.version} + + io.fabric8 + kubernetes-httpclient-vertx-5 + ${fabric8-client.version} + io.fabric8 kubernetes-httpclient-jdk From 6a69b0eef378a78c1738f16b1c3aac4348ad18a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Attila=20M=C3=A9sz=C3=A1ros?= Date: Tue, 27 Oct 2026 14:05:09 +0100 Subject: [PATCH 08/23] fix: issues with rebase on main MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Attila Mészáros --- .../ManagedInformerEventSourceNamespaceChangeTest.java | 10 +++++----- .../operator/config/loader/ConfigLoaderTest.java | 4 +++- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/ManagedInformerEventSourceNamespaceChangeTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/ManagedInformerEventSourceNamespaceChangeTest.java index 0a00723800..e28becd6f2 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/ManagedInformerEventSourceNamespaceChangeTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/ManagedInformerEventSourceNamespaceChangeTest.java @@ -158,11 +158,11 @@ private void stubInformerStore() { /** The mock client hands out the very same informer for every namespace. */ private SharedIndexInformer informer() { return clientMock - .resources(Deployment.class) - .inNamespace("ns1") - .withLabelSelector((String) null) - .withShardSelector(null) - .runnableInformer(0); + .resources(Deployment.class) + .inNamespace("ns1") + .withLabelSelector((String) null) + .withShardSelector((String) null) + .runnableInformer(0); } private InformerEventSource buildEventSource() { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/loader/ConfigLoaderTest.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/loader/ConfigLoaderTest.java index cbec1f2a3c..0b014bb6f7 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/loader/ConfigLoaderTest.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/loader/ConfigLoaderTest.java @@ -330,6 +330,7 @@ public Optional getValue(String key, Class type) { Map.entry("withDefaultFilters", "default-filters"), Map.entry("withInformerListLimit", "informer.list-limit"), Map.entry("withComparableResourceVersions", "informer.comparable-resource-versions"), + Map.entry("withoutNamespaceIndex", "informer.without-namespace-index"), // not a plain binding: the value is a comma-separated list of namespaces Map.entry("settingNamespace", "namespaces")); @@ -650,8 +651,9 @@ private static boolean isTypeCompatible(Class methodParam, Class bindingTy if (methodParam == Long.class && bindingType == long.class) return true; if (methodParam == double.class && bindingType == Double.class) return true; return methodParam == Double.class && bindingType == double.class; - // -- watched namespaces ----------------------------------------------------- + // -- watched namespaces ----------------------------------------------------- } + private static Set applyAndGetNamespaces( java.util.function.Consumer< ControllerConfigurationOverrider> From 070a20043bd825be88626252e182aed2bfa1b4de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Attila=20M=C3=A9sz=C3=A1ros?= Date: Tue, 3 Nov 2026 19:24:08 +0100 Subject: [PATCH 09/23] feat: add Operator.keepAlive to keep the JVM running until the operator is stopped (#3669) Co-authored-by: Claude Sonnet 5.5 --- .../documentation/operations/configuration.md | 18 ++++ .../io/javaoperatorsdk/operator/Operator.java | 36 +++++++ .../operator/OperatorKeepAliveTest.java | 95 +++++++++++++++++++ 3 files changed, 149 insertions(+) create mode 100644 operator-framework-core/src/test/java/io/javaoperatorsdk/operator/OperatorKeepAliveTest.java diff --git a/docs/content/en/docs/documentation/operations/configuration.md b/docs/content/en/docs/documentation/operations/configuration.md index 182fd19555..86d5ff90df 100644 --- a/docs/content/en/docs/documentation/operations/configuration.md +++ b/docs/content/en/docs/documentation/operations/configuration.md @@ -101,6 +101,24 @@ See also the [integration test](https://github.com/operator-framework/java-operator-sdk/tree/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/changenamespace) for this feature. +## Keeping the JVM Alive + +The operator normally keeps the JVM running through the non-daemon threads of its thread pools. If +nothing else does, for example because all the threads of the operator are daemon threads as it is +the case with virtual threads, the JVM exits as soon as the `main` method returns after starting +the operator. Call `Operator.keepAlive()` to have a non-daemon thread keep the JVM running until the +operator is stopped: + +```java +public static void main(String[] args) { + Operator operator = new Operator(); + operator.register(new MyReconciler()); + operator.installShutdownHook(); + operator.start(); + operator.keepAlive(); +} +``` + ## DependentResource-level configuration It is possible to define custom annotations to configure custom `DependentResource` implementations. In order to provide diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/Operator.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/Operator.java index 1e9f927f79..780cd52813 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/Operator.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/Operator.java @@ -20,6 +20,8 @@ import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.LockSupport; import java.util.function.Consumer; import org.slf4j.Logger; @@ -45,6 +47,7 @@ public class Operator implements LifecycleAware { private ConfigurationService configurationService; private volatile boolean started = false; private final AtomicBoolean shutdownHookInstalled = new AtomicBoolean(false); + private final AtomicReference keepAliveThread = new AtomicReference<>(); public Operator() { init(initConfigurationService(null, null), true); @@ -175,6 +178,38 @@ public void installShutdownHook(Duration gracefulShutdownTimeout) { installShutdownHook(); } + /** + * Keeps the JVM running until this operator is stopped, by starting a non-daemon thread that does + * nothing but wait. This is useful when the {@code main} method of the application returns after + * starting the operator and nothing else keeps the JVM alive, for example when the threads of the + * operator are all daemon threads, as is the case with virtual threads. + * + *

    It can be called before or after {@link #start()}, and calling it again while the thread is + * already running has no effect. The thread ends when {@link #stop()} is called, so the operator + * can be stopped from a shutdown hook, see {@link #installShutdownHook()}. + */ + public void keepAlive() { + var thread = + new Thread( + () -> { + while (!Thread.currentThread().isInterrupted()) { + LockSupport.park(); + } + }, + "josdk-keep-alive"); + thread.setDaemon(false); + if (keepAliveThread.compareAndSet(null, thread)) { + thread.start(); + } + } + + private void stopKeepAlive() { + var thread = keepAliveThread.getAndSet(null); + if (thread != null) { + thread.interrupt(); + } + } + public KubernetesClient getKubernetesClient() { return configurationService.getKubernetesClient(); } @@ -240,6 +275,7 @@ public synchronized void start() { */ @Override public void stop() throws OperatorException { + stopKeepAlive(); Duration reconciliationTerminationTimeout = configurationService.reconciliationTerminationTimeout(); diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/OperatorKeepAliveTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/OperatorKeepAliveTest.java new file mode 100644 index 0000000000..89bb2c2b70 --- /dev/null +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/OperatorKeepAliveTest.java @@ -0,0 +1,95 @@ +/* + * 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; + +import java.util.Optional; + +import org.junit.jupiter.api.Test; + +import io.javaoperatorsdk.operator.sample.simple.TestCustomResource; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +class OperatorKeepAliveTest { + + @Test + void keepsTheJvmAliveWithANonDaemonThreadUntilStopped() { + var operator = newOperator(); + + operator.keepAlive(); + + assertThat(keepAliveThread()).hasValueSatisfying(t -> assertThat(t.isDaemon()).isFalse()); + + operator.stop(); + + await().untilAsserted(() -> assertThat(keepAliveThread()).isEmpty()); + } + + @Test + void callingItAgainDoesNotStartAnotherThread() { + var operator = newOperator(); + try { + operator.keepAlive(); + operator.keepAlive(); + + assertThat(keepAliveThreads()).isEqualTo(1); + } finally { + operator.stop(); + } + } + + @Test + void canBeStartedAgainAfterTheOperatorWasStopped() { + var operator = newOperator(); + operator.keepAlive(); + operator.stop(); + await().untilAsserted(() -> assertThat(keepAliveThread()).isEmpty()); + + operator.keepAlive(); + try { + assertThat(keepAliveThread()).isPresent(); + } finally { + operator.stop(); + } + } + + @Test + void noThreadIsStartedUnlessRequested() { + var operator = newOperator(); + try { + assertThat(keepAliveThread()).isEmpty(); + } finally { + operator.stop(); + } + } + + private static Operator newOperator() { + return new Operator(MockKubernetesClient.client(TestCustomResource.class)); + } + + private static long keepAliveThreads() { + return Thread.getAllStackTraces().keySet().stream() + .filter(t -> t.getName().equals("josdk-keep-alive") && t.isAlive()) + .count(); + } + + private static Optional keepAliveThread() { + return Thread.getAllStackTraces().keySet().stream() + .filter(t -> t.getName().equals("josdk-keep-alive") && t.isAlive()) + .findFirst(); + } +} From 808cd1bfe89ee61d87612f2a810c3b432772459c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Attila=20M=C3=A9sz=C3=A1ros?= Date: Wed, 4 Nov 2026 23:00:45 +0100 Subject: [PATCH 10/23] feat: use the Vert.x HTTP client of the Fabric8 client by default (#3674) * feat: use the Vert.x HTTP client of the Fabric8 client by default The operator-framework artifact now brings kubernetes-httpclient-vertx-5, the default of the Fabric8 client itself, instead of kubernetes-httpclient-jdk. The migration guide describes how to keep using the JDK client. Co-authored-by: Claude Sonnet 5.5 --- .github/workflows/integration-tests.yml | 2 +- .../en/docs/migration/v5-7-migration.md | 37 +++++++++++++++++++ micrometer-support/pom.xml | 2 +- pom.xml | 2 +- sample-operators/tomcat-operator/pom.xml | 4 -- 5 files changed, 40 insertions(+), 7 deletions(-) diff --git a/.github/workflows/integration-tests.yml b/.github/workflows/integration-tests.yml index 3f1353efea..d29d1f1d21 100644 --- a/.github/workflows/integration-tests.yml +++ b/.github/workflows/integration-tests.yml @@ -12,7 +12,7 @@ on: http-client: type: string required: false - default: 'vertx' + default: 'vertx-5' experimental: type: boolean required: false diff --git a/docs/content/en/docs/migration/v5-7-migration.md b/docs/content/en/docs/migration/v5-7-migration.md index a5fb257fd3..8d735c8acd 100644 --- a/docs/content/en/docs/migration/v5-7-migration.md +++ b/docs/content/en/docs/migration/v5-7-migration.md @@ -41,3 +41,40 @@ Other notable Jackson 3 differences: ```java client.pods().withShardSelector((String) null); ``` + +## Default HTTP client is now Vert.x 5 + +The `operator-framework` artifact now brings the Vert.x 5 based HTTP client of the Fabric8 client +(`kubernetes-httpclient-vertx-5`), which is also the default of the Fabric8 client itself, instead of +the JDK one (`kubernetes-httpclient-jdk`). If your operator doesn't declare an HTTP client +implementation of its own there is nothing to do, it gets the new default. To keep using the JDK +client, or to use another implementation, exclude the default from the `operator-framework` +dependency and add the one you want: + +```xml + + io.javaoperatorsdk + operator-framework + + + io.fabric8 + kubernetes-httpclient-vertx-5 + + + + + io.fabric8 + kubernetes-httpclient-jdk + 8.0.0 + +``` + +The implementations provided as part of the Fabric8 client all follow the +`kubernetes-httpclient-` pattern for their artifact identifier. + +If your operator already replaced the default HTTP client, update the exclusion: excluding +`kubernetes-httpclient-jdk` no longer has any effect and `kubernetes-httpclient-vertx-5` would end up +on the classpath next to your implementation. This is especially important if you use the Vert.x 4 +based client (`kubernetes-httpclient-vertx`), since Vert.x 4 and Vert.x 5 cannot be used together. +If you want to keep the Vert.x 4 based client, use it in place of `kubernetes-httpclient-jdk` in the +snippet above. diff --git a/micrometer-support/pom.xml b/micrometer-support/pom.xml index ae3c4d0be1..29dcf1f9f5 100644 --- a/micrometer-support/pom.xml +++ b/micrometer-support/pom.xml @@ -64,7 +64,7 @@ io.fabric8 - kubernetes-httpclient-vertx + kubernetes-httpclient-${fabric8-httpclient-impl.name} test diff --git a/pom.xml b/pom.xml index d160549315..63efbd29e7 100644 --- a/pom.xml +++ b/pom.xml @@ -69,7 +69,7 @@ ${java.version} java-operator-sdk https://sonarcloud.io - jdk + vertx-5 6.1.3 8.0.0 2.0.20 diff --git a/sample-operators/tomcat-operator/pom.xml b/sample-operators/tomcat-operator/pom.xml index ea964a2b07..0a05fffc1c 100644 --- a/sample-operators/tomcat-operator/pom.xml +++ b/sample-operators/tomcat-operator/pom.xml @@ -53,10 +53,6 @@ - - io.fabric8 - kubernetes-httpclient-vertx - org.apache.logging.log4j log4j-slf4j2-impl From 1ce0ecc717693036afc6b30ceadb67a8f465c7ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Attila=20M=C3=A9sz=C3=A1ros?= Date: Thu, 5 Nov 2026 01:07:51 +0100 Subject: [PATCH 11/23] feat: virtual thread support (#3664) Add the useVirtualThreads flag (ConfigurationServiceOverrider. withUseVirtualThreads, josdk.use-virtual-threads) that runs the framework's concurrent work on virtual threads. It is off by default and only supported on Java 25 or later (JEP 491); on an older JVM a warning is logged and platform threads are used. With the flag on: - reconciliations and dependent workflows run on virtual threads, still capped by concurrentReconciliationThreads and concurrentWorkflowExecutorThreads - the caching executor used for internal housekeeping uses a virtual thread per task - the Kubernetes client created by the framework runs its internal task executor on virtual threads, a provided client is used as is - scheduled tasks run on virtual threads through the new VirtualThreadScheduledExecutor, a daemon timing thread firing each task on a virtual thread, with the semantics of the platform default (waiting and periodic tasks discarded on shutdown, running tasks let finish, fixed rate tasks catch up after an overrun) Scheduled work no longer relies on java.util.Timer: - PollingEventSource and PerResourcePollingEventSource poll on an executor of their own, provided through the configuration builder or created, and shut down, by the event source, on virtual threads when the flag is on. A provided executor is never shut down by the source. They can be started again after a stop, and a poll in flight is not interrupted by it. - PerResourcePollingEventSource registers the resources of the primary cache when it starts, drops the result of a poll of a previous run, and forgets the registration of a resource that is gone from the cache so that it is polled again if recreated - TimerEventSource schedules on the retry and reschedule executor managed by ExecutorServiceManager, see ConfigurationService.getRetryAndRescheduleExecutorService and concurrentRetryAndRescheduleThreads. Timers pending on an executor the operator replaced are not scheduled again. - the default pools use daemon threads, discard delayed tasks on shutdown and let idle threads time out Behavior and API changes, described in the v5.7 migration guide: - an executor provided to PerResourcePollingConfigurationBuilder is not shut down by the event source anymore, and the configuration returns a null executor when none was provided - PollingEventSource(Class, PollingConfiguration), the TimerEventSource(String, boolean) constructor and ExecutorServiceManager.scheduledExecutorService() are deprecated - ConfigurationServiceOverrider rebuilds the default retry executor when the flag or its thread count changes, a custom executor of the wrapped configuration is then replaced, see the Javadoc Also: configuration keys in ConfigLoader, documentation (Virtual Threads, polling event source threading, migration guide), the webpage and mysql-schema samples run with virtual threads, VirtualThreadsIT, and a spotbugs exclusion for the scheduled executor handles. Co-Authored-By: Claude Sonnet 5.5 --- .../content/en/docs/documentation/eventing.md | 31 ++ .../documentation/operations/configuration.md | 61 +++ .../en/docs/migration/v5-7-migration.md | 32 ++ .../operator/ExecutorUtilsInternal.java | 77 ++++ .../api/config/ConfigurationService.java | 121 +++++- .../config/ConfigurationServiceOverrider.java | 94 +++++ .../api/config/ExecutorServiceManager.java | 109 ++++- .../VirtualThreadScheduledExecutor.java | 312 +++++++++++++++ .../operator/api/config/VirtualThreads.java | 280 +++++++++++++ .../external/PollingDependentResource.java | 1 + .../processing/event/EventSourceManager.java | 4 +- .../processing/event/EventSources.java | 13 +- .../PerResourcePollingConfiguration.java | 16 +- ...erResourcePollingConfigurationBuilder.java | 8 + .../PerResourcePollingEventSource.java | 120 +++++- .../source/polling/PollingConfiguration.java | 19 +- .../polling/PollingConfigurationBuilder.java | 20 +- .../source/polling/PollingEventSource.java | 148 +++++-- .../event/source/timer/TimerEventSource.java | 101 ++++- .../operator/ExecutorUtilsInternalTest.java | 53 +++ .../VirtualThreadsStartupDeadlockTest.java | 99 +++++ .../ConfigurationServiceOverriderTest.java | 101 +++++ .../config/ExecutorServiceManagerTest.java | 46 ++- .../VirtualThreadScheduledExecutorTest.java | 322 +++++++++++++++ .../api/config/VirtualThreadsTest.java | 221 +++++++++++ .../PerResourcePollingEventSourceTest.java | 372 ++++++++++++++++++ .../polling/PollingEventSourceTest.java | 297 +++++++++++++- .../source/timer/TimerEventSourceTest.java | 173 ++++++++ .../operator/config/loader/ConfigLoader.java | 8 + .../VirtualThreadsCustomResource.java | 30 ++ .../virtualthreads/VirtualThreadsIT.java | 92 +++++ .../VirtualThreadsTestReconciler.java | 84 ++++ .../config/loader/ConfigLoaderTest.java | 19 +- ...edExternalDependentResourceReconciler.java | 1 + .../operator/sample/MySQLSchemaOperator.java | 9 +- .../sample/MySQLSchemaOperatorE2E.java | 1 + .../operator/sample/WebPageOperator.java | 4 +- .../operator/sample/WebPageOperatorE2E.java | 1 + ...eOperatorManagedDependentResourcesE2E.java | 1 + ...eratorStandaloneDependentResourcesE2E.java | 1 + spotbugs-exclude.xml | 10 + 41 files changed, 3411 insertions(+), 101 deletions(-) create mode 100644 operator-framework-core/src/main/java/io/javaoperatorsdk/operator/ExecutorUtilsInternal.java create mode 100644 operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/VirtualThreadScheduledExecutor.java create mode 100644 operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/VirtualThreads.java create mode 100644 operator-framework-core/src/test/java/io/javaoperatorsdk/operator/ExecutorUtilsInternalTest.java create mode 100644 operator-framework-core/src/test/java/io/javaoperatorsdk/operator/VirtualThreadsStartupDeadlockTest.java create mode 100644 operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/VirtualThreadScheduledExecutorTest.java create mode 100644 operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/VirtualThreadsTest.java create mode 100644 operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/virtualthreads/VirtualThreadsCustomResource.java create mode 100644 operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/virtualthreads/VirtualThreadsIT.java create mode 100644 operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/virtualthreads/VirtualThreadsTestReconciler.java diff --git a/docs/content/en/docs/documentation/eventing.md b/docs/content/en/docs/documentation/eventing.md index 4b890407e4..03d4dcab86 100644 --- a/docs/content/en/docs/documentation/eventing.md +++ b/docs/content/en/docs/documentation/eventing.md @@ -222,6 +222,37 @@ is similar to `PerResourcePollingEventSource` except that, contrary to that even doesn't poll a specific API separately per resource, but periodically and independently of actually observed primary resources. +#### Threading of the polling event sources + +Each polling event source polls on a scheduled executor of its own, so a slow poll of one event +source never delays the polls of the others. Unless you provide one, the event source creates a +single daemon thread executor when it is started and shuts it down when it is stopped. With a single +thread the polls of a source run one after the other. A `PollingEventSource` runs a single periodic +task, so more threads would not help it. A `PerResourcePollingEventSource` however polls each +registered resource on its own, so if it has many registered resources or fetches slowly, it can be +given an executor with more threads using the `withExecutorService` method of its configuration +builder: + +```java +var config = + new PerResourcePollingConfigurationBuilder<>(this::fetchResources, Duration.ofSeconds(5)) + .withExecutorService(Executors.newScheduledThreadPool(4)) + .build(); +``` + +An executor provided that way is not managed by the operator: it is your responsibility to shut it +down. It is only ever used as is, the virtual threads flag has no effect on it. You can also share +it between multiple event sources deliberately. + +With virtual threads enabled, see [virtual threads](../operations/configuration/#virtual-threads), +the executor the event source creates runs the polls on virtual threads, only keeping one platform +thread to do the timing. The number of polls running at the same time is then not limited. + +Retried and rescheduled reconciliations are triggered on a separate executor, so a slow poll can +never delay them. It is sized with `withConcurrentRetryAndRescheduleThreads` (2 threads by +default); few threads are needed there since triggering a reconciliation only enqueues an event +for one of the reconciliation threads to pick up. + #### Inbound event sources [SimpleInboundEventSource](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/inbound/SimpleInboundEventSource.java) diff --git a/docs/content/en/docs/documentation/operations/configuration.md b/docs/content/en/docs/documentation/operations/configuration.md index 86d5ff90df..831c1aa60b 100644 --- a/docs/content/en/docs/documentation/operations/configuration.md +++ b/docs/content/en/docs/documentation/operations/configuration.md @@ -23,6 +23,60 @@ Operator operator = new Operator( override -> override .withLeaderElectionConfiguration(new LeaderElectionConfiguration("bar", "barNS"))); ``` +### Virtual Threads + +Reconciliation is mostly about blocking: talking to the Kubernetes API server or to external +systems. Virtual threads make such blocking calls much cheaper than platform threads, and the +framework can be switched over to them with a single flag: + +```java +Operator operator = new Operator(override -> override.withUseVirtualThreads(true)); +``` + +When enabled, reconciliations, dependent resource workflows and the framework's internal +housekeeping (starting the informers, for example) all run on virtual threads. + +Enabling virtual threads does **not** remove the concurrency limits, parallelism is configured +exactly as before: `withConcurrentReconciliationThreads(int)` still caps how many reconciliations +run at the same time and `withConcurrentWorkflowExecutorThreads(int)` how many dependent resources +of a workflow are processed concurrently. Only the threads backing those limits change. Since +virtual threads are cheap, these limits can usually be raised significantly compared to what is +reasonable with platform threads. + +Things to keep in mind: + +- Virtual threads are only supported on **Java 25 or later**. Before Java 25 a virtual thread pins + its carrier thread while it is inside a `synchronized` block, which can starve the carrier pool + and even deadlock the operator on startup. [JEP 491](https://openjdk.org/jeps/491), delivered in + Java 25, removed that pinning. This is checked at runtime: on an older JVM, including the ones + where virtual threads exist (Java 21 to 24), a warning is logged and platform threads are used + instead, so the same configuration works on any Java version the operator runs on. +- The scheduled tasks (the polls of the polling event sources, which each create an executor of + their own unless one is provided, and the retried and rescheduled reconciliations) run on virtual + threads too. The JDK has no scheduled executor backed by virtual threads, so the default ones keep + a single platform thread for the timing only and run each task they fire on a virtual thread. The + number of those tasks running at the same time is not limited, so + `withConcurrentRetryAndRescheduleThreads(int)` only applies to platform threads. +- Virtual threads are always daemon threads, so unlike the threads of the platform thread pools they + don't keep the JVM running: if the `main` method of your application returns after starting the + operator and nothing else keeps the JVM alive, call `Operator.keepAlive()`, see + [Keeping the JVM Alive](#keeping-the-jvm-alive). +- A custom `ExecutorService` provided through `withExecutorService(...)` or + `withWorkflowExecutorService(...)` is always used as is, the flag has no effect on it. The same + goes for `withRetryAndRescheduleExecutorService(...)`. Note however that overriding the flag, or + `withConcurrentRetryAndRescheduleThreads(int)`, of a configuration that provides its own retry and + reschedule executor replaces that executor with the default one, so provide it again with + `withRetryAndRescheduleExecutorService(...)` in that case. +- The Kubernetes client the framework creates when none is provided also switches its internal + task executor (used to dispatch informer events to their handlers and to deliver watch events) + to virtual threads. A client you provide through `withKubernetesClient(...)` is used as is: to + get the same behavior, configure it yourself, e.g. with + `new KubernetesClientBuilder().withTaskExecutor(Executors.newVirtualThreadPerTaskExecutor())` + (the client doesn't shut down an executor passed that way, use `withTaskExecutorSupplier(...)` + if it should be shut down when the client is closed). + Either way, the blocking calls your reconciler makes through the client work well on virtual + threads without any client-side change. + ## Reconciler-Level Configuration While reconcilers are typically configured using the `@ControllerConfiguration` annotation, you can also override configuration at runtime when registering the reconciler with the operator. You can either: @@ -285,6 +339,7 @@ All operator-level keys are prefixed with `josdk.`. |---|---|---| | `josdk.check-crd` | `Boolean` | Validate CRDs against local model on startup | | `josdk.close-client-on-stop` | `Boolean` | Close the Kubernetes client when the operator stops | +| `josdk.use-virtual-threads` | `Boolean` | Run the framework's concurrent work on virtual threads (only supported on Java 25+, platform threads are used on older versions) | | `josdk.use-ssa-to-patch-primary-resource` | `Boolean` | Use Server-Side Apply to patch the primary resource | | `josdk.clone-secondary-resources-when-getting-from-cache` | `Boolean` | Clone secondary resources on cache reads | @@ -301,6 +356,12 @@ All operator-level keys are prefixed with `josdk.`. |---|---|---| | `josdk.workflow.executor-threads` | `Integer` | Thread pool size for workflow execution | +#### Retry and Reschedule + +| Key | Type | Description | +|---|---|---| +| `josdk.retry-and-reschedule.concurrent-threads` | `Integer` | Thread pool size for triggering retried and rescheduled reconciliations | + #### Informer | Key | Type | Description | diff --git a/docs/content/en/docs/migration/v5-7-migration.md b/docs/content/en/docs/migration/v5-7-migration.md index 8d735c8acd..9ac3ae40b4 100644 --- a/docs/content/en/docs/migration/v5-7-migration.md +++ b/docs/content/en/docs/migration/v5-7-migration.md @@ -78,3 +78,35 @@ on the classpath next to your implementation. This is especially important if yo based client (`kubernetes-httpclient-vertx`), since Vert.x 4 and Vert.x 5 cannot be used together. If you want to keep the Vert.x 4 based client, use it in place of `kubernetes-httpclient-jdk` in the snippet above. + +## Executors of the polling and timer event sources + +The polling event sources and the internal `TimerEventSource` no longer use a `java.util.Timer`, and +`PerResourcePollingEventSource` no longer creates its executor when its configuration is built. They +run on scheduled executors, see [virtual threads](../documentation/operations/configuration/#virtual-threads) +and [Threading of the polling event sources](../documentation/eventing/#threading-of-the-polling-event-sources). +This is transparent unless your operator provides an executor to a polling event source, or relies +on one of the following: + +- A `ScheduledExecutorService` provided with `withExecutorService(...)` to a + `PerResourcePollingConfigurationBuilder` was shut down with `shutdownNow()` when the event source + was stopped. It is not anymore: **an executor you provide is yours to shut down**, like it is for + `PollingConfigurationBuilder`. If you relied on the event source for this, shut it down yourself + after stopping the operator, otherwise its threads can keep the JVM from exiting if they are not + daemon threads. +- `PerResourcePollingConfiguration.executorService()` returns `null` when no executor was provided, + it used to be a `ScheduledThreadPoolExecutor` with a single non-daemon thread created by the + configuration. The event source now creates a single daemon thread executor, or one running on + virtual threads if `useVirtualThreads` is enabled, when it starts, shuts it down when it stops, and + creates a new one if it is started again. `PerResourcePollingConfiguration.DEFAULT_EXECUTOR_THREAD_NUMBER` + is deprecated, it isn't used anymore. +- Each polling event source has an executor of its own: they don't share threads, and the number of + threads of a source is not configurable other than by providing an executor. +- `new PollingEventSource<>(Class, PollingConfiguration)` is deprecated. Use the constructor that + takes the `EventSourceContext` as well, `new PollingEventSource<>(Class, EventSourceContext, + PollingConfiguration)`, otherwise the event source cannot know about the `useVirtualThreads` + setting and polls on a platform thread. +- `TimerEventSource(String, boolean)` is deprecated, use the constructor that also takes an + executor supplier, `null` to have the event source create an executor of its own. +- `ExecutorServiceManager.scheduledExecutorService()` is deprecated. The framework doesn't use it + anymore, it creates the executor on first use, and shuts it down when the manager is stopped. diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/ExecutorUtilsInternal.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/ExecutorUtilsInternal.java new file mode 100644 index 0000000000..e9ebdb6673 --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/ExecutorUtilsInternal.java @@ -0,0 +1,77 @@ +/* + * 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; + +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; + +public class ExecutorUtilsInternal { + + private static final long SCHEDULED_THREAD_KEEP_ALIVE_SECONDS = 60; + + // prevent instantiation of util class + private ExecutorUtilsInternal() {} + + /** + * Creates a {@link ThreadFactory} producing daemon threads named after the specified prefix. + * Daemon threads don't keep the JVM alive if the {@link Operator} is never stopped, and naming + * them makes the pool they belong to identifiable in thread dumps. + * + * @param namePrefix the prefix the created threads are named after + * @return a {@link ThreadFactory} creating named daemon threads + */ + public static ThreadFactory daemonThreadFactory(String namePrefix) { + final var defaultThreadFactory = Executors.defaultThreadFactory(); + final var counter = new AtomicLong(); + return runnable -> { + final var thread = defaultThreadFactory.newThread(runnable); + thread.setName(namePrefix + "-" + counter.incrementAndGet()); + thread.setDaemon(true); + return thread; + }; + } + + /** + * Creates the kind of {@link ScheduledExecutorService} the operator runs its scheduled (i.e. + * periodic or delayed) tasks on: one whose threads are daemon threads named after the specified + * prefix, and which doesn't let the tasks that were scheduled for later delay its shutdown. + * + * @param corePoolSize the maximal number of threads of the pool, which are created on demand and + * let go if idle for a while + * @param threadNamePrefix the prefix the threads of the pool are named after + * @return a {@link ScheduledExecutorService} to run scheduled tasks on + */ + public static ScheduledExecutorService daemonScheduledThreadPool( + int corePoolSize, String threadNamePrefix) { + final var executor = + new ScheduledThreadPoolExecutor(corePoolSize, daemonThreadFactory(threadNamePrefix)); + // tasks that are scheduled far out (a reconciliation rescheduled in an hour, say) would + // otherwise keep the pool from terminating until the graceful shutdown timeout expires + executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); + // cancelled tasks are frequent (every retry that is superseded by a new event cancels one) and + // would otherwise be retained until their delay elapses + executor.setRemoveOnCancelPolicy(true); + // the threads are created as tasks get scheduled, not as the load requires, so without this + // they would all stay around idle for good; the pool always keeps a thread for delayed tasks + executor.setKeepAliveTime(SCHEDULED_THREAD_KEEP_ALIVE_SECONDS, TimeUnit.SECONDS); + executor.allowCoreThreadTimeOut(true); + return executor; + } +} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java index 336af9e2a8..92d1729619 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java @@ -20,7 +20,7 @@ import java.util.Optional; import java.util.Set; import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; import java.util.function.Consumer; import org.slf4j.Logger; @@ -64,6 +64,12 @@ public interface ConfigurationService { /** The default number of threads used to process dependent workflows */ int DEFAULT_WORKFLOW_EXECUTOR_THREAD_NUMBER = DEFAULT_RECONCILIATION_THREADS_NUMBER; + /** + * The default number of threads used to trigger the operator's retried and rescheduled + * reconciliations + */ + int DEFAULT_RETRY_AND_RESCHEDULE_THREADS_NUMBER = 2; + /** * Creates a new {@link ConfigurationService} instance used to configure an {@link * io.javaoperatorsdk.operator.Operator} instance, starting from the specified base configuration @@ -155,6 +161,12 @@ public R clone(R object) { * io.javaoperatorsdk.operator.Operator#Operator(Consumer)}, passing your custom instance with * {@link ConfigurationServiceOverrider#withKubernetesClient(KubernetesClient)}. * + *

    When {@link #useVirtualThreads()} is enabled (and supported by the JVM), the default client + * runs its internal asynchronous tasks, such as dispatching informer events to their handlers and + * delivering watch events, on virtual threads instead of its default cached platform thread pool. + * A client provided by overriding this method or through {@link + * ConfigurationServiceOverrider#withKubernetesClient(KubernetesClient)} is used as is. + * *

    NOTE: It is strongly suggested that implementors override this method since the * default implementation creates a new {@link KubernetesClient} instance each time this method is * called. @@ -163,13 +175,17 @@ public R clone(R object) { * @since 4.4.0 */ default KubernetesClient getKubernetesClient() { - return new KubernetesClientBuilder() - .withConfig( - new ConfigBuilder(Config.autoConfigure(null)) - .withMaxConcurrentRequests(DEFAULT_MAX_CONCURRENT_REQUEST) - .build()) - .withKubernetesSerialization(new KubernetesSerialization()) - .build(); + final var builder = + new KubernetesClientBuilder() + .withConfig( + new ConfigBuilder(Config.autoConfigure(null)) + .withMaxConcurrentRequests(DEFAULT_MAX_CONCURRENT_REQUEST) + .build()) + .withKubernetesSerialization(new KubernetesSerialization()); + if (VirtualThreads.shouldUse(useVirtualThreads())) { + builder.withTaskExecutorSupplier(VirtualThreads.newKubernetesClientTaskExecutorSupplier()); + } + return builder.build(); } /** @@ -203,6 +219,11 @@ default boolean checkCRDAndValidateLocalModel() { * The number of threads the operator can spin out to dispatch reconciliation requests to * reconcilers with the default executors * + *

    This is a concurrency limit and applies regardless of whether the default executor is backed + * by platform or by virtual threads, see {@link #useVirtualThreads()}: with virtual threads it + * caps how many reconciliations run at the same time rather than the size of a thread pool. Since + * virtual threads are cheap, the limit can be set considerably higher when they are enabled. + * * @return the number of concurrent reconciliation threads */ default int concurrentReconciliationThreads() { @@ -213,12 +234,32 @@ default int concurrentReconciliationThreads() { * Number of threads the operator can spin out to be used in the workflows with the default * executor. * + *

    This is a concurrency limit and applies regardless of whether the default executor is backed + * by platform or by virtual threads, see {@link #useVirtualThreads()}: with virtual threads it + * caps how many dependent resources are processed at the same time rather than the size of a + * thread pool. Since virtual threads are cheap, the limit can be set considerably higher when + * they are enabled. + * * @return the maximum number of concurrent workflow threads */ default int concurrentWorkflowExecutorThreads() { return DEFAULT_WORKFLOW_EXECUTOR_THREAD_NUMBER; } + /** + * Number of threads the operator can spin out to trigger its retried and rescheduled + * reconciliations with the default executor. These threads are shared by all the controllers of + * the operator, but the tasks they run only enqueue an event for the reconciliation to happen on + * a reconciliation thread, so few of them are needed. Not used when virtual threads are enabled, + * see {@link #useVirtualThreads()}. + * + * @return the maximum number of concurrent retry and reschedule threads + * @since 5.7.0 + */ + default int concurrentRetryAndRescheduleThreads() { + return DEFAULT_RETRY_AND_RESCHEDULE_THREADS_NUMBER; + } + /** * Override to provide a custom {@link Metrics} implementation * @@ -228,6 +269,46 @@ default Metrics getMetrics() { return Metrics.NOOP; } + /** + * Whether the framework should run the tasks it executes concurrently — reconciliations, + * dependent workflows and internal housekeeping such as starting the informers — on virtual + * threads instead of platform threads. + * + *

    Virtual threads make blocking operations, which is essentially all a reconciler does while + * talking to the Kubernetes API server or to external systems, much cheaper. Enabling them does + * not lift the configured concurrency limits: {@link #concurrentReconciliationThreads()} + * and {@link #concurrentWorkflowExecutorThreads()} still cap how many reconciliations, + * respectively dependent resources, are processed at the same time, they just aren't backed by a + * pool of platform threads anymore. Since virtual threads are cheap, those limits can be set + * considerably higher than what would be reasonable for platform threads. + * + *

    Virtual threads are only supported on Java 25 or later, where JEP 491 removed the pinning of the carrier thread by + * {@code synchronized} blocks. This is checked at runtime: on an older JVM, a warning is logged + * and platform threads are used, so that the same configuration works regardless of the Java + * version the operator runs on. + * + *

    Note that this only affects the executors created by the framework: a custom {@link + * ExecutorService} provided through {@link #getExecutorService()} or {@link + * #getWorkflowExecutorService()}, or a custom {@link ScheduledExecutorService} provided through + * {@link #getRetryAndRescheduleExecutorService()} or the polling configuration, is used as is. + * The default scheduled executors, including the ones the polling event sources create for + * themselves, keep a single platform thread for the timing and run each task they fire on a + * virtual thread. The same goes for the {@link KubernetesClient}: the default client created by + * {@link #getKubernetesClient()} then also runs its internal asynchronous tasks (informer event + * dispatching, watch event delivery) on virtual threads, while a custom client, e.g. provided + * through {@link ConfigurationServiceOverrider#withKubernetesClient(KubernetesClient)}, keeps + * whatever task executor it was built with. The blocking calls a reconciler performs through the + * client don't need any of this: they already park the calling virtual thread rather than its + * carrier. + * + * @return {@code true} to use virtual threads, {@code false} (default) to use platform threads + * @since 5.7.0 + */ + default boolean useVirtualThreads() { + return false; + } + /** * Override to provide a custom {@link ExecutorService} implementation to change how threads * handle concurrent reconciliations @@ -236,7 +317,8 @@ default Metrics getMetrics() { * processing */ default ExecutorService getExecutorService() { - return Executors.newFixedThreadPool(concurrentReconciliationThreads()); + return ExecutorServiceManager.newBoundedExecutorService( + concurrentReconciliationThreads(), useVirtualThreads()); } /** @@ -246,7 +328,26 @@ default ExecutorService getExecutorService() { * @return the {@link ExecutorService} implementation to use for dependent workflow processing */ default ExecutorService getWorkflowExecutorService() { - return Executors.newFixedThreadPool(concurrentWorkflowExecutorThreads()); + return ExecutorServiceManager.newBoundedExecutorService( + concurrentWorkflowExecutorThreads(), useVirtualThreads()); + } + + /** + * Override to provide a custom {@link ScheduledExecutorService} implementation to change how the + * operator's retried and rescheduled reconciliations are triggered. + * + *

    Note that the default implementation lets the executor discard the tasks that were scheduled + * for later when it is shut down, so that they don't delay the termination of the operator, and + * that it creates daemon threads so that a never stopped operator doesn't keep the JVM alive. + * Custom implementations are advised to do the same. + * + * @return the {@link ScheduledExecutorService} implementation to use to trigger retried and + * rescheduled reconciliations + * @since 5.7.0 + */ + default ScheduledExecutorService getRetryAndRescheduleExecutorService() { + return ExecutorServiceManager.newScheduledExecutorService( + concurrentRetryAndRescheduleThreads(), useVirtualThreads(), "josdk-retry-reschedule"); } /** diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverrider.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverrider.java index 2cf6540af0..05112b4da7 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverrider.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverrider.java @@ -21,6 +21,7 @@ import java.util.Optional; import java.util.Set; import java.util.concurrent.ExecutorService; +import java.util.concurrent.ScheduledExecutorService; import java.util.function.Function; import org.slf4j.Logger; @@ -45,11 +46,14 @@ public class ConfigurationServiceOverrider { private Boolean checkCR; private Integer concurrentReconciliationThreads; private Integer concurrentWorkflowExecutorThreads; + private Integer concurrentRetryAndRescheduleThreads; private Cloner cloner; private Boolean closeClientOnStop; private KubernetesClient client; private ExecutorService executorService; private ExecutorService workflowExecutorService; + private Boolean useVirtualThreads; + private ScheduledExecutorService retryAndRescheduleExecutorService; private LeaderElectionConfiguration leaderElectionConfiguration; private String clusterScopedEventNamespace; private EventRecorder eventRecorder; @@ -86,6 +90,25 @@ public ConfigurationServiceOverrider withConcurrentWorkflowExecutorThreads(int t return this; } + /** + * Sets the number of threads used to trigger the operator's retried and rescheduled + * reconciliations, which are shared by all its controllers. + * + *

    Note that changing the number of threads makes the overridden configuration build the + * default retry and reschedule executor itself, so a custom one provided by the configuration + * being overridden is not used anymore. Use {@link #withRetryAndRescheduleExecutorService} to + * provide one. + * + * @param threadNumber the maximum number of concurrent retry and reschedule threads + * @return this {@link ConfigurationServiceOverrider} for chained customization + * @see ConfigurationService#concurrentRetryAndRescheduleThreads() + * @since 5.7.0 + */ + public ConfigurationServiceOverrider withConcurrentRetryAndRescheduleThreads(int threadNumber) { + this.concurrentRetryAndRescheduleThreads = threadNumber; + return this; + } + @SuppressWarnings("rawtypes") public ConfigurationServiceOverrider withDependentResourceFactory( DependentResourceFactory dependentResourceFactory) { @@ -119,6 +142,41 @@ public ConfigurationServiceOverrider withWorkflowExecutorService( return this; } + /** + * Replaces the executor used to trigger the operator's retried and rescheduled reconciliations, + * which is shared by all its controllers. + * + * @param retryAndRescheduleExecutorService the executor to trigger retried and rescheduled + * reconciliations on + * @return this {@link ConfigurationServiceOverrider} for chained customization + * @see ConfigurationService#getRetryAndRescheduleExecutorService() + * @since 5.7.0 + */ + public ConfigurationServiceOverrider withRetryAndRescheduleExecutorService( + ScheduledExecutorService retryAndRescheduleExecutorService) { + this.retryAndRescheduleExecutorService = retryAndRescheduleExecutorService; + return this; + } + + /** + * Makes the framework run the tasks it executes concurrently on virtual threads instead of + * platform threads. Only supported on Java 25 or later, see {@link + * ConfigurationService#useVirtualThreads()} for the details. + * + *

    Note that if this changes the value of the configuration being overridden, the overridden + * configuration builds the default retry and reschedule executor itself, so a custom one provided + * by the configuration being overridden is replaced and not used as is. Use {@link + * #withRetryAndRescheduleExecutorService} to provide one along with this setting. + * + * @param useVirtualThreads {@code true} to use virtual threads + * @return this {@link ConfigurationServiceOverrider} for chained customization + * @since 5.7.0 + */ + public ConfigurationServiceOverrider withUseVirtualThreads(boolean useVirtualThreads) { + this.useVirtualThreads = useVirtualThreads; + return this; + } + /** * Replaces the default {@link KubernetesClient} instance by the specified one. This is the * preferred mechanism to configure which client will be used to access the cluster. @@ -312,6 +370,17 @@ public int concurrentWorkflowExecutorThreads() { original.concurrentWorkflowExecutorThreads()); } + @Override + public int concurrentRetryAndRescheduleThreads() { + return Utils.ensureValid( + overriddenValueOrDefault( + concurrentRetryAndRescheduleThreads, + ConfigurationService::concurrentRetryAndRescheduleThreads), + "maximum retry and reschedule threads", + 1, + original.concurrentRetryAndRescheduleThreads()); + } + @Override public Metrics getMetrics() { return overriddenValueOrDefault(metrics, ConfigurationService::getMetrics); @@ -322,6 +391,11 @@ public boolean closeClientOnStop() { return overriddenValueOrDefault(closeClientOnStop, ConfigurationService::closeClientOnStop); } + @Override + public boolean useVirtualThreads() { + return overriddenValueOrDefault(useVirtualThreads, ConfigurationService::useVirtualThreads); + } + @Override public ExecutorService getExecutorService() { if (executorService != null) { @@ -340,6 +414,26 @@ public ExecutorService getWorkflowExecutorService() { } } + @Override + public ScheduledExecutorService getRetryAndRescheduleExecutorService() { + if (retryAndRescheduleExecutorService != null) { + return retryAndRescheduleExecutorService; + } else if (!changes( + concurrentRetryAndRescheduleThreads, original.concurrentRetryAndRescheduleThreads())) { + return original.getRetryAndRescheduleExecutorService(); + } else { + return super.getRetryAndRescheduleExecutorService(); + } + } + + // the default scheduled executors are only built anew when an override actually changes the + // way they are built, otherwise the ones of the original configuration are kept, which also + // preserves a custom executor the original provides + private boolean changes(Integer overriddenThreads, int originalThreads) { + return (overriddenThreads != null && overriddenThreads != originalThreads) + || (useVirtualThreads != null && useVirtualThreads != original.useVirtualThreads()); + } + @Override public Optional getLeaderElectionConfiguration() { return leaderElectionConfiguration != null diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ExecutorServiceManager.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ExecutorServiceManager.java index cdcafcaa46..7f90b1b60d 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ExecutorServiceManager.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ExecutorServiceManager.java @@ -33,6 +33,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import io.javaoperatorsdk.operator.ExecutorUtilsInternal; import io.javaoperatorsdk.operator.OperatorException; public class ExecutorServiceManager { @@ -42,6 +43,7 @@ public class ExecutorServiceManager { private ExecutorService workflowExecutor; private ExecutorService cachingExecutorService; private ScheduledExecutorService scheduledExecutorService; + private ScheduledExecutorService retryAndRescheduleExecutorService; private boolean started; private ConfigurationService configurationService; @@ -49,6 +51,59 @@ public class ExecutorServiceManager { start(configurationService); } + /** + * Creates the executor service used to run a bounded number of tasks concurrently, either backed + * by virtual threads or by a fixed size pool of platform threads. The concurrency limit is + * enforced in both cases. + * + * @param maxConcurrency the maximal number of tasks executed at the same time + * @param useVirtualThreads whether virtual threads should be used, see {@link + * ConfigurationService#useVirtualThreads()} + * @return the created {@link ExecutorService} + */ + public static ExecutorService newBoundedExecutorService( + int maxConcurrency, boolean useVirtualThreads) { + return VirtualThreads.shouldUse(useVirtualThreads) + ? VirtualThreads.newBoundedVirtualThreadExecutor(maxConcurrency) + : Executors.newFixedThreadPool(maxConcurrency); + } + + /** + * Creates the executor service used to run scheduled (i.e. periodic or delayed) tasks, either + * firing them on virtual threads or on a pool of platform threads. The platform thread variant is + * the one of {@link ExecutorUtilsInternal#daemonScheduledThreadPool(int, String)}. In both cases + * the threads are daemon threads. Virtual threads are cheap and the tasks scheduled are typically + * blocking calls, so their number is not limited. + * + * @param maxConcurrency the number of threads of the platform thread pool, not used with virtual + * threads + * @param useVirtualThreads whether virtual threads should be used, see {@link + * ConfigurationService#useVirtualThreads()} + * @param threadNamePrefix the prefix the threads of the executor are named after + * @return the {@link ScheduledExecutorService} to run scheduled tasks on + * @since 5.7.0 + */ + public static ScheduledExecutorService newScheduledExecutorService( + int maxConcurrency, boolean useVirtualThreads, String threadNamePrefix) { + return VirtualThreads.shouldUse(useVirtualThreads) + ? VirtualThreads.newScheduledExecutor(threadNamePrefix) + : ExecutorUtilsInternal.daemonScheduledThreadPool(maxConcurrency, threadNamePrefix); + } + + /** + * Creates the executor service used to run an unbounded number of tasks concurrently, either + * backed by virtual threads or by a cached pool of platform threads. + * + * @param useVirtualThreads whether virtual threads should be used, see {@link + * ConfigurationService#useVirtualThreads()} + * @return the created {@link ExecutorService} + */ + public static ExecutorService newUnboundedExecutorService(boolean useVirtualThreads) { + return VirtualThreads.shouldUse(useVirtualThreads) + ? VirtualThreads.newVirtualThreadPerTaskExecutor() + : Executors.newCachedThreadPool(); + } + /** * Uses cachingExecutorService from this manager. Use this only for tasks, that don't have dynamic * nature, in sense that won't grow with the number of inputs (thus kubernetes resources) @@ -128,30 +183,63 @@ public ExecutorService cachingExecutorService() { return cachingExecutorService; } - public ScheduledExecutorService scheduledExecutorService() { + /** + * A general purpose scheduled executor, created on first use, which is shut down by {@link + * #stop(Duration)} and replaced by a fresh one on the next use after a {@link + * #start(ConfigurationService)}. The framework itself doesn't use it: the polling event sources + * poll on executors of their own, and retries are triggered on {@link + * #retryAndRescheduleExecutorService()}. + * + * @return the executor to run scheduled tasks on + * @deprecated the framework doesn't use this executor anymore, create and manage the executor you + * need yourself, e.g. with {@link #newScheduledExecutorService(int, boolean, String)} + */ + @Deprecated(since = "5.7.0") + public synchronized ScheduledExecutorService scheduledExecutorService() { + if (scheduledExecutorService == null) { + scheduledExecutorService = + newScheduledExecutorService( + 1, configurationService.useVirtualThreads(), "josdk-scheduled-task"); + } return scheduledExecutorService; } + /** + * The executor the operator triggers its retried and rescheduled reconciliations on. Note that it + * is only valid while the manager is started: it is shut down by {@link #stop(Duration)} and + * replaced by a fresh one on the next {@link #start(ConfigurationService)}, so callers should + * retrieve it when they start rather than hold on to it. + * + * @return the executor to trigger retried and rescheduled reconciliations on + */ + public ScheduledExecutorService retryAndRescheduleExecutorService() { + return retryAndRescheduleExecutorService; + } + public synchronized void start(ConfigurationService configurationService) { if (!started) { this.configurationService = configurationService; // used to lazy init workflow executor - this.cachingExecutorService = Executors.newCachedThreadPool(); - this.scheduledExecutorService = Executors.newScheduledThreadPool(0); + this.cachingExecutorService = + newUnboundedExecutorService(configurationService.useVirtualThreads()); + this.retryAndRescheduleExecutorService = + configurationService.getRetryAndRescheduleExecutorService(); this.executor = new InstrumentedExecutorService(configurationService.getExecutorService()); started = true; } } public synchronized void stop(Duration gracefulShutdownTimeout) { - var parallelExec = Executors.newFixedThreadPool(4); + var shutdowns = + List.of( + shutdown(executor, gracefulShutdownTimeout), + shutdown(workflowExecutor, gracefulShutdownTimeout), + shutdown(cachingExecutorService, gracefulShutdownTimeout), + shutdown(scheduledExecutorService, gracefulShutdownTimeout), + shutdown(retryAndRescheduleExecutorService, gracefulShutdownTimeout)); + var parallelExec = Executors.newFixedThreadPool(shutdowns.size()); try { log.debug("Closing executor"); - parallelExec.invokeAll( - List.of( - shutdown(executor, gracefulShutdownTimeout), - shutdown(workflowExecutor, gracefulShutdownTimeout), - shutdown(cachingExecutorService, gracefulShutdownTimeout), - shutdown(scheduledExecutorService, gracefulShutdownTimeout))); + parallelExec.invokeAll(shutdowns); } catch (InterruptedException e) { log.debug("Exception closing executor: {}", e.getLocalizedMessage()); Thread.currentThread().interrupt(); @@ -161,6 +249,7 @@ public synchronized void stop(Duration gracefulShutdownTimeout) { // silently leaving the manager with already terminated executors parallelExec.shutdownNow(); workflowExecutor = null; + scheduledExecutorService = null; started = false; } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/VirtualThreadScheduledExecutor.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/VirtualThreadScheduledExecutor.java new file mode 100644 index 0000000000..3e3935e5ad --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/VirtualThreadScheduledExecutor.java @@ -0,0 +1,312 @@ +/* + * 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.api.config; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.AbstractExecutorService; +import java.util.concurrent.Callable; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Delayed; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import io.javaoperatorsdk.operator.ExecutorUtilsInternal; + +/** + * A {@link ScheduledExecutorService} running the tasks it fires on the threads of another executor, + * which is how scheduled tasks end up on virtual threads: the JDK has no virtual thread backed + * {@link ScheduledExecutorService}, so a single daemon platform thread does the timing and only + * hands each fired task off. + * + *

    The semantics follow the ones of the default scheduled executor of the SDK, see {@link + * ExecutorUtilsInternal#daemonScheduledThreadPool(int, String)}: tasks that were scheduled for + * later, and periodic tasks, are discarded when the executor is shut down, while tasks that already + * started are let finish. + */ +final class VirtualThreadScheduledExecutor extends AbstractExecutorService + implements ScheduledExecutorService { + + private final ExecutorService worker; + private final ScheduledExecutorService timer; + private final Set> waiting = ConcurrentHashMap.newKeySet(); + private final Object lifecycleLock = new Object(); + + VirtualThreadScheduledExecutor(ExecutorService worker, String threadNamePrefix) { + this.worker = worker; + this.timer = ExecutorUtilsInternal.daemonScheduledThreadPool(1, threadNamePrefix + "-timer"); + } + + @Override + public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) { + Objects.requireNonNull(command); + return start(new Handle(Executors.callable(command, null), 0), delay, unit); + } + + @Override + public ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit) { + Objects.requireNonNull(callable); + return start(new Handle<>(callable, 0), delay, unit); + } + + @Override + public ScheduledFuture scheduleAtFixedRate( + Runnable command, long initialDelay, long period, TimeUnit unit) { + Objects.requireNonNull(command); + if (period <= 0) { + throw new IllegalArgumentException("period must be positive"); + } + return start( + new Handle(Executors.callable(command, null), unit.toNanos(period)), + initialDelay, + unit); + } + + @Override + public ScheduledFuture scheduleWithFixedDelay( + Runnable command, long initialDelay, long delay, TimeUnit unit) { + Objects.requireNonNull(command); + if (delay <= 0) { + throw new IllegalArgumentException("delay must be positive"); + } + return start( + new Handle(Executors.callable(command, null), -unit.toNanos(delay)), + initialDelay, + unit); + } + + private Handle start(Handle handle, long initialDelay, TimeUnit unit) { + handle.arm(System.nanoTime() + Math.max(0, unit.toNanos(initialDelay))); + return handle; + } + + @Override + public void execute(Runnable command) { + worker.execute(Objects.requireNonNull(command)); + } + + @Override + public void shutdown() { + synchronized (lifecycleLock) { + cancelWaiting(false); + timer.shutdown(); + worker.shutdown(); + } + } + + @Override + public List shutdownNow() { + final var notStarted = new ArrayList(); + synchronized (lifecycleLock) { + cancelWaiting(true); + timer.shutdownNow(); + for (var task : worker.shutdownNow()) { + if (task instanceof Dispatched dispatched) { + dispatched.handle.cancel(false); + } else { + notStarted.add(task); + } + } + } + return Collections.unmodifiableList(notStarted); + } + + private void cancelWaiting(boolean mayInterruptIfRunning) { + for (var handle : waiting) { + handle.cancel(mayInterruptIfRunning); + } + } + + @Override + public boolean isShutdown() { + return timer.isShutdown() && worker.isShutdown(); + } + + @Override + public boolean isTerminated() { + return timer.isTerminated() && worker.isTerminated(); + } + + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { + final var deadline = System.nanoTime() + unit.toNanos(timeout); + return timer.awaitTermination(timeout, unit) + && worker.awaitTermination(deadline - System.nanoTime(), TimeUnit.NANOSECONDS); + } + + /** + * What is handed to the worker once a task fires, so that it can be traced back to its handle. + */ + private record Dispatched(Handle handle) implements Runnable { + @Override + public void run() { + handle.runOnWorker(); + } + } + + /** + * The future of a scheduled task. A positive {@code period} makes it a task at a fixed rate, a + * negative one a task with a fixed delay, whose absolute value is the delay. + */ + private final class Handle implements ScheduledFuture { + + private final Callable callable; + private final long period; + private final CompletableFuture result = new CompletableFuture<>(); + + private volatile ScheduledFuture timerFuture; + private volatile Thread runner; + private volatile long triggerTime; + + private Handle(Callable callable, long period) { + this.callable = callable; + this.period = period; + } + + private void arm(long triggerNanos) { + triggerTime = triggerNanos; + final var delayNanos = Math.max(0, triggerNanos - System.nanoTime()); + synchronized (lifecycleLock) { + waiting.add(this); + try { + timerFuture = timer.schedule(this::dispatch, delayNanos, TimeUnit.NANOSECONDS); + } catch (RejectedExecutionException e) { + waiting.remove(this); + throw e; + } + } + if (result.isDone()) { + waiting.remove(this); + timerFuture.cancel(false); + } + } + + private void dispatch() { + waiting.remove(this); + if (result.isDone()) { + return; + } + try { + worker.execute(new Dispatched(this)); + } catch (RejectedExecutionException e) { + result.cancel(false); + } + } + + private void runOnWorker() { + runner = Thread.currentThread(); + try { + if (result.isDone()) { + return; + } + if (period == 0) { + result.complete(callable.call()); + return; + } + callable.call(); + } catch (Throwable t) { + result.completeExceptionally(t); + return; + } finally { + runner = null; + } + rearm(); + } + + private void rearm() { + if (result.isDone()) { + return; + } + final long nextTrigger; + if (period > 0) { + nextTrigger = triggerTime + period; + } else { + nextTrigger = System.nanoTime() - period; + } + try { + arm(nextTrigger); + } catch (RejectedExecutionException e) { + result.cancel(false); + } + } + + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + final var cancelled = result.cancel(mayInterruptIfRunning); + if (cancelled) { + waiting.remove(this); + final var future = timerFuture; + if (future != null) { + future.cancel(false); + } + final var thread = runner; + if (mayInterruptIfRunning && thread != null) { + thread.interrupt(); + } + } + return cancelled; + } + + @Override + public boolean isCancelled() { + return result.isCancelled(); + } + + @Override + public boolean isDone() { + return result.isDone(); + } + + @Override + public V get() throws InterruptedException, ExecutionException { + return result.get(); + } + + @Override + public V get(long timeout, TimeUnit unit) + throws InterruptedException, ExecutionException, TimeoutException { + return result.get(timeout, unit); + } + + @Override + public long getDelay(TimeUnit unit) { + return unit.convert(triggerTime - System.nanoTime(), TimeUnit.NANOSECONDS); + } + + @Override + public int compareTo(Delayed other) { + if (other == this) { + return 0; + } + if (other instanceof Handle otherHandle) { + // the deadlines are compared as they are, sampling the remaining delay of each handle + // separately would make a.compareTo(b) and b.compareTo(a) disagree for close deadlines + return Long.compare(triggerTime - otherHandle.triggerTime, 0); + } + return Long.compare(getDelay(TimeUnit.NANOSECONDS), other.getDelay(TimeUnit.NANOSECONDS)); + } + } +} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/VirtualThreads.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/VirtualThreads.java new file mode 100644 index 0000000000..a47f09b320 --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/VirtualThreads.java @@ -0,0 +1,280 @@ +/* + * 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.api.config; + +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.AbstractExecutorService; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.fabric8.kubernetes.client.KubernetesClientBuilder.ExecutorSupplier; +import io.javaoperatorsdk.operator.OperatorException; + +/** + * Creates the virtual thread based executors used when {@link + * ConfigurationService#useVirtualThreads()} is enabled. + * + *

    Virtual threads are only supported on Java 25 or later, where JEP 491 removed the pinning of the carrier thread by + * {@code synchronized} blocks. On older JVMs, including the ones where virtual threads already + * exist, the request is ignored with a warning and platform threads are used, see {@link + * #shouldUse(boolean)}. + * + *

    The SDK is compiled for Java 17, in which virtual threads don't exist yet, so {@code + * Executors.newVirtualThreadPerTaskExecutor()} is looked up reflectively. + * + *

    The JDK provides no virtual thread backed {@link + * java.util.concurrent.ScheduledExecutorService} (the Loom runtime itself uses a platform thread + * scheduler to unpark timed out virtual threads), so the scheduled variant, see {@link + * #newScheduledExecutor(String)}, keeps a single platform thread for the timing only and hands each + * fired task off to a virtual thread. + */ +final class VirtualThreads { + + private static final Logger log = LoggerFactory.getLogger(VirtualThreads.class); + + /** The first Java version virtual threads are supported on. */ + static final int MINIMUM_SUPPORTED_JAVA_VERSION = 25; + + private static final MethodHandle NEW_VIRTUAL_THREAD_PER_TASK_EXECUTOR = lookupFactoryMethod(); + private static final AtomicBoolean UNSUPPORTED_WARNING_LOGGED = new AtomicBoolean(); + + private VirtualThreads() {} + + private static MethodHandle lookupFactoryMethod() { + try { + return MethodHandles.publicLookup() + .findStatic( + Executors.class, + "newVirtualThreadPerTaskExecutor", + MethodType.methodType(ExecutorService.class)); + } catch (NoSuchMethodException | IllegalAccessException e) { + log.debug("Virtual threads are not available on this JVM", e); + return null; + } + } + + /** + * Whether the JVM the operator runs on supports virtual threads, i.e. is Java {@value + * #MINIMUM_SUPPORTED_JAVA_VERSION} or later. + */ + static boolean isSupported() { + return isSupported(Runtime.version().feature()); + } + + static boolean isSupported(int javaFeatureVersion) { + return NEW_VIRTUAL_THREAD_PER_TASK_EXECUTOR != null + && javaFeatureVersion >= MINIMUM_SUPPORTED_JAVA_VERSION; + } + + /** + * Whether virtual threads should effectively be used, i.e. they were requested through {@link + * ConfigurationService#useVirtualThreads()} and the JVM supports them. Requesting them + * on a JVM that doesn't support them is only warned about, so that the same configuration can be + * used regardless of the Java version the operator ends up running on, the only consequence being + * that platform threads are used instead. Concurrency limits are enforced either way. + */ + static boolean shouldUse(boolean requested) { + if (!requested || isSupported()) { + return requested; + } + if (UNSUPPORTED_WARNING_LOGGED.compareAndSet(false, true)) { + log.warn( + "Virtual threads were requested but are only supported on Java {} or later, and the JVM" + + " in use is Java {}. Falling back to platform threads.", + MINIMUM_SUPPORTED_JAVA_VERSION, + Runtime.version().feature()); + } + return false; + } + + /** An unbounded executor starting a new virtual thread for each submitted task. */ + static ExecutorService newVirtualThreadPerTaskExecutor() { + if (!isSupported()) { + throw new OperatorException( + "Virtual threads are only supported on Java " + + MINIMUM_SUPPORTED_JAVA_VERSION + + " or later"); + } + try { + return (ExecutorService) NEW_VIRTUAL_THREAD_PER_TASK_EXECUTOR.invokeExact(); + } catch (Throwable e) { + throw new OperatorException("Couldn't create a virtual thread per task executor", e); + } + } + + /** + * Supplies the task executor of the default {@link io.fabric8.kubernetes.client.KubernetesClient} + * created by {@link ConfigurationService#getKubernetesClient()}: an unbounded virtual thread + * executor, replacing the client's default cached platform thread pool, that is shut down when + * the client is closed. + */ + static ExecutorSupplier newKubernetesClientTaskExecutorSupplier() { + return new ExecutorSupplier() { + @Override + public Executor get() { + return newVirtualThreadPerTaskExecutor(); + } + + @Override + public void onClose(Executor executor) { + ((ExecutorService) executor).shutdownNow(); + } + }; + } + + /** + * A {@link ScheduledExecutorService} running the tasks it fires on virtual threads, without + * limiting how many of them run at the same time. The timing is done by a single daemon platform + * thread named after {@code threadNamePrefix}, which only hands the tasks off. + */ + static ScheduledExecutorService newScheduledExecutor(String threadNamePrefix) { + return new VirtualThreadScheduledExecutor(newVirtualThreadPerTaskExecutor(), threadNamePrefix); + } + + /** + * A virtual thread based executor executing at most {@code maxConcurrency} tasks at the same + * time, the equivalent of a fixed size platform thread pool. + */ + static ExecutorService newBoundedVirtualThreadExecutor(int maxConcurrency) { + if (maxConcurrency <= 0) { + throw new IllegalArgumentException("maxConcurrency must be positive: " + maxConcurrency); + } + return new BoundedExecutorService(newVirtualThreadPerTaskExecutor(), maxConcurrency); + } + + /** + * Limits how many of the tasks submitted to the wrapped executor run at the same time. + * + *

    A thread is started for each task as soon as it is submitted, the task then waits for a + * permit before it actually runs. This only makes sense with virtual threads, which are cheap + * enough to be parked in large numbers, and has the property that submitting a task never blocks + * the submitting thread, just like queuing it on a fixed size platform thread pool wouldn't. + */ + private static final class BoundedExecutorService extends AbstractExecutorService { + + private final ExecutorService delegate; + private final Semaphore permits; + private final Set pending = ConcurrentHashMap.newKeySet(); + private final Object lifecycleLock = new Object(); + + private BoundedExecutorService(ExecutorService delegate, int maxConcurrency) { + this.delegate = delegate; + this.permits = new Semaphore(maxConcurrency, true); + } + + @Override + public void execute(Runnable command) { + Objects.requireNonNull(command); + var task = new PendingTask(command); + // admission is closed under the same lock that shutdownNow drains pending tasks with, so a + // task is either rejected or seen by the drain, and never interrupted while unaccounted for + synchronized (lifecycleLock) { + pending.add(task); + try { + delegate.execute(task); + } catch (RuntimeException e) { + pending.remove(task); + throw e; + } + } + } + + private final class PendingTask implements Runnable { + + private final Runnable command; + private final AtomicBoolean claimed = new AtomicBoolean(); + + private PendingTask(Runnable command) { + this.command = command; + } + + private boolean claim() { + return claimed.compareAndSet(false, true); + } + + @Override + public void run() { + try { + permits.acquire(); + } catch (InterruptedException e) { + // shutdownNow interrupted us and already handed the task back to its caller + Thread.currentThread().interrupt(); + return; + } + try { + if (!claim()) { + return; + } + pending.remove(this); + command.run(); + } finally { + permits.release(); + } + } + } + + @Override + public void shutdown() { + delegate.shutdown(); + } + + @Override + public List shutdownNow() { + var notStarted = new ArrayList(); + synchronized (lifecycleLock) { + for (var task : pending) { + if (task.claim()) { + pending.remove(task); + notStarted.add(task.command); + } + } + delegate.shutdownNow(); + } + return notStarted; + } + + @Override + public boolean isShutdown() { + return delegate.isShutdown(); + } + + @Override + public boolean isTerminated() { + return delegate.isTerminated(); + } + + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { + return delegate.awaitTermination(timeout, unit); + } + } +} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/external/PollingDependentResource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/external/PollingDependentResource.java index 894e359d57..a524fc2ec1 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/external/PollingDependentResource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/external/PollingDependentResource.java @@ -55,6 +55,7 @@ protected ExternalResourceCachingEventSource createEventSource( EventSourceContext

    context) { return new PollingEventSource<>( resourceType(), + context, new PollingConfiguration<>(name(), this, getPollingPeriod(), resourceIDMapper)); } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSourceManager.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSourceManager.java index d553d14cf9..bd5222fbbb 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSourceManager.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSourceManager.java @@ -55,7 +55,9 @@ public class EventSourceManager

    public EventSourceManager(Controller

    controller) { this( controller, - new EventSources<>(controller.getConfiguration().triggerReconcilerOnAllEvents())); + new EventSources<>( + controller.getConfiguration().triggerReconcilerOnAllEvents(), + () -> controller.getExecutorServiceManager().retryAndRescheduleExecutorService())); } EventSourceManager(Controller

    controller, EventSources

    eventSources) { diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSources.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSources.java index b482d26dca..2e8a523de0 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSources.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSources.java @@ -23,6 +23,8 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentNavigableMap; import java.util.concurrent.ConcurrentSkipListMap; +import java.util.concurrent.ScheduledExecutorService; +import java.util.function.Supplier; import java.util.stream.Stream; import io.fabric8.kubernetes.api.model.HasMetadata; @@ -41,8 +43,17 @@ class EventSources

    { private ControllerEventSource

    controllerEventSource; public EventSources(boolean triggerReconcilerOnAllEvents) { + this(triggerReconcilerOnAllEvents, null); + } + + public EventSources( + boolean triggerReconcilerOnAllEvents, + Supplier scheduledExecutorServiceSupplier) { retryAndRescheduleTimerEventSource = - new TimerEventSource<>("RetryAndRescheduleTimerEventSource", triggerReconcilerOnAllEvents); + new TimerEventSource<>( + "RetryAndRescheduleTimerEventSource", + triggerReconcilerOnAllEvents, + scheduledExecutorServiceSupplier); } EventSources() { diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingConfiguration.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingConfiguration.java index 599647ff29..4f184bd94e 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingConfiguration.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingConfiguration.java @@ -18,12 +18,16 @@ import java.time.Duration; import java.util.Objects; import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.function.Predicate; import io.fabric8.kubernetes.api.model.HasMetadata; import io.javaoperatorsdk.operator.processing.ResourceIDMapper; +/** + * @param executorService the executor to run the polls on, {@code null} (the default) to have the + * event source create one of its own, on virtual threads if enabled, which it shuts down when + * stopped. A provided executor is not shut down by the event source. + */ public record PerResourcePollingConfiguration( String name, ScheduledExecutorService executorService, @@ -32,6 +36,11 @@ public record PerResourcePollingConfiguration( Predicate

    registerPredicate, Duration defaultPollingPeriod) { + /** + * @deprecated not used anymore, the event source creates an executor of its own unless one is + * explicitly configured + */ + @Deprecated(forRemoval = true) public static final int DEFAULT_EXECUTOR_THREAD_NUMBER = 1; public PerResourcePollingConfiguration( @@ -42,10 +51,7 @@ public PerResourcePollingConfiguration( Predicate

    registerPredicate, Duration defaultPollingPeriod) { this.name = name; - this.executorService = - executorService == null - ? new ScheduledThreadPoolExecutor(DEFAULT_EXECUTOR_THREAD_NUMBER) - : executorService; + this.executorService = executorService; this.resourceIDMapper = resourceIDMapper == null ? ResourceIDMapper.resourceIdProviderMapper() : resourceIDMapper; this.resourceFetcher = Objects.requireNonNull(resourceFetcher); diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingConfigurationBuilder.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingConfigurationBuilder.java index 6fcf5d2678..115d3ee9f3 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingConfigurationBuilder.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingConfigurationBuilder.java @@ -39,6 +39,14 @@ public PerResourcePollingConfigurationBuilder( this.defaultPollingPeriod = defaultPollingPeriod; } + /** + * Runs the polls on the specified executor instead of the one the event source creates by + * default. Note that an explicitly provided executor is not managed by the operator: it is the + * caller's responsibility to shut it down. It can be shared between event sources. + * + * @param executorService the executor to run the polls on + * @return this builder for chained customization + */ @SuppressWarnings("unused") public PerResourcePollingConfigurationBuilder withExecutorService( ScheduledExecutorService executorService) { diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSource.java index 1ab750d8f0..10c8cba913 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSource.java @@ -31,6 +31,8 @@ import io.fabric8.kubernetes.api.model.HasMetadata; import io.javaoperatorsdk.operator.OperatorException; +import io.javaoperatorsdk.operator.api.config.ConfigurationService; +import io.javaoperatorsdk.operator.api.config.ExecutorServiceManager; import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; import io.javaoperatorsdk.operator.processing.event.ResourceID; import io.javaoperatorsdk.operator.processing.event.source.Cache; @@ -56,11 +58,19 @@ public class PerResourcePollingEventSource private final Cache

    primaryResourceCache; private final Set fetchedForPrimaries = ConcurrentHashMap.newKeySet(); - private final ScheduledExecutorService executorService; + private final ScheduledExecutorService configuredExecutorService; + private final boolean useVirtualThreads; + private final boolean ownsExecutorService; private final ResourceFetcher resourceFetcher; private final Predicate

    registerPredicate; private final Duration period; + private volatile ScheduledExecutorService executorService; + + // incremented on every stop, to tell the polls of previous runs apart, which can outlive the + // stop when the fetcher ignores the interruption; guarded by this + private long lifecycleGeneration; + public PerResourcePollingEventSource( Class resourceClass, EventSourceContext

    context, @@ -69,20 +79,87 @@ public PerResourcePollingEventSource( this.primaryResourceCache = context.getPrimaryCache(); this.resourceFetcher = config.resourceFetcher(); this.registerPredicate = config.registerPredicate(); - this.executorService = config.executorService(); + this.configuredExecutorService = config.executorService(); + var configurationService = configurationServiceOf(context); + this.useVirtualThreads = + configurationService != null && configurationService.useVirtualThreads(); + this.ownsExecutorService = configuredExecutorService == null; this.period = config.defaultPollingPeriod(); } + /** + * The configuration of the operator the event source belongs to, or {@code null} if it doesn't + * belong to one, which only happens when the event source is used standalone, outside an + * operator. + */ + private static ConfigurationService configurationServiceOf(EventSourceContext context) { + final var controllerConfiguration = context.getControllerConfiguration(); + return controllerConfiguration == null + ? null + : controllerConfiguration.getConfigurationService(); + } + + @Override + public void start() throws OperatorException { + if (isRunning()) { + return; + } + executorService = resolveExecutorService(); + super.start(); + // the primary informer is started before this event source, and the executor to poll on is + // only resolved when this one starts, so the resources seen in the meantime are registered now + primaryResourceCache.list().forEach(this::checkAndRegisterTask); + } + + /** + * Resolves the executor to poll on. Note that this happens on every start, since an executor + * created by this event source is shut down when it is stopped. + */ + private ScheduledExecutorService resolveExecutorService() { + if (configuredExecutorService != null) { + return configuredExecutorService; + } + return ExecutorServiceManager.newScheduledExecutorService( + 1, useVirtualThreads, "josdk-polling-" + name()); + } + private Set getAndCacheResource(P primary, boolean fromGetter) { var values = resourceFetcher.fetchResources(primary); + cacheResources(primary, values, fromGetter); + return values; + } + + private void cacheResources(P primary, Set values, boolean fromGetter) { var primaryID = ResourceID.fromResource(primary); handleResources(primaryID, values, !fromGetter); fetchedForPrimaries.add(primaryID); - return values; + } + + // the polling of a resource that is gone ends with its last task, which would otherwise stay + // registered and keep the resource from being polled again if it is recreated + private synchronized void forgetTask(ResourceID primaryID, long generation) { + if (generation == lifecycleGeneration) { + scheduledFutures.remove(primaryID); + } + } + + // a fetch ignoring the interruption of a stop can return after a restart, its result is not to + // overwrite what the polls of the new run cached in the meantime + private synchronized void cacheAndScheduleNextExecution( + P primary, Set values, long generation) { + if (generation != lifecycleGeneration) { + return; + } + cacheResources(primary, values, false); + scheduleNextExecution(primary, values, generation); } @SuppressWarnings("unchecked") - private void scheduleNextExecution(P primary, Set actualResources) { + private synchronized void scheduleNextExecution( + P primary, Set actualResources, long generation) { + if (generation != lifecycleGeneration) { + return; + } var primaryID = ResourceID.fromResource(primary); var fetchDelay = resourceFetcher.fetchDelay(actualResources, primary); var fetchDuration = fetchDelay.orElse(period); @@ -90,7 +167,9 @@ private void scheduleNextExecution(P primary, Set actualResources) { ScheduledFuture scheduledFuture = (ScheduledFuture) executorService.schedule( - new FetchingExecutor(primaryID), fetchDuration.toMillis(), TimeUnit.MILLISECONDS); + new FetchingExecutor(primaryID, generation), + fetchDuration.toMillis(), + TimeUnit.MILLISECONDS); scheduledFutures.put(primaryID, scheduledFuture); } @@ -105,7 +184,7 @@ public void onResourceUpdated(P newResource, P oldResource) { } @Override - public void onResourceDeleted(P resource) { + public synchronized void onResourceDeleted(P resource) { var resourceID = ResourceID.fromResource(resource); var scheduledFuture = scheduledFutures.remove(resourceID); if (scheduledFuture != null) { @@ -119,7 +198,12 @@ public void onResourceDeleted(P resource) { // This method is always called from the same Thread for the same resource, // since events from ResourceEventAware are propagated from the thread of the informer. This is // important because otherwise there will be a race condition related to the timerTasks. - private void checkAndRegisterTask(P resource) { + private synchronized void checkAndRegisterTask(P resource) { + // stop() clears the running flag before it takes the monitor, so a registration that raced it + // is dropped, otherwise a task scheduled after the stop would block a restart + if (!isRunning()) { + return; + } var primaryID = ResourceID.fromResource(resource); if (scheduledFutures.get(primaryID) == null && (registerPredicate == null || registerPredicate.test(resource))) { @@ -127,15 +211,17 @@ private void checkAndRegisterTask(P resource) { var actualResources = cachedResources.isEmpty() ? null : cachedResources; // note that there is a delay, to not do two fetches when the resources first appeared // and getSecondaryResource is called on reconciliation. - scheduleNextExecution(resource, actualResources); + scheduleNextExecution(resource, actualResources, lifecycleGeneration); } } private class FetchingExecutor implements Runnable { private final ResourceID primaryID; + private final long generation; - public FetchingExecutor(ResourceID primaryID) { + public FetchingExecutor(ResourceID primaryID, long generation) { this.primaryID = primaryID; + this.generation = generation; } @Override @@ -149,9 +235,10 @@ public void run() { if (primary.isEmpty()) { log.warn("No resource in cache for resource ID: {}", primaryID); // no new execution is scheduled in this case, an on delete event should be received shortly + forgetTask(primaryID, generation); } else { - var actualResources = primary.map(p -> getAndCacheResource(p, false)); - scheduleNextExecution(primary.get(), actualResources.orElse(null)); + var values = resourceFetcher.fetchResources(primary.get()); + cacheAndScheduleNextExecution(primary.get(), values, generation); } } } @@ -202,6 +289,15 @@ default Optional fetchDelay(Set lastFetchedResource, P primary) { @Override public void stop() throws OperatorException { super.stop(); - executorService.shutdownNow(); + // the tasks have to be cancelled explicitly since a provided executor is not shut down, and the + // map cleared so that they are registered again on a restart + synchronized (this) { + lifecycleGeneration++; + scheduledFutures.values().forEach(future -> future.cancel(true)); + scheduledFutures.clear(); + } + if (ownsExecutorService && executorService != null) { + executorService.shutdownNow(); + } } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingConfiguration.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingConfiguration.java index 9ac1b8cc96..6ca904eca1 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingConfiguration.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingConfiguration.java @@ -17,24 +17,41 @@ import java.time.Duration; import java.util.Objects; +import java.util.concurrent.ScheduledExecutorService; import io.javaoperatorsdk.operator.processing.ResourceIDMapper; +/** + * @param executorService the executor to run the polls on, {@code null} (the default) to have the + * event source create one of its own, on virtual threads if enabled, which it shuts down when + * stopped. A provided executor is not shut down by the event source. + */ public record PollingConfiguration( String name, PollingEventSource.GenericResourceFetcher genericResourceFetcher, Duration period, - ResourceIDMapper resourceIDMapper) { + ResourceIDMapper resourceIDMapper, + ScheduledExecutorService executorService) { public PollingConfiguration( String name, PollingEventSource.GenericResourceFetcher genericResourceFetcher, Duration period, ResourceIDMapper resourceIDMapper) { + this(name, genericResourceFetcher, period, resourceIDMapper, null); + } + + public PollingConfiguration( + String name, + PollingEventSource.GenericResourceFetcher genericResourceFetcher, + Duration period, + ResourceIDMapper resourceIDMapper, + ScheduledExecutorService executorService) { this.name = name; this.genericResourceFetcher = Objects.requireNonNull(genericResourceFetcher); this.period = period; this.resourceIDMapper = resourceIDMapper == null ? ResourceIDMapper.resourceIdProviderMapper() : resourceIDMapper; + this.executorService = executorService; } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingConfigurationBuilder.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingConfigurationBuilder.java index 0e68876b60..d9e072bd9e 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingConfigurationBuilder.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingConfigurationBuilder.java @@ -16,6 +16,7 @@ package io.javaoperatorsdk.operator.processing.event.source.polling; import java.time.Duration; +import java.util.concurrent.ScheduledExecutorService; import io.javaoperatorsdk.operator.processing.ResourceIDMapper; @@ -24,6 +25,7 @@ public final class PollingConfigurationBuilder { private final PollingEventSource.GenericResourceFetcher genericResourceFetcher; private ResourceIDMapper resourceIDMapper; private String name; + private ScheduledExecutorService executorService; public PollingConfigurationBuilder( PollingEventSource.GenericResourceFetcher fetcher, Duration period) { @@ -42,7 +44,23 @@ public PollingConfigurationBuilder withName(String name) { return this; } + /** + * Runs the polls on the specified executor instead of the one the event source creates by + * default. Note that an explicitly provided executor is not managed by the operator: it is the + * caller's responsibility to shut it down. It can be shared between event sources. + * + * @param executorService the executor to run the polls on + * @return this builder for chained customization + * @since 5.7.0 + */ + public PollingConfigurationBuilder withExecutorService( + ScheduledExecutorService executorService) { + this.executorService = executorService; + return this; + } + public PollingConfiguration build() { - return new PollingConfiguration<>(name, genericResourceFetcher, period, resourceIDMapper); + return new PollingConfiguration<>( + name, genericResourceFetcher, period, resourceIDMapper, executorService); } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingEventSource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingEventSource.java index 5c85c24f90..a33e6cb44e 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingEventSource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingEventSource.java @@ -18,8 +18,10 @@ import java.time.Duration; import java.util.Map; import java.util.Set; -import java.util.Timer; -import java.util.TimerTask; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; @@ -27,6 +29,9 @@ import io.fabric8.kubernetes.api.model.HasMetadata; import io.javaoperatorsdk.operator.OperatorException; +import io.javaoperatorsdk.operator.api.config.ConfigurationService; +import io.javaoperatorsdk.operator.api.config.ExecutorServiceManager; +import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; import io.javaoperatorsdk.operator.health.Status; import io.javaoperatorsdk.operator.processing.event.ResourceID; import io.javaoperatorsdk.operator.processing.event.source.ExternalResourceCachingEventSource; @@ -62,45 +67,128 @@ public class PollingEventSource private static final Logger log = LoggerFactory.getLogger(PollingEventSource.class); - private Timer timer; private final GenericResourceFetcher genericResourceFetcher; private final Duration period; private final AtomicBoolean healthy = new AtomicBoolean(true); + private final ScheduledExecutorService configuredExecutorService; + private final boolean useVirtualThreads; + private final boolean ownsExecutorService; + private volatile ScheduledExecutorService executorService; + private volatile ScheduledFuture pollingTask; + + /** + * Creates an event source polling on an executor of its own: the one provided by the + * configuration, or otherwise one it creates and shuts down itself, which runs on virtual threads + * if {@link ConfigurationService#useVirtualThreads()} is enabled. + * + * @param resourceClass the type of the polled resource + * @param context the context this event source is created for + * @param config the configuration of the polling + * @since 5.7.0 + */ + public PollingEventSource( + Class resourceClass, EventSourceContext

    context, PollingConfiguration config) { + this(resourceClass, config, configurationServiceOf(context)); + } + + /** + * @deprecated use {@link #PollingEventSource(Class, EventSourceContext, PollingConfiguration)} + * instead: without a context, and unless the configuration provides an executor, this event + * source polls on a platform thread even if the operator is configured to use virtual + * threads. + */ + @Deprecated(since = "5.7.0") public PollingEventSource(Class resourceClass, PollingConfiguration config) { + this(resourceClass, config, null); + } + + private PollingEventSource( + Class resourceClass, + PollingConfiguration config, + ConfigurationService configurationService) { super(config.name(), resourceClass, config.resourceIDMapper()); this.genericResourceFetcher = config.genericResourceFetcher(); this.period = config.period(); + this.configuredExecutorService = config.executorService(); + this.useVirtualThreads = + configurationService != null && configurationService.useVirtualThreads(); + this.ownsExecutorService = configuredExecutorService == null; + } + + /** + * The configuration of the operator the event source belongs to, or {@code null} if it doesn't + * belong to one, which only happens when the event source is used standalone, outside an + * operator. + */ + private static ConfigurationService configurationServiceOf(EventSourceContext context) { + final var controllerConfiguration = context.getControllerConfiguration(); + return controllerConfiguration == null + ? null + : controllerConfiguration.getConfigurationService(); } @Override public void start() throws OperatorException { - if (timer != null) { + if (pollingTask != null) { return; } super.start(); + executorService = resolveExecutorService(); getStateAndFillCache(); - timer = new Timer(true); - timer.schedule( - new TimerTask() { - @Override - public void run() { - try { - if (!isRunning()) { - log.debug("Event source not yet started. Will not run."); - return; - } - getStateAndFillCache(); - healthy.set(true); - } catch (Exception e) { - // Exception is required because of Kotlin - healthy.set(false); - log.error("Error during polling.", e); - } - } - }, - period.toMillis(), - period.toMillis()); + schedulePolling(); + } + + private void schedulePolling() { + ScheduledFuture task; + try { + task = + executorService.scheduleWithFixedDelay( + this::poll, period.toMillis(), period.toMillis(), TimeUnit.MILLISECONDS); + } catch (RejectedExecutionException e) { + // a stop during the initial fetch shut down the executor this event source owns + if (isRunning()) { + throw e; + } + return; + } + pollingTask = task; + // stop() clears the running flag before it looks for the task, so a stop that happened during + // the initial fetch is either seen by stop (which cancels the task) or caught here + if (!isRunning()) { + task.cancel(false); + pollingTask = null; + if (ownsExecutorService) { + executorService.shutdown(); + } + } + } + + private void poll() { + try { + if (!isRunning()) { + log.debug("Event source not yet started. Will not run."); + return; + } + getStateAndFillCache(); + healthy.set(true); + } catch (Exception e) { + // Exception is required because of Kotlin + healthy.set(false); + log.error("Error during polling.", e); + } + } + + /** + * Resolves the executor to poll on. Note that this happens on every start, since an executor + * created by this event source is shut down when it is stopped. + */ + private ScheduledExecutorService resolveExecutorService() { + if (configuredExecutorService != null) { + return configuredExecutorService; + } + return ExecutorServiceManager.newScheduledExecutorService( + 1, useVirtualThreads, "josdk-polling-" + name()); } protected synchronized void getStateAndFillCache() { @@ -115,9 +203,13 @@ public interface GenericResourceFetcher { @Override public void stop() throws OperatorException { super.stop(); - if (timer != null) { - timer.cancel(); - timer = null; + if (pollingTask != null) { + // as with the java.util.Timer this replaces, an ongoing poll is left to finish + pollingTask.cancel(false); + pollingTask = null; + } + if (ownsExecutorService && executorService != null) { + executorService.shutdown(); } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/timer/TimerEventSource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/timer/TimerEventSource.java index eae9663fe6..c244242a62 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/timer/TimerEventSource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/timer/TimerEventSource.java @@ -17,14 +17,20 @@ import java.util.Map; import java.util.Set; -import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.fabric8.kubernetes.api.model.HasMetadata; +import io.javaoperatorsdk.operator.ExecutorUtilsInternal; import io.javaoperatorsdk.operator.api.reconciler.BaseControl; import io.javaoperatorsdk.operator.health.Status; import io.javaoperatorsdk.operator.processing.event.Event; @@ -36,17 +42,41 @@ public class TimerEventSource extends AbstractEventSource implements ResourceEventAware { private static final Logger log = LoggerFactory.getLogger(TimerEventSource.class); - private Timer timer; - private final Map onceTasks = new ConcurrentHashMap<>(); + private final Map> onceTasks = new ConcurrentHashMap<>(); + private final Supplier executorServiceSupplier; + private final boolean ownsExecutorService; private boolean triggerReconcilerOnAllEvents; + private volatile ScheduledExecutorService executorService; public TimerEventSource() { super(Void.class); + this.executorServiceSupplier = null; + this.ownsExecutorService = true; } public TimerEventSource(String name, boolean triggerReconcilerOnAllEvents) { + this(name, triggerReconcilerOnAllEvents, null); + } + + /** + * Creates an event source scheduling on the executor provided by the specified supplier. The + * supplier is called on every start, and not once at creation time, since the operator shuts its + * executors down when it is stopped and creates new ones if it is started again. + * + * @param name the name of the event source + * @param triggerReconcilerOnAllEvents whether the reconciler is triggered on all events + * @param executorServiceSupplier supplies the executor to schedule on, {@code null} to have the + * event source create, and shut down, an executor of its own + * @since 5.7.0 + */ + public TimerEventSource( + String name, + boolean triggerReconcilerOnAllEvents, + Supplier executorServiceSupplier) { super(Void.class, name); this.triggerReconcilerOnAllEvents = triggerReconcilerOnAllEvents; + this.executorServiceSupplier = executorServiceSupplier; + this.ownsExecutorService = executorServiceSupplier == null; } @SuppressWarnings("unused") @@ -55,19 +85,40 @@ public void scheduleOnce(R resource, long delay) { } public void scheduleOnce(ResourceID resourceID, long delay) { - if (!isRunning()) { + final var executor = executorService; + if (!isRunning() || executor == null) { throw new IllegalStateException("The TimerEventSource is not running"); } - if (onceTasks.containsKey(resourceID)) { + if (delay == BaseControl.INSTANT_RESCHEDULE) { cancelOnceSchedule(resourceID); + new EventProducerTimeTask(resourceID).run(); + return; } - EventProducerTimeTask task = new EventProducerTimeTask(resourceID); - if (delay == BaseControl.INSTANT_RESCHEDULE) { - task.run(); - } else { - onceTasks.put(resourceID, task); - timer.schedule(task, delay); + + var scheduled = new AtomicReference>(); + try { + onceTasks.compute( + resourceID, + (id, alreadyScheduled) -> { + if (alreadyScheduled != null) { + alreadyScheduled.cancel(false); + } + var future = + executor.schedule(new EventProducerTimeTask(id), delay, TimeUnit.MILLISECONDS); + scheduled.set(future); + return future; + }); + } catch (RejectedExecutionException e) { + if (isRunning()) { + throw e; + } + throw new IllegalStateException("The TimerEventSource is not running", e); + } + // stop() clears the running flag before cancelling the tasks, so a task that got registered + // concurrently with it is either cancelled by stop, or withdrawn here + if (!isRunning() && onceTasks.remove(resourceID, scheduled.get())) { + scheduled.get().cancel(false); } } @@ -81,26 +132,42 @@ public void onResourceDeleted(R resource) { } public void cancelOnceSchedule(ResourceID customResourceUid) { - TimerTask timerTask = onceTasks.remove(customResourceUid); - if (timerTask != null) { - timerTask.cancel(); + var scheduled = onceTasks.remove(customResourceUid); + if (scheduled != null) { + // as with the java.util.TimerTask this replaces, a task that is already running is left to + // finish + scheduled.cancel(false); } } @Override public void start() { + // the operator replaces its executors when it is started again, which can happen while this + // event source keeps running, when a previous start failed after it started. The timers + // pending on the replaced executor are not scheduled again. + if (!isRunning() || !ownsExecutorService) { + executorService = resolveExecutorService(); + } if (!isRunning()) { super.start(); - timer = new Timer(true); } } + private ScheduledExecutorService resolveExecutorService() { + if (executorServiceSupplier != null) { + return executorServiceSupplier.get(); + } + return ExecutorUtilsInternal.daemonScheduledThreadPool(1, "josdk-timer-" + name()); + } + @Override public void stop() { if (isRunning()) { - onceTasks.keySet().forEach(this::cancelOnceSchedule); - timer.cancel(); super.stop(); + onceTasks.keySet().forEach(this::cancelOnceSchedule); + if (ownsExecutorService && executorService != null) { + executorService.shutdown(); + } } } diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/ExecutorUtilsInternalTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/ExecutorUtilsInternalTest.java new file mode 100644 index 0000000000..ac2775714e --- /dev/null +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/ExecutorUtilsInternalTest.java @@ -0,0 +1,53 @@ +/* + * 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; + +import java.time.Duration; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +class ExecutorUtilsInternalTest { + + @Test + void idleThreadsOfTheScheduledPoolAreLetGoButDelayedTasksStillRun() throws Exception { + var executor = + (ScheduledThreadPoolExecutor) + ExecutorUtilsInternal.daemonScheduledThreadPool(4, "idle-test"); + try { + executor.setKeepAliveTime(100, TimeUnit.MILLISECONDS); + var ran = new CountDownLatch(1); + for (int i = 0; i < 4; i++) { + executor.schedule(() -> {}, 0, TimeUnit.MILLISECONDS); + } + executor.schedule(ran::countDown, 1, TimeUnit.SECONDS); + assertThat(executor.getPoolSize()).isGreaterThan(1); + + await() + .atMost(Duration.ofSeconds(10)) + .untilAsserted(() -> assertThat(executor.getPoolSize()).isLessThanOrEqualTo(1)); + + assertThat(ran.await(10, TimeUnit.SECONDS)).isTrue(); + } finally { + executor.shutdownNow(); + } + } +} diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/VirtualThreadsStartupDeadlockTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/VirtualThreadsStartupDeadlockTest.java new file mode 100644 index 0000000000..0262e5faff --- /dev/null +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/VirtualThreadsStartupDeadlockTest.java @@ -0,0 +1,99 @@ +/* + * 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; + +import java.time.Duration; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledForJreRange; +import org.junit.jupiter.api.condition.JRE; + +import io.fabric8.kubernetes.api.model.ConfigMap; +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.Reconciler; +import io.javaoperatorsdk.operator.processing.Controller; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Starting as many controllers as there are virtual thread carriers must not deadlock. On Java 21 + * to 24 (no JEP 491) it does: each controller is started on a virtual thread of the caching + * executor that blocks, while holding the monitors of the synchronized Controller.start / + * EventSourceManager.start / ControllerEventSource.start, on informer-start tasks submitted to the + * very same virtual thread executor, and the carriers are pinned by those monitors. This is why the + * virtual thread variant only runs on Java 25 or later, the official baseline for virtual thread + * support, where the monitors don't pin the carriers anymore. + */ +class VirtualThreadsStartupDeadlockTest { + + @Test + @EnabledForJreRange(min = JRE.JAVA_25) + @SuppressWarnings({"rawtypes", "unchecked"}) + void startingControllersOnVirtualThreadsDoesNotDeadlock() throws Exception { + assertStartsWithoutDeadlock(true); + } + + @Test + void controlStartingControllersOnPlatformThreads() throws Exception { + assertStartsWithoutDeadlock(false); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + private static void assertStartsWithoutDeadlock(boolean useVirtualThreads) throws Exception { + final var mockClient = MockKubernetesClient.client(ConfigMap.class); + final ConfigurationService configService = + ConfigurationService.newOverriddenConfigurationService( + new BaseConfigurationService(), + o -> o.withKubernetesClient(mockClient).withUseVirtualThreads(useVirtualThreads)); + final var executorServiceManager = configService.getExecutorServiceManager(); + final var controllerManager = new ControllerManager(executorServiceManager); + + final int controllers = Runtime.getRuntime().availableProcessors(); + for (int i = 0; i < controllers; i++) { + final var configuration = MockControllerConfiguration.forResource(ConfigMap.class); + when(configuration.getConfigurationService()).thenReturn(configService); + when(configuration.getName()).thenReturn("controller-" + i); + controllerManager.add(new Controller(mock(Reconciler.class), configuration, mockClient)); + } + + final var start = CompletableFuture.runAsync(() -> controllerManager.start(false)); + try { + start.get(20, TimeUnit.SECONDS); + } catch (TimeoutException e) { + // break the deadlock (interrupts the pinned virtual threads) so that the shared virtual + // thread scheduler isn't left starved for the rest of the test JVM + executorServiceManager.stop(Duration.ZERO); + try { + start.get(20, TimeUnit.SECONDS); + } catch (Exception ignored) { + // expected once the stuck start was interrupted + } + assertThat(false) + .as( + "ControllerManager.start deadlocked starting %d controllers on virtual threads", + controllers) + .isTrue(); + } + executorServiceManager.stop(Duration.ZERO); + } +} diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverriderTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverriderTest.java index aec8381135..9c356b55f7 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverriderTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverriderTest.java @@ -20,6 +20,8 @@ import java.util.Optional; import java.util.Set; import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor; import org.junit.jupiter.api.Test; @@ -117,6 +119,98 @@ public R clone(R object) { config.reconciliationTerminationTimeout(), overridden.reconciliationTerminationTimeout()); } + @Test + void retryAndRescheduleExecutorCanBeOverridden() { + final var retryExecutorService = Executors.newScheduledThreadPool(1); + try { + final var overridden = + new ConfigurationServiceOverrider(config) + .withConcurrentRetryAndRescheduleThreads(5) + .withRetryAndRescheduleExecutorService(retryExecutorService) + .build(); + + assertThat(overridden.concurrentRetryAndRescheduleThreads()).isEqualTo(5); + assertThat(overridden.getRetryAndRescheduleExecutorService()).isSameAs(retryExecutorService); + } finally { + retryExecutorService.shutdownNow(); + } + } + + @Test + void executorOfTheOriginalConfigurationIsKeptUnlessItsSettingsAreOverridden() { + final var retryExecutorService = Executors.newScheduledThreadPool(1); + try { + final var original = + new BaseConfigurationService() { + @Override + public ScheduledExecutorService getRetryAndRescheduleExecutorService() { + return retryExecutorService; + } + }; + + final var overridden = + new ConfigurationServiceOverrider(original).withCloseClientOnStop(false); + + assertThat(overridden.build().getRetryAndRescheduleExecutorService()) + .isSameAs(retryExecutorService); + + final var resized = overridden.withConcurrentRetryAndRescheduleThreads(3).build(); + final var defaultRetry = resized.getRetryAndRescheduleExecutorService(); + try { + assertThat(defaultRetry).isNotSameAs(retryExecutorService); + assertThat(((ScheduledThreadPoolExecutor) defaultRetry).getCorePoolSize()).isEqualTo(3); + } finally { + defaultRetry.shutdownNow(); + } + } finally { + retryExecutorService.shutdownNow(); + } + } + + @Test + void executorOfTheOriginalConfigurationIsKeptWhenOverridesDoNotChangeItsSettings() { + final var retryExecutorService = Executors.newScheduledThreadPool(1); + try { + final var original = + new BaseConfigurationService() { + @Override + public ScheduledExecutorService getRetryAndRescheduleExecutorService() { + return retryExecutorService; + } + }; + + final var overridden = + new ConfigurationServiceOverrider(original) + .withUseVirtualThreads(original.useVirtualThreads()) + .withConcurrentRetryAndRescheduleThreads( + original.concurrentRetryAndRescheduleThreads()) + .build(); + + assertThat(overridden.getRetryAndRescheduleExecutorService()).isSameAs(retryExecutorService); + } finally { + retryExecutorService.shutdownNow(); + } + } + + @Test + void retryAndRescheduleExecutorDefaultsToADaemonPoolOfTheConfiguredSize() { + final var overridden = + (ScheduledThreadPoolExecutor) + new ConfigurationServiceOverrider(config) + .withConcurrentRetryAndRescheduleThreads(3) + .build() + .getRetryAndRescheduleExecutorService(); + + try { + assertThat(overridden.getCorePoolSize()).isEqualTo(3); + // scheduled tasks must not delay the termination of the operator, nor keep the JVM alive + assertThat(overridden.getExecuteExistingDelayedTasksAfterShutdownPolicy()).isFalse(); + assertThat(overridden.getThreadFactory().newThread(() -> {}).isDaemon()).isTrue(); + } finally { + overridden.shutdownNow(); + } + } + @Test void eventRecorderIsNotConfiguredByDefaultAndCanBeOverridden() { final var eventRecorder = @@ -152,6 +246,13 @@ void threadCountConfiguredProperly() { .isEqualTo(14); } + @Test + void virtualThreadsAreDisabledByDefaultAndCanBeOverridden() { + assertThat(config.useVirtualThreads()).isFalse(); + assertThat(new ConfigurationServiceOverrider(config).withUseVirtualThreads(true).build()) + .returns(true, ConfigurationService::useVirtualThreads); + } + @SuppressWarnings("rawtypes") @Test void dependentResourceFactoryDefaultsToTheSharedOneAndCanBeOverridden() { diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/ExecutorServiceManagerTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/ExecutorServiceManagerTest.java index 40ffded241..5105139e02 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/ExecutorServiceManagerTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/ExecutorServiceManagerTest.java @@ -18,6 +18,8 @@ import java.time.Duration; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledForJreRange; +import org.junit.jupiter.api.condition.JRE; import static org.assertj.core.api.Assertions.assertThat; @@ -26,18 +28,38 @@ class ExecutorServiceManagerTest { private static final Duration SHUTDOWN_TIMEOUT = Duration.ofMillis(100); @Test - void stopShutsDownTheScheduledExecutorService() { + @SuppressWarnings("deprecation") + void stopShutsDownTheScheduledExecutorServiceAndItIsReplacedAfterARestart() { ConfigurationService configurationService = new BaseConfigurationService(); var manager = configurationService.getExecutorServiceManager(); var scheduled = manager.scheduledExecutorService(); + assertThat(scheduled.isShutdown()).isFalse(); + manager.stop(SHUTDOWN_TIMEOUT); + assertThat(scheduled.isShutdown()).isTrue(); + + manager.start(configurationService); try { - assertThat(scheduled.isShutdown()).isFalse(); + assertThat(manager.scheduledExecutorService()).isNotSameAs(scheduled); + assertThat(manager.scheduledExecutorService().isShutdown()).isFalse(); } finally { manager.stop(SHUTDOWN_TIMEOUT); } + } - assertThat(scheduled.isShutdown()).isTrue(); + @Test + void stopShutsDownTheRetryAndRescheduleExecutorService() { + ConfigurationService configurationService = new BaseConfigurationService(); + var manager = configurationService.getExecutorServiceManager(); + var retryAndReschedule = manager.retryAndRescheduleExecutorService(); + + try { + assertThat(retryAndReschedule.isShutdown()).isFalse(); + } finally { + manager.stop(SHUTDOWN_TIMEOUT); + } + + assertThat(retryAndReschedule.isShutdown()).isTrue(); } @Test @@ -52,8 +74,24 @@ void canBeRestartedAfterStop() { // handing out already terminated executors assertThat(manager.reconcileExecutorService().isShutdown()).isFalse(); assertThat(manager.cachingExecutorService().isShutdown()).isFalse(); - assertThat(manager.scheduledExecutorService().isShutdown()).isFalse(); + assertThat(manager.retryAndRescheduleExecutorService().isShutdown()).isFalse(); manager.stop(SHUTDOWN_TIMEOUT); } + + @Test + @EnabledForJreRange(min = JRE.JAVA_25) + void cachingExecutorRunsOnVirtualThreadsWhenRequested() throws Exception { + var configurationService = + ConfigurationService.newOverriddenConfigurationService( + new BaseConfigurationService(), o -> o.withUseVirtualThreads(true)); + var manager = configurationService.getExecutorServiceManager(); + try { + var virtual = + manager.cachingExecutorService().submit(() -> VirtualThreadsTest.onVirtualThread()).get(); + assertThat(virtual).isTrue(); + } finally { + manager.stop(SHUTDOWN_TIMEOUT); + } + } } diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/VirtualThreadScheduledExecutorTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/VirtualThreadScheduledExecutorTest.java new file mode 100644 index 0000000000..a567f3e56d --- /dev/null +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/VirtualThreadScheduledExecutorTest.java @@ -0,0 +1,322 @@ +/* + * 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.api.config; + +import java.time.Duration; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Delayed; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledForJreRange; +import org.junit.jupiter.api.condition.JRE; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.awaitility.Awaitility.await; + +@EnabledForJreRange(min = JRE.JAVA_25) +class VirtualThreadScheduledExecutorTest { + + private static final int MAX_CONCURRENCY = 2; + private static final int TASKS = 10; + + private ScheduledExecutorService executor; + + @BeforeEach + void setUp() { + executor = ExecutorServiceManager.newScheduledExecutorService(MAX_CONCURRENCY, true, "test"); + } + + @AfterEach + void tearDown() { + executor.shutdownNow(); + } + + @Test + void runsDelayedTasksOnVirtualThreads() throws Exception { + var future = executor.schedule(VirtualThreadsTest::onVirtualThread, 50, TimeUnit.MILLISECONDS); + + assertThat(future.get(10, TimeUnit.SECONDS)).isTrue(); + } + + @Test + void keepsTheTimingOnADaemonPlatformThread() { + executor.schedule(() -> {}, 10, TimeUnit.MINUTES); + + assertThat(Thread.getAllStackTraces().keySet()) + .filteredOn(t -> t.getName().startsWith("test-timer")) + .isNotEmpty() + .allSatisfy(t -> assertThat(t.isDaemon()).isTrue()); + } + + @Test + void delayedTasksDoNotRunEarly() throws Exception { + var start = System.nanoTime(); + + executor.schedule(() -> {}, 200, TimeUnit.MILLISECONDS).get(10, TimeUnit.SECONDS); + + assertThat(Duration.ofNanos(System.nanoTime() - start)) + .isGreaterThanOrEqualTo(Duration.ofMillis(190)); + } + + @Test + void cancellingBeforeTheTaskFiresPreventsIt() throws Exception { + var ran = new AtomicBoolean(); + var future = executor.schedule(() -> ran.set(true), 200, TimeUnit.MILLISECONDS); + + assertThat(future.cancel(false)).isTrue(); + + assertThat(future.isCancelled()).isTrue(); + assertThatExceptionOfType(CancellationException.class).isThrownBy(future::get); + Thread.sleep(400); + assertThat(ran).isFalse(); + } + + @Test + void propagatesTheFailureOfATask() { + var future = + executor.schedule( + () -> { + throw new IllegalStateException("failed"); + }, + 0, + TimeUnit.MILLISECONDS); + + assertThatExceptionOfType(ExecutionException.class) + .isThrownBy(() -> future.get(10, TimeUnit.SECONDS)) + .withCauseInstanceOf(IllegalStateException.class); + } + + @Test + void repeatsTasksWithAFixedDelayUntilCancelled() { + var runs = new AtomicInteger(); + var onVirtualThread = new AtomicBoolean(true); + + var future = + executor.scheduleWithFixedDelay( + () -> { + onVirtualThread.compareAndSet(true, VirtualThreadsTest.onVirtualThread()); + runs.incrementAndGet(); + }, + 0, + 20, + TimeUnit.MILLISECONDS); + + await() + .atMost(Duration.ofSeconds(10)) + .untilAsserted(() -> assertThat(runs).hasValueGreaterThan(3)); + assertThat(future.cancel(false)).isTrue(); + var runsAtCancel = runs.get(); + await() + .pollDelay(Duration.ofMillis(200)) + .untilAsserted(() -> assertThat(runs.get()).isLessThanOrEqualTo(runsAtCancel + 1)); + assertThat(onVirtualThread).isTrue(); + } + + @Test + void repeatsTasksAtAFixedRate() { + var runs = new AtomicInteger(); + + executor.scheduleAtFixedRate(runs::incrementAndGet, 0, 20, TimeUnit.MILLISECONDS); + + await() + .atMost(Duration.ofSeconds(10)) + .untilAsserted(() -> assertThat(runs).hasValueGreaterThan(3)); + } + + @Test + void scheduledFuturesAreOrderedConsistentlyByTheirDeadline() { + var first = (Delayed) executor.schedule(() -> {}, 10, TimeUnit.SECONDS); + var second = (Delayed) executor.schedule(() -> {}, 10, TimeUnit.SECONDS); + var later = (Delayed) executor.schedule(() -> {}, 20, TimeUnit.SECONDS); + + assertThat(first.compareTo(first)).isZero(); + assertThat(first.compareTo(later)).isNegative(); + assertThat(later.compareTo(first)).isPositive(); + assertThat(first.compareTo(second)).isLessThanOrEqualTo(0); + // comparing the futures must not depend on when it happens, i.e. on the remaining delays + for (int i = 0; i < 10_000; i++) { + assertThat(Integer.signum(first.compareTo(second))) + .isEqualTo(-Integer.signum(second.compareTo(first))); + } + } + + @Test + void aFixedRateTaskCatchesUpAfterAnOverrun() { + var starts = new CopyOnWriteArrayList(); + var firstRunEnd = new AtomicLong(); + + executor.scheduleAtFixedRate( + () -> { + starts.add(System.nanoTime()); + if (starts.size() == 1) { + try { + Thread.sleep(350); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + firstRunEnd.set(System.nanoTime()); + } + }, + 0, + 100, + TimeUnit.MILLISECONDS); + + await() + .atMost(Duration.ofSeconds(10)) + .untilAsserted(() -> assertThat(starts).hasSizeGreaterThanOrEqualTo(4)); + // the three executions missed during the first run are made up for right after it, instead of + // being skipped, which would space the fourth one a full period behind the third + assertThat(Duration.ofNanos(starts.get(3) - firstRunEnd.get())) + .isLessThan(Duration.ofMillis(150)); + } + + @Test + void aFailingPeriodicTaskIsNotRepeated() { + var runs = new AtomicInteger(); + + var future = + executor.scheduleWithFixedDelay( + () -> { + runs.incrementAndGet(); + throw new IllegalStateException("failed"); + }, + 0, + 20, + TimeUnit.MILLISECONDS); + + assertThatExceptionOfType(ExecutionException.class) + .isThrownBy(() -> future.get(10, TimeUnit.SECONDS)); + await().pollDelay(Duration.ofMillis(200)).untilAsserted(() -> assertThat(runs).hasValue(1)); + } + + @Test + void doesNotLimitTheNumberOfTasksRunningAtTheSameTime() throws Exception { + var allStarted = new CountDownLatch(TASKS); + var done = new CountDownLatch(TASKS); + for (int i = 0; i < TASKS; i++) { + executor.schedule( + () -> { + allStarted.countDown(); + try { + // only returns if all the tasks are running at the same time, which with more tasks + // than the (platform thread) concurrency would never be the case if it was limited + if (allStarted.await(30, TimeUnit.SECONDS)) { + done.countDown(); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }, + 0, + TimeUnit.MILLISECONDS); + } + + assertThat(done.await(30, TimeUnit.SECONDS)).isTrue(); + } + + @Test + void shutdownDiscardsTasksScheduledForLaterAndRejectsNewOnes() throws Exception { + var ran = new AtomicBoolean(); + var later = executor.schedule(() -> ran.set(true), 10, TimeUnit.MINUTES); + var periodic = executor.scheduleWithFixedDelay(() -> {}, 10, 10, TimeUnit.MINUTES); + + executor.shutdown(); + + assertThat(later.isCancelled()).isTrue(); + assertThat(periodic.isCancelled()).isTrue(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + assertThat(ran).isFalse(); + assertThatExceptionOfType(RejectedExecutionException.class) + .isThrownBy(() -> executor.schedule(() -> {}, 0, TimeUnit.MILLISECONDS)); + } + + @Test + void shutdownLetsStartedTasksFinish() throws Exception { + var started = new CountDownLatch(1); + var finished = new AtomicBoolean(); + var future = + executor.schedule( + () -> { + started.countDown(); + Thread.sleep(200); + finished.set(true); + return true; + }, + 0, + TimeUnit.MILLISECONDS); + assertThat(started.await(10, TimeUnit.SECONDS)).isTrue(); + + executor.shutdown(); + + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + assertThat(future.get()).isTrue(); + assertThat(finished).isTrue(); + } + + @Test + void shutdownNowInterruptsRunningTasks() throws Exception { + var started = new CountDownLatch(1); + var interrupted = new CountDownLatch(1); + executor.schedule( + () -> { + started.countDown(); + try { + Thread.sleep(60_000); + } catch (InterruptedException e) { + interrupted.countDown(); + } + }, + 0, + TimeUnit.MILLISECONDS); + assertThat(started.await(10, TimeUnit.SECONDS)).isTrue(); + + executor.shutdownNow(); + + assertThat(interrupted.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + } + + @Test + void theOperatorsDefaultRetryAndRescheduleExecutorRunsOnVirtualThreadsWhenRequested() + throws Exception { + var configurationService = + ConfigurationService.newOverriddenConfigurationService( + new BaseConfigurationService(), o -> o.withUseVirtualThreads(true)); + var manager = configurationService.getExecutorServiceManager(); + try { + assertThat( + manager + .retryAndRescheduleExecutorService() + .schedule(VirtualThreadsTest::onVirtualThread, 0, TimeUnit.MILLISECONDS) + .get(10, TimeUnit.SECONDS)) + .isTrue(); + } finally { + manager.stop(Duration.ofMillis(100)); + } + } +} diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/VirtualThreadsTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/VirtualThreadsTest.java new file mode 100644 index 0000000000..349baf5247 --- /dev/null +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/VirtualThreadsTest.java @@ -0,0 +1,221 @@ +/* + * 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.api.config; + +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.IntStream; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledForJreRange; +import org.junit.jupiter.api.condition.JRE; + +import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.impl.BaseClient; + +import static org.assertj.core.api.Assertions.assertThat; + +class VirtualThreadsTest { + + private static final int MAX_CONCURRENCY = 3; + private static final int TASK_NUMBER = 20; + private static final int TIMEOUT_SECONDS = 30; + + @Test + void usesPlatformThreadPoolWhenVirtualThreadsAreNotRequested() throws Exception { + var executor = ExecutorServiceManager.newBoundedExecutorService(MAX_CONCURRENCY, false); + try { + assertThat(executor).isInstanceOf(ThreadPoolExecutor.class); + assertThat(executor.submit(VirtualThreadsTest::onVirtualThread).get()).isFalse(); + } finally { + executor.shutdownNow(); + } + } + + @Test + void virtualThreadsAreOnlySupportedFromJava25() { + assertThat(VirtualThreads.isSupported(17)).isFalse(); + assertThat(VirtualThreads.isSupported(21)).isFalse(); + assertThat(VirtualThreads.isSupported(24)).isFalse(); + assertThat(VirtualThreads.isSupported(Runtime.version().feature())) + .isEqualTo(Runtime.version().feature() >= 25); + } + + @Test + @EnabledForJreRange(max = JRE.JAVA_24) + void fallsBackToPlatformThreadsBeforeJava25() throws Exception { + var executor = ExecutorServiceManager.newBoundedExecutorService(MAX_CONCURRENCY, true); + var scheduled = ExecutorServiceManager.newScheduledExecutorService(MAX_CONCURRENCY, true, "t"); + try { + assertThat(executor).isInstanceOf(ThreadPoolExecutor.class); + assertThat(executor.submit(VirtualThreadsTest::onVirtualThread).get()).isFalse(); + assertThat(scheduled.submit(VirtualThreadsTest::onVirtualThread).get()).isFalse(); + } finally { + executor.shutdownNow(); + scheduled.shutdownNow(); + } + } + + @Test + @EnabledForJreRange(min = JRE.JAVA_25) + void usesVirtualThreadsWhenRequested() throws Exception { + var virtualExecutor = ExecutorServiceManager.newBoundedExecutorService(MAX_CONCURRENCY, true); + try { + assertThat(virtualExecutor.submit(VirtualThreadsTest::onVirtualThread).get()).isTrue(); + } finally { + virtualExecutor.shutdownNow(); + } + + var unbounded = ExecutorServiceManager.newUnboundedExecutorService(true); + try { + assertThat(unbounded.submit(VirtualThreadsTest::onVirtualThread).get()).isTrue(); + } finally { + unbounded.shutdownNow(); + } + } + + @Test + @EnabledForJreRange(min = JRE.JAVA_25) + void boundedVirtualThreadExecutorRespectsTheConfiguredConcurrency() throws Exception { + var executor = ExecutorServiceManager.newBoundedExecutorService(MAX_CONCURRENCY, true); + try { + final var running = new AtomicInteger(); + final var maxObservedConcurrency = new AtomicInteger(); + final var done = new CountDownLatch(TASK_NUMBER); + // each task gets its own (virtual) thread, only the number of concurrently running ones is + // capped + final Set usedThreads = ConcurrentHashMap.newKeySet(); + + IntStream.range(0, TASK_NUMBER) + .forEach( + i -> + executor.execute( + () -> { + usedThreads.add(Thread.currentThread()); + maxObservedConcurrency.accumulateAndGet( + running.incrementAndGet(), Math::max); + try { + Thread.sleep(50); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + running.decrementAndGet(); + done.countDown(); + } + })); + + assertThat(done.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)).isTrue(); + assertThat(maxObservedConcurrency).hasValue(MAX_CONCURRENCY); + assertThat(usedThreads).hasSize(TASK_NUMBER); + } finally { + executor.shutdownNow(); + } + } + + @Test + @EnabledForJreRange(min = JRE.JAVA_25) + void executeAndWaitForAllToCompleteRespectsTheBoundOfTheExecutor() { + var executor = ExecutorServiceManager.newBoundedExecutorService(MAX_CONCURRENCY, true); + try { + final var running = new AtomicInteger(); + final var maxObservedConcurrency = new AtomicInteger(); + + ExecutorServiceManager.executeAndWaitForAllToComplete( + IntStream.range(0, TASK_NUMBER).boxed(), + i -> { + maxObservedConcurrency.accumulateAndGet(running.incrementAndGet(), Math::max); + try { + Thread.sleep(50); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + running.decrementAndGet(); + } + return null; + }, + i -> "task-" + i, + executor); + + assertThat(maxObservedConcurrency).hasValue(MAX_CONCURRENCY); + } finally { + executor.shutdownNow(); + } + } + + @Test + @EnabledForJreRange(min = JRE.JAVA_25) + void shutdownTerminatesOnceTheAlreadySubmittedTasksAreDone() throws Exception { + ExecutorService executor = + ExecutorServiceManager.newBoundedExecutorService(MAX_CONCURRENCY, true); + final var done = new CountDownLatch(TASK_NUMBER); + + IntStream.range(0, TASK_NUMBER).forEach(i -> executor.execute(done::countDown)); + executor.shutdown(); + + assertThat(executor.awaitTermination(TIMEOUT_SECONDS, TimeUnit.SECONDS)).isTrue(); + assertThat(executor.isShutdown()).isTrue(); + assertThat(done.getCount()).isZero(); + } + + @Test + void defaultKubernetesClientKeepsPlatformThreadsWhenVirtualThreadsAreNotRequested() + throws Exception { + try (var client = defaultKubernetesClient(false)) { + assertThat(runsTasksOnVirtualThread(client)).isFalse(); + } + } + + @Test + @EnabledForJreRange(min = JRE.JAVA_25) + void defaultKubernetesClientRunsItsTasksOnVirtualThreadsWhenRequested() throws Exception { + ExecutorService executor; + try (var client = defaultKubernetesClient(true)) { + assertThat(runsTasksOnVirtualThread(client)).isTrue(); + executor = (ExecutorService) client.adapt(BaseClient.class).getExecutor(); + } + assertThat(executor.isShutdown()).isTrue(); + } + + private static KubernetesClient defaultKubernetesClient(boolean useVirtualThreads) { + return ConfigurationService.newOverriddenConfigurationService( + o -> o.withUseVirtualThreads(useVirtualThreads)) + .getKubernetesClient(); + } + + private static boolean runsTasksOnVirtualThread(KubernetesClient client) throws Exception { + return CompletableFuture.supplyAsync( + VirtualThreadsTest::onVirtualThread, client.adapt(BaseClient.class).getExecutor()) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + } + + /** + * {@code Thread.isVirtual} only exists as of Java 21 while the tests are compiled for Java 17, + * hence the reflective call. + */ + static boolean onVirtualThread() { + try { + return (Boolean) Thread.class.getMethod("isVirtual").invoke(Thread.currentThread()); + } catch (ReflectiveOperationException e) { + return false; + } + } +} diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSourceTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSourceTest.java index 907ed19fe5..f5109532d1 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSourceTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSourceTest.java @@ -19,11 +19,22 @@ import java.util.Collections; import java.util.Optional; import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledForJreRange; +import org.junit.jupiter.api.condition.JRE; 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.ControllerConfiguration; import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; import io.javaoperatorsdk.operator.processing.ResourceIDMapper; import io.javaoperatorsdk.operator.processing.event.EventHandler; @@ -88,6 +99,53 @@ void pollsTheResourceAfterAwareOfIt() { }); } + @Test + void resourcesInThePrimaryCacheArePolledOnceStarted() { + source.stop(); + setUpSource( + new PerResourcePollingEventSource<>( + SampleExternalResource.class, + context, + new PerResourcePollingConfigurationBuilder< + SampleExternalResource, TestCustomResource, String>( + supplier, Duration.ofMillis(PERIOD)) + .withResourceIDMapper(r -> r.getName() + "#" + r.getValue()) + .build()), + false); + when(resourceCache.list()).thenAnswer(i -> Stream.of(testCustomResource)); + + source.onResourceCreated(testCustomResource); + verify(supplier, never()).fetchResources(any()); + + source.start(); + + await() + .untilAsserted(() -> verify(supplier, atLeast(1)).fetchResources(eq(testCustomResource))); + } + + @Test + void resourcesDeletedBeforeStartAreNotPolled() { + source.stop(); + setUpSource( + new PerResourcePollingEventSource<>( + SampleExternalResource.class, + context, + new PerResourcePollingConfigurationBuilder< + SampleExternalResource, TestCustomResource, String>( + supplier, Duration.ofMillis(PERIOD)) + .withResourceIDMapper(r -> r.getName() + "#" + r.getValue()) + .build()), + false); + + source.onResourceCreated(testCustomResource); + source.onResourceDeleted(testCustomResource); + source.start(); + + await() + .pollDelay(Duration.ofMillis(2 * PERIOD)) + .untilAsserted(() -> verify(supplier, never()).fetchResources(any())); + } + @Test void registeringTaskOnAPredicate() { setUpSource( @@ -215,6 +273,320 @@ void supportsDynamicPollingDelay() { .untilAsserted(() -> verify(supplier, times(2)).fetchResources(any())); } + @Test + void pollsAgainAfterRestart() { + source.onResourceCreated(testCustomResource); + await().untilAsserted(() -> verify(supplier, atLeast(2)).fetchResources(any())); + source.stop(); + + source.start(); + clearInvocations(supplier); + source.onResourceCreated(testCustomResource); + + await().untilAsserted(() -> verify(supplier, atLeast(2)).fetchResources(any())); + } + + @Test + void aFetchOutlivingARestartDoesNotStartASecondPollingChain() throws Exception { + var fetching = new CountDownLatch(1); + var release = new CountDownLatch(1); + when(supplier.fetchResources(any())) + .thenAnswer( + invocation -> { + fetching.countDown(); + var interrupted = false; + while (release.getCount() > 0) { + try { + release.await(); + } catch (InterruptedException e) { + interrupted = true; + } + } + if (interrupted) { + Thread.currentThread().interrupt(); + } + return Set.of(SampleExternalResource.testResource1()); + }) + .thenReturn(Set.of(SampleExternalResource.testResource1())); + + source.onResourceCreated(testCustomResource); + assertThat(fetching.await(5, TimeUnit.SECONDS)).isTrue(); + source.stop(); + source.start(); + source.onResourceCreated(testCustomResource); + clearInvocations(supplier); + release.countDown(); + + await() + .pollDelay(Duration.ofMillis(10 * PERIOD)) + .untilAsserted(() -> verify(supplier, atMost(15)).fetchResources(any())); + } + + @Test + void aFetchOutlivingARestartDoesNotOverwriteTheCacheOfTheNewRun() throws Exception { + var fetching = new CountDownLatch(1); + var release = new CountDownLatch(1); + var oldResource = SampleExternalResource.testResource1(); + var newResource = SampleExternalResource.testResource2(); + when(supplier.fetchResources(any())) + .thenAnswer( + invocation -> { + fetching.countDown(); + var interrupted = false; + while (release.getCount() > 0) { + try { + release.await(); + } catch (InterruptedException e) { + interrupted = true; + } + } + if (interrupted) { + Thread.currentThread().interrupt(); + } + return Set.of(oldResource); + }) + .thenReturn(Set.of(newResource)); + + source.onResourceCreated(testCustomResource); + assertThat(fetching.await(5, TimeUnit.SECONDS)).isTrue(); + source.stop(); + source.start(); + source.onResourceCreated(testCustomResource); + await().untilAsserted(() -> verify(supplier, atLeast(2)).fetchResources(any())); + await() + .untilAsserted( + () -> + assertThat(source.getSecondaryResources(testCustomResource)) + .containsExactly(newResource)); + + release.countDown(); + + await() + .pollDelay(Duration.ofMillis(PERIOD / 3)) + .untilAsserted( + () -> + assertThat(source.getSecondaryResources(testCustomResource)) + .containsExactly(newResource)); + } + + @Test + void aRegistrationRacingStopDoesNotBlockPollingAfterARestart() throws Exception { + var configurationService = new BaseConfigurationService(); + var executorServiceManager = configurationService.getExecutorServiceManager(); + var controllerConfiguration = mock(ControllerConfiguration.class); + when(controllerConfiguration.getConfigurationService()).thenReturn(configurationService); + when(context.getControllerConfiguration()).thenReturn(controllerConfiguration); + setUpSource( + new PerResourcePollingEventSource<>( + SampleExternalResource.class, + context, + new PerResourcePollingConfigurationBuilder< + SampleExternalResource, TestCustomResource, String>( + supplier, Duration.ofMillis(PERIOD)) + .withResourceIDMapper(r -> r.getName() + "#" + r.getValue()) + .build())); + + try { + Thread informer; + synchronized (source) { + informer = new Thread(() -> source.onResourceCreated(testCustomResource)); + informer.start(); + await().until(() -> informer.getState() == Thread.State.BLOCKED); + source.stop(); + } + informer.join(); + executorServiceManager.stop(Duration.ofMillis(100)); + executorServiceManager.start(configurationService); + + source.start(); + clearInvocations(supplier); + source.onResourceCreated(testCustomResource); + + await().untilAsserted(() -> verify(supplier, atLeast(2)).fetchResources(any())); + } finally { + source.stop(); + executorServiceManager.stop(Duration.ofMillis(100)); + } + } + + @Test + void createsAnExecutorOfItsOwnAndShutsItDownOnStop() { + var pollingThreads = new CopyOnWriteArrayList(); + when(supplier.fetchResources(any())) + .thenAnswer( + invocation -> { + pollingThreads.add(Thread.currentThread()); + return Set.of(SampleExternalResource.testResource1()); + }); + setUpSource(eventSourceFor(new BaseConfigurationService(), null)); + + source.onResourceCreated(testCustomResource); + + await().until(() -> !pollingThreads.isEmpty()); + var pollingThread = pollingThreads.get(0); + assertThat(pollingThread.getName()).startsWith("josdk-polling-"); + assertThat(pollingThread.isDaemon()).isTrue(); + + source.stop(); + + await().untilAsserted(() -> assertThat(pollingThread.isAlive()).isFalse()); + } + + @Test + void usesANewExecutorWhenStartedAfterStop() { + setUpSource(eventSourceFor(new BaseConfigurationService(), null)); + source.onResourceCreated(testCustomResource); + await().untilAsserted(() -> verify(supplier, atLeast(2)).fetchResources(any())); + source.stop(); + clearInvocations(supplier); + + source.start(); + source.onResourceCreated(testCustomResource); + + await().untilAsserted(() -> verify(supplier, atLeast(2)).fetchResources(any())); + } + + @Test + void pollsOnTheProvidedExecutorAndLeavesItRunningOnStop() { + var pollingThreadNames = new CopyOnWriteArrayList(); + when(supplier.fetchResources(any())) + .thenAnswer( + invocation -> { + pollingThreadNames.add(Thread.currentThread().getName()); + return Set.of(SampleExternalResource.testResource1()); + }); + var provided = + Executors.newSingleThreadScheduledExecutor(runnable -> new Thread(runnable, "provided")); + setUpSource(eventSourceFor(new BaseConfigurationService(), provided)); + + try { + source.onResourceCreated(testCustomResource); + await().untilAsserted(() -> assertThat(pollingThreadNames).contains("provided")); + + source.stop(); + + assertThat(provided.isShutdown()).isFalse(); + assertThat(pollingThreadNames).containsOnly("provided"); + } finally { + provided.shutdownNow(); + } + } + + @Test + void eventSourcesDoNotShareTheirExecutor() throws Exception { + var otherThreads = new CopyOnWriteArrayList(); + var blockFirst = new CountDownLatch(1); + var firstPolling = new CountDownLatch(1); + when(supplier.fetchResources(any())) + .thenAnswer( + invocation -> { + firstPolling.countDown(); + blockFirst.await(); + return Set.of(SampleExternalResource.testResource1()); + }); + @SuppressWarnings("unchecked") + PerResourcePollingEventSource.ResourceFetcher + otherSupplier = mock(PerResourcePollingEventSource.ResourceFetcher.class); + when(otherSupplier.fetchResources(any())) + .thenAnswer( + invocation -> { + otherThreads.add(Thread.currentThread()); + return Set.of(SampleExternalResource.testResource1()); + }); + var configurationService = new BaseConfigurationService(); + var first = eventSourceFor(configurationService, supplier, null); + var second = eventSourceFor(configurationService, otherSupplier, null); + first.setEventHandler(mock(EventHandler.class)); + second.setEventHandler(mock(EventHandler.class)); + + try { + first.start(); + second.start(); + first.onResourceCreated(testCustomResource); + assertThat(firstPolling.await(5, TimeUnit.SECONDS)).isTrue(); + second.onResourceCreated(testCustomResource); + + // a poll of the first one hanging must not delay the polls of the second one + await().until(() -> otherThreads.size() >= 2); + } finally { + blockFirst.countDown(); + first.stop(); + second.stop(); + } + } + + @Test + @EnabledForJreRange(min = JRE.JAVA_25) + void pollsOnVirtualThreadsWhenEnabledInTheConfiguration() { + var onVirtualThread = new CopyOnWriteArrayList(); + when(supplier.fetchResources(any())) + .thenAnswer( + invocation -> { + onVirtualThread.add(isVirtual(Thread.currentThread())); + return Set.of(SampleExternalResource.testResource1()); + }); + var configurationService = + ConfigurationService.newOverriddenConfigurationService( + new BaseConfigurationService(), o -> o.withUseVirtualThreads(true)); + setUpSource(eventSourceFor(configurationService, null)); + + try { + source.onResourceCreated(testCustomResource); + + await().untilAsserted(() -> assertThat(onVirtualThread).contains(true)); + } finally { + source.stop(); + } + } + + private PerResourcePollingEventSource + eventSourceFor( + ConfigurationService configurationService, ScheduledExecutorService executorService) { + return eventSourceFor(configurationService, supplier, executorService); + } + + private PerResourcePollingEventSource + eventSourceFor( + ConfigurationService configurationService, + PerResourcePollingEventSource.ResourceFetcher + fetcher, + ScheduledExecutorService executorService) { + var controllerConfiguration = mock(ControllerConfiguration.class); + when(controllerConfiguration.getConfigurationService()).thenReturn(configurationService); + when(context.getControllerConfiguration()).thenReturn(controllerConfiguration); + return new PerResourcePollingEventSource<>( + SampleExternalResource.class, + context, + new PerResourcePollingConfigurationBuilder< + SampleExternalResource, TestCustomResource, String>( + fetcher, Duration.ofMillis(PERIOD)) + .withResourceIDMapper(r -> r.getName() + "#" + r.getValue()) + .withExecutorService(executorService) + .build()); + } + + private static boolean isVirtual(Thread thread) { + try { + return (Boolean) Thread.class.getMethod("isVirtual").invoke(thread); + } catch (ReflectiveOperationException e) { + return false; + } + } + + @Test + void aResourceGoneFromTheCacheWhenItsPollRunsIsPolledAgainWhenRecreated() { + when(resourceCache.get(any())).thenReturn(Optional.empty()); + source.onResourceCreated(testCustomResource); + await() + .pollDelay(Duration.ofMillis(2 * PERIOD)) + .untilAsserted(() -> verify(supplier, never()).fetchResources(any())); + + when(resourceCache.get(any())).thenReturn(Optional.of(testCustomResource)); + source.onResourceCreated(testCustomResource); + + await().untilAsserted(() -> verify(supplier, atLeast(1)).fetchResources(any())); + } + @Test void deleteEventCancelsTheScheduling() { when(supplier.fetchResources(any())).thenReturn(Set.of(SampleExternalResource.testResource1())); diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingEventSourceTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingEventSourceTest.java index 92400df4de..9641a7302f 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingEventSourceTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingEventSourceTest.java @@ -19,11 +19,25 @@ import java.util.HashMap; import java.util.Map; import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledForJreRange; +import org.junit.jupiter.api.condition.JRE; import io.fabric8.kubernetes.api.model.HasMetadata; +import io.javaoperatorsdk.operator.api.config.BaseConfigurationService; +import io.javaoperatorsdk.operator.api.config.ConfigurationService; +import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; import io.javaoperatorsdk.operator.health.Status; import io.javaoperatorsdk.operator.processing.event.EventHandler; import io.javaoperatorsdk.operator.processing.event.ResourceID; @@ -46,6 +60,7 @@ class PollingEventSourceTest private final PollingEventSource.GenericResourceFetcher resourceFetcher = mock(PollingEventSource.GenericResourceFetcher.class); + @SuppressWarnings("deprecation") private final PollingEventSource pollingEventSource = new PollingEventSource<>( SampleExternalResource.class, @@ -67,15 +82,57 @@ void canBeRestartedAfterStop() throws InterruptedException { Thread.sleep(DEFAULT_WAIT_PERIOD); pollingEventSource.stop(); - // a cancelled java.util.Timer cannot be reused, a new one has to be created on start + // the polling task is cancelled on stop, a new one has to be scheduled on start pollingEventSource.start(); - Thread.sleep(DEFAULT_WAIT_PERIOD); + clearInvocations(resourceFetcher); + await().untilAsserted(() -> verify(resourceFetcher, atLeast(2)).fetchResources()); assertThat(pollingEventSource.getStatus()).isEqualTo(Status.HEALTHY); } @Test - void timerThreadIsADaemonSoItDoesNotKeepTheJvmAlive() throws InterruptedException { + void stoppingDoesNotInterruptAPollInFlight() throws Exception { + var polling = new CountDownLatch(1); + var release = new CountDownLatch(1); + var interrupted = new AtomicBoolean(); + var fetches = new AtomicInteger(); + when(resourceFetcher.fetchResources()) + .thenAnswer( + invocation -> { + if (fetches.incrementAndGet() > 1) { + polling.countDown(); + try { + release.await(); + } catch (InterruptedException e) { + interrupted.set(true); + } + } + return testResponseWithOneValue(); + }); + + pollingEventSource.start(); + assertThat(polling.await(5, TimeUnit.SECONDS)).isTrue(); + pollingEventSource.stop(); + release.countDown(); + + await().pollDelay(Duration.ofMillis(DEFAULT_WAIT_PERIOD)).until(() -> !interrupted.get()); + } + + @Test + void stopCancelsThePollingTask() throws InterruptedException { + when(resourceFetcher.fetchResources()).thenReturn(testResponseWithTwoValues()); + pollingEventSource.start(); + Thread.sleep(DEFAULT_WAIT_PERIOD); + pollingEventSource.stop(); + clearInvocations(resourceFetcher); + + Thread.sleep(DEFAULT_WAIT_PERIOD); + + verify(resourceFetcher, never()).fetchResources(); + } + + @Test + void pollingThreadIsADaemonSoItDoesNotKeepTheJvmAlive() throws InterruptedException { when(resourceFetcher.fetchResources()).thenReturn(testResponseWithTwoValues()); var threadsBeforeStart = Thread.getAllStackTraces().keySet(); @@ -83,13 +140,13 @@ void timerThreadIsADaemonSoItDoesNotKeepTheJvmAlive() throws InterruptedExceptio pollingEventSource.start(); Thread.sleep(DEFAULT_WAIT_PERIOD); - var newTimerThreads = + var newPollingThreads = Thread.getAllStackTraces().keySet().stream() - .filter(t -> t.getName().startsWith("Timer-")) + .filter(t -> t.getName().startsWith("josdk-polling-")) .filter(t -> !threadsBeforeStart.contains(t)) .toList(); - assertThat(newTimerThreads).isNotEmpty().allMatch(Thread::isDaemon); + assertThat(newPollingThreads).isNotEmpty().allMatch(Thread::isDaemon); } @Test @@ -154,6 +211,234 @@ void updatesHealthIndicatorBasedOnExceptionsInFetcher() { .untilAsserted(() -> assertThat(pollingEventSource.getStatus()).isEqualTo(Status.HEALTHY)); } + @Test + void createsAnExecutorOfItsOwnAndShutsItDownOnStop() { + var pollingThreads = new CopyOnWriteArrayList(); + when(resourceFetcher.fetchResources()) + .thenAnswer( + invocation -> { + pollingThreads.add(Thread.currentThread()); + return testResponseWithOneValue(); + }); + var eventSource = eventSourceFor(new BaseConfigurationService(), null); + + eventSource.start(); + + // the initial fetch happens on the calling thread, the scheduled ones on the own executor + await() + .untilAsserted( + () -> + assertThat(pollingThreads) + .anyMatch(thread -> thread.getName().startsWith("josdk-polling-"))); + var pollingThread = + pollingThreads.stream() + .filter(thread -> thread.getName().startsWith("josdk-polling-")) + .findFirst() + .orElseThrow(); + assertThat(pollingThread.isDaemon()).isTrue(); + + eventSource.stop(); + + await().untilAsserted(() -> assertThat(pollingThread.isAlive()).isFalse()); + } + + @Test + void usesANewExecutorWhenStartedAfterStop() { + var pollingThreads = new CopyOnWriteArrayList(); + when(resourceFetcher.fetchResources()) + .thenAnswer( + invocation -> { + pollingThreads.add(Thread.currentThread()); + return testResponseWithOneValue(); + }); + var eventSource = eventSourceFor(new BaseConfigurationService(), null); + + try { + eventSource.start(); + await() + .until(() -> pollingThreads.stream().anyMatch(PollingEventSourceTest::isPollingThread)); + eventSource.stop(); + pollingThreads.clear(); + + eventSource.start(); + + await() + .until(() -> pollingThreads.stream().anyMatch(PollingEventSourceTest::isPollingThread)); + } finally { + eventSource.stop(); + } + } + + @Test + void pollsOnTheProvidedExecutorAndLeavesItRunningOnStop() { + var pollingThreadNames = new CopyOnWriteArrayList(); + when(resourceFetcher.fetchResources()) + .thenAnswer( + invocation -> { + pollingThreadNames.add(Thread.currentThread().getName()); + return testResponseWithOneValue(); + }); + var provided = + Executors.newSingleThreadScheduledExecutor(runnable -> new Thread(runnable, "provided")); + var eventSource = eventSourceFor(new BaseConfigurationService(), provided); + + try { + eventSource.start(); + await().untilAsserted(() -> assertThat(pollingThreadNames).contains("provided")); + + eventSource.stop(); + + assertThat(provided.isShutdown()).isFalse(); + assertThat(pollingThreadNames).noneMatch(name -> name.startsWith("josdk-polling-")); + } finally { + provided.shutdownNow(); + } + } + + @Test + void eventSourcesDoNotShareTheirExecutor() { + var firstThreads = new CopyOnWriteArrayList(); + var secondThreads = new CopyOnWriteArrayList(); + var blockFirst = new CountDownLatch(1); + @SuppressWarnings("unchecked") + PollingEventSource.GenericResourceFetcher slowFetcher = + mock(PollingEventSource.GenericResourceFetcher.class); + var fetches = new AtomicInteger(); + when(slowFetcher.fetchResources()) + .thenAnswer( + invocation -> { + if (fetches.incrementAndGet() > 1) { + firstThreads.add(Thread.currentThread()); + blockFirst.await(); + } + return testResponseWithOneValue(); + }); + when(resourceFetcher.fetchResources()) + .thenAnswer( + invocation -> { + secondThreads.add(Thread.currentThread()); + return testResponseWithOneValue(); + }); + var configurationService = new BaseConfigurationService(); + var first = eventSourceFor(configurationService, slowFetcher, null); + var second = eventSourceFor(configurationService, resourceFetcher, null); + + try { + first.start(); + await().until(() -> !firstThreads.isEmpty()); + second.start(); + + // a poll of the first one hanging must not delay the polls of the second one + await().until(() -> secondThreads.size() > 2); + assertThat(secondThreads).doesNotContainAnyElementsOf(firstThreads); + } finally { + blockFirst.countDown(); + first.stop(); + second.stop(); + } + } + + @Test + @EnabledForJreRange(min = JRE.JAVA_25) + void pollsOnVirtualThreadsWhenEnabledInTheConfiguration() { + var onVirtualThread = new CopyOnWriteArrayList(); + when(resourceFetcher.fetchResources()) + .thenAnswer( + invocation -> { + onVirtualThread.add(isVirtual(Thread.currentThread())); + return testResponseWithOneValue(); + }); + var configurationService = + ConfigurationService.newOverriddenConfigurationService( + new BaseConfigurationService(), o -> o.withUseVirtualThreads(true)); + var eventSource = eventSourceFor(configurationService, null); + + try { + eventSource.start(); + + // the initial fetch happens on the calling thread, the scheduled ones on virtual threads + await().untilAsserted(() -> assertThat(onVirtualThread).contains(true)); + } finally { + eventSource.stop(); + } + } + + @Test + void stoppingDuringTheInitialFetchEndsStartCleanly() throws Exception { + var fetching = new CountDownLatch(1); + var release = new CountDownLatch(1); + when(resourceFetcher.fetchResources()) + .thenAnswer( + invocation -> { + fetching.countDown(); + release.await(); + return testResponseWithOneValue(); + }); + var eventSource = eventSourceFor(new BaseConfigurationService(), null); + var failure = new AtomicReference(); + var starter = + new Thread( + () -> { + try { + eventSource.start(); + } catch (Throwable t) { + failure.set(t); + } + }); + + starter.start(); + assertThat(fetching.await(5, TimeUnit.SECONDS)).isTrue(); + eventSource.stop(); + release.countDown(); + starter.join(5000); + + assertThat(starter.isAlive()).isFalse(); + assertThat(failure.get()).isNull(); + clearInvocations(resourceFetcher); + Thread.sleep(DEFAULT_WAIT_PERIOD); + verify(resourceFetcher, never()).fetchResources(); + } + + private PollingEventSource eventSourceFor( + ConfigurationService configurationService, ScheduledExecutorService executorService) { + return eventSourceFor(configurationService, resourceFetcher, executorService); + } + + private PollingEventSource eventSourceFor( + ConfigurationService configurationService, + PollingEventSource.GenericResourceFetcher fetcher, + ScheduledExecutorService executorService) { + var eventSource = + new PollingEventSource( + SampleExternalResource.class, + contextFor(configurationService), + new PollingConfiguration<>(null, fetcher, POLL_PERIOD, null, executorService)); + eventSource.setEventHandler(mock(EventHandler.class)); + return eventSource; + } + + private static boolean isPollingThread(Thread thread) { + return thread.getName().startsWith("josdk-polling-"); + } + + private static boolean isVirtual(Thread thread) { + try { + return (Boolean) Thread.class.getMethod("isVirtual").invoke(thread); + } catch (ReflectiveOperationException e) { + return false; + } + } + + @SuppressWarnings("unchecked") + private static EventSourceContext contextFor( + ConfigurationService configurationService) { + var controllerConfiguration = mock(ControllerConfiguration.class); + when(controllerConfiguration.getConfigurationService()).thenReturn(configurationService); + var context = mock(EventSourceContext.class); + when(context.getControllerConfiguration()).thenReturn(controllerConfiguration); + return context; + } + private Map> testResponseWithTwoValueForSameId() { Map> res = new HashMap<>(); res.put(primaryID1(), Set.of(testResource1(), testResource2())); diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/timer/TimerEventSourceTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/timer/TimerEventSourceTest.java index 3a4e1cb80d..e5ac53441d 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/timer/TimerEventSourceTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/timer/TimerEventSourceTest.java @@ -17,7 +17,13 @@ import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import org.awaitility.Awaitility; import org.awaitility.core.ConditionFactory; @@ -25,6 +31,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import io.javaoperatorsdk.operator.ExecutorUtilsInternal; import io.javaoperatorsdk.operator.TestUtils; import io.javaoperatorsdk.operator.api.reconciler.BaseControl; import io.javaoperatorsdk.operator.health.Status; @@ -94,6 +101,116 @@ public void deRegistersOnceEventSources() { assertThat(source.getStatus()).isEqualTo(Status.HEALTHY); } + @Test + public void schedulesOnTheNewExecutorWhenStartedAgainWhileRunning() { + var first = Executors.newScheduledThreadPool(1); + var second = Executors.newScheduledThreadPool(1); + var current = new AtomicReference(first); + var timerSource = new TimerEventSource("timer", false, current::get); + setUpSource(timerSource, new CapturingEventHandler()); + try { + first.shutdownNow(); + current.set(second); + + source.start(); + source.scheduleOnce(ResourceID.fromResource(TestUtils.testCustomResource()), PERIOD); + + untilAsserted(() -> assertThat(eventHandler.events).hasSize(1)); + } finally { + second.shutdownNow(); + } + } + + @Test + public void timersThatAlreadyFiredAreNotScheduledAgainOnTheNewExecutor() { + var first = Executors.newScheduledThreadPool(1); + var second = Executors.newScheduledThreadPool(1); + var current = new AtomicReference(first); + var timerSource = new TimerEventSource("timer", false, current::get); + setUpSource(timerSource, new CapturingEventHandler()); + try { + source.scheduleOnce(ResourceID.fromResource(TestUtils.testCustomResource()), PERIOD); + untilAsserted(() -> assertThat(eventHandler.events).hasSize(1)); + first.shutdownNow(); + current.set(second); + + source.start(); + + untilAsserted(PERIOD * 4, 0, () -> assertThat(eventHandler.events).hasSize(1)); + } finally { + second.shutdownNow(); + } + } + + @Test + public void timersWhoseHandlerIsStillRunningAreNotScheduledAgainOnTheNewExecutor() + throws Exception { + var first = Executors.newScheduledThreadPool(1); + var second = Executors.newScheduledThreadPool(1); + var current = new AtomicReference(first); + var handling = new CountDownLatch(1); + var release = new CountDownLatch(1); + var handled = new AtomicInteger(); + var timerSource = new TimerEventSource("timer", false, current::get); + setUpSource( + timerSource, + new CapturingEventHandler() { + @Override + public void handleEvent(Event event) { + if (handled.incrementAndGet() > 1) { + return; + } + handling.countDown(); + try { + release.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + }); + try { + source.scheduleOnce(ResourceID.fromResource(TestUtils.testCustomResource()), PERIOD); + assertThat(handling.await(5, TimeUnit.SECONDS)).isTrue(); + first.shutdown(); + current.set(second); + + source.start(); + + untilAsserted(PERIOD * 4, 0, () -> assertThat(handled).hasValue(1)); + } finally { + release.countDown(); + first.shutdownNow(); + second.shutdownNow(); + } + } + + @Test + public void stoppingDoesNotInterruptAnEventHandlerInFlight() throws Exception { + var handling = new CountDownLatch(1); + var release = new CountDownLatch(1); + var interrupted = new AtomicBoolean(); + setUpSource( + new TimerEventSource<>(), + new CapturingEventHandler() { + @Override + public void handleEvent(Event event) { + handling.countDown(); + try { + release.await(); + } catch (InterruptedException e) { + interrupted.set(true); + } + } + }); + + source.scheduleOnce(ResourceID.fromResource(TestUtils.testCustomResource()), 1); + assertThat(handling.await(5, TimeUnit.SECONDS)).isTrue(); + source.stop(); + release.countDown(); + + untilAsserted(PERIOD * 2, 0, () -> assertThat(interrupted).isFalse()); + } + @Test public void eventNotRegisteredIfStopped() { var resourceID = ResourceID.fromResource(TestUtils.testCustomResource()); @@ -125,6 +242,60 @@ public void handlesInstanceReschedule() { assertThat(eventHandler.events).hasSize(1); } + @Test + public void schedulesOnTheProvidedExecutorAndLeavesItRunningOnStop() { + var providedExecutor = + Executors.newSingleThreadScheduledExecutor( + ExecutorUtilsInternal.daemonThreadFactory("provided-timer-executor")); + var handler = new CapturingEventHandler(); + var eventSource = + new TimerEventSource("timer", false, () -> providedExecutor); + eventSource.setEventHandler(handler); + + try { + eventSource.start(); + eventSource.scheduleOnce(ResourceID.fromResource(TestUtils.testCustomResource()), PERIOD); + + untilAsserted( + () -> + assertThat(handler.eventProducingThreadNames) + .containsExactly("provided-timer-executor-1")); + + eventSource.stop(); + + // the executor is not the event source's to shut down + assertThat(providedExecutor.isShutdown()).isFalse(); + } finally { + providedExecutor.shutdownNow(); + } + } + + @Test + public void shutsDownTheExecutorItCreatedItselfAndCreatesANewOneOnRestart() { + var eventSource = new TimerEventSource(); + var handler = new CapturingEventHandler(); + eventSource.setEventHandler(handler); + + eventSource.start(); + eventSource.scheduleOnce(ResourceID.fromResource(TestUtils.testCustomResource()), PERIOD); + untilAsserted(() -> assertThat(handler.eventProducingThreadNames).hasSize(1)); + var firstThreadName = handler.eventProducingThreadNames.get(0); + assertThat(firstThreadName).startsWith("josdk-timer-"); + + eventSource.stop(); + Awaitility.await() + .untilAsserted( + () -> + assertThat(Thread.getAllStackTraces().keySet()) + .noneMatch(t -> t.getName().equals(firstThreadName))); + + eventSource.start(); + eventSource.scheduleOnce(ResourceID.fromResource(TestUtils.testCustomResource()), PERIOD); + untilAsserted(() -> assertThat(handler.events).hasSize(2)); + + eventSource.stop(); + } + private void untilAsserted(ThrowingRunnable assertion) { untilAsserted(INITIAL_DELAY, PERIOD, assertion); } @@ -150,10 +321,12 @@ private void untilAsserted(long initialDelay, long interval, ThrowingRunnable as public static class CapturingEventHandler implements EventHandler { private final List events = new CopyOnWriteArrayList<>(); + private final List eventProducingThreadNames = new CopyOnWriteArrayList<>(); @Override public void handleEvent(Event event) { events.add(event); + eventProducingThreadNames.add(Thread.currentThread().getName()); } } } diff --git a/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/loader/ConfigLoader.java b/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/loader/ConfigLoader.java index 1a221fb76c..56e98721a1 100644 --- a/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/loader/ConfigLoader.java +++ b/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/loader/ConfigLoader.java @@ -82,10 +82,18 @@ public static ConfigLoader getDefault() { "workflow.executor-threads", Integer.class, ConfigurationServiceOverrider::withConcurrentWorkflowExecutorThreads), + new ConfigBinding<>( + "retry-and-reschedule.concurrent-threads", + Integer.class, + ConfigurationServiceOverrider::withConcurrentRetryAndRescheduleThreads), new ConfigBinding<>( "close-client-on-stop", Boolean.class, ConfigurationServiceOverrider::withCloseClientOnStop), + new ConfigBinding<>( + "use-virtual-threads", + Boolean.class, + ConfigurationServiceOverrider::withUseVirtualThreads), new ConfigBinding<>( "informer.stop-on-error-during-startup", Boolean.class, diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/virtualthreads/VirtualThreadsCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/virtualthreads/VirtualThreadsCustomResource.java new file mode 100644 index 0000000000..be086a5f1b --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/virtualthreads/VirtualThreadsCustomResource.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.virtualthreads; + +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.Kind; +import io.fabric8.kubernetes.model.annotation.ShortNames; +import io.fabric8.kubernetes.model.annotation.Version; + +@Group("sample.javaoperatorsdk") +@Version("v1") +@Kind("VirtualThreadsCustomResource") +@ShortNames("vtc") +public class VirtualThreadsCustomResource extends CustomResource + implements Namespaced {} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/virtualthreads/VirtualThreadsIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/virtualthreads/VirtualThreadsIT.java new file mode 100644 index 0000000000..67ed2c780d --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/virtualthreads/VirtualThreadsIT.java @@ -0,0 +1,92 @@ +/* + * 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.virtualthreads; + +import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import io.fabric8.kubernetes.api.model.ObjectMeta; +import io.javaoperatorsdk.annotation.Sample; +import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; + +import static io.javaoperatorsdk.operator.baseapi.virtualthreads.VirtualThreadsTestReconciler.onVirtualThread; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +@Sample( + tldr = "Running reconciliations on virtual threads", + description = + """ + Demonstrates how to make the framework execute its concurrent work on virtual threads by \ + simply setting a flag on the ConfigurationService. Virtual threads make the blocking calls \ + a reconciler typically performs much cheaper, while the configured concurrency limits are \ + still enforced: the test verifies that the reconciler runs on virtual threads and that no \ + more than the configured number of reconciliations happen at the same time. + """) +class VirtualThreadsIT { + + static final int CONCURRENT_RECONCILIATION_THREADS = 2; + static final int NUMBER_OF_RESOURCES = 10; + + /** + * Virtual threads require Java 25, on an older JVM the framework transparently falls back to + * platform threads, which this test also covers since only the concurrency assertions apply then. + */ + private static final boolean VIRTUAL_THREADS_SUPPORTED = Runtime.version().feature() >= 25; + + @RegisterExtension + LocallyRunOperatorExtension operator = + LocallyRunOperatorExtension.builder() + .withConfigurationService( + o -> + o.withUseVirtualThreads(true) + .withConcurrentReconciliationThreads(CONCURRENT_RECONCILIATION_THREADS)) + .withReconciler(new VirtualThreadsTestReconciler()) + .build(); + + @Test + void reconciliationsRunOnVirtualThreadsWithinTheConfiguredConcurrency() { + // the test itself runs on a platform thread, so the reconciler assertion below can only pass + // if the framework actually switched to virtual threads + assertThat(onVirtualThread()).isFalse(); + + IntStream.range(0, NUMBER_OF_RESOURCES).forEach(i -> operator.create(testResource(i))); + + var reconciler = operator.getReconcilerOfType(VirtualThreadsTestReconciler.class); + await() + .atMost(2, TimeUnit.MINUTES) + .untilAsserted( + () -> + assertThat(reconciler.getNumberOfExecutions()) + .isGreaterThanOrEqualTo(NUMBER_OF_RESOURCES)); + + // parallelism is retained: reconciliations do happen concurrently, but never more than the + // configured number of them + assertThat(reconciler.getMaxConcurrentReconciliations()) + .isEqualTo(CONCURRENT_RECONCILIATION_THREADS); + assertThat(reconciler.allExecutionsOnVirtualThreads()).isEqualTo(VIRTUAL_THREADS_SUPPORTED); + } + + private VirtualThreadsCustomResource testResource(int index) { + var resource = new VirtualThreadsCustomResource(); + resource.setMetadata(new ObjectMeta()); + resource.getMetadata().setName("virtual-threads-test-" + index); + return resource; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/virtualthreads/VirtualThreadsTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/virtualthreads/VirtualThreadsTestReconciler.java new file mode 100644 index 0000000000..ee6f00f499 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/virtualthreads/VirtualThreadsTestReconciler.java @@ -0,0 +1,84 @@ +/* + * 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.virtualthreads; + +import java.time.Duration; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +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; +import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; + +/** + * Blocks for a while during reconciliation, recording on what kind of thread it ran and how many + * reconciliations were in flight at the same time. + */ +@ControllerConfiguration +public class VirtualThreadsTestReconciler + implements Reconciler, TestExecutionInfoProvider { + + public static final Duration RECONCILIATION_DURATION = Duration.ofMillis(300); + + private final AtomicInteger numberOfExecutions = new AtomicInteger(); + private final AtomicInteger runningReconciliations = new AtomicInteger(); + private final AtomicInteger maxConcurrentReconciliations = new AtomicInteger(); + private final AtomicBoolean allExecutionsOnVirtualThreads = new AtomicBoolean(true); + + @Override + public UpdateControl reconcile( + VirtualThreadsCustomResource resource, Context context) + throws InterruptedException { + if (!onVirtualThread()) { + allExecutionsOnVirtualThreads.set(false); + } + maxConcurrentReconciliations.accumulateAndGet( + runningReconciliations.incrementAndGet(), Math::max); + try { + Thread.sleep(RECONCILIATION_DURATION.toMillis()); + } finally { + runningReconciliations.decrementAndGet(); + numberOfExecutions.incrementAndGet(); + } + return UpdateControl.noUpdate(); + } + + public int getNumberOfExecutions() { + return numberOfExecutions.get(); + } + + public int getMaxConcurrentReconciliations() { + return maxConcurrentReconciliations.get(); + } + + public boolean allExecutionsOnVirtualThreads() { + return allExecutionsOnVirtualThreads.get(); + } + + /** + * {@code Thread.isVirtual} only exists as of Java 21 while the tests are compiled for Java 17, + * hence the reflective call. + */ + static boolean onVirtualThread() { + try { + return (Boolean) Thread.class.getMethod("isVirtual").invoke(Thread.currentThread()); + } catch (ReflectiveOperationException e) { + return false; + } + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/loader/ConfigLoaderTest.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/loader/ConfigLoaderTest.java index 0b014bb6f7..0cd384e936 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/loader/ConfigLoaderTest.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/loader/ConfigLoaderTest.java @@ -86,6 +86,18 @@ void applyConfigsAppliesConcurrentWorkflowExecutorThreads() { assertThat(result.concurrentWorkflowExecutorThreads()).isEqualTo(3); } + @Test + void applyConfigsAppliesConcurrentRetryAndRescheduleThreads() { + var loader = + new ConfigLoader(mapProvider(Map.of("josdk.retry-and-reschedule.concurrent-threads", 6))); + + var base = new BaseConfigurationService(null); + var result = + ConfigurationService.newOverriddenConfigurationService(base, loader.applyConfigs()); + + assertThat(result.concurrentRetryAndRescheduleThreads()).isEqualTo(6); + } + @Test void applyConfigsAppliesBooleanFlags() { var values = new HashMap(); @@ -95,6 +107,7 @@ void applyConfigsAppliesBooleanFlags() { values.put("josdk.dependent-resources.ssa-based-create-update-match", false); values.put("josdk.use-ssa-to-patch-primary-resource", false); values.put("josdk.clone-secondary-resources-when-getting-from-cache", true); + values.put("josdk.use-virtual-threads", true); var loader = new ConfigLoader(mapProvider(values)); var base = new BaseConfigurationService(null); @@ -107,6 +120,7 @@ void applyConfigsAppliesBooleanFlags() { assertThat(result.ssaBasedCreateUpdateMatchForDependentResources()).isFalse(); assertThat(result.useSSAToPatchPrimaryResource()).isFalse(); assertThat(result.cloneSecondaryResourcesWhenGettingFromCache()).isTrue(); + assertThat(result.useVirtualThreads()).isTrue(); } @Test @@ -311,7 +325,10 @@ public Optional getValue(String key, Class type) { Map.entry( "withCloneSecondaryResourcesWhenGettingFromCache", "clone-secondary-resources-when-getting-from-cache"), - Map.entry("withClusterScopedEventNamespace", "events.cluster-scoped-namespace")); + Map.entry("withClusterScopedEventNamespace", "events.cluster-scoped-namespace"), + Map.entry( + "withConcurrentRetryAndRescheduleThreads", "retry-and-reschedule.concurrent-threads"), + Map.entry("withUseVirtualThreads", "use-virtual-threads")); /** * Maps every scalar setter of {@link ControllerConfigurationOverrider} to the property key suffix diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanagedexternaldependenttype/MultipleManagedExternalDependentResourceReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanagedexternaldependenttype/MultipleManagedExternalDependentResourceReconciler.java index dec9422486..33b7f965f3 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanagedexternaldependenttype/MultipleManagedExternalDependentResourceReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanagedexternaldependenttype/MultipleManagedExternalDependentResourceReconciler.java @@ -96,6 +96,7 @@ public int getNumberOfExecutions() { pollingEventSource = new PollingEventSource<>( ExternalResource.class, + context, new PollingConfigurationBuilder( fetcher, Duration.ofMillis(1000L)) .withName(EVENT_SOURCE_NAME) diff --git a/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/MySQLSchemaOperator.java b/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/MySQLSchemaOperator.java index 3e8a9df13f..e8a2d6838c 100644 --- a/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/MySQLSchemaOperator.java +++ b/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/MySQLSchemaOperator.java @@ -41,9 +41,12 @@ public static void main(String[] args) throws IOException { Operator operator = new Operator( overrider -> - overrider.withMetrics( - new MicrometerMetricsV2.MicrometerMetricsV2Builder(new LoggingMeterRegistry()) - .build())); + overrider + .withMetrics( + new MicrometerMetricsV2.MicrometerMetricsV2Builder( + new LoggingMeterRegistry()) + .build()) + .withUseVirtualThreads(true)); MySQLSchemaReconciler schemaReconciler = new MySQLSchemaReconciler(); diff --git a/sample-operators/mysql-schema/src/test/java/io/javaoperatorsdk/operator/sample/MySQLSchemaOperatorE2E.java b/sample-operators/mysql-schema/src/test/java/io/javaoperatorsdk/operator/sample/MySQLSchemaOperatorE2E.java index 622c693fd5..70e98d5c92 100644 --- a/sample-operators/mysql-schema/src/test/java/io/javaoperatorsdk/operator/sample/MySQLSchemaOperatorE2E.java +++ b/sample-operators/mysql-schema/src/test/java/io/javaoperatorsdk/operator/sample/MySQLSchemaOperatorE2E.java @@ -74,6 +74,7 @@ boolean isLocal() { .withReconciler(new MySQLSchemaReconciler()) // configuration for schema comes from // SchemaDependentResource annotation .withInfrastructure(infrastructure) + .withConfigurationService(o -> o.withUseVirtualThreads(true)) .withDeleteCRDs(false) .withPortForward(MY_SQL_NS, "app", "mysql", 3306, SchemaDependentResource.LOCAL_PORT) .build() diff --git a/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/WebPageOperator.java b/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/WebPageOperator.java index 5366dc2e9a..392172886f 100644 --- a/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/WebPageOperator.java +++ b/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/WebPageOperator.java @@ -40,7 +40,9 @@ public class WebPageOperator { public static void main(String[] args) throws IOException { log.info("WebServer Operator starting!"); - Operator operator = new Operator(o -> o.withStopOnInformerErrorDuringStartup(false)); + Operator operator = + new Operator( + o -> o.withStopOnInformerErrorDuringStartup(false).withUseVirtualThreads(true)); String reconcilerEnvVar = System.getenv(WEBPAGE_RECONCILER_ENV); if (WEBPAGE_CLASSIC_RECONCILER_ENV_VALUE.equals(reconcilerEnvVar)) { operator.register(new WebPageReconciler()); diff --git a/sample-operators/webpage/src/test/java/io/javaoperatorsdk/operator/sample/WebPageOperatorE2E.java b/sample-operators/webpage/src/test/java/io/javaoperatorsdk/operator/sample/WebPageOperatorE2E.java index 8b0ed5fe69..ac6e595da6 100644 --- a/sample-operators/webpage/src/test/java/io/javaoperatorsdk/operator/sample/WebPageOperatorE2E.java +++ b/sample-operators/webpage/src/test/java/io/javaoperatorsdk/operator/sample/WebPageOperatorE2E.java @@ -41,6 +41,7 @@ public WebPageOperatorE2E() throws FileNotFoundException {} AbstractOperatorExtension operator = isLocal() ? LocallyRunOperatorExtension.builder() + .withConfigurationService(o -> o.withUseVirtualThreads(true)) .waitForNamespaceDeletion(false) .withDeleteCRDs(false) .withReconciler(new WebPageReconciler()) diff --git a/sample-operators/webpage/src/test/java/io/javaoperatorsdk/operator/sample/WebPageOperatorManagedDependentResourcesE2E.java b/sample-operators/webpage/src/test/java/io/javaoperatorsdk/operator/sample/WebPageOperatorManagedDependentResourcesE2E.java index 20c27529d4..1c8df953ae 100644 --- a/sample-operators/webpage/src/test/java/io/javaoperatorsdk/operator/sample/WebPageOperatorManagedDependentResourcesE2E.java +++ b/sample-operators/webpage/src/test/java/io/javaoperatorsdk/operator/sample/WebPageOperatorManagedDependentResourcesE2E.java @@ -41,6 +41,7 @@ public WebPageOperatorManagedDependentResourcesE2E() throws FileNotFoundExceptio ? LocallyRunOperatorExtension.builder() .waitForNamespaceDeletion(false) .withDeleteCRDs(false) + .withConfigurationService(o -> o.withUseVirtualThreads(true)) .withReconciler(new WebPageManagedDependentsReconciler()) .build() : ClusterDeployedOperatorExtension.builder() diff --git a/sample-operators/webpage/src/test/java/io/javaoperatorsdk/operator/sample/WebPageOperatorStandaloneDependentResourcesE2E.java b/sample-operators/webpage/src/test/java/io/javaoperatorsdk/operator/sample/WebPageOperatorStandaloneDependentResourcesE2E.java index 2073bf3daa..8e667e60e4 100644 --- a/sample-operators/webpage/src/test/java/io/javaoperatorsdk/operator/sample/WebPageOperatorStandaloneDependentResourcesE2E.java +++ b/sample-operators/webpage/src/test/java/io/javaoperatorsdk/operator/sample/WebPageOperatorStandaloneDependentResourcesE2E.java @@ -35,6 +35,7 @@ public WebPageOperatorStandaloneDependentResourcesE2E() throws FileNotFoundExcep .waitForNamespaceDeletion(false) .withDeleteCRDs(false) .withReconciler(new WebPageStandaloneDependentsReconciler()) + .withConfigurationService(o -> o.withUseVirtualThreads(true)) .build() : ClusterDeployedOperatorExtension.builder() .waitForNamespaceDeletion(false) diff --git a/spotbugs-exclude.xml b/spotbugs-exclude.xml index f6107ac4ea..9c516e059e 100644 --- a/spotbugs-exclude.xml +++ b/spotbugs-exclude.xml @@ -67,4 +67,14 @@ + + + + + + From c50f673630df71895653a1e86e09b27485bbe573 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Attila=20M=C3=A9sz=C3=A1ros?= Date: Thu, 5 Nov 2026 19:49:08 +0100 Subject: [PATCH 12/23] fix: event recorder aggregation, long names and cluster scoped events (#3665) Correctness fixes of the event recorder, found while reviewing the virtual thread support (#3664). - Aggregating onto a named event now updates its type, reason and action along with the count, last timestamp and message, so a Warning repeated under the name of a Normal event is no longer reported as the Normal one. An occurrence without an action clears the earlier action, except on an event that carries an eventTime, where the reason stands in for it, as the API server requires an action for such events. The API server only makes these fields immutable for events.k8s.io/v1, not for the core API the sink writes to. - Supplied event names longer than the Kubernetes limit are shortened with a hash of the full name instead of being plainly truncated, so distinct names sharing a long prefix no longer merge into one event. Trailing '-' and '.' are stripped before the hash is appended, for supplied and generated names alike, so a name is never cut into an invalid "...-.". - Events about cluster scoped resources in the kube-system namespace carry an eventTime and an action (defaulting to the reason), which is what the API server requires to accept them there. Events in the default namespace are unchanged. The API server rejects such events in any other namespace, so the javadocs and docs no longer suggest the namespace the operator runs in. Tests: regression and unit tests, a kube-api-test based DefaultEventRecorderIntegrationTest recording events against a real API server, and ITs for cluster scoped resources in default and kube-system. --- .../documentation/operations/configuration.md | 7 +- .../api/config/ConfigurationService.java | 8 +- .../config/ConfigurationServiceOverrider.java | 4 +- .../api/event/DefaultEventRecorder.java | 60 +++- .../operator/api/event/DefaultEventSink.java | 16 +- .../api/event/EventNamingStrategy.java | 5 +- .../DefaultEventRecorderIntegrationTest.java | 235 +++++++++++++ .../api/event/DefaultEventRecorderTest.java | 30 +- .../event/EventRecorderRegressionTest.java | 310 ++++++++++++++++++ .../ClusterScopedEventRecorderIT.java | 83 +++++ .../ClusterScopedEventRecorderReconciler.java | 36 ++ ...lusterScopedKubeSystemEventRecorderIT.java | 87 +++++ 12 files changed, 853 insertions(+), 28 deletions(-) create mode 100644 operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorderIntegrationTest.java create mode 100644 operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/EventRecorderRegressionTest.java create mode 100644 operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorder/ClusterScopedEventRecorderIT.java create mode 100644 operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorder/ClusterScopedEventRecorderReconciler.java create mode 100644 operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorder/ClusterScopedKubeSystemEventRecorderIT.java diff --git a/docs/content/en/docs/documentation/operations/configuration.md b/docs/content/en/docs/documentation/operations/configuration.md index 831c1aa60b..0b469e8312 100644 --- a/docs/content/en/docs/documentation/operations/configuration.md +++ b/docs/content/en/docs/documentation/operations/configuration.md @@ -379,7 +379,7 @@ All operator-level keys are prefixed with `josdk.`. | Key | Type | Description | |---|---|---| -| `josdk.events.cluster-scoped-namespace` | `String` | Namespace to record events about cluster scoped resources in (defaults to `default`) | +| `josdk.events.cluster-scoped-namespace` | `String` | Namespace to record events about cluster scoped resources in (defaults to `default`); the API server only accepts `default` and `kube-system` | Recording events requires the operator's service account to be allowed `get`, `create` and `patch` on `events` in the core (`""`) API group. All three are used: an event that does not exist yet is @@ -395,6 +395,11 @@ therefore has to grant the permission in every namespace events are recorded in `default`, or whatever `josdk.events.cluster-scoped-namespace` is set to, if the operator reconciles cluster scoped resources. A `ClusterRole` covers all of them at once. +The API server only accepts events about cluster scoped objects in the `default` and `kube-system` +namespaces, so those are the only values `josdk.events.cluster-scoped-namespace` can usefully be set +to. In particular, the namespace the operator itself runs in is rejected, and the event dropped with +a warning in the operator log. + #### Leader Election Leader election is activated when at least one `josdk.leader-election.*` key is present. diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java index 92d1729619..6a7f2f93d5 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java @@ -389,9 +389,11 @@ default Optional getLeaderElectionConfiguration() { *

    Defaults to the {@code default} namespace, following the Kubernetes convention, which is * also what the Go client does, so that events recorded by an operator end up alongside the ones * recorded by the built-in controllers. Operators whose RBAC does not allow creating events in - * the {@code default} namespace should override this, typically with the namespace the operator - * itself runs in. Note that recording an event is best effort, so a missing permission results in - * the event being dropped with a warning in the log rather than in an error. + * the {@code default} namespace can override this with {@code kube-system}. The API server + * rejects events about cluster scoped resources in any other namespace, such as the namespace the + * operator itself runs in. Note that recording an event is best effort, so a missing permission + * or a rejected namespace results in the event being dropped with a warning in the log rather + * than in an error. * * @return the namespace to record events about cluster scoped resources in */ diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverrider.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverrider.java index 05112b4da7..c95b9cc54a 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverrider.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverrider.java @@ -201,8 +201,8 @@ public ConfigurationServiceOverrider withLeaderElectionConfiguration( /** * Sets the namespace in which Kubernetes events about cluster scoped resources are recorded. Use - * this when the operator is not allowed to create events in the {@code default} namespace, - * passing for example the namespace the operator itself runs in. + * this when the operator is not allowed to create events in the {@code default} namespace. The + * API server only accepts {@code default} and {@code kube-system} for such events. * * @param namespace the namespace to record events about cluster scoped resources in * @return this {@link ConfigurationServiceOverrider} for chained customization diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorder.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorder.java index 67764b7146..9bd54ef96c 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorder.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorder.java @@ -21,6 +21,8 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.HexFormat; import java.util.Objects; @@ -32,6 +34,7 @@ import io.fabric8.kubernetes.api.model.Event; import io.fabric8.kubernetes.api.model.EventBuilder; import io.fabric8.kubernetes.api.model.HasMetadata; +import io.fabric8.kubernetes.api.model.MicroTime; import io.fabric8.kubernetes.api.model.ObjectReference; import io.fabric8.kubernetes.api.model.ObjectReferenceBuilder; import io.javaoperatorsdk.operator.api.config.LeaderElectionConfiguration; @@ -47,7 +50,8 @@ *

    Events for cluster scoped objects have to live in some namespace: by default the {@value * #CLUSTER_SCOPED_EVENT_NAMESPACE} namespace is used, following the Kubernetes convention, but it * can be overridden, see {@link - * io.javaoperatorsdk.operator.api.config.ConfigurationService#clusterScopedEventNamespace()}. + * io.javaoperatorsdk.operator.api.config.ConfigurationService#clusterScopedEventNamespace()}. The + * API server only accepts such events in the {@code default} and {@code kube-system} namespaces. * *

    By default, events are named deterministically, after the object they are about plus a hash of * everything that identifies the event, so that recording the same event again resolves to the @@ -61,6 +65,8 @@ public class DefaultEventRecorder implements EventRecorder { public static final String CLUSTER_SCOPED_EVENT_NAMESPACE = "default"; + private static final String KUBE_SYSTEM_NAMESPACE = "kube-system"; + /** * Kubernetes limits object names to 253 characters, as they have to be valid RFC 1123 DNS * subdomains. @@ -75,6 +81,12 @@ public class DefaultEventRecorder implements EventRecorder { private static final int IDENTITY_HASH_LENGTH = 32; + /** + * The fixed width format of {@code MicroTime}, which the API server refuses to read otherwise. + */ + private static final DateTimeFormatter EVENT_TIME_FORMAT = + DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'").withZone(ZoneOffset.UTC); + /** What the API server accepts as an object name, see RFC 1123 on DNS subdomains. */ private static final Pattern RFC_1123_SUBDOMAIN = Pattern.compile("[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*"); @@ -211,11 +223,12 @@ protected Event toEvent(Context context, EventRecord record) { var regarding = context.getPrimaryResource(); var now = Instant.now().truncatedTo(ChronoUnit.SECONDS).toString(); var involvedObject = objectReferenceFor(regarding); + var namespace = eventNamespace(regarding, context); var builder = new EventBuilder() .withNewMetadata() .withName(eventName(regarding, record, controllerName)) - .withNamespace(eventNamespace(regarding, context)) + .withNamespace(namespace) .withLabels(record.labels()) .withAnnotations(record.annotations()) .endMetadata() @@ -255,10 +268,28 @@ protected Event toEvent(Context context, EventRecord record) { .endOwnerReference() .endMetadata(); } - record.action().ifPresent(builder::withAction); + var action = record.action().filter(a -> !a.isBlank()); + action.ifPresent(builder::withAction); + if (requiresEventTime(regarding, namespace)) { + builder.withEventTime(new MicroTime(EVENT_TIME_FORMAT.format(Instant.now()))); + if (action.isEmpty()) { + builder.withAction(record.reason()); + } + } return builder.build(); } + /** + * The API server only accepts an event without {@code eventTime} for a cluster scoped object if + * the event lives in the {@code default} namespace. An event that carries an {@code eventTime} + * (and with it an {@code action}) is also accepted in the {@code kube-system} namespace. No other + * namespace is accepted for such an event, whether it has an {@code eventTime} or not. + */ + private static boolean requiresEventTime(HasMetadata regarding, String eventNamespace) { + return regarding.getMetadata().getNamespace() == null + && KUBE_SYSTEM_NAMESPACE.equals(eventNamespace); + } + private String eventNamespace(HasMetadata regarding, Context context) { var namespace = regarding.getMetadata().getNamespace(); if (namespace != null) { @@ -295,14 +326,20 @@ private static String truncateToMaxNameLength(String name) { if (name.length() <= MAX_NAME_LENGTH) { return name; } - var truncated = name.substring(0, MAX_NAME_LENGTH); + var suffix = "." + identityDigest(name); + var shortened = truncate(name, MAX_NAME_LENGTH - suffix.length()) + suffix; + log.warn( + "Shortened the name of event {} to {} to stay within the Kubernetes name limit", + name, + shortened); + return shortened; + } + + private static String truncate(String name, int maxLength) { + var truncated = name.substring(0, Math.min(name.length(), maxLength)); while (truncated.endsWith("-") || truncated.endsWith(".")) { truncated = truncated.substring(0, truncated.length() - 1); } - log.warn( - "Truncated the name of event {} to {} to stay within the Kubernetes name limit", - name, - truncated); return truncated; } @@ -337,12 +374,7 @@ private String identityHashName( .orElseGet(() -> requireNonNullElse(record.message(), ""))); var suffix = "." + identityDigest(identity); - var prefix = metadata.getName(); - var maxPrefixLength = MAX_NAME_LENGTH - suffix.length(); - if (prefix.length() > maxPrefixLength) { - prefix = prefix.substring(0, maxPrefixLength); - } - return prefix + suffix; + return truncate(metadata.getName(), MAX_NAME_LENGTH - suffix.length()) + suffix; } /** diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventSink.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventSink.java index c2f5461ae8..ddb0b074bb 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventSink.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventSink.java @@ -30,8 +30,13 @@ *

    An event that does not exist yet is created. An event that does is a repeat of one already * recorded, since the name of an event is derived from everything that identifies it (see {@link * DefaultEventRecorder}), and is aggregated onto the recorded one by patching its {@code count} and - * {@code lastTimestamp}. That is what makes {@code kubectl describe} report a repeating event once, - * as {@code (x12 over 3m)}, rather than filling the event list with copies of it. + * {@code lastTimestamp}, along with its {@code message}, {@code type}, {@code reason} and {@code + * action}, which events sharing a name explicitly may differ in: they describe the latest + * occurrence. The API server only makes them immutable for {@code events.k8s.io/v1} requests, not + * for the core group this sink writes to. An event that carries an {@code eventTime} needs an + * {@code action}, so the reason stands in for it when the occurrence has none. That is what makes + * {@code kubectl describe} report a repeating event once, as {@code (x12 over 3m)}, rather than + * filling the event list with copies of it. * *

    Recording therefore needs {@code get}, {@code create} and {@code patch} on {@code events} in * the core API group. The patch is made on the resource version the event was read at, so two @@ -55,11 +60,18 @@ public void emit(Event event, Context context) { if (existing == null) { events.resource(event).create(); } else { + var action = event.getAction(); + if (action == null && existing.getEventTime() != null) { + action = event.getReason(); + } var aggregated = new EventBuilder(existing) .withCount(requireNonNullElse(existing.getCount(), 1) + 1) .withLastTimestamp(event.getLastTimestamp()) .withMessage(event.getMessage()) + .withType(event.getType()) + .withReason(event.getReason()) + .withAction(action) .build(); events.resource(existing).patch(aggregated); } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventNamingStrategy.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventNamingStrategy.java index 80f6f33e82..4fb3e7ae64 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventNamingStrategy.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventNamingStrategy.java @@ -30,8 +30,9 @@ * *

    A name must be a valid RFC 1123 DNS subdomain: at most 253 lowercase alphanumeric characters, * {@code -} or {@code .}, starting and ending with an alphanumeric character. Names longer than the - * limit are truncated. A name derived from the object and a fixed lowercase suffix (such as {@code - * -status-report}) satisfies all of this by construction. + * limit are shortened, keeping a hash of the full name so distinct names stay distinct. A name + * derived from the object and a fixed lowercase suffix (such as {@code -status-report}) + * satisfies all of this by construction. * *

    An empty result or an invalid name falls back to the default {@code .} * name, rather than the event being lost to the API server rejecting the name. diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorderIntegrationTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorderIntegrationTest.java new file mode 100644 index 0000000000..9c60ac6b4e --- /dev/null +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorderIntegrationTest.java @@ -0,0 +1,235 @@ +/* + * 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.api.event; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +import org.junit.jupiter.api.Test; + +import io.fabric8.kubeapitest.junit.EnableKubeAPIServer; +import io.fabric8.kubernetes.api.model.ConfigMapBuilder; +import io.fabric8.kubernetes.api.model.Event; +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.fabric8.kubernetes.api.model.NamespaceBuilder; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.KubernetesClientException; +import io.javaoperatorsdk.operator.api.config.ConfigurationService; +import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.Context; + +import static io.javaoperatorsdk.operator.api.config.LeaderElectionConfigurationBuilder.aLeaderElectionConfiguration; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Records events against a real API server, which validates and aggregates them as in a cluster. + */ +@EnableKubeAPIServer +class DefaultEventRecorderIntegrationTest { + + static KubernetesClient client; + + @Test + void countsRepeatedEventsAboutANamespacedResource() { + var configMap = configMap("test1"); + var context = context(configMap, "default"); + + recorder().record(EventRecord.normal("Ready", "all good"), context); + recorder().record(EventRecord.normal("Ready", "all good"), context); + + var events = eventsAbout(configMap, configMap.getMetadata().getNamespace()); + assertThat(events).hasSize(1); + assertThat(events.get(0).getCount()).isEqualTo(2); + } + + @Test + void countsRepeatedEventsAboutAClusterScopedResourceInTheDefaultNamespace() { + var namespace = clusterScoped(); + var context = context(namespace, "default"); + + recorder().record(EventRecord.normal("Ready", "all good"), context); + recorder().record(EventRecord.normal("Ready", "all good"), context); + + var events = eventsAbout(namespace, "default"); + assertThat(events).hasSize(1); + assertThat(events.get(0).getCount()).isEqualTo(2); + assertThat(events.get(0).getEventTime()).isNull(); + } + + @Test + void countsRepeatedEventsAboutAClusterScopedResourceInTheKubeSystemNamespace() { + var namespace = clusterScoped(); + var context = context(namespace, "kube-system"); + + recorder().record(EventRecord.normal("Ready", "all good"), context); + recorder().record(EventRecord.normal("Ready", "all good"), context); + + var events = eventsAbout(namespace, "kube-system"); + assertThat(events).hasSize(1); + assertThat(events.get(0).getCount()).isEqualTo(2); + assertThat(events.get(0).getEventTime()).isNotNull(); + assertThat(events.get(0).getAction()).isEqualTo("Ready"); + } + + @Test + void clusterScopedEventsInOtherNamespacesAreRejectedByTheApiServer() { + client + .namespaces() + .resource( + new NamespaceBuilder().withNewMetadata().withName("operator-ns").endMetadata().build()) + .serverSideApply(); + var namespace = clusterScoped(); + var context = context(namespace, "operator-ns"); + var event = recorder().toEvent(context, EventRecord.normal("Ready", "all good")); + + assertThatThrownBy(() -> new DefaultEventSink(client).emit(event, context)) + .isInstanceOf(KubernetesClientException.class); + assertThat(eventsAbout(namespace, "operator-ns")).isEmpty(); + } + + @Test + void aggregatingOntoANamedEventTakesTheTypeReasonAndActionOfTheLatestOccurrence() { + var configMap = configMap("test2"); + var context = context(configMap, "default"); + var recorder = namedRecorder("named-event-" + UUID.randomUUID()); + + recorder.record( + EventRecord.builder() + .type(EventType.NORMAL) + .reason("Ready") + .message("all good") + .action("Create") + .build(), + context); + recorder.record(EventRecord.warning("Degraded", "replica down"), context); + + var events = eventsAbout(configMap, "default"); + assertThat(events).hasSize(1); + var event = events.get(0); + assertThat(event.getCount()).isEqualTo(2); + assertThat(event.getType()).isEqualTo("Warning"); + assertThat(event.getReason()).isEqualTo("Degraded"); + assertThat(event.getMessage()).isEqualTo("replica down"); + assertThat(event.getAction()).isNull(); + } + + @Test + void aggregatingOntoANamedEventWithAnEventTimeTakesTheTypeReasonAndActionOfTheLatestOccurrence() { + var namespace = clusterScoped(); + var context = context(namespace, "kube-system"); + var recorder = namedRecorder("named-event-" + UUID.randomUUID()); + + recorder.record(EventRecord.normal("Ready", "all good"), context); + recorder.record(EventRecord.warning("Degraded", "replica down"), context); + + var events = eventsAbout(namespace, "kube-system"); + assertThat(events).hasSize(1); + var event = events.get(0); + assertThat(event.getCount()).isEqualTo(2); + assertThat(event.getType()).isEqualTo("Warning"); + assertThat(event.getReason()).isEqualTo("Degraded"); + assertThat(event.getAction()).isEqualTo("Degraded"); + } + + @Test + void longSuppliedNamesAreAcceptedAndStayDistinct() { + var configMap = configMap("test3"); + var context = context(configMap, "default"); + var prefix = "a".repeat(219) + "-"; + var recorder = + DefaultEventRecorder.builder(new DefaultEventSink(client)) + .namingStrategy( + (regarding, record) -> Optional.of(prefix + record.reason().toLowerCase() + "x")) + .build(); + + recorder.record(EventRecord.normal("First", "first"), context); + recorder.record(EventRecord.normal("Second", "second"), context); + + var events = eventsAbout(configMap, "default"); + assertThat(events).hasSize(2); + assertThat(events) + .allSatisfy(event -> assertThat(event.getMetadata().getName()).hasSizeLessThan(254)); + } + + @Test + void generatedNamesShortenedAtASeparatorAreAccepted() { + var configMap = configMap("a".repeat(219) + "-" + "b".repeat(10)); + var context = context(configMap, "default"); + + recorder().record(EventRecord.normal("Ready", "all good"), context); + + assertThat(eventsAbout(configMap, "default")).hasSize(1); + } + + private static DefaultEventRecorder recorder() { + return new DefaultEventRecorder(new DefaultEventSink(client)); + } + + private static DefaultEventRecorder namedRecorder(String name) { + return DefaultEventRecorder.builder(new DefaultEventSink(client)) + .namingStrategy((regarding, record) -> Optional.of(name)) + .build(); + } + + private static List eventsAbout(HasMetadata resource, String namespace) { + return client + .v1() + .events() + .inNamespace(namespace) + .withField("involvedObject.uid", resource.getMetadata().getUid()) + .list() + .getItems(); + } + + private static HasMetadata configMap(String name) { + return new ConfigMapBuilder() + .withNewMetadata() + .withName(name) + .withNamespace("default") + .withUid(UUID.randomUUID().toString()) + .endMetadata() + .build(); + } + + private static HasMetadata clusterScoped() { + return new NamespaceBuilder() + .withNewMetadata() + .withName("ns-" + UUID.randomUUID()) + .withUid(UUID.randomUUID().toString()) + .endMetadata() + .build(); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + private static Context context(HasMetadata primaryResource, String clusterScopedNamespace) { + var configurationService = mock(ConfigurationService.class); + when(configurationService.getLeaderElectionConfiguration()) + .thenReturn( + Optional.of(aLeaderElectionConfiguration("lease").withIdentity("pod-1").build())); + when(configurationService.clusterScopedEventNamespace()).thenReturn(clusterScopedNamespace); + ControllerConfiguration controllerConfiguration = mock(ControllerConfiguration.class); + when(controllerConfiguration.getName()).thenReturn("testcontroller"); + when(controllerConfiguration.getConfigurationService()).thenReturn(configurationService); + Context context = mock(Context.class); + when(context.getPrimaryResource()).thenReturn(primaryResource); + when(context.getControllerConfiguration()).thenReturn(controllerConfiguration); + return context; + } +} diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorderTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorderTest.java index 388217b9be..3cedc6cc9f 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorderTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorderTest.java @@ -436,19 +436,41 @@ void stripsTrailingSeparatorsFromTruncatedNames() { EventRecord.builder() .reason("Created") .message("created") - .name("a".repeat(252) + "." + "b".repeat(47)) + .name("a".repeat(219) + "." + "b".repeat(47)) .build(), context(configMap())); recorder.record( EventRecord.builder() .reason("Created") .message("created") - .name("b".repeat(252) + "-" + "c".repeat(47)) + .name("b".repeat(219) + "-" + "c".repeat(47)) .build(), context(configMap())); - assertThat(emitted.get(0).getMetadata().getName()).isEqualTo("a".repeat(252)); - assertThat(emitted.get(1).getMetadata().getName()).isEqualTo("b".repeat(252)); + assertThat(emitted.get(0).getMetadata().getName()).matches("a{219}\\.[0-9a-f]{32}"); + assertThat(emitted.get(1).getMetadata().getName()).matches("b{219}\\.[0-9a-f]{32}"); + } + + @Test + void keepsLongSuppliedNamesSharingTheirPrefixDistinct() { + recorder.record( + EventRecord.builder() + .reason("Created") + .message("created") + .name("a".repeat(300) + "-one") + .build(), + context(configMap())); + recorder.record( + EventRecord.builder() + .reason("Created") + .message("created") + .name("a".repeat(300) + "-two") + .build(), + context(configMap())); + + assertThat(emitted.get(0).getMetadata().getName()).hasSize(253); + assertThat(emitted.get(0).getMetadata().getName()) + .isNotEqualTo(emitted.get(1).getMetadata().getName()); } @Test diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/EventRecorderRegressionTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/EventRecorderRegressionTest.java new file mode 100644 index 0000000000..582b379859 --- /dev/null +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/EventRecorderRegressionTest.java @@ -0,0 +1,310 @@ +/* + * 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.api.event; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.jupiter.api.Test; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.ConfigMapBuilder; +import io.fabric8.kubernetes.api.model.Event; +import io.fabric8.kubernetes.api.model.EventBuilder; +import io.fabric8.kubernetes.api.model.EventList; +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.fabric8.kubernetes.api.model.MicroTime; +import io.fabric8.kubernetes.api.model.NamespaceBuilder; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.dsl.MixedOperation; +import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; +import io.fabric8.kubernetes.client.dsl.Resource; +import io.fabric8.kubernetes.client.dsl.V1APIGroupDSL; +import io.javaoperatorsdk.operator.api.config.ConfigurationService; +import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.Context; + +import static io.javaoperatorsdk.operator.api.config.LeaderElectionConfigurationBuilder.aLeaderElectionConfiguration; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** Regression tests for the aggregation, naming and namespacing of recorded events. */ +class EventRecorderRegressionTest { + + private final List emitted = new ArrayList<>(); + + /** + * The core/v1 API server (legacyValidateEvent in pkg/apis/core/validation/events.go) rejects an + * event whose involvedObject.namespace is empty unless the event itself lives in "" or "default", + * or in "kube-system" if it carries an eventTime, and with it an action. No other namespace is + * accepted. + */ + @Test + void clusterScopedEventsInTheKubeSystemNamespaceCarryAnEventTimeAndAnAction() { + var recorder = new DefaultEventRecorder((event, context) -> emitted.add(event)); + + recorder.record( + EventRecord.normal("Created", "created"), context(clusterScoped("ns1"), "kube-system")); + + var event = emitted.get(0); + assertThat(event.getInvolvedObject().getNamespace()).isNull(); + assertThat(event.getMetadata().getNamespace()).isEqualTo("kube-system"); + assertThat(event.getEventTime().getTime()) + .matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{6}Z"); + assertThat(event.getAction()).isEqualTo("Created"); + } + + @Test + void aSuppliedActionIsKeptOnClusterScopedEventsInTheKubeSystemNamespace() { + var recorder = new DefaultEventRecorder((event, context) -> emitted.add(event)); + + recorder.record( + EventRecord.builder() + .type(EventType.NORMAL) + .reason("Created") + .message("created") + .action("Create") + .build(), + context(clusterScoped("ns1"), "kube-system")); + + assertThat(emitted.get(0).getAction()).isEqualTo("Create"); + } + + @Test + void clusterScopedEventsInTheDefaultNamespaceDoNotCarryAnEventTime() { + var recorder = new DefaultEventRecorder((event, context) -> emitted.add(event)); + + recorder.record( + EventRecord.normal("Created", "created"), context(clusterScoped("ns1"), "default")); + + assertThat(emitted.get(0).getEventTime()).isNull(); + assertThat(emitted.get(0).getMetadata().getNamespace()).isEqualTo("default"); + } + + /** + * A naming strategy (here the one EventNamingStrategy's javadoc suggests, a fixed suffix per + * object) makes the name the aggregation identity on its own, so records with different type and + * reason resolve to the same event. DefaultEventSink patches type and reason along with count, + * lastTimestamp and message, so the event describes the latest occurrence. + */ + @Test + void aggregatingOntoANamedEventTakesTheTypeAndReasonOfTheLatestOccurrence() { + var stored = new AtomicReference(); + var patched = new AtomicReference(); + var sink = new DefaultEventSink(mockClient(stored, patched)); + var recorder = + DefaultEventRecorder.builder(sink) + .namingStrategy( + (regarding, record) -> + Optional.of(regarding.getMetadata().getName() + "-status-report")) + .build(); + var context = context(configMap("test1"), "default"); + + recorder.record(EventRecord.normal("Ready", "all good"), context); + recorder.record(EventRecord.warning("Degraded", "replica down"), context); + + assertThat(patched.get()).isNotNull(); + assertThat(patched.get().getCount()).isEqualTo(2); + assertThat(patched.get().getMessage()).isEqualTo("replica down"); + assertThat(patched.get().getType()).isEqualTo("Warning"); + assertThat(patched.get().getReason()).isEqualTo("Degraded"); + } + + @Test + void aggregatingOntoAnEventWithAnEventTimeUpdatesTypeReasonAndAction() { + var stored = new AtomicReference(); + var patched = new AtomicReference(); + var sink = new DefaultEventSink(mockClient(stored, patched)); + var recorder = + DefaultEventRecorder.builder(sink) + .namingStrategy((regarding, record) -> Optional.of("fixed-name")) + .build(); + var context = context(clusterScoped("ns1"), "kube-system"); + + recorder.record(EventRecord.normal("Ready", "all good"), context); + recorder.record(EventRecord.warning("Degraded", "replica down"), context); + + assertThat(stored.get().getEventTime()).isNotNull(); + assertThat(patched.get().getCount()).isEqualTo(2); + assertThat(patched.get().getType()).isEqualTo("Warning"); + assertThat(patched.get().getReason()).isEqualTo("Degraded"); + assertThat(patched.get().getAction()).isEqualTo("Degraded"); + } + + @Test + void aggregatingOntoANamedEventWithoutAnActionClearsTheActionOfTheEarlierOccurrence() { + var stored = new AtomicReference(); + var patched = new AtomicReference(); + var sink = new DefaultEventSink(mockClient(stored, patched)); + var recorder = + DefaultEventRecorder.builder(sink) + .namingStrategy((regarding, record) -> Optional.of("fixed-name")) + .build(); + var context = context(configMap("test1"), "default"); + + recorder.record( + EventRecord.builder() + .type(EventType.NORMAL) + .reason("Created") + .message("created") + .action("Create") + .build(), + context); + recorder.record(EventRecord.warning("Degraded", "replica down"), context); + + assertThat(patched.get().getAction()).isNull(); + } + + @Test + void aggregatingOntoAnEventWithAnEventTimeWithoutAnActionFallsBackToTheReason() { + var stored = new AtomicReference(); + var patched = new AtomicReference(); + stored.set( + new EventBuilder() + .withNewMetadata() + .withName("fixed-name") + .withNamespace("default") + .endMetadata() + .withEventTime(new MicroTime("2026-01-01T00:00:00.000000Z")) + .withAction("Create") + .withCount(1) + .build()); + var sink = new DefaultEventSink(mockClient(stored, patched)); + var recorder = + DefaultEventRecorder.builder(sink) + .namingStrategy((regarding, record) -> Optional.of("fixed-name")) + .build(); + + recorder.record( + EventRecord.warning("Degraded", "replica down"), context(configMap("test1"), "default")); + + assertThat(patched.get().getEventTime()).isNotNull(); + assertThat(patched.get().getAction()).isEqualTo("Degraded"); + } + + @Test + void shortenedGeneratedNamesDoNotEndInASeparatorBeforeTheHash() { + var recorder = new DefaultEventRecorder((event, context) -> emitted.add(event)); + + recorder.record( + EventRecord.normal("Created", "created"), + context(configMap("a".repeat(219) + "-" + "b".repeat(10)), "default")); + + assertThat(emitted.get(0).getMetadata().getName()).matches("a{219}\\.[0-9a-f]{32}"); + } + + /** + * Supplied names longer than 253 characters are shortened with a hash of the full name, so two + * different events of a long-named object are not merged into one. + */ + @Test + void longSuppliedNamesStayDistinct() { + var recorder = + DefaultEventRecorder.builder((event, context) -> emitted.add(event)) + .namingStrategy( + (regarding, record) -> + Optional.of( + regarding.getMetadata().getName() + "-" + record.reason().toLowerCase())) + .build(); + var context = context(configMap("a".repeat(245)), "default"); + + recorder.record(EventRecord.warning("BackoffLimitExceeded", "job failed"), context); + recorder.record(EventRecord.warning("BackoffStarted", "job retrying"), context); + + assertThat(emitted.get(0).getMetadata().getName()) + .isNotEqualTo(emitted.get(1).getMetadata().getName()); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private KubernetesClient mockClient( + AtomicReference stored, AtomicReference patched) { + var client = mock(KubernetesClient.class); + var v1 = mock(V1APIGroupDSL.class); + MixedOperation> events = mock(MixedOperation.class); + NonNamespaceOperation> inNs = + mock(NonNamespaceOperation.class); + when(client.v1()).thenReturn(v1); + when(v1.events()).thenReturn(events); + when(events.inNamespace(anyString())).thenReturn(inNs); + Resource byName = mock(Resource.class); + when(inNs.withName(anyString())).thenReturn(byName); + when(byName.get()).thenAnswer(i -> stored.get()); + when(inNs.resource(any(Event.class))) + .thenAnswer( + i -> { + Event target = i.getArgument(0); + Resource r = mock(Resource.class); + when(r.create()) + .thenAnswer( + c -> { + stored.set(target); + return target; + }); + when(r.patch(any(Event.class))) + .thenAnswer( + p -> { + Event e = p.getArgument(0); + patched.set(e); + stored.set(e); + return e; + }); + return r; + }); + return client; + } + + @SuppressWarnings("rawtypes") + private Context context(HasMetadata primaryResource, String clusterScopedEventNamespace) { + var configurationService = mock(ConfigurationService.class); + when(configurationService.getLeaderElectionConfiguration()) + .thenReturn( + Optional.of(aLeaderElectionConfiguration("lease").withIdentity("pod-1").build())); + when(configurationService.clusterScopedEventNamespace()) + .thenReturn(clusterScopedEventNamespace); + ControllerConfiguration controllerConfiguration = mock(ControllerConfiguration.class); + when(controllerConfiguration.getName()).thenReturn("testcontroller"); + when(controllerConfiguration.getConfigurationService()).thenReturn(configurationService); + Context context = mock(Context.class); + when(context.getPrimaryResource()).thenReturn(primaryResource); + when(context.getControllerConfiguration()).thenReturn(controllerConfiguration); + return context; + } + + private HasMetadata clusterScoped(String name) { + return new NamespaceBuilder() + .withNewMetadata() + .withName(name) + .withUid("uid-3") + .endMetadata() + .build(); + } + + private ConfigMap configMap(String name) { + return new ConfigMapBuilder() + .withNewMetadata() + .withName(name) + .withNamespace("ns1") + .withUid("uid-1") + .withResourceVersion("42") + .endMetadata() + .build(); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorder/ClusterScopedEventRecorderIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorder/ClusterScopedEventRecorderIT.java new file mode 100644 index 0000000000..7af90b3373 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorder/ClusterScopedEventRecorderIT.java @@ -0,0 +1,83 @@ +/* + * 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.eventrecorder; + +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import io.fabric8.kubernetes.api.model.Event; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.baseapi.clusterscopedresource.ClusterScopedCustomResource; +import io.javaoperatorsdk.operator.baseapi.clusterscopedresource.ClusterScopedCustomResourceSpec; +import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +class ClusterScopedEventRecorderIT { + + public static final String TEST_RESOURCE_NAME = "event-recorder-test1"; + + @RegisterExtension + LocallyRunOperatorExtension extension = + LocallyRunOperatorExtension.builder() + .withReconciler(new ClusterScopedEventRecorderReconciler()) + .build(); + + @Test + void recordsAndCountsEventsAboutAClusterScopedResourceInTheDefaultNamespace() { + var resource = extension.create(testResource()); + var uid = resource.getMetadata().getUid(); + await().untilAsserted(() -> assertThat(eventsAbout(uid)).hasSize(1)); + + resource.getMetadata().setAnnotations(Map.of("reconcile", "again")); + extension.replace(resource); + + await() + .untilAsserted( + () -> { + var events = eventsAbout(uid); + assertThat(events).hasSize(1); + assertThat(events.get(0).getReason()) + .isEqualTo(ClusterScopedEventRecorderReconciler.REASON); + assertThat(events.get(0).getInvolvedObject().getNamespace()).isNull(); + assertThat(events.get(0).getCount()).isGreaterThanOrEqualTo(2); + }); + } + + private List eventsAbout(String uid) { + return extension + .getKubernetesClient() + .v1() + .events() + .inNamespace("default") + .withField("involvedObject.uid", uid) + .list() + .getItems(); + } + + ClusterScopedCustomResource testResource() { + var resource = new ClusterScopedCustomResource(); + resource.setMetadata(new ObjectMetaBuilder().withName(TEST_RESOURCE_NAME).build()); + resource.setSpec(new ClusterScopedCustomResourceSpec()); + resource.getSpec().setTargetNamespace(extension.getNamespace()); + resource.getSpec().setData("data"); + return resource; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorder/ClusterScopedEventRecorderReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorder/ClusterScopedEventRecorderReconciler.java new file mode 100644 index 0000000000..988c46f597 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorder/ClusterScopedEventRecorderReconciler.java @@ -0,0 +1,36 @@ +/* + * 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.eventrecorder; + +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; +import io.javaoperatorsdk.operator.baseapi.clusterscopedresource.ClusterScopedCustomResource; + +@ControllerConfiguration(generationAwareEventProcessing = false) +public class ClusterScopedEventRecorderReconciler + implements Reconciler { + + public static final String REASON = "Reconciled"; + + @Override + public UpdateControl reconcile( + ClusterScopedCustomResource resource, Context context) { + context.eventRecorder().normal(REASON, "cluster scoped resource reconciled"); + return UpdateControl.noUpdate(); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorder/ClusterScopedKubeSystemEventRecorderIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorder/ClusterScopedKubeSystemEventRecorderIT.java new file mode 100644 index 0000000000..eebe152fd3 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorder/ClusterScopedKubeSystemEventRecorderIT.java @@ -0,0 +1,87 @@ +/* + * 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.eventrecorder; + +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import io.fabric8.kubernetes.api.model.Event; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.baseapi.clusterscopedresource.ClusterScopedCustomResource; +import io.javaoperatorsdk.operator.baseapi.clusterscopedresource.ClusterScopedCustomResourceSpec; +import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +class ClusterScopedKubeSystemEventRecorderIT { + + public static final String TEST_RESOURCE_NAME = "event-recorder-test2"; + + @RegisterExtension + LocallyRunOperatorExtension extension = + LocallyRunOperatorExtension.builder() + .withReconciler(new ClusterScopedEventRecorderReconciler()) + .withConfigurationService(o -> o.withClusterScopedEventNamespace("kube-system")) + .build(); + + @Test + void recordsAndCountsEventsAboutAClusterScopedResourceInTheKubeSystemNamespace() { + var resource = extension.create(testResource()); + var uid = resource.getMetadata().getUid(); + await().untilAsserted(() -> assertThat(eventsAbout(uid)).hasSize(1)); + + resource.getMetadata().setAnnotations(Map.of("reconcile", "again")); + extension.replace(resource); + + await() + .untilAsserted( + () -> { + var events = eventsAbout(uid); + assertThat(events).hasSize(1); + assertThat(events.get(0).getReason()) + .isEqualTo(ClusterScopedEventRecorderReconciler.REASON); + assertThat(events.get(0).getInvolvedObject().getNamespace()).isNull(); + assertThat(events.get(0).getEventTime()).isNotNull(); + assertThat(events.get(0).getAction()) + .isEqualTo(ClusterScopedEventRecorderReconciler.REASON); + assertThat(events.get(0).getCount()).isGreaterThanOrEqualTo(2); + }); + } + + private List eventsAbout(String uid) { + return extension + .getKubernetesClient() + .v1() + .events() + .inNamespace("kube-system") + .withField("involvedObject.uid", uid) + .list() + .getItems(); + } + + ClusterScopedCustomResource testResource() { + var resource = new ClusterScopedCustomResource(); + resource.setMetadata(new ObjectMetaBuilder().withName(TEST_RESOURCE_NAME).build()); + resource.setSpec(new ClusterScopedCustomResourceSpec()); + resource.getSpec().setTargetNamespace(extension.getNamespace()); + resource.getSpec().setData("data"); + return resource; + } +} From 527361fd1ea84a5f495b492ad75bada2b8000fd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Attila=20M=C3=A9sz=C3=A1ros?= Date: Fri, 6 Nov 2026 00:32:37 +0100 Subject: [PATCH 13/23] fix: missing override annotation (#3677) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Attila Mészáros --- .../baseapi/virtualthreads/VirtualThreadsTestReconciler.java | 1 + 1 file changed, 1 insertion(+) diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/virtualthreads/VirtualThreadsTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/virtualthreads/VirtualThreadsTestReconciler.java index ee6f00f499..50a84d08c1 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/virtualthreads/VirtualThreadsTestReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/virtualthreads/VirtualThreadsTestReconciler.java @@ -58,6 +58,7 @@ public UpdateControl reconcile( return UpdateControl.noUpdate(); } + @Override public int getNumberOfExecutions() { return numberOfExecutions.get(); } From 26e0c0f5bfe86681289070b315f99b516f6ec021 Mon Sep 17 00:00:00 2001 From: Antonio <122279781+afalhambra-hivemq@users.noreply.github.com> Date: Wed, 11 Nov 2026 00:03:16 +0100 Subject: [PATCH 14/23] feat: fail on error option for the default event recorder (#3688) Signed-off-by: Antonio Fernandez Alhambra --- .../documentation/operations/configuration.md | 22 ++++++++-- .../api/config/ConfigurationService.java | 6 +-- .../api/event/DefaultEventRecorder.java | 41 ++++++++++++++++--- .../operator/api/event/DefaultEventSink.java | 3 +- .../operator/api/event/EventRecorder.java | 4 +- .../api/event/ResourceEventRecorder.java | 3 -- .../api/event/DefaultEventRecorderTest.java | 31 ++++++++++++++ 7 files changed, 92 insertions(+), 18 deletions(-) diff --git a/docs/content/en/docs/documentation/operations/configuration.md b/docs/content/en/docs/documentation/operations/configuration.md index 0b469e8312..11d1b7117f 100644 --- a/docs/content/en/docs/documentation/operations/configuration.md +++ b/docs/content/en/docs/documentation/operations/configuration.md @@ -386,8 +386,24 @@ Recording events requires the operator's service account to be allowed `get`, `c created, and an event that does is a repeat of one already recorded, which is patched to count the new occurrence instead of being recorded a second time. The [generic Helm chart](helm-chart.md) grants all three. If you write your own RBAC and a permission is -missing, recording fails silently as far as reconciliation is concerned: the failure is swallowed so -that it cannot break a reconciliation, and only shows up as a warning in the operator log. +missing, recording fails silently as far as reconciliation is concerned by default: the failure is +swallowed so that it cannot break a reconciliation, and only shows up as a warning in the operator +log. Kubernetes treats events as best effort, supplemental data, so this is usually what you want. +Where an event that is not recorded must not go unnoticed, configure a recorder that propagates the +failure to the reconciler instead, so that the reconciliation fails and is retried like any other +failed one: + +```java +KubernetesClient client = new KubernetesClientBuilder().build(); +Operator operator = new Operator(override -> override + .withKubernetesClient(client) + .withEventRecorder(DefaultEventRecorder.builder(new DefaultEventSink(client)) + .failOnError(true) + .build())); +``` + +Every failure propagates then, transient ones included, such as the conflict two replicas run into +when they count the same occurrence of an event at the same time. Note that events live in a namespace of their own choosing, which is the namespace of the object they are about, and for cluster scoped objects the namespace configured above. A namespaced `Role` @@ -398,7 +414,7 @@ cluster scoped resources. A `ClusterRole` covers all of them at once. The API server only accepts events about cluster scoped objects in the `default` and `kube-system` namespaces, so those are the only values `josdk.events.cluster-scoped-namespace` can usefully be set to. In particular, the namespace the operator itself runs in is rejected, and the event dropped with -a warning in the operator log. +a warning in the operator log (or, with `failOnError(true)`, the reconciliation failed). #### Leader Election diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java index 6a7f2f93d5..844af80ce2 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java @@ -391,9 +391,9 @@ default Optional getLeaderElectionConfiguration() { * recorded by the built-in controllers. Operators whose RBAC does not allow creating events in * the {@code default} namespace can override this with {@code kube-system}. The API server * rejects events about cluster scoped resources in any other namespace, such as the namespace the - * operator itself runs in. Note that recording an event is best effort, so a missing permission - * or a rejected namespace results in the event being dropped with a warning in the log rather - * than in an error. + * operator itself runs in. Note that recording an event is best effort by default, so a missing + * permission or a rejected namespace results in the event being dropped with a warning in the log + * rather than in an error. * * @return the namespace to record events about cluster scoped resources in */ diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorder.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorder.java index 9bd54ef96c..248972cd01 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorder.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorder.java @@ -58,6 +58,11 @@ * event already recorded for it. Repeat occurrences are then counted on that event rather than * recorded as copies of it, see {@link DefaultEventSink}. How events aggregate, how they are named * and whether they carry an owner reference can be configured, see {@link #builder(EventSink)}. + * + *

    Recording is best effort by default: an event that cannot be written is logged and dropped, + * and the caller carries on. A recorder built with {@link Builder#failOnError(boolean)} propagates + * the failure to the caller instead, so that a reconciliation that cannot record its events fails + * and is retried. */ public class DefaultEventRecorder implements EventRecorder { @@ -95,20 +100,23 @@ public class DefaultEventRecorder implements EventRecorder { private final EventNamingStrategy namingStrategy; private final EventKeyStrategy keyStrategy; private final boolean ownerReference; + private final boolean failOnError; public DefaultEventRecorder(EventSink sink) { - this(sink, EventNamingStrategy.none(), EventKeyStrategy.none(), false); + this(sink, EventNamingStrategy.none(), EventKeyStrategy.none(), false, false); } private DefaultEventRecorder( EventSink sink, EventNamingStrategy namingStrategy, EventKeyStrategy keyStrategy, - boolean ownerReference) { + boolean ownerReference, + boolean failOnError) { this.sink = sink; this.namingStrategy = namingStrategy; this.keyStrategy = keyStrategy; this.ownerReference = ownerReference; + this.failOnError = failOnError; } public static Builder builder(EventSink sink) { @@ -122,6 +130,7 @@ public static final class Builder { private EventNamingStrategy namingStrategy = EventNamingStrategy.none(); private EventKeyStrategy keyStrategy = EventKeyStrategy.none(); private boolean ownerReference = false; + private boolean failOnError = false; private Builder(EventSink sink) { this.sink = Objects.requireNonNull(sink, "sink must not be null"); @@ -157,8 +166,26 @@ public Builder ownerReference(boolean ownerReference) { return this; } + /** + * When set, a failure to record an event is propagated to the caller rather than logged and + * swallowed, so that the reconciliation recording the event fails and goes through the usual + * error handling and retries. Off by default: Kubernetes treats events as best effort, + * supplemental data, and a controller that cannot reconcile because it cannot write an event is + * usually worse off than one that records nothing. Enable it only where an event that is not + * recorded must not go unnoticed. + * + *

    Every failure propagates, transient ones included, such as a conflicting write when two + * replicas aggregate the same event at the same time; the reconciliation is then retried like + * any other failed one. + */ + public Builder failOnError(boolean failOnError) { + this.failOnError = failOnError; + return this; + } + public DefaultEventRecorder build() { - return new DefaultEventRecorder(sink, namingStrategy, keyStrategy, ownerReference); + return new DefaultEventRecorder( + sink, namingStrategy, keyStrategy, ownerReference, failOnError); } } @@ -199,8 +226,12 @@ public void record(EventRecord event, Context context) { assembled = toEvent(context, event); sink.emit(assembled, context); } catch (Exception e) { - // recording an event must never break the caller: a controller that fails to reconcile - // because it could not write an event is strictly worse than one that records nothing + if (failOnError) { + throw e; + } + // by default recording an event must not break the caller: a controller that fails to + // reconcile because it could not write an event is usually worse off than one that records + // nothing log.warn( "Could not record {} event named {} with reason {} for resource {} in namespace {}", event.type(), diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventSink.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventSink.java index ddb0b074bb..4d86aa0728 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventSink.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventSink.java @@ -41,8 +41,7 @@ *

    Recording therefore needs {@code get}, {@code create} and {@code patch} on {@code events} in * the core API group. The patch is made on the resource version the event was read at, so two * writers counting the same occurrence at the same time conflict, and the one that loses leaves the - * occurrence uncounted and the conflict logged by {@link DefaultEventRecorder}, recording being - * best effort. + * occurrence uncounted and the conflict to {@link DefaultEventRecorder} to handle. */ public class DefaultEventSink implements EventSink { diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventRecorder.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventRecorder.java index 9c4984f187..e752cff939 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventRecorder.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventRecorder.java @@ -34,8 +34,8 @@ * io.javaoperatorsdk.operator.api.reconciler.Context#eventRecorder()}, which is already bound to * the context. * - *

    Recording an event is best effort: failures to write the event to the cluster are logged and - * swallowed, and never fail the caller. + *

    Whether a failure to record an event fails the caller is up to the implementation, see {@link + * DefaultEventRecorder} for the default. */ @Experimental(API_MIGHT_CHANGE) public interface EventRecorder { diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/ResourceEventRecorder.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/ResourceEventRecorder.java index 0350688af3..dfb88dc7fd 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/ResourceEventRecorder.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/ResourceEventRecorder.java @@ -22,9 +22,6 @@ /** * An {@link EventRecorder} bound to a single object, typically the primary resource of the current * reconciliation. - * - *

    Recording an event is best effort: failures to write the event to the cluster are logged and - * swallowed, and never fail the caller. */ @Experimental(API_MIGHT_CHANGE) public interface ResourceEventRecorder { diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorderTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorderTest.java index 3cedc6cc9f..12d1f65907 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorderTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorderTest.java @@ -35,6 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -175,6 +176,36 @@ void aFailingSinkNeverFailsTheCaller() { .doesNotThrowAnyException(); } + @Test + void aFailingSinkFailsTheCallerWhenTheRecorderIsBuiltToFailOnError() { + var failure = new RuntimeException("API server said no"); + var failing = + DefaultEventRecorder.builder( + (event, context) -> { + throw failure; + }) + .failOnError(true) + .build(); + + assertThatThrownBy( + () -> failing.record(EventRecord.normal("Created", "created"), context(configMap()))) + .isSameAs(failure); + } + + @Test + void aFailingSinkNeverFailsTheCallerWhenTheRecorderIsBuiltWithDefaults() { + var failing = + DefaultEventRecorder.builder( + (event, context) -> { + throw new RuntimeException("API server said no"); + }) + .build(); + + assertThatCode( + () -> failing.record(EventRecord.normal("Created", "created"), context(configMap()))) + .doesNotThrowAnyException(); + } + @Test void passesTheContextOnToTheSink() { var contexts = new ArrayList>(); From 4ee71930f3ee1b21a19f65ab876ce0c629181d0d Mon Sep 17 00:00:00 2001 From: Antonio <122279781+afalhambra-hivemq@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:10:13 +0100 Subject: [PATCH 15/23] feat: record events about objects other than the primary resource (#3690) * feat: record events about objects other than the primary resource Signed-off-by: Antonio Fernandez Alhambra --- docs/content/en/docs/documentation/_index.md | 1 + .../docs/documentation/kubernetes-events.md | 93 ++++++++++++ .../documentation/operations/configuration.md | 3 + .../en/docs/migration/v5-7-migration.md | 17 +++ .../api/config/ConfigurationService.java | 4 +- .../api/event/BoundResourceEventRecorder.java | 46 ++++++ .../api/event/DefaultEventRecorder.java | 53 +++---- .../operator/api/event/EventRecorder.java | 69 +++++++-- .../operator/api/event/EventSink.java | 5 +- .../api/event/ResourceEventRecorder.java | 2 +- .../operator/api/reconciler/Context.java | 21 ++- .../api/reconciler/DefaultContext.java | 5 + .../ConfigurationServiceOverriderTest.java | 14 +- .../DefaultEventRecorderIntegrationTest.java | 4 +- .../api/event/DefaultEventRecorderTest.java | 122 +++++++++++++++- .../operator/api/event/EventRecorderTest.java | 136 ++++++++++++++++++ .../api/reconciler/DefaultContextTest.java | 23 +++ .../CleanerForReconcilerIT.java | 3 + .../eventrecorder/EventRecorderIT.java | 53 ++++++- .../EventRecorderReconciler.java | 20 +++ ...nerForManagedDependentResourcesOnlyIT.java | 8 +- 21 files changed, 621 insertions(+), 81 deletions(-) create mode 100644 docs/content/en/docs/documentation/kubernetes-events.md create mode 100644 operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/BoundResourceEventRecorder.java create mode 100644 operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/EventRecorderTest.java diff --git a/docs/content/en/docs/documentation/_index.md b/docs/content/en/docs/documentation/_index.md index d639b8b9f9..a5368978da 100644 --- a/docs/content/en/docs/documentation/_index.md +++ b/docs/content/en/docs/documentation/_index.md @@ -25,6 +25,7 @@ This section contains detailed documentation for all Java Operator SDK features - **[Eventing](eventing/)** - Understanding the event-driven model - **[Event filters](event-filters/)** - Filtering events and the default filter behavior - **[Accessing Resources in Caches](working-with-es-caches/)** - How to access resources in caches +- **[Recording Kubernetes Events](kubernetes-events/)** - Surfacing controller actions in `kubectl describe` - **[Operations](operations/)** - Helm chart, metrics, logging, configurations, leader election - **[Other Features](features/)** - Additional capabilities and integrations diff --git a/docs/content/en/docs/documentation/kubernetes-events.md b/docs/content/en/docs/documentation/kubernetes-events.md new file mode 100644 index 0000000000..23010a588f --- /dev/null +++ b/docs/content/en/docs/documentation/kubernetes-events.md @@ -0,0 +1,93 @@ +--- +title: Recording Kubernetes Events +weight: 51 +--- + +A controller can record Kubernetes events, so that what it does shows up where users already look +for it: `kubectl describe` on the resource the event is about. Events are informational and best +effort by design, Kubernetes keeps them for a limited time and treats them as supplemental data, so +they complement the status of a resource rather than replace it. + +## Recording from a reconciliation + +Inside a reconciliation the recorder is available from the `Context`, bound to the primary resource: + +```java +@Override +public UpdateControl reconcile(MyResource resource, Context context) { + context.eventRecorder().normal("Reconciled", "resource reconciled"); + context.eventRecorder().warn("SomethingIsOff", "this is a warning about the resource"); + return UpdateControl.noUpdate(); +} +``` + +For more control, build an `EventRecord`, which also carries an optional action, reporting +component, labels and annotations: + +```java +context.eventRecorder().record(EventRecord.builder() + .type(EventType.WARNING) + .reason("DeploymentFailed") + .message("could not scale the deployment") + .action("Scaling") + .build()); +``` + +## Recording about another object + +An event does not have to be about the primary resource. A controller reconciling a child resource +can, for example, record on the parent, so that `kubectl describe parent` shows what happened to its +children. Bind the recorder to the other object instead: + +```java +var parent = context.getSecondaryResource(Parent.class).orElseThrow(); +context.eventRecorder(parent).warn("ChildFailed", "could not reconcile child " + name); +``` + +The event references the given object as its involved object and lives in that object's namespace, +or, for a cluster scoped object, in the namespace configured for such events (see below). It is +still attributed to the controller recording it. Aggregation works per object: two children +recording the same reason and message on one parent count as repeats of a single event on the +parent, while different messages stay separate events. + +## What an event carries + +The recorder fills in everything derivable from the controller and the object: the involved object +reference, the reporting controller (the controller name, or the reporting component set on the +record), the reporting instance (the leader election identity when configured, otherwise the host +name, which in a pod is the pod name), the timestamps and the count. + +Repeats are aggregated, not duplicated. Events are named deterministically, after the object they +are about plus a hash of everything that identifies the event, so recording the same event again +resolves to the event already recorded and counts the occurrence on it. That is what makes `kubectl +describe` report a repeating event once, as `(x12 over 3m)`, instead of listing copies. Use +`EventRecord.Builder#key(...)` to control what counts as the same event, or configure the default +through `DefaultEventRecorder.builder(sink).keyStrategy(...)`, see the javadoc of +`EventKeyStrategy` and `EventNamingStrategy`. + +Events about cluster scoped objects live in the namespace configured through +`withClusterScopedEventNamespace(...)` or the `josdk.events.cluster-scoped-namespace` property, +`default` unless configured otherwise. The API server only accepts `default` and `kube-system`. + +## Failure handling + +Recording is best effort by default: a failure to write the event is logged as a warning and +swallowed, and never fails the reconciliation. To make such a failure fail the reconciliation +instead, so that it goes through the usual error handling and retries, configure the default +recorder with `failOnError(true)`, see the +[Events section of the configuration page](operations/configuration.md#events) for the snippet. + +## Custom recorders + +To assemble events differently or send them somewhere else entirely, plug in an `EventRecorder` of +your own for the whole operator with `withEventRecorder(...)`. A custom recorder is shared by all +controllers, so it must be stateless and thread safe; it implements a single method, +`record(HasMetadata regarding, EventRecord event, Context context)`, and gets the bound views for +free. Extend `DefaultEventRecorder` and override `toEvent(...)` to change how events are assembled, +or implement an `EventSink` to change where the assembled events go. + +## Permissions + +Recording needs `get`, `create` and `patch` on `events` in the core API group in every namespace +events are recorded in, see the +[Events section of the configuration page](operations/configuration.md#events). diff --git a/docs/content/en/docs/documentation/operations/configuration.md b/docs/content/en/docs/documentation/operations/configuration.md index 11d1b7117f..6c78efc4d7 100644 --- a/docs/content/en/docs/documentation/operations/configuration.md +++ b/docs/content/en/docs/documentation/operations/configuration.md @@ -377,6 +377,9 @@ All operator-level keys are prefixed with `josdk.`. #### Events +See [Recording Kubernetes Events](../kubernetes-events.md) for how events are recorded. The key +below configures where events about cluster scoped resources go. + | Key | Type | Description | |---|---|---| | `josdk.events.cluster-scoped-namespace` | `String` | Namespace to record events about cluster scoped resources in (defaults to `default`); the API server only accepts `default` and `kube-system` | diff --git a/docs/content/en/docs/migration/v5-7-migration.md b/docs/content/en/docs/migration/v5-7-migration.md index 9ac3ae40b4..faaa8af841 100644 --- a/docs/content/en/docs/migration/v5-7-migration.md +++ b/docs/content/en/docs/migration/v5-7-migration.md @@ -110,3 +110,20 @@ on one of the following: executor supplier, `null` to have the event source create an executor of its own. - `ExecutorServiceManager.scheduledExecutorService()` is deprecated. The framework doesn't use it anymore, it creates the executor on first use, and shuts it down when the manager is stopped. + +## Event recorder: events about any object + +The event recorder can now record events about objects other than the primary resource, with +`context.eventRecorder(otherObject)`, see +[Recording Kubernetes Events](../documentation/kubernetes-events.md). Reconcilers that only use +`context.eventRecorder()` are not affected. The low level API, which is experimental, changed to +make this possible: + +- A custom `EventRecorder` implements + `record(HasMetadata regarding, EventRecord event, Context context)` instead of + `record(EventRecord, Context)` and `forContext(Context)`. Those two are now default methods + that delegate to the new one, as is the new `forResource(HasMetadata, Context)`. +- A subclass of `DefaultEventRecorder` overrides or calls + `toEvent(HasMetadata regarding, EventRecord record, Context context)` instead of + `toEvent(Context, EventRecord)`. An override of the old signature without `@Override` still + compiles but is no longer called. diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java index 844af80ce2..a64c1ab953 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java @@ -408,8 +408,8 @@ default String clusterScopedEventNamespace() { * *

    When empty, which is the default, every controller gets a {@link DefaultEventRecorder} of * its own. A recorder configured here is shared by all controllers of the operator instead, which - * is why the reconciliation an event is recorded from is passed to it per call rather than - * configured on it: implementations have to be stateless and thread safe. + * is why the object an event is about and the reconciliation it is recorded from are passed to it + * per call rather than configured on it: implementations have to be stateless and thread safe. * * @return the event recorder to use for the whole operator, or an empty optional to let each * controller use its own default one diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/BoundResourceEventRecorder.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/BoundResourceEventRecorder.java new file mode 100644 index 0000000000..13a711ac48 --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/BoundResourceEventRecorder.java @@ -0,0 +1,46 @@ +/* + * 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.api.event; + +import java.util.Objects; +import java.util.function.Consumer; + +/** + * A {@link ResourceEventRecorder} that hands every event to a fixed recording, through which an + * {@link EventRecorder} binds it to an object and a reconciliation. + */ +record BoundResourceEventRecorder(Consumer recording) + implements ResourceEventRecorder { + + BoundResourceEventRecorder { + Objects.requireNonNull(recording, "the recording to hand events to must not be null"); + } + + @Override + public void normal(String reason, String message) { + record(EventRecord.normal(reason, message)); + } + + @Override + public void warn(String reason, String message) { + record(EventRecord.warning(reason, message)); + } + + @Override + public void record(EventRecord event) { + recording.accept(event); + } +} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorder.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorder.java index 248972cd01..8fd3f1fc7a 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorder.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorder.java @@ -43,9 +43,9 @@ import static java.util.Objects.requireNonNullElse; /** - * Default {@link EventRecorder}. Assembles events from an {@link EventRecord} plus the context the - * controller already knows about (the involved object reference, the reporting controller and - * instance), then hands them to an {@link EventSink}. + * Default {@link EventRecorder}. Assembles events from an {@link EventRecord} plus what is known + * about the object the event is about (the involved object reference) and the controller recording + * it (the reporting controller and instance), then hands them to an {@link EventSink}. * *

    Events for cluster scoped objects have to live in some namespace: by default the {@value * #CLUSTER_SCOPED_EVENT_NAMESPACE} namespace is used, following the Kubernetes convention, but it @@ -63,6 +63,9 @@ * and the caller carries on. A recorder built with {@link Builder#failOnError(boolean)} propagates * the failure to the caller instead, so that a reconciliation that cannot record its events fails * and is retried. + * + *

    An event can be about any object, not only the primary resource of the reconciliation + * recording it: the object is passed per call, see {@link EventRecorder}. */ public class DefaultEventRecorder implements EventRecorder { @@ -218,12 +221,15 @@ private static String resolve() { } @Override - public void record(EventRecord event, Context context) { - Objects.requireNonNull(context, "the context of the reconciliation must not be null"); + public void record(HasMetadata regarding, EventRecord event, Context context) { + Objects.requireNonNull(regarding, "the object the event is about must not be null"); + Objects.requireNonNull( + regarding.getMetadata(), "the object the event is about must have metadata"); Objects.requireNonNull(event, "event must not be null"); + Objects.requireNonNull(context, "the context of the reconciliation must not be null"); Event assembled = null; try { - assembled = toEvent(context, event); + assembled = toEvent(regarding, event, context); sink.emit(assembled, context); } catch (Exception e) { if (failOnError) { @@ -233,25 +239,19 @@ public void record(EventRecord event, Context context) { // reconcile because it could not write an event is usually worse off than one that records // nothing log.warn( - "Could not record {} event named {} with reason {} for resource {} in namespace {}", + "Could not record {} event named {} with reason {} about {} {} in namespace {}", event.type(), assembled != null ? assembled.getMetadata().getName() : "unknown", event.reason(), - context.getPrimaryResource().getMetadata().getName(), - context.getPrimaryResource().getMetadata().getNamespace(), + regarding.getKind(), + regarding.getMetadata().getName(), + regarding.getMetadata().getNamespace(), e); } } - @Override - public ResourceEventRecorder forContext(Context context) { - Objects.requireNonNull(context, "the context events will be recorded from must not be null"); - return new BoundEventRecorder(this, context); - } - - protected Event toEvent(Context context, EventRecord record) { + protected Event toEvent(HasMetadata regarding, EventRecord record, Context context) { var controllerName = context.getControllerConfiguration().getName(); - var regarding = context.getPrimaryResource(); var now = Instant.now().truncatedTo(ChronoUnit.SECONDS).toString(); var involvedObject = objectReferenceFor(regarding); var namespace = eventNamespace(regarding, context); @@ -443,23 +443,4 @@ private ObjectReference objectReferenceFor(HasMetadata resource) { .withResourceVersion(resource.getMetadata().getResourceVersion()) .build(); } - - private record BoundEventRecorder(EventRecorder delegate, Context context) - implements ResourceEventRecorder { - - @Override - public void normal(String reason, String message) { - delegate.record(EventRecord.normal(reason, message), context); - } - - @Override - public void warn(String reason, String message) { - delegate.record(EventRecord.warning(reason, message), context); - } - - @Override - public void record(EventRecord event) { - delegate.record(event, context); - } - } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventRecorder.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventRecorder.java index e752cff939..d90c4ec492 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventRecorder.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventRecorder.java @@ -15,6 +15,9 @@ */ package io.javaoperatorsdk.operator.api.event; +import java.util.Objects; + +import io.fabric8.kubernetes.api.model.HasMetadata; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.Experimental; @@ -24,37 +27,75 @@ * Records Kubernetes events on behalf of a controller. * *

    This is the unbound form of the API: an instance is shared by all the controllers of the - * operator, and everything that varies between them - the primary resource an event is about, the - * controller the event is attributed to, and the configuration the event is assembled from - is - * passed per call, as the {@link Context} of the reconciliation recording the event. - * Implementations are therefore expected to be stateless and thread safe. To record events through - * an implementation of your own, see {@link - * io.javaoperatorsdk.operator.api.config.ConfigurationService#eventRecorder()}. Within a - * reconciliation, prefer {@link + * operator, and everything that varies between them - the object an event is about, the controller + * the event is attributed to, and the configuration the event is assembled from - is passed per + * call, as the object and the {@link Context} of the reconciliation recording the event. + * Implementations are therefore expected to be stateless and thread safe, and only have to + * implement {@link #record(HasMetadata, EventRecord, Context)}: the other methods are conveniences + * that delegate to it. To record events through an implementation of your own, see {@link + * io.javaoperatorsdk.operator.api.config.ConfigurationService#eventRecorder()}. + * + *

    Within a reconciliation, prefer {@link * io.javaoperatorsdk.operator.api.reconciler.Context#eventRecorder()}, which is already bound to - * the context. + * the primary resource, or {@link + * io.javaoperatorsdk.operator.api.reconciler.Context#eventRecorder(HasMetadata)} for an event about + * another object. * *

    Whether a failure to record an event fails the caller is up to the implementation, see {@link * DefaultEventRecorder} for the default. */ @Experimental(API_MIGHT_CHANGE) +@FunctionalInterface public interface EventRecorder { + /** + * Records an event about the given object from the given reconciliation: the event is attributed + * to the controller of the reconciliation and assembled from its configuration. + * + * @param regarding the object the event is about, referenced as the involved object of the + * resulting event; not necessarily the primary resource of the reconciliation + * @param event the event to record + * @param context the context of the reconciliation recording the event + */ + void record(HasMetadata regarding, EventRecord event, Context context); + /** * Records an event about the primary resource of the given reconciliation. * * @param event the event to record - * @param context the context of the reconciliation recording the event; the event is about its - * primary resource and is attributed to its controller + * @param context the context of the reconciliation recording the event + */ + default void record(EventRecord event, Context context) { + Objects.requireNonNull(context, "the context of the reconciliation must not be null"); + record(context.getPrimaryResource(), event, context); + } + + /** + * Returns a view of this recorder bound to the given object and reconciliation, so that neither + * has to be passed for every event. Events recorded through the view go through {@link + * #record(HasMetadata, EventRecord, Context)}. + * + * @param regarding the object subsequent events will be about + * @param context the context of the reconciliation recording them + * @return a recorder bound to {@code regarding} and {@code context} */ - void record(EventRecord event, Context context); + default ResourceEventRecorder forResource(HasMetadata regarding, Context context) { + Objects.requireNonNull(regarding, "the object events are recorded about must not be null"); + Objects.requireNonNull(context, "the context events are recorded from must not be null"); + return new BoundResourceEventRecorder(event -> record(regarding, event, context)); + } /** - * Returns a view of this recorder bound to the given reconciliation, so that the context doesn't - * have to be passed for every event. + * Returns a view of this recorder bound to the primary resource of the given reconciliation, so + * that the context doesn't have to be passed for every event. Events recorded through the view go + * through {@link #record(EventRecord, Context)}, so an implementation that overrides that method + * sees them. * * @param context the context subsequent events will be recorded from * @return a recorder bound to {@code context} */ - ResourceEventRecorder forContext(Context context); + default ResourceEventRecorder forContext(Context context) { + Objects.requireNonNull(context, "the context events will be recorded from must not be null"); + return new BoundResourceEventRecorder(event -> record(event, context)); + } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventSink.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventSink.java index 93c58dcf54..010e481e79 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventSink.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/EventSink.java @@ -16,6 +16,7 @@ package io.javaoperatorsdk.operator.api.event; import io.fabric8.kubernetes.api.model.Event; +import io.fabric8.kubernetes.api.model.HasMetadata; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.Experimental; @@ -36,7 +37,9 @@ public interface EventSink { * @param event the event to deliver, fully assembled: everything the event says is already built * into it * @param context the context of the reconciliation the event was recorded from, for - * implementations that route the event based on it rather than on its contents. Ignored by + * implementations that route the event based on it rather than on its contents; note that the + * event is not necessarily about the primary resource of that reconciliation, see {@link + * io.javaoperatorsdk.operator.api.reconciler.Context#eventRecorder(HasMetadata)}. Ignored by * {@link DefaultEventSink}. */ @Experimental(API_MIGHT_CHANGE) diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/ResourceEventRecorder.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/ResourceEventRecorder.java index dfb88dc7fd..5a2a94e9b8 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/ResourceEventRecorder.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/event/ResourceEventRecorder.java @@ -21,7 +21,7 @@ /** * An {@link EventRecorder} bound to a single object, typically the primary resource of the current - * reconciliation. + * reconciliation, and to the reconciliation recording events about it. */ @Experimental(API_MIGHT_CHANGE) public interface ResourceEventRecorder { diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/Context.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/Context.java index 5a87659246..201f5bbfff 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/Context.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/Context.java @@ -217,7 +217,8 @@ default Optional getSecondaryResource( /** * Returns a {@link ResourceEventRecorder} bound to this context, to record Kubernetes events * about the primary resource. To record them through an implementation of your own, see {@link - * io.javaoperatorsdk.operator.api.config.ConfigurationService#eventRecorder()}. + * io.javaoperatorsdk.operator.api.config.ConfigurationService#eventRecorder()}. For events about + * another object, see {@link #eventRecorder(HasMetadata)}. * * @return an event recorder bound to the primary resource * @throws UnsupportedOperationException if the implementation does not provide an event recorder @@ -227,6 +228,24 @@ default ResourceEventRecorder eventRecorder() { "This implementation of Context does not provide a ResourceEventRecorder"); } + /** + * Returns a {@link ResourceEventRecorder} bound to the given object, to record Kubernetes events + * about an object other than the primary resource from this reconciliation, for example about the + * parent of the primary resource. With the default recorder, the events are attributed to the + * controller of this reconciliation and live in the namespace of the given object, or, for a + * cluster scoped object, in the namespace configured for such events, see {@link + * io.javaoperatorsdk.operator.api.config.ConfigurationService#clusterScopedEventNamespace()}. + * + * @param regarding the object subsequent events will be about + * @return an event recorder bound to {@code regarding} + * @throws UnsupportedOperationException if the implementation does not provide an event recorder + */ + @Experimental(Experimental.API_MIGHT_CHANGE) + default ResourceEventRecorder eventRecorder(HasMetadata regarding) { + throw new UnsupportedOperationException( + "This implementation of Context does not provide a ResourceEventRecorder"); + } + /** ExecutorService initialized by framework for workflows. Used for workflow standalone mode. */ ExecutorService getWorkflowExecutorService(); diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/DefaultContext.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/DefaultContext.java index 50e61526c4..1be54fc177 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/DefaultContext.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/DefaultContext.java @@ -215,6 +215,11 @@ public ResourceEventRecorder eventRecorder() { return controller.eventRecorder().forContext(this); } + @Override + public ResourceEventRecorder eventRecorder(HasMetadata regarding) { + return controller.eventRecorder().forResource(regarding, this); + } + @Override public ExecutorService getWorkflowExecutorService() { // note that this should be always received from executor service manager, so we are able to do diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverriderTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverriderTest.java index 9c356b55f7..6580931d60 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverriderTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverriderTest.java @@ -30,11 +30,8 @@ import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.api.model.Secret; import io.javaoperatorsdk.operator.api.event.DefaultEventRecorder; -import io.javaoperatorsdk.operator.api.event.EventRecord; import io.javaoperatorsdk.operator.api.event.EventRecorder; -import io.javaoperatorsdk.operator.api.event.ResourceEventRecorder; import io.javaoperatorsdk.operator.api.monitoring.Metrics; -import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResourceFactory; import io.javaoperatorsdk.operator.api.reconciler.dependent.DesiredStateAspect; @@ -213,16 +210,7 @@ void retryAndRescheduleExecutorDefaultsToADaemonPoolOfTheConfiguredSize() { @Test void eventRecorderIsNotConfiguredByDefaultAndCanBeOverridden() { - final var eventRecorder = - new EventRecorder() { - @Override - public void record(EventRecord event, Context context) {} - - @Override - public ResourceEventRecorder forContext(Context context) { - return null; - } - }; + final EventRecorder eventRecorder = (regarding, event, context) -> {}; assertThat(config.eventRecorder()).isEmpty(); assertThat( diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorderIntegrationTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorderIntegrationTest.java index 9c60ac6b4e..cb454f5f38 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorderIntegrationTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorderIntegrationTest.java @@ -97,7 +97,7 @@ void clusterScopedEventsInOtherNamespacesAreRejectedByTheApiServer() { .serverSideApply(); var namespace = clusterScoped(); var context = context(namespace, "operator-ns"); - var event = recorder().toEvent(context, EventRecord.normal("Ready", "all good")); + var event = recorder().toEvent(namespace, EventRecord.normal("Ready", "all good"), context); assertThatThrownBy(() -> new DefaultEventSink(client).emit(event, context)) .isInstanceOf(KubernetesClientException.class); @@ -217,7 +217,7 @@ private static HasMetadata clusterScoped() { .build(); } - @SuppressWarnings({"rawtypes", "unchecked"}) + @SuppressWarnings({"rawtypes"}) private static Context context(HasMetadata primaryResource, String clusterScopedNamespace) { var configurationService = mock(ConfigurationService.class); when(configurationService.getLeaderElectionConfiguration()) diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorderTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorderTest.java index 12d1f65907..abe0d24442 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorderTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/DefaultEventRecorderTest.java @@ -27,6 +27,7 @@ import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.api.model.Namespace; import io.fabric8.kubernetes.api.model.NamespaceBuilder; +import io.fabric8.kubernetes.api.model.SecretBuilder; import io.javaoperatorsdk.operator.api.config.ConfigurationService; import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; import io.javaoperatorsdk.operator.api.reconciler.Context; @@ -35,6 +36,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatNullPointerException; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -231,6 +233,98 @@ void boundRecorderRecordsAboutThePrimaryResourceOfTheBoundContext() { assertThat(emitted.get(1).getType()).isEqualTo("Warning"); } + @Test + void recordsEventsAboutAnObjectOtherThanThePrimaryResource() { + var other = + new ConfigMapBuilder() + .withNewMetadata() + .withName("parent") + .withNamespace("ns2") + .withUid("uid-parent") + .endMetadata() + .build(); + + recorder.record( + other, EventRecord.warning("ChildFailed", "child failed"), context(configMap())); + + assertThat(emitted).hasSize(1); + var event = emitted.get(0); + assertThat(event.getInvolvedObject().getKind()).isEqualTo("ConfigMap"); + assertThat(event.getInvolvedObject().getName()).isEqualTo("parent"); + assertThat(event.getInvolvedObject().getNamespace()).isEqualTo("ns2"); + assertThat(event.getInvolvedObject().getUid()).isEqualTo("uid-parent"); + assertThat(event.getMetadata().getNamespace()).isEqualTo("ns2"); + assertThat(event.getMetadata().getName()).startsWith("parent."); + assertThat(event.getReportingComponent()).isEqualTo(CONTROLLER); + assertThat(event.getReportingInstance()).isEqualTo(INSTANCE); + } + + @Test + void recordsEventsAboutClusterScopedObjectsOtherThanThePrimaryInTheConfiguredNamespace() { + recorder.record( + clusterScoped(), + EventRecord.normal("Noticed", "noticed"), + context(configMap(), "kube-system")); + + assertThat(emitted.get(0).getMetadata().getNamespace()).isEqualTo("kube-system"); + assertThat(emitted.get(0).getInvolvedObject().getKind()).isEqualTo("Namespace"); + } + + @Test + void theSameRecordAboutObjectsDifferingOnlyInKindResolvesToDifferentEvents() { + var record = EventRecord.normal("Noticed", "noticed"); + var context = context(configMap()); + var configMap = + new ConfigMapBuilder() + .withNewMetadata() + .withName("test1") + .withNamespace("ns1") + .endMetadata() + .build(); + var secret = + new SecretBuilder() + .withNewMetadata() + .withName("test1") + .withNamespace("ns1") + .endMetadata() + .build(); + + recorder.record(configMap, record, context); + recorder.record(secret, record, context); + + assertThat(emitted).hasSize(2); + assertThat(emitted).allSatisfy(e -> assertThat(e.getMetadata().getName()).startsWith("test1.")); + assertThat(emitted.get(0).getMetadata().getName()) + .isNotEqualTo(emitted.get(1).getMetadata().getName()); + } + + @Test + void boundRecorderRecordsAboutTheOtherObjectItIsBoundTo() { + var bound = recorder.forResource(clusterScoped(), context(configMap())); + + bound.normal("Created", "created"); + bound.warn("Failed", "failed"); + + assertThat(emitted).hasSize(2); + assertThat(emitted) + .allSatisfy(e -> assertThat(e.getInvolvedObject().getKind()).isEqualTo("Namespace")); + assertThat(emitted) + .allSatisfy(e -> assertThat(e.getReportingComponent()).isEqualTo(CONTROLLER)); + } + + @Test + void rejectsAnObjectWithoutMetadata() { + assertThatNullPointerException() + .isThrownBy( + () -> + recorder.record( + new ConfigMap(), + EventRecord.normal("Noticed", "noticed"), + context(configMap()))) + .withMessageContaining("metadata"); + assertThat(emitted).isEmpty(); + } + @Test void truncatesTheNameOfTheInvolvedObjectToStayWithinTheKubernetesNameLimit() { var longName = "a".repeat(253); @@ -371,6 +465,26 @@ void setsTheOwnerReferenceToTheInvolvedObjectWhenOwningEventsByRegarding() { }); } + @Test + void setsTheOwnerReferenceToTheOtherObjectWhenRecordingAboutIt() { + var recorder = + DefaultEventRecorder.builder((event, context) -> emitted.add(event)) + .ownerReference(true) + .build(); + + recorder.record( + clusterScoped(), EventRecord.normal("Created", "created"), context(configMap())); + + assertThat(emitted.get(0).getMetadata().getOwnerReferences()) + .singleElement() + .satisfies( + owner -> { + assertThat(owner.getKind()).isEqualTo("Namespace"); + assertThat(owner.getName()).isEqualTo("ns1"); + assertThat(owner.getUid()).isEqualTo("uid-2"); + }); + } + @Test void carriesNoOwnerReferenceByDefault() { recorder.record(EventRecord.normal("Created", "created"), context(configMap())); @@ -576,10 +690,10 @@ Context context(HasMetadata primaryResource) { } /** - * The recorder reads everything it does not get from the {@link EventRecord} off the context: the - * primary resource the event is about, the name of the controller the event is attributed to, and - * the configuration service the reporting instance and the cluster scoped event namespace come - * from. + * The recorder reads everything it does not get from the {@link EventRecord} or the object the + * event is about off the context: the primary resource, which the event is about unless another + * object is given, the name of the controller the event is attributed to, and the configuration + * service the reporting instance and the cluster scoped event namespace come from. */ @SuppressWarnings("rawtypes") Context context(HasMetadata primaryResource, String clusterScopedEventNamespace) { diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/EventRecorderTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/EventRecorderTest.java new file mode 100644 index 0000000000..ced7d9f5e6 --- /dev/null +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/event/EventRecorderTest.java @@ -0,0 +1,136 @@ +/* + * 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.api.event; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.Test; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.ConfigMapBuilder; +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.javaoperatorsdk.operator.api.reconciler.Context; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatNullPointerException; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * The views an {@link EventRecorder} offers are default methods, so that an implementation only has + * to record. This exercises them on a minimal implementation that only records what it was asked. + */ +class EventRecorderTest { + + private record Recording(HasMetadata regarding, EventRecord event, Context context) {} + + private final List recordings = new ArrayList<>(); + private final EventRecorder recorder = + (regarding, event, context) -> recordings.add(new Recording(regarding, event, context)); + + private final ConfigMap primary = configMap("primary"); + private final ConfigMap other = configMap("other"); + private final Context context = context(); + + @Test + void recordingWithoutAnObjectIsAboutThePrimaryResourceOfTheContext() { + var event = EventRecord.normal("Created", "created"); + + recorder.record(event, context); + + assertThat(recordings).containsExactly(new Recording(primary, event, context)); + } + + @Test + void theViewBoundToAContextRecordsAboutItsPrimaryResource() { + var bound = recorder.forContext(context); + + bound.normal("Created", "created"); + bound.warn("Failed", "failed"); + bound.record(EventRecord.builder().reason("Noticed").build()); + + assertThat(recordings).hasSize(3); + assertThat(recordings).allSatisfy(r -> assertThat(r.regarding()).isSameAs(primary)); + assertThat(recordings).allSatisfy(r -> assertThat(r.context()).isSameAs(context)); + assertThat(recordings) + .extracting(r -> r.event().type()) + .containsExactly(EventType.NORMAL, EventType.WARNING, EventType.NORMAL); + assertThat(recordings) + .extracting(r -> r.event().reason()) + .containsExactly("Created", "Failed", "Noticed"); + } + + @Test + void theViewBoundToAnotherObjectRecordsAboutThatObjectFromTheContext() { + var bound = recorder.forResource(other, context); + + bound.normal("Noticed", "noticed"); + bound.warn("Failed", "failed"); + + assertThat(recordings).hasSize(2); + assertThat(recordings).allSatisfy(r -> assertThat(r.regarding()).isSameAs(other)); + assertThat(recordings).allSatisfy(r -> assertThat(r.context()).isSameAs(context)); + } + + @Test + void theContextViewGoesThroughTheTwoArgumentRecordAndTheObjectViewDoesNot() { + var calls = new ArrayList(); + var recorder = + new EventRecorder() { + @Override + public void record(HasMetadata regarding, EventRecord event, Context context) { + calls.add("about " + regarding.getMetadata().getName()); + } + + @Override + public void record(EventRecord event, Context context) { + calls.add("primary"); + EventRecorder.super.record(event, context); + } + }; + + recorder.forContext(context).normal("Created", "created"); + recorder.forResource(other, context).normal("Noticed", "noticed"); + + assertThat(calls).containsExactly("primary", "about primary", "about other"); + } + + @Test + void viewsRejectMissingArguments() { + assertThatNullPointerException().isThrownBy(() -> recorder.forContext(null)); + assertThatNullPointerException().isThrownBy(() -> recorder.forResource(null, context)); + assertThatNullPointerException().isThrownBy(() -> recorder.forResource(other, null)); + assertThatNullPointerException() + .isThrownBy(() -> recorder.record(EventRecord.normal("Created", "created"), null)); + } + + private Context context() { + Context context = mock(Context.class); + when(context.getPrimaryResource()).thenAnswer(invocation -> primary); + return context; + } + + private static ConfigMap configMap(String name) { + return new ConfigMapBuilder() + .withNewMetadata() + .withName(name) + .withNamespace("ns1") + .withUid("uid-" + name) + .endMetadata() + .build(); + } +} diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/reconciler/DefaultContextTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/reconciler/DefaultContextTest.java index 7b9658f98d..58b437b359 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/reconciler/DefaultContextTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/reconciler/DefaultContextTest.java @@ -31,6 +31,8 @@ import io.fabric8.kubernetes.api.model.PodBuilder; import io.fabric8.kubernetes.api.model.Secret; import io.fabric8.kubernetes.api.model.SecretBuilder; +import io.javaoperatorsdk.operator.api.event.EventRecorder; +import io.javaoperatorsdk.operator.api.event.ResourceEventRecorder; import io.javaoperatorsdk.operator.processing.Controller; import io.javaoperatorsdk.operator.processing.event.EventSourceManager; import io.javaoperatorsdk.operator.processing.event.NoEventSourceForClassException; @@ -403,4 +405,25 @@ void latestDistinctComparesNumericVersionsCorrectly() { HasMetadata resultPod = result.iterator().next(); assertThat(resultPod.getMetadata().getResourceVersion()).isEqualTo("1000"); } + + @Test + void eventRecorderIsBoundToThePrimaryResource() { + var recorder = mock(EventRecorder.class); + var bound = mock(ResourceEventRecorder.class); + when(mockController.eventRecorder()).thenReturn(recorder); + when(recorder.forContext(context)).thenReturn(bound); + + assertThat(context.eventRecorder()).isSameAs(bound); + } + + @Test + void eventRecorderCanBeBoundToAnotherObject() { + var other = new ConfigMapBuilder().withNewMetadata().withName("parent").endMetadata().build(); + var recorder = mock(EventRecorder.class); + var bound = mock(ResourceEventRecorder.class); + when(mockController.eventRecorder()).thenReturn(recorder); + when(recorder.forResource(other, context)).thenReturn(bound); + + assertThat(context.eventRecorder(other)).isSameAs(bound); + } } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/cleanerforreconciler/CleanerForReconcilerIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/cleanerforreconciler/CleanerForReconcilerIT.java index 4a28425e54..bdafb9e507 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/cleanerforreconciler/CleanerForReconcilerIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/cleanerforreconciler/CleanerForReconcilerIT.java @@ -63,6 +63,9 @@ void addsFinalizerAndCallsCleanupIfCleanerImplemented() { .getMetadata() .getFinalizers() .isEmpty()); + // adding the finalizer does not reconcile, the update event it produces does: deleting before + // that event is processed turns the pending execution into a cleanup and no reconcile ever runs + await().until(() -> reconciler.getNumberOfExecutions() >= 1); operator.delete(testResource); diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorder/EventRecorderIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorder/EventRecorderIT.java index 5c1319d884..036b158556 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorder/EventRecorderIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorder/EventRecorderIT.java @@ -21,6 +21,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; +import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.Event; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.annotation.Sample; @@ -37,11 +38,13 @@ recorder available from the reconciliation context. Verifies that both normal and warning \ events reach the cluster, refer to the primary resource as their involved object, and are \ attributed to the reporting controller, and that recording the same event again counts the \ - occurrence on the event already recorded instead of recording it a second time. + occurrence on the event already recorded instead of recording it a second time. Also \ + records an event about an object other than the primary resource from the reconciliation. """) class EventRecorderIT { public static final String TEST_RESOURCE_NAME = "test1"; + public static final String PARENT_NAME = "parent-of-the-resource"; private final EventRecorderReconciler reconciler = new EventRecorderReconciler(); @@ -106,17 +109,59 @@ void countsRepeatedOccurrencesOnTheEventAlreadyRecorded() { }); } + @Test + void recordsEventsAboutAnotherObjectFromTheReconciliation() { + extension.create( + new ConfigMapBuilder().withNewMetadata().withName(PARENT_NAME).endMetadata().build()); + var resource = testResource(); + resource + .getMetadata() + .setAnnotations(Map.of(EventRecorderReconciler.PARENT_ANNOTATION, PARENT_NAME)); + extension.create(resource); + + await() + .untilAsserted( + () -> { + var events = eventsAbout(PARENT_NAME); + assertThat(events) + .extracting(Event::getReason) + .contains(EventRecorderReconciler.OTHER_OBJECT_REASON); + var event = + events.stream() + .filter( + e -> EventRecorderReconciler.OTHER_OBJECT_REASON.equals(e.getReason())) + .findFirst() + .orElseThrow(); + assertThat(event.getInvolvedObject().getKind()).isEqualTo("ConfigMap"); + assertThat(event.getInvolvedObject().getName()).isEqualTo(PARENT_NAME); + assertThat(event.getInvolvedObject().getUid()).isNotBlank(); + assertThat(event.getMessage()) + .isEqualTo("child " + TEST_RESOURCE_NAME + " reconciled"); + assertThat(event.getReportingComponent()).isEqualTo(controllerName()); + }); + } + private List eventsForTestResource() { + return eventsAbout(TEST_RESOURCE_NAME); + } + + private List eventsAbout(String involvedObjectName) { return extension .getKubernetesClient() - .v1() - .events() + .resources(Event.class) .inNamespace(extension.getNamespace()) - .withField("involvedObject.name", TEST_RESOURCE_NAME) + .withField("involvedObject.name", involvedObjectName) .list() .getItems(); } + private String controllerName() { + return extension + .getRegisteredControllerForReconcile(EventRecorderReconciler.class) + .getConfiguration() + .getName(); + } + EventRecorderCustomResource testResource() { var resource = new EventRecorderCustomResource(); resource.setMetadata(new ObjectMetaBuilder().withName(TEST_RESOURCE_NAME).build()); diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorder/EventRecorderReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorder/EventRecorderReconciler.java index 8108eb4031..5e3c2393fd 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorder/EventRecorderReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/eventrecorder/EventRecorderReconciler.java @@ -27,6 +27,8 @@ public class EventRecorderReconciler implements Reconciler reconcile( numberOfExecutions.incrementAndGet(); context.eventRecorder().normal(NORMAL_REASON, "resource reconciled"); context.eventRecorder().warn(WARNING_REASON, "this is a warning about the resource"); + + var annotations = resource.getMetadata().getAnnotations(); + var parentName = annotations == null ? null : annotations.get(PARENT_ANNOTATION); + if (parentName != null) { + var parent = + context + .getClient() + .configMaps() + .inNamespace(resource.getMetadata().getNamespace()) + .withName(parentName) + .get(); + if (parent != null) { + context + .eventRecorder(parent) + .normal( + OTHER_OBJECT_REASON, "child " + resource.getMetadata().getName() + " reconciled"); + } + } return UpdateControl.noUpdate(); } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/cleanermanageddependent/CleanerForManagedDependentResourcesOnlyIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/cleanermanageddependent/CleanerForManagedDependentResourcesOnlyIT.java index bd3dd9802e..86274616c4 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/cleanermanageddependent/CleanerForManagedDependentResourcesOnlyIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/cleanermanageddependent/CleanerForManagedDependentResourcesOnlyIT.java @@ -46,6 +46,8 @@ class CleanerForManagedDependentResourcesOnlyIT { @Test void addsFinalizerAndCallsCleanupIfCleanerImplemented() { + CleanerForManagedDependentTestReconciler reconciler = + (CleanerForManagedDependentTestReconciler) operator.getFirstReconciler(); var testResource = createTestResource(); operator.create(testResource); @@ -57,6 +59,9 @@ void addsFinalizerAndCallsCleanupIfCleanerImplemented() { .getMetadata() .getFinalizers() .isEmpty()); + // adding the finalizer does not reconcile, the update event it produces does: deleting before + // that event is processed turns the pending execution into a cleanup and no reconcile ever runs + await().until(() -> reconciler.getNumberOfExecutions() >= 1); operator.delete(testResource); @@ -66,9 +71,6 @@ void addsFinalizerAndCallsCleanupIfCleanerImplemented() { operator.get(CleanerForManagedDependentCustomResource.class, TEST_RESOURCE_NAME) == null); - CleanerForManagedDependentTestReconciler reconciler = - (CleanerForManagedDependentTestReconciler) operator.getFirstReconciler(); - assertThat(reconciler.getNumberOfExecutions()).isEqualTo(1); assertThat(ConfigMapDependentResource.getNumberOfCleanupExecutions()).isEqualTo(1); } From b1684fa3dc135310217423ea78c024ed3905f95a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Attila=20M=C3=A9sz=C3=A1ros?= Date: Wed, 18 Nov 2026 12:54:55 +0100 Subject: [PATCH 16/23] fix: address code review findings on virtual thread support (#3685) - deprecate TimerEventSource(String, boolean), as documented in the migration guide - correct @since of the desired state aspect APIs to 5.7.0 - extract the executor creation shared by the polling event sources - remove comments restating the code --- .../api/config/ConfigurationService.java | 2 +- .../config/ConfigurationServiceOverrider.java | 4 +- .../BulkDependentResourceReconciler.java | 3 -- .../informer/pool/AbstractInformerPool.java | 1 - .../PerResourcePollingEventSource.java | 21 +-------- .../source/polling/PollingEventSource.java | 28 ++--------- .../source/polling/PollingExecutors.java | 46 +++++++++++++++++++ .../event/source/timer/TimerEventSource.java | 7 ++- 8 files changed, 61 insertions(+), 51 deletions(-) create mode 100644 operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingExecutors.java diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java index a64c1ab953..3e34946c73 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java @@ -653,7 +653,7 @@ default InformerPool informerPool() { * the operator creates or updates. * * @return the list of aspects to apply to computed desired states, empty by default - * @since 5.6.0 + * @since 5.7.0 */ default List desiredStateAspects() { return List.of(); diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverrider.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverrider.java index c95b9cc54a..2330a83ee4 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverrider.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverrider.java @@ -297,7 +297,7 @@ public ConfigurationServiceOverrider withInformerPool(InformerPool informerPool) * * @param desiredStateAspects the aspects to apply, in the order in which they should be applied * @return this {@link ConfigurationServiceOverrider} for chained customization - * @since 5.6.0 + * @since 5.7.0 */ public ConfigurationServiceOverrider withDesiredStateAspects( List desiredStateAspects) { @@ -312,7 +312,7 @@ public ConfigurationServiceOverrider withDesiredStateAspects( * * @param desiredStateAspects the aspects to append, in the order in which they should be applied * @return this {@link ConfigurationServiceOverrider} for chained customization - * @since 5.6.0 + * @since 5.7.0 */ public ConfigurationServiceOverrider addDesiredStateAspects( DesiredStateAspect... desiredStateAspects) { diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/BulkDependentResourceReconciler.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/BulkDependentResourceReconciler.java index 2428eeba96..53ccf67cb2 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/BulkDependentResourceReconciler.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/BulkDependentResourceReconciler.java @@ -117,9 +117,6 @@ public R update(R actual, R desired, P primary, Context

    context) { @Override public Result match(R resource, P primary, Context

    context) { - // retrieve the desired state via the context so that it is processed the same way as for - // non-bulk dependents, in particular so that configured DesiredStateAspects are applied - // before matching return bulkDependentResource.match(resource, getOrComputeDesired(context), primary, context); } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/AbstractInformerPool.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/AbstractInformerPool.java index 21464b378b..ab9859518e 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/AbstractInformerPool.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/pool/AbstractInformerPool.java @@ -117,7 +117,6 @@ protected SharedIndexInformer createInformer(InformerClassifier classifier) { Optional.ofNullable(classifier.itemStore()).ifPresent(informer::itemStore); if (classifier.withoutNamespaceIndex()) { - // the framework only reads the indexes registered through the resource cache, never this one informer.removeNamespaceIndex(); } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSource.java index 10c8cba913..6a4fe5ca79 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSource.java @@ -31,8 +31,6 @@ import io.fabric8.kubernetes.api.model.HasMetadata; import io.javaoperatorsdk.operator.OperatorException; -import io.javaoperatorsdk.operator.api.config.ConfigurationService; -import io.javaoperatorsdk.operator.api.config.ExecutorServiceManager; import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; import io.javaoperatorsdk.operator.processing.event.ResourceID; import io.javaoperatorsdk.operator.processing.event.source.Cache; @@ -80,25 +78,11 @@ public PerResourcePollingEventSource( this.resourceFetcher = config.resourceFetcher(); this.registerPredicate = config.registerPredicate(); this.configuredExecutorService = config.executorService(); - var configurationService = configurationServiceOf(context); - this.useVirtualThreads = - configurationService != null && configurationService.useVirtualThreads(); + this.useVirtualThreads = PollingExecutors.useVirtualThreads(context); this.ownsExecutorService = configuredExecutorService == null; this.period = config.defaultPollingPeriod(); } - /** - * The configuration of the operator the event source belongs to, or {@code null} if it doesn't - * belong to one, which only happens when the event source is used standalone, outside an - * operator. - */ - private static ConfigurationService configurationServiceOf(EventSourceContext context) { - final var controllerConfiguration = context.getControllerConfiguration(); - return controllerConfiguration == null - ? null - : controllerConfiguration.getConfigurationService(); - } - @Override public void start() throws OperatorException { if (isRunning()) { @@ -119,8 +103,7 @@ private ScheduledExecutorService resolveExecutorService() { if (configuredExecutorService != null) { return configuredExecutorService; } - return ExecutorServiceManager.newScheduledExecutorService( - 1, useVirtualThreads, "josdk-polling-" + name()); + return PollingExecutors.newExecutor(name(), useVirtualThreads); } private Set getAndCacheResource(P primary, boolean fromGetter) { diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingEventSource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingEventSource.java index a33e6cb44e..b2272822e7 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingEventSource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingEventSource.java @@ -30,7 +30,6 @@ import io.fabric8.kubernetes.api.model.HasMetadata; import io.javaoperatorsdk.operator.OperatorException; import io.javaoperatorsdk.operator.api.config.ConfigurationService; -import io.javaoperatorsdk.operator.api.config.ExecutorServiceManager; import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; import io.javaoperatorsdk.operator.health.Status; import io.javaoperatorsdk.operator.processing.event.ResourceID; @@ -89,7 +88,7 @@ public class PollingEventSource */ public PollingEventSource( Class resourceClass, EventSourceContext

    context, PollingConfiguration config) { - this(resourceClass, config, configurationServiceOf(context)); + this(resourceClass, config, PollingExecutors.useVirtualThreads(context)); } /** @@ -100,34 +99,19 @@ public PollingEventSource( */ @Deprecated(since = "5.7.0") public PollingEventSource(Class resourceClass, PollingConfiguration config) { - this(resourceClass, config, null); + this(resourceClass, config, false); } private PollingEventSource( - Class resourceClass, - PollingConfiguration config, - ConfigurationService configurationService) { + Class resourceClass, PollingConfiguration config, boolean useVirtualThreads) { super(config.name(), resourceClass, config.resourceIDMapper()); this.genericResourceFetcher = config.genericResourceFetcher(); this.period = config.period(); this.configuredExecutorService = config.executorService(); - this.useVirtualThreads = - configurationService != null && configurationService.useVirtualThreads(); + this.useVirtualThreads = useVirtualThreads; this.ownsExecutorService = configuredExecutorService == null; } - /** - * The configuration of the operator the event source belongs to, or {@code null} if it doesn't - * belong to one, which only happens when the event source is used standalone, outside an - * operator. - */ - private static ConfigurationService configurationServiceOf(EventSourceContext context) { - final var controllerConfiguration = context.getControllerConfiguration(); - return controllerConfiguration == null - ? null - : controllerConfiguration.getConfigurationService(); - } - @Override public void start() throws OperatorException { if (pollingTask != null) { @@ -187,8 +171,7 @@ private ScheduledExecutorService resolveExecutorService() { if (configuredExecutorService != null) { return configuredExecutorService; } - return ExecutorServiceManager.newScheduledExecutorService( - 1, useVirtualThreads, "josdk-polling-" + name()); + return PollingExecutors.newExecutor(name(), useVirtualThreads); } protected synchronized void getStateAndFillCache() { @@ -204,7 +187,6 @@ public interface GenericResourceFetcher { public void stop() throws OperatorException { super.stop(); if (pollingTask != null) { - // as with the java.util.Timer this replaces, an ongoing poll is left to finish pollingTask.cancel(false); pollingTask = null; } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingExecutors.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingExecutors.java new file mode 100644 index 0000000000..7e949881e4 --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingExecutors.java @@ -0,0 +1,46 @@ +/* + * 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.source.polling; + +import java.util.concurrent.ScheduledExecutorService; + +import io.javaoperatorsdk.operator.api.config.ExecutorServiceManager; +import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; + +final class PollingExecutors { + + private PollingExecutors() {} + + /** + * Whether the operator the event source belongs to is configured to use virtual threads. The + * controller configuration is {@code null} when the event source is used standalone, outside an + * operator. + */ + static boolean useVirtualThreads(EventSourceContext context) { + final var controllerConfiguration = context.getControllerConfiguration(); + if (controllerConfiguration == null) { + return false; + } + final var configurationService = controllerConfiguration.getConfigurationService(); + return configurationService != null && configurationService.useVirtualThreads(); + } + + static ScheduledExecutorService newExecutor(String eventSourceName, boolean useVirtualThreads) { + return ExecutorServiceManager.newScheduledExecutorService( + 1, useVirtualThreads, "josdk-polling-" + eventSourceName); + } +} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/timer/TimerEventSource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/timer/TimerEventSource.java index c244242a62..2aecabaa6b 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/timer/TimerEventSource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/timer/TimerEventSource.java @@ -54,6 +54,11 @@ public TimerEventSource() { this.ownsExecutorService = true; } + /** + * @deprecated use {@link #TimerEventSource(String, boolean, Supplier)} instead, passing {@code + * null} as the supplier to keep the previous behavior. + */ + @Deprecated(since = "5.7.0") public TimerEventSource(String name, boolean triggerReconcilerOnAllEvents) { this(name, triggerReconcilerOnAllEvents, null); } @@ -134,8 +139,6 @@ public void onResourceDeleted(R resource) { public void cancelOnceSchedule(ResourceID customResourceUid) { var scheduled = onceTasks.remove(customResourceUid); if (scheduled != null) { - // as with the java.util.TimerTask this replaces, a task that is already running is left to - // finish scheduled.cancel(false); } } From 31741bd83b992bd2d708749fc13e0725d317dfe0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Attila=20M=C3=A9sz=C3=A1ros?= Date: Wed, 18 Nov 2026 16:35:25 +0100 Subject: [PATCH 17/23] fix: log and recover from failures in PerResourcePollingEventSource polling (#3700) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Exceptions thrown by the resource fetcher are logged and the next poll is scheduled, errors are logged and rethrown. A registered task that ended without scheduling the next one is discarded and polling rescheduled when the primary resource is registered again. A fetch ignoring the interruption of the deletion could reschedule after the resource was recreated, leaving two polling chains for it. Signed-off-by: Attila Mészáros --- .../PerResourcePollingEventSource.java | 98 +++++++++++++++---- .../PerResourcePollingEventSourceTest.java | 83 ++++++++++++++++ 2 files changed, 163 insertions(+), 18 deletions(-) diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSource.java index 6a4fe5ca79..b7c6970290 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSource.java @@ -20,7 +20,9 @@ import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.concurrent.CancellationException; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -52,7 +54,7 @@ public class PerResourcePollingEventSource private static final Logger log = LoggerFactory.getLogger(PerResourcePollingEventSource.class); - private final Map> scheduledFutures = new ConcurrentHashMap<>(); + private final Map scheduledFutures = new ConcurrentHashMap<>(); private final Cache

    primaryResourceCache; private final Set fetchedForPrimaries = ConcurrentHashMap.newKeySet(); @@ -120,26 +122,34 @@ private void cacheResources(P primary, Set values, boolean fromGetter) { // the polling of a resource that is gone ends with its last task, which would otherwise stay // registered and keep the resource from being polled again if it is recreated - private synchronized void forgetTask(ResourceID primaryID, long generation) { - if (generation == lifecycleGeneration) { + private synchronized void forgetTask(ResourceID primaryID, long generation, Object chain) { + if (generation == lifecycleGeneration && isCurrentChain(primaryID, chain)) { scheduledFutures.remove(primaryID); } } + // a chain is replaced or dropped when its resource is deleted, a fetch of the replaced chain + // outliving that is not to continue it, or it would run next to the one of a recreated resource + private boolean isCurrentChain(ResourceID primaryID, Object chain) { + var current = scheduledFutures.get(primaryID); + return current != null && current.chain() == chain; + } + // a fetch ignoring the interruption of a stop can return after a restart, its result is not to // overwrite what the polls of the new run cached in the meantime private synchronized void cacheAndScheduleNextExecution( - P primary, Set values, long generation) { - if (generation != lifecycleGeneration) { + P primary, Set values, long generation, Object chain) { + if (generation != lifecycleGeneration + || !isCurrentChain(ResourceID.fromResource(primary), chain)) { return; } cacheResources(primary, values, false); - scheduleNextExecution(primary, values, generation); + scheduleNextExecution(primary, values, generation, chain); } @SuppressWarnings("unchecked") private synchronized void scheduleNextExecution( - P primary, Set actualResources, long generation) { + P primary, Set actualResources, long generation, Object chain) { if (generation != lifecycleGeneration) { return; } @@ -150,10 +160,10 @@ private synchronized void scheduleNextExecution( ScheduledFuture scheduledFuture = (ScheduledFuture) executorService.schedule( - new FetchingExecutor(primaryID, generation), + new FetchingExecutor(primaryID, generation, chain), fetchDuration.toMillis(), TimeUnit.MILLISECONDS); - scheduledFutures.put(primaryID, scheduledFuture); + scheduledFutures.put(primaryID, new ScheduledPoll(chain, scheduledFuture)); } @Override @@ -169,10 +179,10 @@ public void onResourceUpdated(P newResource, P oldResource) { @Override public synchronized void onResourceDeleted(P resource) { var resourceID = ResourceID.fromResource(resource); - var scheduledFuture = scheduledFutures.remove(resourceID); - if (scheduledFuture != null) { + var scheduledPoll = scheduledFutures.remove(resourceID); + if (scheduledPoll != null) { log.debug("Canceling scheduledFuture for resource: {}", resource); - scheduledFuture.cancel(true); + scheduledPoll.future().cancel(true); } handleDelete(resourceID); fetchedForPrimaries.remove(resourceID); @@ -188,23 +198,68 @@ private synchronized void checkAndRegisterTask(P resource) { return; } var primaryID = ResourceID.fromResource(resource); + discardTaskIfFailed(primaryID); if (scheduledFutures.get(primaryID) == null && (registerPredicate == null || registerPredicate.test(resource))) { var cachedResources = cachedResourcesFor(primaryID); var actualResources = cachedResources.isEmpty() ? null : cachedResources; // note that there is a delay, to not do two fetches when the resources first appeared // and getSecondaryResource is called on reconciliation. - scheduleNextExecution(resource, actualResources, lifecycleGeneration); + scheduleNextExecution(resource, actualResources, lifecycleGeneration, new Object()); + } + } + + // a task that ended without scheduling the next one, e.g. on an Error, would otherwise stay + // registered and keep the resource from being polled again + private void discardTaskIfFailed(ResourceID primaryID) { + var poll = scheduledFutures.get(primaryID); + if (poll == null || !poll.future().isDone()) { + return; } + var future = poll.future(); + try { + future.get(); + } catch (ExecutionException e) { + log.error( + "Previous polling task for resource {} failed unexpectedly, polling is rescheduled", + primaryID, + e.getCause()); + } catch (CancellationException e) { + log.debug("Previous polling task for resource {} was cancelled", primaryID); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + scheduledFutures.remove(primaryID, poll); } + private synchronized void rescheduleAfterFailure( + ResourceID primaryID, long generation, Object chain, Exception failure) { + if (generation != lifecycleGeneration || !isCurrentChain(primaryID, chain)) { + log.debug( + "Polling of resource {} failed after it was stopped or its resource deleted", primaryID); + return; + } + log.error("Exception during polling for resource: {}", primaryID, failure); + // not scheduled for a resource that is gone, the polling of it was cancelled with its deletion + primaryResourceCache + .get(primaryID) + .ifPresentOrElse( + primary -> scheduleNextExecution(primary, null, generation, chain), + () -> forgetTask(primaryID, generation, chain)); + } + + private record ScheduledPoll(Object chain, ScheduledFuture future) {} + private class FetchingExecutor implements Runnable { private final ResourceID primaryID; private final long generation; + private final Object chain; - public FetchingExecutor(ResourceID primaryID, long generation) { + public FetchingExecutor(ResourceID primaryID, long generation, Object chain) { this.primaryID = primaryID; this.generation = generation; + this.chain = chain; } @Override @@ -218,10 +273,17 @@ public void run() { if (primary.isEmpty()) { log.warn("No resource in cache for resource ID: {}", primaryID); // no new execution is scheduled in this case, an on delete event should be received shortly - forgetTask(primaryID, generation); + forgetTask(primaryID, generation, chain); } else { - var values = resourceFetcher.fetchResources(primary.get()); - cacheAndScheduleNextExecution(primary.get(), values, generation); + try { + var values = resourceFetcher.fetchResources(primary.get()); + cacheAndScheduleNextExecution(primary.get(), values, generation, chain); + } catch (Exception e) { + rescheduleAfterFailure(primaryID, generation, chain, e); + } catch (Error e) { + log.error("Fatal error during polling for resource: {}", primaryID, e); + throw e; + } } } } @@ -276,7 +338,7 @@ public void stop() throws OperatorException { // map cleared so that they are registered again on a restart synchronized (this) { lifecycleGeneration++; - scheduledFutures.values().forEach(future -> future.cancel(true)); + scheduledFutures.values().forEach(poll -> poll.future().cancel(true)); scheduledFutures.clear(); } if (ownsExecutorService && executorService != null) { diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSourceTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSourceTest.java index f5109532d1..5229877e52 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSourceTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSourceTest.java @@ -24,6 +24,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; @@ -273,6 +274,39 @@ void supportsDynamicPollingDelay() { .untilAsserted(() -> verify(supplier, times(2)).fetchResources(any())); } + @Test + void keepsPollingAfterTheFetcherThrowsAnException() { + when(supplier.fetchResources(any())) + .thenThrow(new IllegalStateException("temporary failure")) + .thenReturn(Set.of(SampleExternalResource.testResource1())); + + source.onResourceCreated(testCustomResource); + + await() + .untilAsserted( + () -> { + verify(supplier, atLeast(3)).fetchResources(eq(testCustomResource)); + verify(eventHandler, atLeastOnce()).handleEvent(any()); + }); + } + + @Test + void pollingFailedWithAnErrorIsRegisteredAgainWhenTheResourceIsUpdated() { + when(supplier.fetchResources(any())) + .thenThrow(new OutOfMemoryError("test")) + .thenReturn(Set.of(SampleExternalResource.testResource1())); + + source.onResourceCreated(testCustomResource); + await().untilAsserted(() -> verify(supplier, times(1)).fetchResources(any())); + await() + .pollDelay(Duration.ofMillis(2 * PERIOD)) + .untilAsserted(() -> verify(supplier, times(1)).fetchResources(any())); + + source.onResourceUpdated(testCustomResource, testCustomResource); + + await().untilAsserted(() -> verify(supplier, atLeast(3)).fetchResources(any())); + } + @Test void pollsAgainAfterRestart() { source.onResourceCreated(testCustomResource); @@ -286,6 +320,55 @@ void pollsAgainAfterRestart() { await().untilAsserted(() -> verify(supplier, atLeast(2)).fetchResources(any())); } + @Test + void aFailingFetchOutlivingTheDeletionDoesNotStartASecondPollingChain() throws Exception { + verifyFetchOutlivingDeletionDoesNotStartASecondPollingChain( + () -> { + throw new IllegalStateException("failure after the deletion"); + }); + } + + @Test + void aFetchOutlivingTheDeletionDoesNotStartASecondPollingChain() throws Exception { + verifyFetchOutlivingDeletionDoesNotStartASecondPollingChain( + () -> Set.of(SampleExternalResource.testResource1())); + } + + private void verifyFetchOutlivingDeletionDoesNotStartASecondPollingChain( + Supplier> result) throws Exception { + var fetching = new CountDownLatch(1); + var release = new CountDownLatch(1); + when(supplier.fetchResources(any())) + .thenAnswer( + invocation -> { + fetching.countDown(); + var interrupted = false; + while (release.getCount() > 0) { + try { + release.await(); + } catch (InterruptedException e) { + interrupted = true; + } + } + if (interrupted) { + Thread.currentThread().interrupt(); + } + return result.get(); + }) + .thenReturn(Set.of(SampleExternalResource.testResource1())); + + source.onResourceCreated(testCustomResource); + assertThat(fetching.await(5, TimeUnit.SECONDS)).isTrue(); + source.onResourceDeleted(testCustomResource); + source.onResourceCreated(testCustomResource); + clearInvocations(supplier); + release.countDown(); + + await() + .pollDelay(Duration.ofMillis(10 * PERIOD)) + .untilAsserted(() -> verify(supplier, atMost(15)).fetchResources(any())); + } + @Test void aFetchOutlivingARestartDoesNotStartASecondPollingChain() throws Exception { var fetching = new CountDownLatch(1); From ed5a21a6da794875282debcc21f394cfd104175d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Attila=20M=C3=A9sz=C3=A1ros?= Date: Wed, 18 Nov 2026 17:03:49 +0100 Subject: [PATCH 18/23] fix: use monotonic clock for remaining retry duration (#3702) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GenericRetryExecution used System.currentTimeMillis(), so a system clock step could make the preserved retry deadline too long or too short. Signed-off-by: Attila Mészáros --- .../processing/retry/GenericRetryExecution.java | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/retry/GenericRetryExecution.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/retry/GenericRetryExecution.java index fadc022de7..8428e32a5a 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/retry/GenericRetryExecution.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/retry/GenericRetryExecution.java @@ -17,6 +17,7 @@ import java.time.Duration; import java.util.Optional; +import java.util.concurrent.TimeUnit; public class GenericRetryExecution implements RetryExecution { @@ -24,7 +25,7 @@ public class GenericRetryExecution implements RetryExecution { private int lastAttemptIndex = 0; private long currentInterval; - private Long lastNextDelayCallEpochMillis; + private Long lastNextDelayCallNanos; public GenericRetryExecution(GenericRetry genericRetry) { this.genericRetry = genericRetry; @@ -42,7 +43,7 @@ public Optional nextDelay() { } } lastAttemptIndex++; - lastNextDelayCallEpochMillis = System.currentTimeMillis(); + lastNextDelayCallNanos = System.nanoTime(); return Optional.of(currentInterval); } @@ -58,13 +59,15 @@ public int getAttemptCount() { @Override public Optional remainingDurationUntilNextRetry() { - if (lastNextDelayCallEpochMillis == null) { + if (lastNextDelayCallNanos == null) { return Optional.empty(); } - long remaining = (lastNextDelayCallEpochMillis + currentInterval) - System.currentTimeMillis(); - if (remaining <= 0) { + var remainingNanos = + TimeUnit.MILLISECONDS.toNanos(currentInterval) + - (System.nanoTime() - lastNextDelayCallNanos); + if (remainingNanos <= 0) { return Optional.empty(); } - return Optional.of(Duration.ofMillis(remaining)); + return Optional.of(Duration.ofNanos(remainingNanos)); } } From 3d73338856345aae45302bb83f3cfdd579711820 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Attila=20M=C3=A9sz=C3=A1ros?= Date: Wed, 18 Nov 2026 17:06:36 +0100 Subject: [PATCH 19/23] fix: handle namespace removed concurrently in temporary resource cache (#3703) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit InformerManager.lastSyncResourceVersion throws NoSuchElementException if the namespace informer is removed between the isWatchingNamespace check and the call. Handle it in putResource and ghost resource cleanup, and tolerate an unknown last sync resource version during ghost cleanup. Signed-off-by: Attila Mészáros --- .../informer/TemporaryResourceCache.java | 28 +++++++++++-- .../informer/TemporaryResourceCacheTest.java | 39 +++++++++++++++++++ 2 files changed, 63 insertions(+), 4 deletions(-) diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/TemporaryResourceCache.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/TemporaryResourceCache.java index a557fd1fc5..53528c28e6 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/TemporaryResourceCache.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/TemporaryResourceCache.java @@ -16,6 +16,7 @@ package io.javaoperatorsdk.operator.processing.event.source.informer; import java.util.Map; +import java.util.NoSuchElementException; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; @@ -173,7 +174,16 @@ public synchronized void putResource(T newResource) { // // this also prevents resurrecting recently deleted entities for which the delete event // has already been processed - var latestRV = getLastSyncResourceVersion(ns); + final String latestRV; + try { + latestRV = getLastSyncResourceVersion(ns); + } catch (NoSuchElementException e) { + log.debug( + "Skipping caching of resource: {} since namespace is not being watched anymore: {}", + resourceId, + ns); + return; + } if (latestRV != null && ReconcilerUtilsInternal.compareResourceVersions( latestRV, newResource.getMetadata().getResourceVersion()) @@ -225,8 +235,17 @@ public synchronized void checkGhostResources() { var e = iterator.next(); var ns = e.getValue().getMetadata().getNamespace(); + String lastSyncResourceVersion = null; + var watched = managedInformerEventSource.manager().isWatchingNamespace(ns); + if (watched) { + try { + lastSyncResourceVersion = getLastSyncResourceVersion(ns); + } catch (NoSuchElementException ex) { + watched = false; + } + } // this can happen if followed namespaces are changed dynamically - if (!managedInformerEventSource.manager().isWatchingNamespace(ns)) { + if (!watched) { log.debug( "Removing resource: {} from cache as part of ghost cleanup. Namespace is not followed" + " anymore: {}", @@ -236,8 +255,9 @@ public synchronized void checkGhostResources() { eventFilteringSupport.handleGhostResourceRemoval(e.getKey()); continue; } - if ((ReconcilerUtilsInternal.compareResourceVersions( - e.getValue().getMetadata().getResourceVersion(), getLastSyncResourceVersion(ns)) + if (lastSyncResourceVersion != null + && (ReconcilerUtilsInternal.compareResourceVersions( + e.getValue().getMetadata().getResourceVersion(), lastSyncResourceVersion) < 0) // making sure we have the situation where resource is missing from the cache && managedInformerEventSource.manager().get(e.getKey()).isEmpty()) { diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/TemporaryResourceCacheTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/TemporaryResourceCacheTest.java index 158e42180f..20a9323eb6 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/TemporaryResourceCacheTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/TemporaryResourceCacheTest.java @@ -16,6 +16,7 @@ package io.javaoperatorsdk.operator.processing.event.source.informer; import java.util.Map; +import java.util.NoSuchElementException; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; @@ -28,6 +29,7 @@ import io.javaoperatorsdk.operator.processing.event.source.ResourceAction; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; @@ -399,4 +401,41 @@ ConfigMap testResource() { configMap.getMetadata().setUid("test-uid"); return configMap; } + + @Test + void putResourceIgnoredIfNamespaceRemovedAfterWatchCheck() { + var mim = managedInformerEventSource.manager(); + when(mim.lastSyncResourceVersion(any())).thenThrow(new NoSuchElementException()); + var testResource = testResource(); + + assertDoesNotThrow(() -> temporaryResourceCache.putResource(testResource)); + + assertThat(temporaryResourceCache.getResourceFromCache(ResourceID.fromResource(testResource))) + .isEmpty(); + } + + @Test + void ghostCheckRemovesResourceIfNamespaceRemovedAfterWatchCheck() { + var testResource = testResource(); + temporaryResourceCache.putResource(testResource); + var mim = managedInformerEventSource.manager(); + when(mim.lastSyncResourceVersion(any())).thenThrow(new NoSuchElementException()); + + assertDoesNotThrow(() -> temporaryResourceCache.checkGhostResources()); + + assertThat(temporaryResourceCache.getResourceFromCache(ResourceID.fromResource(testResource))) + .isEmpty(); + } + + @Test + void ghostCheckKeepsResourceIfLastSyncResourceVersionUnknown() { + var testResource = testResource(); + temporaryResourceCache.putResource(testResource); + latestSyncVersion = null; + + assertDoesNotThrow(() -> temporaryResourceCache.checkGhostResources()); + + assertThat(temporaryResourceCache.getResourceFromCache(ResourceID.fromResource(testResource))) + .isPresent(); + } } From b3f9d72345e29ceebd93fbc588a4cac8e77ea769 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Attila=20M=C3=A9sz=C3=A1ros?= Date: Wed, 18 Nov 2026 17:07:47 +0100 Subject: [PATCH 20/23] fix: do not resurrect resources deleted while BoundedItemStore refetches them (#3706) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit refreshMissingStateFromServer fetched without holding the lock and then put the result back if the cache was empty, even when the informer had removed the key in the meantime. Signed-off-by: Attila Mészáros --- .../event/source/cache/BoundedItemStore.java | 4 ++++ .../source/cache/BoundedItemStoreTest.java | 17 +++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/cache/BoundedItemStore.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/cache/BoundedItemStore.java index abf12bcf58..fc57e3637a 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/cache/BoundedItemStore.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/cache/BoundedItemStore.java @@ -140,6 +140,10 @@ protected R refreshMissingStateFromServer(String key) { var newRes = resourceFetcher.fetchResource(key); synchronized (this) { log.debug("Fetched resource: {}", newRes); + if (!existingMinimalResources.containsKey(key)) { + // the resource was removed (deleted) while fetching, must not be resurrected + return null; + } var actual = cache.get(key); if (newRes == null) { // double-checking if actual, not received since. diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/cache/BoundedItemStoreTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/cache/BoundedItemStoreTest.java index e6b2810721..5b6500ff36 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/cache/BoundedItemStoreTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/cache/BoundedItemStoreTest.java @@ -80,6 +80,23 @@ void removesResourcesNotFoundOnServerFromStore() { assertThat(boundedItemStore.keySet()).isEmpty(); } + @Test + void doesNotResurrectResourceRemovedWhileFetchingFromServer() { + boundedItemStore.put(testRes1Key(), TestUtils.testCustomResource1()); + when(resourceFetcher.fetchResource(testRes1Key())) + .thenAnswer( + invocation -> { + boundedItemStore.remove(testRes1Key()); + return TestUtils.testCustomResource1(); + }); + + var res = boundedItemStore.get(testRes1Key()); + + assertThat(res).isNull(); + assertThat(boundedItemStore.keySet()).isEmpty(); + verify(boundedCache, times(1)).put(any(), any()); + } + @Test void removesResourceFromCache() { boundedItemStore.put(testRes1Key(), TestUtils.testCustomResource1()); From e8ea39783cbad553af84459bb455cdd2178c4653 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Attila=20M=C3=A9sz=C3=A1ros?= Date: Wed, 18 Nov 2026 17:33:49 +0100 Subject: [PATCH 21/23] fix: rate limiter allows more reconciliations than limit and uses wall clock (#3701) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The rate limiter only checked for an expired period once the limit was reached, so a stale period could grant more permits than configured. It also used LocalDateTime, which jumps on DST changes; use System.nanoTime. Signed-off-by: Attila Mészáros --- .../event/rate/LinearRateLimiter.java | 16 +++++++--------- .../processing/event/rate/RateState.java | 18 ++++++++---------- .../event/rate/LinearRateLimiterTest.java | 11 +++++++++++ 3 files changed, 26 insertions(+), 19 deletions(-) diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/LinearRateLimiter.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/LinearRateLimiter.java index 52425f815a..86e88ff112 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/LinearRateLimiter.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/LinearRateLimiter.java @@ -16,7 +16,6 @@ package io.javaoperatorsdk.operator.processing.event.rate; import java.time.Duration; -import java.time.LocalDateTime; import java.util.Optional; import io.javaoperatorsdk.operator.api.config.AnnotationConfigurable; @@ -53,18 +52,17 @@ public Optional isLimited(RateLimitState rateLimitState) { if (!isActivated() || !(rateLimitState instanceof RateState actualState)) { return Optional.empty(); } - var now = LocalDateTime.now(); + var now = System.nanoTime(); + var periodNanos = refreshPeriod.toNanos(); + var elapsedNanos = now - actualState.getLastRefreshNanos(); + if (elapsedNanos > periodNanos) { + actualState.reset(now); + } if (actualState.getCount() < limitForPeriod) { actualState.increaseCount(); return Optional.empty(); - } else if (actualState.getLastRefreshTime().isBefore(now.minus(refreshPeriod))) { - actualState.reset(); - actualState.increaseCount(); - return Optional.empty(); - } else { - var remaining = Duration.between(now, actualState.getLastRefreshTime().plus(refreshPeriod)); - return Optional.of(remaining.isNegative() ? Duration.ZERO : remaining); } + return Optional.of(Duration.ofNanos(Math.max(0, periodNanos - elapsedNanos))); } @Override diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/RateState.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/RateState.java index e3159dccdb..aad7b74554 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/RateState.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/RateState.java @@ -15,21 +15,19 @@ */ package io.javaoperatorsdk.operator.processing.event.rate; -import java.time.LocalDateTime; - import io.javaoperatorsdk.operator.processing.event.rate.RateLimiter.RateLimitState; class RateState implements RateLimitState { - private LocalDateTime lastRefreshTime; + private long lastRefreshNanos; private int count; public static RateState initialState() { - return new RateState(LocalDateTime.now(), 0); + return new RateState(System.nanoTime(), 0); } - RateState(LocalDateTime lastRefreshTime, int count) { - this.lastRefreshTime = lastRefreshTime; + RateState(long lastRefreshNanos, int count) { + this.lastRefreshNanos = lastRefreshNanos; this.count = count; } @@ -37,13 +35,13 @@ public void increaseCount() { count = count + 1; } - public void reset() { - lastRefreshTime = LocalDateTime.now(); + public void reset(long nowNanos) { + lastRefreshNanos = nowNanos; count = 0; } - public LocalDateTime getLastRefreshTime() { - return lastRefreshTime; + public long getLastRefreshNanos() { + return lastRefreshNanos; } public int getCount() { diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/rate/LinearRateLimiterTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/rate/LinearRateLimiterTest.java index 7c5bdac479..89c88b6598 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/rate/LinearRateLimiterTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/rate/LinearRateLimiterTest.java @@ -94,4 +94,15 @@ void rateLimitCanBeTurnedOff() { assertThat(res).isEmpty(); } + + @Test + void expiredPeriodIsResetEvenIfLimitWasNotReached() { + var rl = new LinearRateLimiter(REFRESH_PERIOD, 2); + var staleState = + new RateState(System.nanoTime() - REFRESH_PERIOD.multipliedBy(10).toNanos(), 1); + + assertThat(rl.isLimited(staleState)).isEmpty(); + assertThat(rl.isLimited(staleState)).isEmpty(); + assertThat(rl.isLimited(staleState)).isPresent(); + } } From 1cd68ed24236fe3a4bbc1e2859fef82fd928b175 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Attila=20M=C3=A9sz=C3=A1ros?= Date: Thu, 19 Nov 2026 14:15:17 +0100 Subject: [PATCH 22/23] docs: add v5.7 release blog post (#3708) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit docs: add v5.7 release blog post Signed-off-by: Attila Mészáros --- docs/content/en/blog/releases/v5-7-release.md | 270 ++++++++++++++++++ 1 file changed, 270 insertions(+) create mode 100644 docs/content/en/blog/releases/v5-7-release.md diff --git a/docs/content/en/blog/releases/v5-7-release.md b/docs/content/en/blog/releases/v5-7-release.md new file mode 100644 index 0000000000..5b92e8bacb --- /dev/null +++ b/docs/content/en/blog/releases/v5-7-release.md @@ -0,0 +1,270 @@ +--- +title: Version 5.7 Released! +date: 2026-11-19 +author: >- + [Attila Mészáros](https://github.com/csviri) +--- + +We're pleased to announce the release of Java Operator SDK v5.7.0! The headline features of this +minor version are **virtual thread support**, an upgrade to the **Fabric8 Kubernetes Client 8.0** +(with the **Vert.x 5 HTTP client** as the new default), **desired state aspects** for adding common +metadata to all managed resources, and a much more capable **event recorder**. Because of the client +upgrade, which moves to Jackson 3, this release contains **breaking changes** for operators that use +Jackson types directly — see the migration notes. + +## Key Features + +### Virtual threads + +Reconciliation is mostly about blocking: talking to the Kubernetes API server or to external systems. +Virtual threads make such blocking calls much cheaper than platform threads, and the framework can now +be switched over to them with a single flag: + +```java +Operator operator = new Operator(override -> override.withUseVirtualThreads(true)); +``` + +The same can be set with the `josdk.use-virtual-threads` configuration property. When enabled, +reconciliations, dependent resource workflows and the framework's internal housekeeping (starting the +informers, for example) all run on virtual threads. So do the polls of the polling event sources and +the retried and rescheduled reconciliations; the Kubernetes client the framework creates also +dispatches informer and watch events on virtual threads. + +Enabling virtual threads does **not** remove the concurrency limits. `withConcurrentReconciliationThreads` +and `withConcurrentWorkflowExecutorThreads` still cap the parallelism exactly as before, only the +threads backing those limits change. Since virtual threads are cheap, these limits can usually be +raised significantly compared to what is reasonable with platform threads. + +A few things to keep in mind: + +- Virtual threads are only supported on **Java 25 or later**, the first LTS release where a virtual + thread no longer pins its carrier thread while inside a `synchronized` block + ([JEP 491](https://openjdk.org/jeps/491), delivered in Java 24). Without that, pinning can starve + the carrier pool and even deadlock an operator on startup. This is checked at runtime: on an older + JVM a warning is logged and platform threads are used, so the same configuration works on any Java + version the operator runs on. +- Virtual threads are daemon threads, so they don't keep the JVM running. If nothing else does, call + the new `Operator.keepAlive()` after starting the operator (see below). +- An executor you provide yourself is always used as is, the flag has no effect on it. There is one + catch: overriding `useVirtualThreads`, or `withConcurrentRetryAndRescheduleThreads`, of a + configuration that provides its own retry and reschedule executor replaces that executor with the + default one, so provide it again with `withRetryAndRescheduleExecutorService(...)` in that case. + +#### Keeping the JVM alive + +Until now the JVM was kept running as a side effect of the non-daemon threads of the operator's thread +pools. With virtual threads that is no longer the case, so `Operator.keepAlive()` starts a non-daemon +thread that keeps the JVM running until the operator is stopped: + +```java +public static void main(String[] args) { + Operator operator = new Operator(override -> override.withUseVirtualThreads(true)); + operator.register(new MyReconciler()); + operator.installShutdownHook(); + operator.start(); + operator.keepAlive(); +} +``` + +#### Polling event sources have their own executors + +To make this work, the polling event sources and the internal `TimerEventSource` no longer use a +`java.util.Timer`. Each polling event source now polls on a scheduled executor of its own, so a slow +poll of one event source never delays the polls of the others, and retried and rescheduled +reconciliations run on a separate executor that a slow poll can never delay. A +`PerResourcePollingEventSource` with many registered resources can be given an executor with more +threads: + +```java +var config = + new PerResourcePollingConfigurationBuilder<>(this::fetchResources, Duration.ofSeconds(5)) + .withExecutorService(Executors.newScheduledThreadPool(4)) + .build(); +``` + +An executor provided that way is yours to shut down. See the +[configuration](/docs/documentation/operations/configuration/#virtual-threads) and +[eventing](/docs/documentation/eventing/#threading-of-the-polling-event-sources) documentation for +details, and the migration guide for the (small) behavioral differences. + +### Fabric8 Kubernetes Client 8.0 and the Vert.x 5 HTTP client + +JOSDK 5.7 is built on version 8.0.0 of the +[Fabric8 Kubernetes Client](https://github.com/fabric8io/kubernetes-client). The most visible change +of the client is the move from Jackson 2 to **Jackson 3**: the packages changed from +`com.fasterxml.jackson` to `tools.jackson` (the annotations being the exception). If your operator +uses Jackson types directly, you will need to update your imports and dependencies. + +In line with the client's own default, the `operator-framework` artifact now brings the **Vert.x 5** +based HTTP client instead of the JDK one. If you don't declare an HTTP client of your own there is +nothing to do. To keep the JDK client, or to use another implementation, exclude the default and add the +one you want: + +```xml + + io.javaoperatorsdk + operator-framework + + + io.fabric8 + kubernetes-httpclient-vertx-5 + + + + + io.fabric8 + kubernetes-httpclient-jdk + 8.0.0 + +``` + +### Desired state aspects + +Operators often need to mark every resource they manage in a uniform way, for example with an +`app.kubernetes.io/managed-by` label, so that these resources can be easily identified, selected or +garbage-collected later on. Instead of repeating that logic in every `desired()` implementation, a +`DesiredStateAspect` can now be registered once, at the operator level, and is applied to the desired +state of every Kubernetes dependent resource the operator manages: + +```java +Operator operator = new Operator(overrider -> overrider + .withDesiredStateAspects(List.of( + (desired, dependentResource, context) -> desired.getMetadata().getLabels() + .put("app.kubernetes.io/managed-by", "my-operator")))); +``` + +Aspects are applied in registration order, right after the desired state is computed and before it is +matched against the actual resource. The metadata an aspect adds is therefore part of the desired +state proper: if it is removed from the actual resource, or the aspect itself changes, the secondary +resources are updated accordingly on the next reconciliation. Aspects are called at most once per +dependent resource and reconciliation, are not called for external (non-Kubernetes) dependent +resources, and need to be thread-safe. + +Thanks to [Martin Stefanko](https://github.com/xstefank) for this contribution! + +### A more capable event recorder + +The [event recorder](/docs/documentation/kubernetes-events) introduced in 5.6 got several additions, +and has a documentation page of its own now. + +**Events about any object.** An event does not have to be about the primary resource. A controller +reconciling a child resource can, for example, record on the parent, so that `kubectl describe parent` +shows what happened to its children. Bind the recorder to the other object: + +```java +var parent = context.getSecondaryResource(Parent.class).orElseThrow(); +context.eventRecorder(parent).warn("ChildFailed", "could not reconcile child " + name); +``` + +Aggregation works per object: two children recording the same reason and message on one parent count +as repeats of a single event on the parent, while different messages stay separate events. + +**Fail on error.** Recording an event is best effort by default: a failure to write it is logged and +swallowed. Where an event that is not recorded must not go unnoticed, the default recorder can be +configured to propagate the failure, so that the reconciliation fails and is retried like any other: + +```java +KubernetesClient client = new KubernetesClientBuilder().build(); +Operator operator = new Operator(override -> override + .withKubernetesClient(client) + .withEventRecorder(DefaultEventRecorder.builder(new DefaultEventSink(client)) + .failOnError(true) + .build())); +``` + +**Configurable aggregation, owner references and naming.** `DefaultEventRecorder` can now be built with +an `EventKeyStrategy`, controlling what counts as the same event, an `EventNamingStrategy`, +controlling how events are named, and optionally sets an `ownerReference` to the object an event is +about. `EventRecord.Builder#key(...)` and `ownedByRegarding(...)` override these per event. + +**Correctness fixes.** Aggregating onto an existing event now also updates its type, reason and +action, so a `Warning` repeated under the name of a `Normal` event is no longer reported as the +`Normal` one. Event names longer than the Kubernetes limit are shortened with a hash instead of being +plainly truncated, so distinct names sharing a long prefix no longer merge into one event. Events +about cluster scoped resources now carry what the API server requires to accept them in `kube-system` +(the API server only accepts such events in `default` and `kube-system`, so the documentation no +longer suggests the namespace the operator runs in). + +Thanks to [Antonio Fernandez Alhambra](https://github.com/afalhambra-hivemq) for the event recorder +contributions! + +### Removing the namespace index of informers + +Informers keep an index from namespace to the cached resources. JOSDK never reads that index, so for +informers caching a large number of resources it can be removed to save an entry per cached resource, +which matters most together with a custom item store that caches only a reduced form of each resource: + +```java +@ControllerConfiguration(informer = @Informer(withoutNamespaceIndex = true)) +public class MyReconciler implements Reconciler { } +``` + +The option is also available on `InformerEventSourceConfiguration.Builder` and `InformerConfiguration.Builder`, +and as the `josdk.controller..informer.without-namespace-index` property. Note that it takes +part in the informer pool identity: event sources watching the same resource type, where only one +removes the index, don't share an informer. + +Thanks to [Antonio Fernandez Alhambra](https://github.com/afalhambra-hivemq) for this contribution too! + +## Bug Fixes + +- **`comparableResourceVersions` is kept when a dependent resource's informer configuration is + copied**, it used to be lost. +- **The `version.properties` resource was renamed to `operator-sdk-version.properties`** to avoid + collisions with resources of the same name on the classpath. + +## Migration Notes + +### Fabric8 Kubernetes Client 8.0 / Jackson 3 + +This is the only source-incompatible change for most operators. Besides the package change +(`com.fasterxml.jackson` to `tools.jackson`), `JsonProcessingException` was replaced by the unchecked +`JacksonException`, some `JsonNode` methods were renamed (`fields()` to `properties()`, `asText()` to +`asString()`), and `ObjectMapper` instances are created using builders. Also, calls to +`withShardSelector(null)` no longer compile because of an additional overload, cast the argument: +`withShardSelector((String) null)`. + +### Default HTTP client is now Vert.x 5 + +If your operator already replaced the default HTTP client by excluding `kubernetes-httpclient-jdk`, +update the exclusion to `kubernetes-httpclient-vertx-5`, otherwise it ends up on the classpath next to +your implementation. This is especially important with the Vert.x 4 based client, since Vert.x 4 and +Vert.x 5 cannot be used together. + +### Polling and timer event sources + +An executor provided to a `PerResourcePollingConfigurationBuilder` is no longer shut down by the event +source, and `PerResourcePollingConfiguration.executorService()` returns `null` when none was provided. +`PollingEventSource(Class, PollingConfiguration)` and `TimerEventSource(String, boolean)` are +deprecated; use the constructors that take an `EventSourceContext` and an executor supplier respectively. + +### Low level event recorder API + +The low level event recorder API changed to support events about any object: a custom +`EventRecorder` now implements `record(HasMetadata regarding, EventRecord event, Context context)` +and a subclass of `DefaultEventRecorder` overrides `toEvent(HasMetadata, EventRecord, Context)`. +Reconcilers that only use `context.eventRecorder()` are not affected. + +See the [migration guide](/docs/migration/v5-7-migration) for all the details. + +## Getting Started + +```xml + + io.javaoperatorsdk + operator-framework + 5.7.0 + +``` + +## All Changes + +See the [comparison view](https://github.com/operator-framework/java-operator-sdk/compare/v5.6.4...v5.7.0) +for the full list of changes. + +## Feedback + +Please report issues or suggest improvements on our +[GitHub repository](https://github.com/operator-framework/java-operator-sdk/issues). + +Happy operator building! 🚀 From 45515dff409e8e36b7de33f811fef8dc348b3344 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Attila=20M=C3=A9sz=C3=A1ros?= Date: Thu, 19 Nov 2026 14:58:17 +0100 Subject: [PATCH 23/23] fix: skip stale ghost resources in temporary cache merge for list, byIndex and keys (#3704) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Resources only present in the temporary cache were always added to list, byIndex and keys results. When the informer had already processed a newer state (e.g. a delete, or a version no longer matching the index) but its event handler had not yet cleared the temporary cache, a stale copy was returned. Apply the same last sync resource version check as get(). Signed-off-by: Attila Mészáros --- .../informer/ManagedInformerEventSource.java | 46 +++-- .../informer/InformerEventSourceTest.java | 182 ++++++++++++++++++ 2 files changed, 217 insertions(+), 11 deletions(-) diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/ManagedInformerEventSource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/ManagedInformerEventSource.java index 86e4e03d99..e9de15ba52 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/ManagedInformerEventSource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/ManagedInformerEventSource.java @@ -24,6 +24,7 @@ import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; +import java.util.function.Supplier; import java.util.function.UnaryOperator; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -307,7 +308,7 @@ public void addIndexers(Map>> indexers) { */ @Override public Stream list(String namespace, Predicate predicate) { - return mergeWithTempCacheForList(manager().list(namespace), namespace, predicate); + return mergeWithTempCacheForList(() -> manager().list(namespace), namespace, predicate); } /** @@ -318,7 +319,7 @@ public Stream list(String namespace, Predicate predicate) { */ @Override public Stream list(Predicate predicate) { - return mergeWithTempCacheForList(manager().list(), null, predicate); + return mergeWithTempCacheForList(() -> manager().list(), null, predicate); } /** @@ -347,19 +348,23 @@ public List byIndex(String indexName, String indexKey) { } // namespace is filtered on informer manager level + // The informer stream is supplied lazily because the namespace-scoped list snapshots the informer + // cache as soon as it is created. The superseded ids have to be computed before that snapshot, + // otherwise a resource the informer catches up with in between is missing from both. private Stream mergeWithTempCacheForList( - Stream stream, String namespace, Predicate predicate) { + Supplier> streamSupplier, String namespace, Predicate predicate) { if (!comparableResourceVersions || temporaryResourceCache.isEmpty()) { - - return stream.filter(filterResourceByPredicate(predicate)); + return streamSupplier.get().filter(filterResourceByPredicate(predicate)); } var tempResources = new HashMap<>(temporaryResourceCache.getResources()); if (tempResources.isEmpty()) { - return stream.filter(filterResourceByPredicate(predicate)); + return streamSupplier.get().filter(filterResourceByPredicate(predicate)); } + var supersededIds = idsSupersededByInformer(tempResources); var upToDateList = - stream + streamSupplier + .get() .map( r -> { var resourceID = ResourceID.fromResource(r); @@ -376,6 +381,7 @@ private Stream mergeWithTempCacheForList( return Stream.concat( tempResources.values().stream() + .filter(r -> !supersededIds.contains(ResourceID.fromResource(r))) .filter(filterResourceByNamespaceAndPredicate(namespace, predicate)), upToDateList.stream()); } @@ -394,6 +400,7 @@ private Stream mergeWithTempCacheForIndex( if (indexer == null) { throw new IllegalArgumentException("Indexer not found for: " + indexName); } + var supersededIds = idsSupersededByInformer(tempResources); var upToDateList = stream @@ -413,9 +420,12 @@ private Stream mergeWithTempCacheForIndex( .filter(Objects::nonNull) .toList(); - // remaining temp resources are ghost resources — include only those matching the index + // remaining temp resources are ghost resources — include only those matching the index and + // not already superseded in the informer return Stream.concat( - tempResources.values().stream().filter(r -> indexer.apply(r).contains(indexKey)), + tempResources.values().stream() + .filter(r -> !supersededIds.contains(ResourceID.fromResource(r))) + .filter(r -> indexer.apply(r).contains(indexKey)), upToDateList.stream()); } @@ -452,10 +462,24 @@ public Stream keys() { if (!comparableResourceVersions || temporaryResourceCache.isEmpty()) { return manager().keys(); } + var tempResources = temporaryResourceCache.getResources(); + var supersededIds = idsSupersededByInformer(tempResources); var managerKeys = manager().keys().collect(Collectors.toSet()); - var tempKeys = temporaryResourceCache.getResources().keySet(); return Stream.concat( - managerKeys.stream(), tempKeys.stream().filter(k -> !managerKeys.contains(k))); + managerKeys.stream(), + tempResources.keySet().stream() + .filter(k -> !managerKeys.contains(k) && !supersededIds.contains(k))); + } + + /** + * Has to be evaluated before the informer state is read, so a resource that the informer catches + * up with in the meantime is not missing from both. + */ + private Set idsSupersededByInformer(Map tempResources) { + return tempResources.entrySet().stream() + .filter(e -> !isLaterThanLastSyncResourceVersion(e.getValue())) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); } @Override diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerEventSourceTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerEventSourceTest.java index 01ee25e44c..4664c18c25 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerEventSourceTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerEventSourceTest.java @@ -23,6 +23,7 @@ import java.util.Optional; import java.util.Set; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; @@ -374,6 +375,7 @@ void listAddsGhostResources() { .thenReturn(new HashMap<>(Map.of(ResourceID.fromResource(ghostResource), ghostResource))); var mim = mock(InformerManager.class); + stubLastSyncResourceVersion(mim, "1"); when(mim.list(nullable(String.class))).thenReturn(Stream.of(resource)); when(informerEventSource.manager()).thenReturn(mim); @@ -382,6 +384,163 @@ void listAddsGhostResources() { assertThat(result).containsExactlyInAnyOrder(resource, ghostResource); } + @Test + void listSkipsGhostResourcesAlreadyCoveredByInformer() { + var resource = testDeployment(); + var ghostResource = testDeployment(); + ghostResource.getMetadata().setName("ghost"); + + when(temporaryResourceCache.getResources()) + .thenReturn(new HashMap<>(Map.of(ResourceID.fromResource(ghostResource), ghostResource))); + + var mim = mock(InformerManager.class); + stubLastSyncResourceVersion(mim, DEFAULT_RESOURCE_VERSION); + when(mim.list(nullable(String.class))).thenReturn(Stream.of(resource)); + when(informerEventSource.manager()).thenReturn(mim); + + var result = informerEventSource.list(null, r -> true).toList(); + + assertThat(result).containsExactly(resource); + } + + @Test + void byIndexSkipsOlderTempCacheResourceNoLongerInIndexedInformerResult() { + var staleTemp = testDeployment(); + staleTemp.getMetadata().setLabels(Map.of("app", "key")); + + when(temporaryResourceCache.getResources()) + .thenReturn(new HashMap<>(Map.of(ResourceID.fromResource(staleTemp), staleTemp))); + + var informerManager = mock(InformerManager.class); + stubLastSyncResourceVersion(informerManager, "5"); + when(informerManager.byIndexStream(any(), any())).thenReturn(Stream.empty()); + when(informerEventSource.manager()).thenReturn(informerManager); + informerEventSource.addIndexers( + Map.of("idx", d -> List.of(d.getMetadata().getLabels().get("app")))); + + var result = informerEventSource.byIndexStream("idx", "key").toList(); + + assertThat(result).isEmpty(); + } + + @Test + void byIndexIncludesGhostResourceNotYetSeenByInformer() { + var ghost = testDeployment(); + ghost.getMetadata().setLabels(Map.of("app", "key")); + + when(temporaryResourceCache.getResources()) + .thenReturn(new HashMap<>(Map.of(ResourceID.fromResource(ghost), ghost))); + + var informerManager = mock(InformerManager.class); + stubLastSyncResourceVersion(informerManager, "1"); + when(informerManager.byIndexStream(any(), any())).thenReturn(Stream.empty()); + when(informerEventSource.manager()).thenReturn(informerManager); + informerEventSource.addIndexers( + Map.of("idx", d -> List.of(d.getMetadata().getLabels().get("app")))); + + var result = informerEventSource.byIndexStream("idx", "key").toList(); + + assertThat(result).containsExactly(ghost); + } + + @Test + void listKeepsGhostResourceIfInformerCatchesUpWhileReadingTheInformerState() { + var ghostResource = testDeployment(); + ghostResource.getMetadata().setName("ghost"); + var other = testDeployment(); + other.getMetadata().setName("other"); + var lastSync = new AtomicReference<>("1"); + + when(temporaryResourceCache.getResources()) + .thenReturn(new HashMap<>(Map.of(ResourceID.fromResource(ghostResource), ghostResource))); + var mim = mock(InformerManager.class); + when(mim.isWatchingNamespace(any())).thenReturn(true); + when(mim.lastSyncResourceVersion(any())).thenAnswer(i -> lastSync.get()); + when(mim.list(nullable(String.class))) + .thenReturn(Stream.of(other).peek(r -> lastSync.set("5"))); + when(informerEventSource.manager()).thenReturn(mim); + + var result = informerEventSource.list(null, r -> true).toList(); + + assertThat(result).containsExactlyInAnyOrder(other, ghostResource); + } + + @Test + void listKeepsGhostResourceIfInformerCatchesUpWhenTheInformerSnapshotIsTaken() { + var ghostResource = testDeployment(); + ghostResource.getMetadata().setName("ghost"); + var other = testDeployment(); + other.getMetadata().setName("other"); + var lastSync = new AtomicReference<>("1"); + + when(temporaryResourceCache.getResources()) + .thenReturn(new HashMap<>(Map.of(ResourceID.fromResource(ghostResource), ghostResource))); + var mim = mock(InformerManager.class); + when(mim.isWatchingNamespace(any())).thenReturn(true); + when(mim.lastSyncResourceVersion(any())).thenAnswer(i -> lastSync.get()); + when(mim.list(nullable(String.class))) + .thenAnswer( + i -> { + lastSync.set("5"); + return Stream.of(other); + }); + when(informerEventSource.manager()).thenReturn(mim); + + var result = informerEventSource.list(null, r -> true).toList(); + + assertThat(result).containsExactlyInAnyOrder(other, ghostResource); + } + + @Test + void byIndexKeepsGhostResourceIfInformerCatchesUpWhileReadingTheInformerState() { + var ghostResource = testDeployment(); + ghostResource.getMetadata().setName("ghost"); + var other = testDeployment(); + other.getMetadata().setName("other"); + var lastSync = new AtomicReference<>("1"); + + when(temporaryResourceCache.getResources()) + .thenReturn(new HashMap<>(Map.of(ResourceID.fromResource(ghostResource), ghostResource))); + var mim = mock(InformerManager.class); + when(mim.isWatchingNamespace(any())).thenReturn(true); + when(mim.lastSyncResourceVersion(any())).thenAnswer(i -> lastSync.get()); + when(mim.byIndexStream(any(), any())).thenReturn(Stream.of(other).peek(r -> lastSync.set("5"))); + when(informerEventSource.manager()).thenReturn(mim); + informerEventSource.addIndexers(Map.of("idx", d -> List.of("key"))); + + var result = informerEventSource.byIndexStream("idx", "key").toList(); + + assertThat(result).containsExactlyInAnyOrder(other, ghostResource); + } + + @Test + void keysKeepGhostResourceKeyIfInformerCatchesUpWhileReadingTheInformerState() { + var ghostResource = testDeployment(); + ghostResource.getMetadata().setName("ghost"); + var other = testDeployment(); + other.getMetadata().setName("other"); + var ghostResourceId = ResourceID.fromResource(ghostResource); + var otherId = ResourceID.fromResource(other); + var lastSync = new AtomicReference<>("1"); + + when(temporaryResourceCache.getResources()).thenReturn(Map.of(ghostResourceId, ghostResource)); + when(temporaryResourceCache.isEmpty()).thenReturn(false); + var mim = mock(InformerManager.class); + when(mim.isWatchingNamespace(any())).thenReturn(true); + when(mim.lastSyncResourceVersion(any())).thenAnswer(i -> lastSync.get()); + when(mim.keys()).thenReturn(Stream.of(otherId).peek(r -> lastSync.set("5"))); + when(informerEventSource.manager()).thenReturn(mim); + + var result = informerEventSource.keys().toList(); + + assertThat(result).containsExactlyInAnyOrder(otherId, ghostResourceId); + } + + private void stubLastSyncResourceVersion(InformerManager mim, String resourceVersion) { + when(mim.isWatchingNamespace(any())).thenReturn(true); + when(mim.lastSyncResourceVersion(any())).thenReturn(resourceVersion); + } + @Test void byIndexStreamReplacesFromTempCache() { var original = testDeployment(); @@ -436,6 +595,7 @@ void keysIncludeGhostResourceKeys() { when(temporaryResourceCache.isEmpty()).thenReturn(false); var mim = mock(InformerManager.class); + stubLastSyncResourceVersion(mim, "1"); when(mim.keys()).thenReturn(Stream.of(resourceId)); when(mim.contains(ghostResourceId)).thenReturn(false); when(informerEventSource.manager()).thenReturn(mim); @@ -445,6 +605,28 @@ void keysIncludeGhostResourceKeys() { assertThat(result).containsExactlyInAnyOrder(resourceId, ghostResourceId); } + @Test + void keysSkipGhostResourceKeysAlreadyCoveredByInformer() { + var resource = testDeployment(); + var ghostResource = testDeployment(); + ghostResource.getMetadata().setName("ghost"); + + var resourceId = ResourceID.fromResource(resource); + var ghostResourceId = ResourceID.fromResource(ghostResource); + + when(temporaryResourceCache.getResources()).thenReturn(Map.of(ghostResourceId, ghostResource)); + when(temporaryResourceCache.isEmpty()).thenReturn(false); + + var mim = mock(InformerManager.class); + stubLastSyncResourceVersion(mim, DEFAULT_RESOURCE_VERSION); + when(mim.keys()).thenReturn(Stream.of(resourceId)); + when(informerEventSource.manager()).thenReturn(mim); + + var result = informerEventSource.keys().toList(); + + assertThat(result).containsExactly(resourceId); + } + @Test void keysDoNotDuplicateExistingKeys() { var resource = testDeployment();