From 433570147396cd26a52055abb8679e713c35b3c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Attila=20M=C3=A9sz=C3=A1ros?= Date: Fri, 20 Nov 2026 09:26:27 +0100 Subject: [PATCH 1/6] chore: update version to 999-SNAPSHOT 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 | 2 +- operator-framework-junit/pom.xml | 2 +- operator-framework/pom.xml | 2 +- pom.xml | 2 +- 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 | 2 +- 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, 18 insertions(+), 18 deletions(-) diff --git a/bootstrapper-maven-plugin/pom.xml b/bootstrapper-maven-plugin/pom.xml index c002d5a793..b0d36eaf70 100644 --- a/bootstrapper-maven-plugin/pom.xml +++ b/bootstrapper-maven-plugin/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk java-operator-sdk - 5.7.0-SNAPSHOT + 999-SNAPSHOT bootstrapper diff --git a/caffeine-bounded-cache-support/pom.xml b/caffeine-bounded-cache-support/pom.xml index 8854666a76..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.7.0-SNAPSHOT + 999-SNAPSHOT caffeine-bounded-cache-support diff --git a/micrometer-support/pom.xml b/micrometer-support/pom.xml index 7b7b8a9cd9..29dcf1f9f5 100644 --- a/micrometer-support/pom.xml +++ b/micrometer-support/pom.xml @@ -21,7 +21,7 @@ io.javaoperatorsdk java-operator-sdk - 5.7.0-SNAPSHOT + 999-SNAPSHOT micrometer-support diff --git a/migration/pom.xml b/migration/pom.xml index 52fe5b1459..cf5143c925 100644 --- a/migration/pom.xml +++ b/migration/pom.xml @@ -21,7 +21,7 @@ io.javaoperatorsdk java-operator-sdk - 5.7.0-SNAPSHOT + 999-SNAPSHOT migration diff --git a/operator-framework-bom/pom.xml b/operator-framework-bom/pom.xml index 1257f62e67..7ce5b2530b 100644 --- a/operator-framework-bom/pom.xml +++ b/operator-framework-bom/pom.xml @@ -21,7 +21,7 @@ io.javaoperatorsdk operator-framework-bom - 5.7.0-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 c6f356b526..755536add7 100644 --- a/operator-framework-core/pom.xml +++ b/operator-framework-core/pom.xml @@ -21,7 +21,7 @@ io.javaoperatorsdk java-operator-sdk - 5.7.0-SNAPSHOT + 999-SNAPSHOT ../pom.xml diff --git a/operator-framework-junit/pom.xml b/operator-framework-junit/pom.xml index fa831f4c26..aa18d5c778 100644 --- a/operator-framework-junit/pom.xml +++ b/operator-framework-junit/pom.xml @@ -21,7 +21,7 @@ io.javaoperatorsdk java-operator-sdk - 5.7.0-SNAPSHOT + 999-SNAPSHOT operator-framework-junit diff --git a/operator-framework/pom.xml b/operator-framework/pom.xml index 94c8a80875..6d314d4687 100644 --- a/operator-framework/pom.xml +++ b/operator-framework/pom.xml @@ -21,7 +21,7 @@ io.javaoperatorsdk java-operator-sdk - 5.7.0-SNAPSHOT + 999-SNAPSHOT operator-framework diff --git a/pom.xml b/pom.xml index 8ad49e7c1f..63efbd29e7 100644 --- a/pom.xml +++ b/pom.xml @@ -21,7 +21,7 @@ io.javaoperatorsdk java-operator-sdk - 5.7.0-SNAPSHOT + 999-SNAPSHOT pom Operator SDK for Java Java SDK for implementing Kubernetes operators diff --git a/sample-operators/controller-namespace-deletion/pom.xml b/sample-operators/controller-namespace-deletion/pom.xml index 5416bf2b2f..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.7.0-SNAPSHOT + 999-SNAPSHOT sample-controller-namespace-deletion diff --git a/sample-operators/kotlin-operator/pom.xml b/sample-operators/kotlin-operator/pom.xml index e798719851..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.7.0-SNAPSHOT + 999-SNAPSHOT sample-kotlin-operator diff --git a/sample-operators/leader-election/pom.xml b/sample-operators/leader-election/pom.xml index e9a0710de4..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.7.0-SNAPSHOT + 999-SNAPSHOT sample-leader-election diff --git a/sample-operators/mysql-schema/pom.xml b/sample-operators/mysql-schema/pom.xml index 5613a25667..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.7.0-SNAPSHOT + 999-SNAPSHOT sample-mysql-schema-operator diff --git a/sample-operators/operations/pom.xml b/sample-operators/operations/pom.xml index 126cbe86ab..d9eddd1fee 100644 --- a/sample-operators/operations/pom.xml +++ b/sample-operators/operations/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk sample-operators - 5.7.0-SNAPSHOT + 999-SNAPSHOT sample-operations diff --git a/sample-operators/pom.xml b/sample-operators/pom.xml index 291b496a12..704007c076 100644 --- a/sample-operators/pom.xml +++ b/sample-operators/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk java-operator-sdk - 5.7.0-SNAPSHOT + 999-SNAPSHOT sample-operators diff --git a/sample-operators/tomcat-operator/pom.xml b/sample-operators/tomcat-operator/pom.xml index ea32f5c507..0a05fffc1c 100644 --- a/sample-operators/tomcat-operator/pom.xml +++ b/sample-operators/tomcat-operator/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk sample-operators - 5.7.0-SNAPSHOT + 999-SNAPSHOT sample-tomcat-operator diff --git a/sample-operators/webpage/pom.xml b/sample-operators/webpage/pom.xml index ea53493a71..d50e5ef03c 100644 --- a/sample-operators/webpage/pom.xml +++ b/sample-operators/webpage/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk sample-operators - 5.7.0-SNAPSHOT + 999-SNAPSHOT sample-webpage-operator diff --git a/test-index-processor/pom.xml b/test-index-processor/pom.xml index b543d62f48..2ae7c5f454 100644 --- a/test-index-processor/pom.xml +++ b/test-index-processor/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk java-operator-sdk - 5.7.0-SNAPSHOT + 999-SNAPSHOT test-index-processor From a9434cf830532c5e75464527c6d7b5595925ca6d Mon Sep 17 00:00:00 2001 From: hej090224 Date: Sun, 29 Nov 2026 21:12:45 +0900 Subject: [PATCH 2/6] feat: add informer resource version health check (#3730) Signed-off-by: hej090224 --- .../documentation/operations/health-probes.md | 31 ++++-- .../InformerResourceVersionHealthCheck.java | 84 +++++++++++++++ ...nformerResourceVersionHealthCheckTest.java | 100 ++++++++++++++++++ 3 files changed, 205 insertions(+), 10 deletions(-) create mode 100644 operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/InformerResourceVersionHealthCheck.java create mode 100644 operator-framework-core/src/test/java/io/javaoperatorsdk/operator/health/InformerResourceVersionHealthCheckTest.java diff --git a/docs/content/en/docs/documentation/operations/health-probes.md b/docs/content/en/docs/documentation/operations/health-probes.md index f6ec5406e0..b1f2f53be5 100644 --- a/docs/content/en/docs/documentation/operations/health-probes.md +++ b/docs/content/en/docs/documentation/operations/health-probes.md @@ -39,22 +39,33 @@ be valuable for operational dashboards or troubleshooting. An informer whose watch is open but delivers nothing (for example, when the API server replica it’s connected to serves reads from a stale watch cache) still reports `hasSynced()` and `isRunning()`, so its status stays healthy. `InformerHealthIndicator.getLastSyncResourceVersion()` exposes the resource version of the last -event, bookmark or list the informer processed, and returns `null` before the first list. Since events and -bookmarks keep moving this value, a probe can remember it per informer and report the informer unhealthy -once it has not changed for longer than a timeout of your choosing: +event, bookmark or list the informer processed, and returns `null` before the first list. +`InformerResourceVersionHealthCheck` tracks the versions and reports which healthy informers have not +advanced within a timeout you choose: ```java +// Keep this instance across probe requests. +var versionCheck = new InformerResourceVersionHealthCheck(Duration.ofMinutes(15)); + +// On each request, collect every current informer under a unique key. +Map informers = new HashMap<>(); operator.getRuntimeInfo().getRegisteredControllers().forEach(controller -> controller.getControllerHealthInfo().informerEventSourceHealthIndicators() - .forEach((eventSourceName, eventSource) -> - eventSource.informerHealthIndicators().forEach((namespace, informer) -> { - String resourceVersion = informer.getLastSyncResourceVersion(); - // compare with the value seen by the previous check - }))); + .forEach((eventSourceName, eventSource) -> { + InformerWrappingEventSourceHealthIndicator wrapping = eventSource; + wrapping.informerHealthIndicators().forEach((namespace, informer) -> + informers.put(controller.getConfiguration().getName() + "/" + + eventSourceName + "/" + namespace, informer)); + })); +Set stale = versionCheck.staleInformers(informers); ``` -The API server makes no guarantees about how often it sends bookmarks, so set a conservative timeout -(several minutes) to avoid restarting an operator that is simply watching a quiet cluster. +Create the check once and call it on every probe request. Removed informers and those without a resource +version are excluded. A new version clears the stale result. Choose a timeout longer than the client's +maximum watch reconnect interval (currently 10 minutes); 15 minutes leaves room for delays. Kubernetes +does not guarantee a bookmark cadence or that every bookmark advances the resource version. A quiet +cluster can therefore leave the version unchanged even while the watch is working; account for this +when using the stale result to fail a liveness probe. ## Setting Up a Probe Endpoint diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/InformerResourceVersionHealthCheck.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/InformerResourceVersionHealthCheck.java new file mode 100644 index 0000000000..448fe9468d --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/InformerResourceVersionHealthCheck.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.health; + +import java.time.Duration; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.LongSupplier; + +/** + * Tracks how long each informer's last synchronized resource version has remained unchanged. An + * unchanged version can be normal in a quiet cluster, so callers should choose a suitable timeout + * and decide how to use the resulting diagnostic signal. + * + *

Keep one instance for successive checks and pass all current informers to each call. The keys + * should uniquely identify informers across controllers, event sources and namespaces. Informers + * that disappear, have no resource version, or are already unhealthy are forgotten. + */ +public class InformerResourceVersionHealthCheck { + + private final Duration timeout; + private final LongSupplier ticker; + private final Map observations = new HashMap<>(); + + public InformerResourceVersionHealthCheck(Duration timeout) { + this(timeout, System::nanoTime); + } + + InformerResourceVersionHealthCheck(Duration timeout, LongSupplier ticker) { + this.timeout = Objects.requireNonNull(timeout); + if (timeout.isZero() || timeout.isNegative()) { + throw new IllegalArgumentException("timeout must be positive"); + } + this.ticker = Objects.requireNonNull(ticker); + } + + /** + * Returns the keys of healthy informers whose resource version has not advanced by the timeout. + */ + public synchronized Set staleInformers( + Map informers) { + Objects.requireNonNull(informers); + observations.keySet().retainAll(informers.keySet()); + var now = ticker.getAsLong(); + Set stale = new HashSet<>(); + informers.forEach( + (key, informer) -> { + var resourceVersion = informer.getLastSyncResourceVersion(); + if (informer.getStatus() != Status.HEALTHY || resourceVersion == null) { + observations.remove(key); + return; + } + + var last = observations.get(key); + if (last == null + || last.informer() != informer + || !last.resourceVersion().equals(resourceVersion)) { + observations.put(key, new Observation(informer, resourceVersion, now)); + } else if (Duration.ofNanos(now - last.since()).compareTo(timeout) >= 0) { + stale.add(key); + } + }); + return Set.copyOf(stale); + } + + private record Observation( + InformerHealthIndicator informer, String resourceVersion, long since) {} +} diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/health/InformerResourceVersionHealthCheckTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/health/InformerResourceVersionHealthCheckTest.java new file mode 100644 index 0000000000..c3fefc2979 --- /dev/null +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/health/InformerResourceVersionHealthCheckTest.java @@ -0,0 +1,100 @@ +/* + * 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.health; + +import java.time.Duration; +import java.util.Map; +import java.util.concurrent.atomic.AtomicLong; + +import org.junit.jupiter.api.Test; + +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; + +class InformerResourceVersionHealthCheckTest { + + private final AtomicLong time = new AtomicLong(); + private final InformerResourceVersionHealthCheck check = + new InformerResourceVersionHealthCheck(Duration.ofMinutes(10), time::get); + + @Test + void reportsOnlyVersionsThatHaveNotAdvancedWithinTheTimeout() { + var first = indicator("1"); + var second = indicator("2"); + var informers = Map.of("first", first, "second", second); + + assertThat(check.staleInformers(informers)).isEmpty(); + time.set(Duration.ofMinutes(9).toNanos()); + when(second.getLastSyncResourceVersion()).thenReturn("3"); + assertThat(check.staleInformers(informers)).isEmpty(); + + time.set(Duration.ofMinutes(10).toNanos()); + assertThat(check.staleInformers(informers)).containsExactly("first"); + when(first.getLastSyncResourceVersion()).thenReturn("4"); + assertThat(check.staleInformers(informers)).isEmpty(); + + time.set(Duration.ofMinutes(19).toNanos()); + assertThat(check.staleInformers(informers)).containsExactly("second"); + } + + @Test + void ignoresUnavailableVersionsAndResetsAfterAnUnhealthyPeriod() { + var informer = indicator(null); + var informers = Map.of("informer", informer); + + assertThat(check.staleInformers(informers)).isEmpty(); + time.set(Duration.ofMinutes(20).toNanos()); + assertThat(check.staleInformers(informers)).isEmpty(); + + when(informer.getLastSyncResourceVersion()).thenReturn("1"); + assertThat(check.staleInformers(informers)).isEmpty(); + time.set(Duration.ofMinutes(31).toNanos()); + assertThat(check.staleInformers(informers)).containsExactly("informer"); + + when(informer.getStatus()).thenReturn(Status.UNHEALTHY); + assertThat(check.staleInformers(informers)).isEmpty(); + when(informer.getStatus()).thenReturn(Status.HEALTHY); + assertThat(check.staleInformers(informers)).isEmpty(); + } + + @Test + void forgetsRemovedAndReplacedInformers() { + var original = indicator("1"); + assertThat(check.staleInformers(Map.of("informer", original))).isEmpty(); + time.set(Duration.ofMinutes(11).toNanos()); + assertThat(check.staleInformers(Map.of("informer", original))).containsExactly("informer"); + + assertThat(check.staleInformers(Map.of())).isEmpty(); + assertThat(check.staleInformers(Map.of("informer", original))).isEmpty(); + time.set(Duration.ofMinutes(22).toNanos()); + assertThat(check.staleInformers(Map.of("informer", indicator("1")))).isEmpty(); + } + + @Test + void requiresAPositiveTimeout() { + assertThatThrownBy(() -> new InformerResourceVersionHealthCheck(Duration.ZERO)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static InformerHealthIndicator indicator(String resourceVersion) { + var indicator = mock(InformerHealthIndicator.class); + when(indicator.getStatus()).thenReturn(Status.HEALTHY); + when(indicator.getLastSyncResourceVersion()).thenReturn(resourceVersion); + return indicator; + } +} From 79f1670080efbe6da458f5c6f9b8c76acfa150d6 Mon Sep 17 00:00:00 2001 From: Exar Viquez Date: Tue, 1 Dec 2026 02:51:54 -0600 Subject: [PATCH 3/6] feat: configure InformerEventSource indexers from the builder (#3732) Add withIndexer and withIndexers to InformerEventSourceConfiguration.Builder, expose them through getIndexers, and register them when the InformerEventSource is created. Dynamically registered informers can still add indexers at runtime. Document that purpose and point to the builder otherwise. Signed-off-by: Exar-lab --- .../documentation/working-with-es-caches.md | 17 +++++ .../InformerEventSourceConfiguration.java | 65 ++++++++++++++++++- .../source/informer/InformerEventSource.java | 15 +++++ .../InformerEventSourceConfigurationTest.java | 41 ++++++++++++ .../informer/InformerEventSourceTest.java | 19 ++++++ .../ReadOwnUpdatesReconciler.java | 4 +- 6 files changed, 158 insertions(+), 3 deletions(-) diff --git a/docs/content/en/docs/documentation/working-with-es-caches.md b/docs/content/en/docs/documentation/working-with-es-caches.md index d31f1e079f..f9363c4608 100644 --- a/docs/content/en/docs/documentation/working-with-es-caches.md +++ b/docs/content/en/docs/documentation/working-with-es-caches.md @@ -216,6 +216,23 @@ With this index in place, you can retrieve the target resources very efficiently .withNamespacesInheritedFromController().build()); ``` +The same can be done for the cache of a secondary resource: indexers are configured on the +`InformerEventSourceConfiguration.Builder`, and are registered before the event source starts. +`InformerEventSource.addIndexers(..)` is only meant for the dynamic case, where an informer is +registered at runtime and its indexers are only known at that point. Otherwise, use the builder: + +```java +InformerEventSource configMapEventSource = + new InformerEventSource<>( + InformerEventSourceConfiguration.from(ConfigMap.class, MyResource.class) + .withIndexer( + "by-resource-version", cm -> List.of(cm.getMetadata().getResourceVersion())) + .build()); + +// later, e.g. in the reconciler +configMapEventSource.byIndex("by-resource-version", resourceVersion); +``` + ## Read-cache-after-write consistency and event filtering From version 5.3.0 we provide stronger consistency guarantees and 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 d40469de4c..c069ac437d 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 @@ -16,9 +16,14 @@ package io.javaoperatorsdk.operator.api.config.informer; import java.time.Duration; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.function.Function; import io.fabric8.kubernetes.api.model.GenericKubernetesResource; import io.fabric8.kubernetes.api.model.HasMetadata; @@ -86,6 +91,16 @@ default String name() { return getInformerConfig().getName(); } + /** + * The indexers to register on the informer event source, by index name. They are registered when + * the event source is created, so they are in place before it starts. + * + * @return the configured indexers, empty if there are none + */ + default Map>> getIndexers() { + return Map.of(); + } + class DefaultInformerEventSourceConfiguration implements InformerEventSourceConfiguration { private final PrimaryToSecondaryMapper primaryToSecondaryMapper; @@ -93,6 +108,7 @@ class DefaultInformerEventSourceConfiguration private final GroupVersionKind groupVersionKind; private final InformerConfiguration informerConfig; private final KubernetesClient kubernetesClient; + private final Map>> indexers; protected DefaultInformerEventSourceConfiguration( GroupVersionKind groupVersionKind, @@ -100,11 +116,33 @@ protected DefaultInformerEventSourceConfiguration( SecondaryToPrimaryMapper secondaryToPrimaryMapper, InformerConfiguration informerConfig, KubernetesClient kubernetesClient) { + this( + groupVersionKind, + primaryToSecondaryMapper, + secondaryToPrimaryMapper, + informerConfig, + kubernetesClient, + Map.of()); + } + + protected DefaultInformerEventSourceConfiguration( + GroupVersionKind groupVersionKind, + PrimaryToSecondaryMapper primaryToSecondaryMapper, + SecondaryToPrimaryMapper secondaryToPrimaryMapper, + InformerConfiguration informerConfig, + KubernetesClient kubernetesClient, + Map>> indexers) { this.informerConfig = Objects.requireNonNull(informerConfig); this.groupVersionKind = groupVersionKind; this.primaryToSecondaryMapper = primaryToSecondaryMapper; this.secondaryToPrimaryMapper = secondaryToPrimaryMapper; this.kubernetesClient = kubernetesClient; + this.indexers = indexers; + } + + @Override + public Map>> getIndexers() { + return indexers; } @Override @@ -145,6 +183,7 @@ class Builder { private PrimaryToSecondaryMapper primaryToSecondaryMapper; private SecondaryToPrimaryMapper secondaryToPrimaryMapper; private KubernetesClient kubernetesClient; + private final Map>> indexers = new LinkedHashMap<>(); private Builder(Class resourceClass, Class primaryResourceClass) { this(resourceClass, primaryResourceClass, null); @@ -272,6 +311,29 @@ public Builder withGenericFilter(GenericFilter genericFilter) { return this; } + /** + * Registers an indexer on the informer event source, so the resources it caches can be looked + * up by the keys the indexer computes (see {@link + * io.javaoperatorsdk.operator.processing.event.source.IndexerResourceCache#byIndex}). + * + * @param name the name of the index, unique per event source + * @param indexer computes the index keys of a resource + */ + public Builder withIndexer(String name, Function> indexer) { + indexers.put(Objects.requireNonNull(name), Objects.requireNonNull(indexer)); + return this; + } + + /** + * Registers several indexers at once. + * + * @see #withIndexer(String, Function) + */ + public Builder withIndexers(Map>> indexers) { + indexers.forEach(this::withIndexer); + return this; + } + public Builder withItemStore(ItemStore itemStore) { config.withItemStore(itemStore); return this; @@ -345,7 +407,8 @@ public InformerEventSourceConfiguration build() { HasMetadata.getKind(primaryResourceClass), false)), config.build(), - kubernetesClient); + kubernetesClient, + Collections.unmodifiableMap(new LinkedHashMap<>(indexers))); } } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerEventSource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerEventSource.java index abde1f6992..a8418ce738 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerEventSource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerEventSource.java @@ -16,8 +16,11 @@ package io.javaoperatorsdk.operator.processing.event.source.informer; import java.util.HashSet; +import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.function.Function; import java.util.stream.Collectors; import org.slf4j.Logger; @@ -78,6 +81,18 @@ public InformerEventSource(InformerEventSourceConfiguration configuration) { onUpdateFilter = informerConfig.getOnUpdateFilter(); onDeleteFilter = informerConfig.getOnDeleteFilter(); genericFilter = informerConfig.getGenericFilter(); + super.addIndexers(configuration.getIndexers()); + } + + /** + * Adds indexers to an already created event source, for example when the informer is registered + * dynamically and its indexers are only known at that point. Indexers known upfront should be + * configured with {@link InformerEventSourceConfiguration.Builder#withIndexer(String, Function)} + * instead. + */ + @Override + public void addIndexers(Map>> indexers) { + super.addIndexers(indexers); } @Override 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 index 9e43b288cc..be3034af57 100644 --- 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 @@ -15,6 +15,10 @@ */ package io.javaoperatorsdk.operator.api.config; +import java.util.List; +import java.util.Map; +import java.util.function.Function; + import org.junit.jupiter.api.Test; import io.fabric8.kubernetes.api.model.ConfigMap; @@ -22,7 +26,10 @@ import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; class InformerEventSourceConfigurationTest { @@ -39,4 +46,38 @@ void updateFromKeepsComparableResourceVersions() { assertFalse(builder.build().getInformerConfig().isComparableResourceVersions()); } + + @Test + void indexersAreEmptyByDefault() { + var configuration = + InformerEventSourceConfiguration.from(ConfigMap.class, Secret.class).build(); + + assertTrue(configuration.getIndexers().isEmpty()); + } + + @Test + void builderCollectsIndexers() { + Function> byName = cm -> List.of(cm.getMetadata().getName()); + Function> byNamespace = cm -> List.of(cm.getMetadata().getNamespace()); + + var configuration = + InformerEventSourceConfiguration.from(ConfigMap.class, Secret.class) + .withIndexer("name", byName) + .withIndexers(Map.of("namespace", byNamespace)) + .build(); + + assertEquals(Map.of("name", byName, "namespace", byNamespace), configuration.getIndexers()); + } + + @Test + void configuredIndexersCannotBeModifiedAfterBuild() { + var configuration = + InformerEventSourceConfiguration.from(ConfigMap.class, Secret.class) + .withIndexer("name", cm -> List.of(cm.getMetadata().getName())) + .build(); + + assertThrows( + UnsupportedOperationException.class, + () -> configuration.getIndexers().put("other", cm -> List.of())); + } } 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 4664c18c25..9dff538023 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 @@ -423,6 +423,25 @@ void byIndexSkipsOlderTempCacheResourceNoLongerInIndexedInformerResult() { assertThat(result).isEmpty(); } + @Test + void indexersFromConfigurationAreRegisteredOnCreation() { + when(informerEventSourceConfiguration.getIndexers()) + .thenReturn(Map.of("idx", d -> List.of(d.getMetadata().getLabels().get("app")))); + informerEventSource = buildInformerEventSource(); + 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); + + var result = informerEventSource.byIndexStream("idx", "key").toList(); + + assertThat(result).containsExactly(ghost); + } + @Test void byIndexIncludesGhostResourceNotYetSeenByInformer() { var ghost = testDeployment(); diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/readcacheafterwrite/readownupdates/ReadOwnUpdatesReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/readcacheafterwrite/readownupdates/ReadOwnUpdatesReconciler.java index c62d637a88..cc85793508 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/readcacheafterwrite/readownupdates/ReadOwnUpdatesReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/readcacheafterwrite/readownupdates/ReadOwnUpdatesReconciler.java @@ -123,9 +123,9 @@ public List> prepareEventSources( new InformerEventSource<>( InformerEventSourceConfiguration.from( ConfigMap.class, ReadOwnUpdatesCustomResource.class) + .withIndexer( + RESOURCE_VERSION_INDEX, cm -> List.of(cm.getMetadata().getResourceVersion())) .build()); - configMapEventSource.addIndexers( - Map.of(RESOURCE_VERSION_INDEX, cm -> List.of(cm.getMetadata().getResourceVersion()))); return List.of(configMapEventSource); } From a0ec41912c33f01285737c1f67d1fcc8da434362 Mon Sep 17 00:00:00 2001 From: hej090224 Date: Wed, 2 Dec 2026 09:28:40 +0900 Subject: [PATCH 4/6] feat: log informer resource version health transitions and wire into operations sample Log a WARN when an informer's key enters the stale set and an INFO when it recovers, instead of logging on every probe request, so the logs show when the condition started and ended without being noisy. Wire InformerResourceVersionHealthCheck into the operations sample's HealthHandler as a logging-only diagnostic on every probe request, and document both in health-probes.md. Signed-off-by: hej090224 --- .../documentation/operations/health-probes.md | 7 ++ .../InformerResourceVersionHealthCheck.java | 31 +++++++- ...nformerResourceVersionHealthCheckTest.java | 72 +++++++++++++++++++ .../sample/operations/HealthHandler.java | 46 +++++++++++- 4 files changed, 154 insertions(+), 2 deletions(-) diff --git a/docs/content/en/docs/documentation/operations/health-probes.md b/docs/content/en/docs/documentation/operations/health-probes.md index b1f2f53be5..5c51ec863f 100644 --- a/docs/content/en/docs/documentation/operations/health-probes.md +++ b/docs/content/en/docs/documentation/operations/health-probes.md @@ -67,6 +67,13 @@ does not guarantee a bookmark cadence or that every bookmark advances the resour cluster can therefore leave the version unchanged even while the watch is working; account for this when using the stale result to fail a liveness probe. +Each time an informer's key enters or leaves the stale set, `InformerResourceVersionHealthCheck` logs the +transition (a `WARN` when it becomes stale, an `INFO` when it recovers) instead of logging on every +request, so the logs show when the condition started and ended without being noisy. See the +[`operations` sample operator](https://github.com/java-operator-sdk/java-operator-sdk/tree/main/sample-operators/operations)'s +`HealthHandler` for a working example that runs the check on every probe request purely for logging, +without failing the probe. + ## Setting Up a Probe Endpoint The example below uses [Jetty](https://eclipse.dev/jetty/) to expose a `/healthz` endpoint. Any HTTP diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/InformerResourceVersionHealthCheck.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/InformerResourceVersionHealthCheck.java index 448fe9468d..a48898d6d5 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/InformerResourceVersionHealthCheck.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/InformerResourceVersionHealthCheck.java @@ -23,6 +23,9 @@ import java.util.Set; import java.util.function.LongSupplier; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * Tracks how long each informer's last synchronized resource version has remained unchanged. An * unchanged version can be normal in a quiet cluster, so callers should choose a suitable timeout @@ -34,9 +37,13 @@ */ public class InformerResourceVersionHealthCheck { + private static final Logger log = + LoggerFactory.getLogger(InformerResourceVersionHealthCheck.class); + private final Duration timeout; private final LongSupplier ticker; private final Map observations = new HashMap<>(); + private Set previouslyStale = Set.of(); public InformerResourceVersionHealthCheck(Duration timeout) { this(timeout, System::nanoTime); @@ -76,7 +83,29 @@ public synchronized Set staleInformers( stale.add(key); } }); - return Set.copyOf(stale); + logTransitions(stale); + previouslyStale = Set.copyOf(stale); + return previouslyStale; + } + + private void logTransitions(Set stale) { + for (var key : stale) { + if (!previouslyStale.contains(key)) { + log.warn( + "Informer resource version health check: '{}' has not advanced its resource version" + + " for at least {}, marking as stale", + key, + timeout); + } + } + for (var key : previouslyStale) { + if (!stale.contains(key) && observations.containsKey(key)) { + log.info( + "Informer resource version health check: '{}' resource version advanced again," + + " no longer stale", + key); + } + } } private record Observation( diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/health/InformerResourceVersionHealthCheckTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/health/InformerResourceVersionHealthCheckTest.java index c3fefc2979..4cd0575f0b 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/health/InformerResourceVersionHealthCheckTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/health/InformerResourceVersionHealthCheckTest.java @@ -16,9 +16,18 @@ package io.javaoperatorsdk.operator.health; import java.time.Duration; +import java.util.ArrayList; +import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.core.Appender; +import org.apache.logging.log4j.core.Logger; +import org.apache.logging.log4j.core.appender.AbstractAppender; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -32,6 +41,69 @@ class InformerResourceVersionHealthCheckTest { private final InformerResourceVersionHealthCheck check = new InformerResourceVersionHealthCheck(Duration.ofMinutes(10), time::get); + private final List logMessages = new ArrayList<>(); + private Appender logAppender; + private Logger logger; + + @BeforeEach + void setupLogCapture() { + logger = (Logger) LogManager.getLogger(InformerResourceVersionHealthCheck.class); + logAppender = + new AbstractAppender("test-appender", null, null) { + @Override + public void append(org.apache.logging.log4j.core.LogEvent event) { + logMessages.add(event.getLevel() + ": " + event.getMessage().getFormattedMessage()); + } + }; + logAppender.start(); + logger.addAppender(logAppender); + logger.setLevel(Level.ALL); + } + + @AfterEach + void removeLogCapture() { + logger.removeAppender(logAppender); + logAppender.stop(); + } + + @Test + void logsWhenAnInformerBecomesStaleAndRecovers() { + var informer = indicator("1"); + var informers = Map.of("informer", informer); + + assertThat(check.staleInformers(informers)).isEmpty(); + assertThat(logMessages).isEmpty(); + + time.set(Duration.ofMinutes(10).toNanos()); + assertThat(check.staleInformers(informers)).containsExactly("informer"); + assertThat(logMessages).hasSize(1); + assertThat(logMessages.get(0)).contains("WARN").contains("informer").contains("stale"); + + time.set(Duration.ofMinutes(11).toNanos()); + assertThat(check.staleInformers(informers)).containsExactly("informer"); + assertThat(logMessages).hasSize(1); + + when(informer.getLastSyncResourceVersion()).thenReturn("2"); + assertThat(check.staleInformers(informers)).isEmpty(); + assertThat(logMessages).hasSize(2); + assertThat(logMessages.get(1)).contains("INFO").contains("informer").contains("longer stale"); + } + + @Test + void doesNotLogRecoveryWhenAStaleInformerBecomesUnhealthy() { + var informer = indicator("1"); + var informers = Map.of("informer", informer); + + assertThat(check.staleInformers(informers)).isEmpty(); + time.set(Duration.ofMinutes(10).toNanos()); + assertThat(check.staleInformers(informers)).containsExactly("informer"); + assertThat(logMessages).hasSize(1); + + when(informer.getStatus()).thenReturn(Status.UNHEALTHY); + assertThat(check.staleInformers(informers)).isEmpty(); + assertThat(logMessages).hasSize(1); + } + @Test void reportsOnlyVersionsThatHaveNotAdvancedWithinTheTimeout() { var first = indicator("1"); diff --git a/sample-operators/operations/src/main/java/io/javaoperatorsdk/operator/sample/operations/HealthHandler.java b/sample-operators/operations/src/main/java/io/javaoperatorsdk/operator/sample/operations/HealthHandler.java index 156930b7f3..f49043d64e 100644 --- a/sample-operators/operations/src/main/java/io/javaoperatorsdk/operator/sample/operations/HealthHandler.java +++ b/sample-operators/operations/src/main/java/io/javaoperatorsdk/operator/sample/operations/HealthHandler.java @@ -17,6 +17,9 @@ import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.HashMap; +import java.util.Map; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Request; @@ -24,15 +27,24 @@ import org.eclipse.jetty.util.Callback; import io.javaoperatorsdk.operator.Operator; +import io.javaoperatorsdk.operator.health.InformerHealthIndicator; +import io.javaoperatorsdk.operator.health.InformerResourceVersionHealthCheck; +import io.javaoperatorsdk.operator.health.InformerWrappingEventSourceHealthIndicator; /** * Combined health endpoint that checks whether all event sources (informers, polling sources, etc.) * are healthy. Before the operator has fully started the informers will not have synced yet, so * this endpoint naturally covers the startup case as well. + * + *

It also runs {@link InformerResourceVersionHealthCheck} on every request to detect informers + * whose resource version has stopped advancing; see the health-probes documentation for why this is + * only logged here rather than failing the probe. */ public class HealthHandler extends Handler.Abstract { private final Operator operator; + private final InformerResourceVersionHealthCheck resourceVersionHealthCheck = + new InformerResourceVersionHealthCheck(Duration.ofMinutes(15)); public HealthHandler(Operator operator) { this.operator = operator; @@ -41,7 +53,11 @@ public HealthHandler(Operator operator) { @Override public boolean handle(Request request, Response response, Callback callback) { var runtimeInfo = operator.getRuntimeInfo(); - if (runtimeInfo.isStarted() && runtimeInfo.allEventSourcesAreHealthy()) { + var started = runtimeInfo.isStarted(); + if (started) { + resourceVersionHealthCheck.staleInformers(collectInformerHealthIndicators()); + } + if (started && runtimeInfo.allEventSourcesAreHealthy()) { sendMessage(response, 200, "healthy", callback); } else { sendMessage(response, 503, "not healthy", callback); @@ -49,6 +65,34 @@ public boolean handle(Request request, Response response, Callback callback) { return true; } + private Map collectInformerHealthIndicators() { + Map informers = new HashMap<>(); + operator + .getRuntimeInfo() + .getRegisteredControllers() + .forEach( + controller -> + controller + .getControllerHealthInfo() + .informerEventSourceHealthIndicators() + .forEach( + (eventSourceName, eventSource) -> { + InformerWrappingEventSourceHealthIndicator wrapping = eventSource; + wrapping + .informerHealthIndicators() + .forEach( + (namespace, informer) -> + informers.put( + controller.getConfiguration().getName() + + "/" + + eventSourceName + + "/" + + namespace, + informer)); + })); + return informers; + } + static void sendMessage(Response response, int code, String message, Callback callback) { response.setStatus(code); response.getHeaders().put("Content-Type", "text/plain; charset=utf-8"); From 3058dd4032a72af836f74b7d74b0efb9ed31581c Mon Sep 17 00:00:00 2001 From: hej090224 Date: Wed, 2 Dec 2026 09:31:54 +0900 Subject: [PATCH 5/6] Revert "Merge remote-tracking branch 'upstream/next' into issue/3730-last-sync-health" This reverts commit a41d1bc2fedf9669cf4f9b9416b95289d374637d, reversing changes made to a9434cf830532c5e75464527c6d7b5595925ca6d. Signed-off-by: hej090224 --- bootstrapper-maven-plugin/pom.xml | 4 +- caffeine-bounded-cache-support/pom.xml | 2 +- .../documentation/working-with-es-caches.md | 17 ----- micrometer-support/pom.xml | 2 +- migration/pom.xml | 2 +- operator-framework-bom/pom.xml | 2 +- operator-framework-core/pom.xml | 4 +- .../InformerEventSourceConfiguration.java | 65 +------------------ .../source/informer/InformerEventSource.java | 15 ----- .../InformerEventSourceConfigurationTest.java | 41 ------------ .../informer/InformerEventSourceTest.java | 19 ------ operator-framework-junit/pom.xml | 2 +- operator-framework/pom.xml | 2 +- .../ReadOwnUpdatesReconciler.java | 4 +- pom.xml | 6 +- .../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 +- 24 files changed, 26 insertions(+), 181 deletions(-) diff --git a/bootstrapper-maven-plugin/pom.xml b/bootstrapper-maven-plugin/pom.xml index b0d36eaf70..1307be8d55 100644 --- a/bootstrapper-maven-plugin/pom.xml +++ b/bootstrapper-maven-plugin/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk java-operator-sdk - 999-SNAPSHOT + 5.7.1-SNAPSHOT bootstrapper @@ -32,7 +32,7 @@ 3.16.0 - 3.10.1 + 3.10.2 3.2.0 3.16.0 diff --git a/caffeine-bounded-cache-support/pom.xml b/caffeine-bounded-cache-support/pom.xml index be70ab9a2e..a9412ef6ec 100644 --- a/caffeine-bounded-cache-support/pom.xml +++ b/caffeine-bounded-cache-support/pom.xml @@ -21,7 +21,7 @@ io.javaoperatorsdk java-operator-sdk - 999-SNAPSHOT + 5.7.1-SNAPSHOT caffeine-bounded-cache-support diff --git a/docs/content/en/docs/documentation/working-with-es-caches.md b/docs/content/en/docs/documentation/working-with-es-caches.md index f9363c4608..d31f1e079f 100644 --- a/docs/content/en/docs/documentation/working-with-es-caches.md +++ b/docs/content/en/docs/documentation/working-with-es-caches.md @@ -216,23 +216,6 @@ With this index in place, you can retrieve the target resources very efficiently .withNamespacesInheritedFromController().build()); ``` -The same can be done for the cache of a secondary resource: indexers are configured on the -`InformerEventSourceConfiguration.Builder`, and are registered before the event source starts. -`InformerEventSource.addIndexers(..)` is only meant for the dynamic case, where an informer is -registered at runtime and its indexers are only known at that point. Otherwise, use the builder: - -```java -InformerEventSource configMapEventSource = - new InformerEventSource<>( - InformerEventSourceConfiguration.from(ConfigMap.class, MyResource.class) - .withIndexer( - "by-resource-version", cm -> List.of(cm.getMetadata().getResourceVersion())) - .build()); - -// later, e.g. in the reconciler -configMapEventSource.byIndex("by-resource-version", resourceVersion); -``` - ## Read-cache-after-write consistency and event filtering From version 5.3.0 we provide stronger consistency guarantees and diff --git a/micrometer-support/pom.xml b/micrometer-support/pom.xml index 29dcf1f9f5..6dd95add1a 100644 --- a/micrometer-support/pom.xml +++ b/micrometer-support/pom.xml @@ -21,7 +21,7 @@ io.javaoperatorsdk java-operator-sdk - 999-SNAPSHOT + 5.7.1-SNAPSHOT micrometer-support diff --git a/migration/pom.xml b/migration/pom.xml index cf5143c925..f79a594754 100644 --- a/migration/pom.xml +++ b/migration/pom.xml @@ -21,7 +21,7 @@ io.javaoperatorsdk java-operator-sdk - 999-SNAPSHOT + 5.7.1-SNAPSHOT migration diff --git a/operator-framework-bom/pom.xml b/operator-framework-bom/pom.xml index 7ce5b2530b..6308721e7a 100644 --- a/operator-framework-bom/pom.xml +++ b/operator-framework-bom/pom.xml @@ -21,7 +21,7 @@ io.javaoperatorsdk operator-framework-bom - 999-SNAPSHOT + 5.7.1-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 755536add7..08d22b3d5e 100644 --- a/operator-framework-core/pom.xml +++ b/operator-framework-core/pom.xml @@ -21,7 +21,7 @@ io.javaoperatorsdk java-operator-sdk - 999-SNAPSHOT + 5.7.1-SNAPSHOT ../pom.xml @@ -154,7 +154,7 @@ org.codehaus.mojo templating-maven-plugin - 3.1.1 + 3.2.0 filtering-java-templates 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 c069ac437d..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 @@ -16,14 +16,9 @@ package io.javaoperatorsdk.operator.api.config.informer; import java.time.Duration; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; -import java.util.function.Function; import io.fabric8.kubernetes.api.model.GenericKubernetesResource; import io.fabric8.kubernetes.api.model.HasMetadata; @@ -91,16 +86,6 @@ default String name() { return getInformerConfig().getName(); } - /** - * The indexers to register on the informer event source, by index name. They are registered when - * the event source is created, so they are in place before it starts. - * - * @return the configured indexers, empty if there are none - */ - default Map>> getIndexers() { - return Map.of(); - } - class DefaultInformerEventSourceConfiguration implements InformerEventSourceConfiguration { private final PrimaryToSecondaryMapper primaryToSecondaryMapper; @@ -108,7 +93,6 @@ class DefaultInformerEventSourceConfiguration private final GroupVersionKind groupVersionKind; private final InformerConfiguration informerConfig; private final KubernetesClient kubernetesClient; - private final Map>> indexers; protected DefaultInformerEventSourceConfiguration( GroupVersionKind groupVersionKind, @@ -116,33 +100,11 @@ protected DefaultInformerEventSourceConfiguration( SecondaryToPrimaryMapper secondaryToPrimaryMapper, InformerConfiguration informerConfig, KubernetesClient kubernetesClient) { - this( - groupVersionKind, - primaryToSecondaryMapper, - secondaryToPrimaryMapper, - informerConfig, - kubernetesClient, - Map.of()); - } - - protected DefaultInformerEventSourceConfiguration( - GroupVersionKind groupVersionKind, - PrimaryToSecondaryMapper primaryToSecondaryMapper, - SecondaryToPrimaryMapper secondaryToPrimaryMapper, - InformerConfiguration informerConfig, - KubernetesClient kubernetesClient, - Map>> indexers) { this.informerConfig = Objects.requireNonNull(informerConfig); this.groupVersionKind = groupVersionKind; this.primaryToSecondaryMapper = primaryToSecondaryMapper; this.secondaryToPrimaryMapper = secondaryToPrimaryMapper; this.kubernetesClient = kubernetesClient; - this.indexers = indexers; - } - - @Override - public Map>> getIndexers() { - return indexers; } @Override @@ -183,7 +145,6 @@ class Builder { private PrimaryToSecondaryMapper primaryToSecondaryMapper; private SecondaryToPrimaryMapper secondaryToPrimaryMapper; private KubernetesClient kubernetesClient; - private final Map>> indexers = new LinkedHashMap<>(); private Builder(Class resourceClass, Class primaryResourceClass) { this(resourceClass, primaryResourceClass, null); @@ -311,29 +272,6 @@ public Builder withGenericFilter(GenericFilter genericFilter) { return this; } - /** - * Registers an indexer on the informer event source, so the resources it caches can be looked - * up by the keys the indexer computes (see {@link - * io.javaoperatorsdk.operator.processing.event.source.IndexerResourceCache#byIndex}). - * - * @param name the name of the index, unique per event source - * @param indexer computes the index keys of a resource - */ - public Builder withIndexer(String name, Function> indexer) { - indexers.put(Objects.requireNonNull(name), Objects.requireNonNull(indexer)); - return this; - } - - /** - * Registers several indexers at once. - * - * @see #withIndexer(String, Function) - */ - public Builder withIndexers(Map>> indexers) { - indexers.forEach(this::withIndexer); - return this; - } - public Builder withItemStore(ItemStore itemStore) { config.withItemStore(itemStore); return this; @@ -407,8 +345,7 @@ public InformerEventSourceConfiguration build() { HasMetadata.getKind(primaryResourceClass), false)), config.build(), - kubernetesClient, - Collections.unmodifiableMap(new LinkedHashMap<>(indexers))); + kubernetesClient); } } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerEventSource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerEventSource.java index a8418ce738..abde1f6992 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerEventSource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerEventSource.java @@ -16,11 +16,8 @@ package io.javaoperatorsdk.operator.processing.event.source.informer; import java.util.HashSet; -import java.util.List; -import java.util.Map; import java.util.Optional; import java.util.Set; -import java.util.function.Function; import java.util.stream.Collectors; import org.slf4j.Logger; @@ -81,18 +78,6 @@ public InformerEventSource(InformerEventSourceConfiguration configuration) { onUpdateFilter = informerConfig.getOnUpdateFilter(); onDeleteFilter = informerConfig.getOnDeleteFilter(); genericFilter = informerConfig.getGenericFilter(); - super.addIndexers(configuration.getIndexers()); - } - - /** - * Adds indexers to an already created event source, for example when the informer is registered - * dynamically and its indexers are only known at that point. Indexers known upfront should be - * configured with {@link InformerEventSourceConfiguration.Builder#withIndexer(String, Function)} - * instead. - */ - @Override - public void addIndexers(Map>> indexers) { - super.addIndexers(indexers); } @Override 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 index be3034af57..9e43b288cc 100644 --- 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 @@ -15,10 +15,6 @@ */ package io.javaoperatorsdk.operator.api.config; -import java.util.List; -import java.util.Map; -import java.util.function.Function; - import org.junit.jupiter.api.Test; import io.fabric8.kubernetes.api.model.ConfigMap; @@ -26,10 +22,7 @@ import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; -import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; class InformerEventSourceConfigurationTest { @@ -46,38 +39,4 @@ void updateFromKeepsComparableResourceVersions() { assertFalse(builder.build().getInformerConfig().isComparableResourceVersions()); } - - @Test - void indexersAreEmptyByDefault() { - var configuration = - InformerEventSourceConfiguration.from(ConfigMap.class, Secret.class).build(); - - assertTrue(configuration.getIndexers().isEmpty()); - } - - @Test - void builderCollectsIndexers() { - Function> byName = cm -> List.of(cm.getMetadata().getName()); - Function> byNamespace = cm -> List.of(cm.getMetadata().getNamespace()); - - var configuration = - InformerEventSourceConfiguration.from(ConfigMap.class, Secret.class) - .withIndexer("name", byName) - .withIndexers(Map.of("namespace", byNamespace)) - .build(); - - assertEquals(Map.of("name", byName, "namespace", byNamespace), configuration.getIndexers()); - } - - @Test - void configuredIndexersCannotBeModifiedAfterBuild() { - var configuration = - InformerEventSourceConfiguration.from(ConfigMap.class, Secret.class) - .withIndexer("name", cm -> List.of(cm.getMetadata().getName())) - .build(); - - assertThrows( - UnsupportedOperationException.class, - () -> configuration.getIndexers().put("other", cm -> List.of())); - } } 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 9dff538023..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 @@ -423,25 +423,6 @@ void byIndexSkipsOlderTempCacheResourceNoLongerInIndexedInformerResult() { assertThat(result).isEmpty(); } - @Test - void indexersFromConfigurationAreRegisteredOnCreation() { - when(informerEventSourceConfiguration.getIndexers()) - .thenReturn(Map.of("idx", d -> List.of(d.getMetadata().getLabels().get("app")))); - informerEventSource = buildInformerEventSource(); - 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); - - var result = informerEventSource.byIndexStream("idx", "key").toList(); - - assertThat(result).containsExactly(ghost); - } - @Test void byIndexIncludesGhostResourceNotYetSeenByInformer() { var ghost = testDeployment(); diff --git a/operator-framework-junit/pom.xml b/operator-framework-junit/pom.xml index aa18d5c778..53f42977e7 100644 --- a/operator-framework-junit/pom.xml +++ b/operator-framework-junit/pom.xml @@ -21,7 +21,7 @@ io.javaoperatorsdk java-operator-sdk - 999-SNAPSHOT + 5.7.1-SNAPSHOT operator-framework-junit diff --git a/operator-framework/pom.xml b/operator-framework/pom.xml index 6d314d4687..1ed92c899d 100644 --- a/operator-framework/pom.xml +++ b/operator-framework/pom.xml @@ -21,7 +21,7 @@ io.javaoperatorsdk java-operator-sdk - 999-SNAPSHOT + 5.7.1-SNAPSHOT operator-framework diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/readcacheafterwrite/readownupdates/ReadOwnUpdatesReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/readcacheafterwrite/readownupdates/ReadOwnUpdatesReconciler.java index cc85793508..c62d637a88 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/readcacheafterwrite/readownupdates/ReadOwnUpdatesReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/readcacheafterwrite/readownupdates/ReadOwnUpdatesReconciler.java @@ -123,9 +123,9 @@ public List> prepareEventSources( new InformerEventSource<>( InformerEventSourceConfiguration.from( ConfigMap.class, ReadOwnUpdatesCustomResource.class) - .withIndexer( - RESOURCE_VERSION_INDEX, cm -> List.of(cm.getMetadata().getResourceVersion())) .build()); + configMapEventSource.addIndexers( + Map.of(RESOURCE_VERSION_INDEX, cm -> List.of(cm.getMetadata().getResourceVersion()))); return List.of(configMapEventSource); } diff --git a/pom.xml b/pom.xml index 63efbd29e7..7a3c707b2c 100644 --- a/pom.xml +++ b/pom.xml @@ -21,7 +21,7 @@ io.javaoperatorsdk java-operator-sdk - 999-SNAPSHOT + 5.7.1-SNAPSHOT pom Operator SDK for Java Java SDK for implementing Kubernetes operators @@ -75,13 +75,13 @@ 2.0.20 2.26.1 5.24.0 - 3.21.0 + 3.22.0 0.24.0 1.13.0 3.27.7 4.3.0 2.7.3 - 1.17.2 + 1.18.0 3.3.1 0.9.14 2.22.0 diff --git a/sample-operators/controller-namespace-deletion/pom.xml b/sample-operators/controller-namespace-deletion/pom.xml index af4be01972..cf966c9531 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 - 999-SNAPSHOT + 5.7.1-SNAPSHOT sample-controller-namespace-deletion diff --git a/sample-operators/kotlin-operator/pom.xml b/sample-operators/kotlin-operator/pom.xml index 02e345f22c..91a867459e 100644 --- a/sample-operators/kotlin-operator/pom.xml +++ b/sample-operators/kotlin-operator/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk sample-operators - 999-SNAPSHOT + 5.7.1-SNAPSHOT sample-kotlin-operator diff --git a/sample-operators/leader-election/pom.xml b/sample-operators/leader-election/pom.xml index 4f896485d1..bbf22cf753 100644 --- a/sample-operators/leader-election/pom.xml +++ b/sample-operators/leader-election/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk sample-operators - 999-SNAPSHOT + 5.7.1-SNAPSHOT sample-leader-election diff --git a/sample-operators/mysql-schema/pom.xml b/sample-operators/mysql-schema/pom.xml index d2872c921a..641504278e 100644 --- a/sample-operators/mysql-schema/pom.xml +++ b/sample-operators/mysql-schema/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk sample-operators - 999-SNAPSHOT + 5.7.1-SNAPSHOT sample-mysql-schema-operator diff --git a/sample-operators/operations/pom.xml b/sample-operators/operations/pom.xml index d9eddd1fee..89a459f578 100644 --- a/sample-operators/operations/pom.xml +++ b/sample-operators/operations/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk sample-operators - 999-SNAPSHOT + 5.7.1-SNAPSHOT sample-operations @@ -85,7 +85,7 @@ org.eclipse.jetty jetty-server - 12.1.14 + 12.1.15 io.javaoperatorsdk diff --git a/sample-operators/pom.xml b/sample-operators/pom.xml index 704007c076..c51e6ec794 100644 --- a/sample-operators/pom.xml +++ b/sample-operators/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk java-operator-sdk - 999-SNAPSHOT + 5.7.1-SNAPSHOT sample-operators diff --git a/sample-operators/tomcat-operator/pom.xml b/sample-operators/tomcat-operator/pom.xml index 0a05fffc1c..0a7078d463 100644 --- a/sample-operators/tomcat-operator/pom.xml +++ b/sample-operators/tomcat-operator/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk sample-operators - 999-SNAPSHOT + 5.7.1-SNAPSHOT sample-tomcat-operator diff --git a/sample-operators/webpage/pom.xml b/sample-operators/webpage/pom.xml index d50e5ef03c..eb3aa11816 100644 --- a/sample-operators/webpage/pom.xml +++ b/sample-operators/webpage/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk sample-operators - 999-SNAPSHOT + 5.7.1-SNAPSHOT sample-webpage-operator diff --git a/test-index-processor/pom.xml b/test-index-processor/pom.xml index 2ae7c5f454..5ec2e21bcd 100644 --- a/test-index-processor/pom.xml +++ b/test-index-processor/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk java-operator-sdk - 999-SNAPSHOT + 5.7.1-SNAPSHOT test-index-processor From 928445cc775b3a750bffa020123831989162ec5e Mon Sep 17 00:00:00 2001 From: hej090224 Date: Fri, 4 Dec 2026 14:24:22 +0900 Subject: [PATCH 6/6] fix: address review feedback on informer resource version health check Add an InformerResourceVersionHealthCheck.staleInformers(RuntimeInfo) overload and move the operations sample's informer-collection logic into it, so HealthHandler no longer duplicates that traversal. Make the operations sample's HealthHandler use the check's result in the response body instead of only logging it, without changing which status code is returned (a quiet cluster can still make the check report a false positive, per the health-probes documentation). Fix the staleInformers Javadoc, which described the returned keys as "healthy" when they are the ones this check considers unhealthy. Address test review nits: import LogEvent instead of using its fully qualified name, and replace the deprecated AbstractAppender(String, Filter, Layout) constructor. Add a short comment explaining that the package-private timeout/ticker constructor exists only as a test seam. Signed-off-by: hej090224 --- .../documentation/operations/health-probes.md | 18 ++------ .../InformerResourceVersionHealthCheck.java | 42 ++++++++++++++++- ...nformerResourceVersionHealthCheckTest.java | 36 ++++++++++++++- .../sample/operations/HealthHandler.java | 46 ++++--------------- 4 files changed, 88 insertions(+), 54 deletions(-) diff --git a/docs/content/en/docs/documentation/operations/health-probes.md b/docs/content/en/docs/documentation/operations/health-probes.md index 5c51ec863f..64205f3f01 100644 --- a/docs/content/en/docs/documentation/operations/health-probes.md +++ b/docs/content/en/docs/documentation/operations/health-probes.md @@ -47,17 +47,9 @@ advanced within a timeout you choose: // Keep this instance across probe requests. var versionCheck = new InformerResourceVersionHealthCheck(Duration.ofMinutes(15)); -// On each request, collect every current informer under a unique key. -Map informers = new HashMap<>(); -operator.getRuntimeInfo().getRegisteredControllers().forEach(controller -> - controller.getControllerHealthInfo().informerEventSourceHealthIndicators() - .forEach((eventSourceName, eventSource) -> { - InformerWrappingEventSourceHealthIndicator wrapping = eventSource; - wrapping.informerHealthIndicators().forEach((namespace, informer) -> - informers.put(controller.getConfiguration().getName() + "/" + - eventSourceName + "/" + namespace, informer)); - })); -Set stale = versionCheck.staleInformers(informers); +// On each request, collect every current informer and check it. The RuntimeInfo overload +// collects the informers for you; use the Map overload if you need to filter or relabel them. +Set stale = versionCheck.staleInformers(operator.getRuntimeInfo()); ``` Create the check once and call it on every probe request. Removed informers and those without a resource @@ -71,8 +63,8 @@ Each time an informer's key enters or leaves the stale set, `InformerResourceVer transition (a `WARN` when it becomes stale, an `INFO` when it recovers) instead of logging on every request, so the logs show when the condition started and ended without being noisy. See the [`operations` sample operator](https://github.com/java-operator-sdk/java-operator-sdk/tree/main/sample-operators/operations)'s -`HealthHandler` for a working example that runs the check on every probe request purely for logging, -without failing the probe. +`HealthHandler` for a working example that runs the check on every probe request and reports the stale +keys in the response body, without failing the probe. ## Setting Up a Probe Endpoint diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/InformerResourceVersionHealthCheck.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/InformerResourceVersionHealthCheck.java index a48898d6d5..934ce2f77c 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/InformerResourceVersionHealthCheck.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/InformerResourceVersionHealthCheck.java @@ -26,6 +26,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import io.javaoperatorsdk.operator.RuntimeInfo; + /** * Tracks how long each informer's last synchronized resource version has remained unchanged. An * unchanged version can be normal in a quiet cluster, so callers should choose a suitable timeout @@ -49,6 +51,7 @@ public InformerResourceVersionHealthCheck(Duration timeout) { this(timeout, System::nanoTime); } + // package-private seam so tests can supply a controllable ticker instead of System::nanoTime InformerResourceVersionHealthCheck(Duration timeout, LongSupplier ticker) { this.timeout = Objects.requireNonNull(timeout); if (timeout.isZero() || timeout.isNegative()) { @@ -58,7 +61,8 @@ public InformerResourceVersionHealthCheck(Duration timeout) { } /** - * Returns the keys of healthy informers whose resource version has not advanced by the timeout. + * Returns the keys of informers that are considered unhealthy because, despite reporting a + * healthy status, their resource version has not advanced within the timeout. */ public synchronized Set staleInformers( Map informers) { @@ -88,6 +92,42 @@ public synchronized Set staleInformers( return previouslyStale; } + /** + * Convenience overload that collects the current informer health indicators from {@code + * runtimeInfo} and delegates to {@link #staleInformers(Map)}. + */ + public synchronized Set staleInformers(RuntimeInfo runtimeInfo) { + return staleInformers(collectInformerHealthIndicators(runtimeInfo)); + } + + private static Map collectInformerHealthIndicators( + RuntimeInfo runtimeInfo) { + Map informers = new HashMap<>(); + runtimeInfo + .getRegisteredControllers() + .forEach( + controller -> + controller + .getControllerHealthInfo() + .informerEventSourceHealthIndicators() + .forEach( + (eventSourceName, eventSource) -> { + InformerWrappingEventSourceHealthIndicator wrapping = eventSource; + wrapping + .informerHealthIndicators() + .forEach( + (namespace, informer) -> + informers.put( + controller.getConfiguration().getName() + + "/" + + eventSourceName + + "/" + + namespace, + informer)); + })); + return informers; + } + private void logTransitions(Set stale) { for (var key : stale) { if (!previouslyStale.contains(key)) { diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/health/InformerResourceVersionHealthCheckTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/health/InformerResourceVersionHealthCheckTest.java index 4cd0575f0b..47cfe62e4d 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/health/InformerResourceVersionHealthCheckTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/health/InformerResourceVersionHealthCheckTest.java @@ -19,17 +19,24 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.atomic.AtomicLong; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.Appender; +import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.Logger; import org.apache.logging.log4j.core.appender.AbstractAppender; +import org.apache.logging.log4j.core.config.Property; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import io.javaoperatorsdk.operator.RegisteredController; +import io.javaoperatorsdk.operator.RuntimeInfo; +import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; + import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; @@ -49,9 +56,9 @@ class InformerResourceVersionHealthCheckTest { void setupLogCapture() { logger = (Logger) LogManager.getLogger(InformerResourceVersionHealthCheck.class); logAppender = - new AbstractAppender("test-appender", null, null) { + new AbstractAppender("test-appender", null, null, true, Property.EMPTY_ARRAY) { @Override - public void append(org.apache.logging.log4j.core.LogEvent event) { + public void append(LogEvent event) { logMessages.add(event.getLevel() + ": " + event.getMessage().getFormattedMessage()); } }; @@ -157,6 +164,31 @@ void forgetsRemovedAndReplacedInformers() { assertThat(check.staleInformers(Map.of("informer", indicator("1")))).isEmpty(); } + @Test + void collectsInformersFromRuntimeInfo() { + var informer = indicator("1"); + var wrapping = mock(InformerWrappingEventSourceHealthIndicator.class); + when(wrapping.informerHealthIndicators()).thenReturn(Map.of("ns", informer)); + + var controllerHealthInfo = mock(ControllerHealthInfo.class); + when(controllerHealthInfo.informerEventSourceHealthIndicators()) + .thenReturn(Map.of("eventSource", wrapping)); + + var configuration = mock(ControllerConfiguration.class); + when(configuration.getName()).thenReturn("controller"); + + var controller = mock(RegisteredController.class); + when(controller.getConfiguration()).thenReturn(configuration); + when(controller.getControllerHealthInfo()).thenReturn(controllerHealthInfo); + + var runtimeInfo = mock(RuntimeInfo.class); + when(runtimeInfo.getRegisteredControllers()).thenReturn(Set.of(controller)); + + assertThat(check.staleInformers(runtimeInfo)).isEmpty(); + time.set(Duration.ofMinutes(11).toNanos()); + assertThat(check.staleInformers(runtimeInfo)).containsExactly("controller/eventSource/ns"); + } + @Test void requiresAPositiveTimeout() { assertThatThrownBy(() -> new InformerResourceVersionHealthCheck(Duration.ZERO)) diff --git a/sample-operators/operations/src/main/java/io/javaoperatorsdk/operator/sample/operations/HealthHandler.java b/sample-operators/operations/src/main/java/io/javaoperatorsdk/operator/sample/operations/HealthHandler.java index f49043d64e..ec2ce67b71 100644 --- a/sample-operators/operations/src/main/java/io/javaoperatorsdk/operator/sample/operations/HealthHandler.java +++ b/sample-operators/operations/src/main/java/io/javaoperatorsdk/operator/sample/operations/HealthHandler.java @@ -18,8 +18,7 @@ import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.time.Duration; -import java.util.HashMap; -import java.util.Map; +import java.util.Set; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Request; @@ -27,9 +26,7 @@ import org.eclipse.jetty.util.Callback; import io.javaoperatorsdk.operator.Operator; -import io.javaoperatorsdk.operator.health.InformerHealthIndicator; import io.javaoperatorsdk.operator.health.InformerResourceVersionHealthCheck; -import io.javaoperatorsdk.operator.health.InformerWrappingEventSourceHealthIndicator; /** * Combined health endpoint that checks whether all event sources (informers, polling sources, etc.) @@ -37,8 +34,9 @@ * this endpoint naturally covers the startup case as well. * *

It also runs {@link InformerResourceVersionHealthCheck} on every request to detect informers - * whose resource version has stopped advancing; see the health-probes documentation for why this is - * only logged here rather than failing the probe. + * whose resource version has stopped advancing; the result is reported in the response body so it + * is visible to callers, but it does not fail the probe (see the health-probes documentation for + * why a quiet cluster can make this check report a false positive). */ public class HealthHandler extends Handler.Abstract { @@ -54,45 +52,17 @@ public HealthHandler(Operator operator) { public boolean handle(Request request, Response response, Callback callback) { var runtimeInfo = operator.getRuntimeInfo(); var started = runtimeInfo.isStarted(); - if (started) { - resourceVersionHealthCheck.staleInformers(collectInformerHealthIndicators()); - } + Set staleInformers = + started ? resourceVersionHealthCheck.staleInformers(runtimeInfo) : Set.of(); if (started && runtimeInfo.allEventSourcesAreHealthy()) { - sendMessage(response, 200, "healthy", callback); + var message = staleInformers.isEmpty() ? "healthy" : "healthy, stale: " + staleInformers; + sendMessage(response, 200, message, callback); } else { sendMessage(response, 503, "not healthy", callback); } return true; } - private Map collectInformerHealthIndicators() { - Map informers = new HashMap<>(); - operator - .getRuntimeInfo() - .getRegisteredControllers() - .forEach( - controller -> - controller - .getControllerHealthInfo() - .informerEventSourceHealthIndicators() - .forEach( - (eventSourceName, eventSource) -> { - InformerWrappingEventSourceHealthIndicator wrapping = eventSource; - wrapping - .informerHealthIndicators() - .forEach( - (namespace, informer) -> - informers.put( - controller.getConfiguration().getName() - + "/" - + eventSourceName - + "/" - + namespace, - informer)); - })); - return informers; - } - static void sendMessage(Response response, int code, String message, Callback callback) { response.setStatus(code); response.getHeaders().put("Content-Type", "text/plain; charset=utf-8");