From 4a053acb05406bb3ee7bf7648cd9f3590608bdf2 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/3] 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 1307be8d55..5a4a9d4f39 100644 --- a/bootstrapper-maven-plugin/pom.xml +++ b/bootstrapper-maven-plugin/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk java-operator-sdk - 5.7.1-SNAPSHOT + 999-SNAPSHOT bootstrapper diff --git a/caffeine-bounded-cache-support/pom.xml b/caffeine-bounded-cache-support/pom.xml index a9412ef6ec..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.1-SNAPSHOT + 999-SNAPSHOT caffeine-bounded-cache-support diff --git a/micrometer-support/pom.xml b/micrometer-support/pom.xml index 6dd95add1a..29dcf1f9f5 100644 --- a/micrometer-support/pom.xml +++ b/micrometer-support/pom.xml @@ -21,7 +21,7 @@ io.javaoperatorsdk java-operator-sdk - 5.7.1-SNAPSHOT + 999-SNAPSHOT micrometer-support diff --git a/migration/pom.xml b/migration/pom.xml index f79a594754..cf5143c925 100644 --- a/migration/pom.xml +++ b/migration/pom.xml @@ -21,7 +21,7 @@ io.javaoperatorsdk java-operator-sdk - 5.7.1-SNAPSHOT + 999-SNAPSHOT migration diff --git a/operator-framework-bom/pom.xml b/operator-framework-bom/pom.xml index 6308721e7a..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.1-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 08d22b3d5e..04b0850795 100644 --- a/operator-framework-core/pom.xml +++ b/operator-framework-core/pom.xml @@ -21,7 +21,7 @@ io.javaoperatorsdk java-operator-sdk - 5.7.1-SNAPSHOT + 999-SNAPSHOT ../pom.xml diff --git a/operator-framework-junit/pom.xml b/operator-framework-junit/pom.xml index 53f42977e7..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.1-SNAPSHOT + 999-SNAPSHOT operator-framework-junit diff --git a/operator-framework/pom.xml b/operator-framework/pom.xml index 1ed92c899d..6d314d4687 100644 --- a/operator-framework/pom.xml +++ b/operator-framework/pom.xml @@ -21,7 +21,7 @@ io.javaoperatorsdk java-operator-sdk - 5.7.1-SNAPSHOT + 999-SNAPSHOT operator-framework diff --git a/pom.xml b/pom.xml index 9c3ca5f30d..293892ef59 100644 --- a/pom.xml +++ b/pom.xml @@ -21,7 +21,7 @@ io.javaoperatorsdk java-operator-sdk - 5.7.1-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 cf966c9531..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.1-SNAPSHOT + 999-SNAPSHOT sample-controller-namespace-deletion diff --git a/sample-operators/kotlin-operator/pom.xml b/sample-operators/kotlin-operator/pom.xml index 91a867459e..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.1-SNAPSHOT + 999-SNAPSHOT sample-kotlin-operator diff --git a/sample-operators/leader-election/pom.xml b/sample-operators/leader-election/pom.xml index bbf22cf753..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.1-SNAPSHOT + 999-SNAPSHOT sample-leader-election diff --git a/sample-operators/mysql-schema/pom.xml b/sample-operators/mysql-schema/pom.xml index 641504278e..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.1-SNAPSHOT + 999-SNAPSHOT sample-mysql-schema-operator diff --git a/sample-operators/operations/pom.xml b/sample-operators/operations/pom.xml index 89a459f578..788bb62575 100644 --- a/sample-operators/operations/pom.xml +++ b/sample-operators/operations/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk sample-operators - 5.7.1-SNAPSHOT + 999-SNAPSHOT sample-operations diff --git a/sample-operators/pom.xml b/sample-operators/pom.xml index c51e6ec794..704007c076 100644 --- a/sample-operators/pom.xml +++ b/sample-operators/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk java-operator-sdk - 5.7.1-SNAPSHOT + 999-SNAPSHOT sample-operators diff --git a/sample-operators/tomcat-operator/pom.xml b/sample-operators/tomcat-operator/pom.xml index d9632210e0..3d43df47da 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.1-SNAPSHOT + 999-SNAPSHOT sample-tomcat-operator diff --git a/sample-operators/webpage/pom.xml b/sample-operators/webpage/pom.xml index eb3aa11816..d50e5ef03c 100644 --- a/sample-operators/webpage/pom.xml +++ b/sample-operators/webpage/pom.xml @@ -22,7 +22,7 @@ io.javaoperatorsdk sample-operators - 5.7.1-SNAPSHOT + 999-SNAPSHOT sample-webpage-operator diff --git a/test-index-processor/pom.xml b/test-index-processor/pom.xml index 5ec2e21bcd..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.1-SNAPSHOT + 999-SNAPSHOT test-index-processor From 787856eaf16a208bef6d5c5cbd85a5a4d5cb0702 Mon Sep 17 00:00:00 2001 From: Exar Viquez Date: Tue, 1 Dec 2026 02:51:54 -0600 Subject: [PATCH 2/3] 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 16592d93c8e3c168bffc90b661069e0d7ef68bf4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=ED=95=9C=EC=9D=98=EC=A4=80?= Date: Fri, 4 Dec 2026 18:19:41 +0900 Subject: [PATCH 3/3] feat: add informer resource version health check utility (#3733) An informer can stay healthy while its watch has stopped delivering events. Add InformerResourceVersionHealthCheck, which reports healthy informers whose last sync resource version has not advanced within a configurable timeout. It logs when an informer becomes stale and when it recovers. A staleInformers(RuntimeInfo) overload collects the informers of all registered controllers. The operations sample and the health probes docs show how to use it. Signed-off-by: hej090224 Signed-off-by: Exar-lab Co-authored-by: Exar Viquez --- .../documentation/operations/health-probes.md | 34 +-- .../InformerResourceVersionHealthCheck.java | 153 +++++++++++++ ...nformerResourceVersionHealthCheckTest.java | 204 ++++++++++++++++++ .../sample/operations/HealthHandler.java | 18 +- 4 files changed, 395 insertions(+), 14 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..64205f3f01 100644 --- a/docs/content/en/docs/documentation/operations/health-probes.md +++ b/docs/content/en/docs/documentation/operations/health-probes.md @@ -39,22 +39,32 @@ 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 -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 - }))); +// Keep this instance across probe requests. +var versionCheck = new InformerResourceVersionHealthCheck(Duration.ofMinutes(15)); + +// 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()); ``` -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. + +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 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 new file mode 100644 index 0000000000..934ce2f77c --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/InformerResourceVersionHealthCheck.java @@ -0,0 +1,153 @@ +/* + * 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; + +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 + * 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 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); + } + + // 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()) { + throw new IllegalArgumentException("timeout must be positive"); + } + this.ticker = Objects.requireNonNull(ticker); + } + + /** + * 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) { + 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); + } + }); + logTransitions(stale); + previouslyStale = Set.copyOf(stale); + 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)) { + 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( + 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..47cfe62e4d --- /dev/null +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/health/InformerResourceVersionHealthCheckTest.java @@ -0,0 +1,204 @@ +/* + * 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.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; +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); + + 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, true, Property.EMPTY_ARRAY) { + @Override + public void append(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"); + 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 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)) + .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; + } +} 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..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 @@ -17,6 +17,8 @@ import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Set; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Request; @@ -24,15 +26,23 @@ import org.eclipse.jetty.util.Callback; import io.javaoperatorsdk.operator.Operator; +import io.javaoperatorsdk.operator.health.InformerResourceVersionHealthCheck; /** * 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; 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 { private final Operator operator; + private final InformerResourceVersionHealthCheck resourceVersionHealthCheck = + new InformerResourceVersionHealthCheck(Duration.ofMinutes(15)); public HealthHandler(Operator operator) { this.operator = operator; @@ -41,8 +51,12 @@ public HealthHandler(Operator operator) { @Override public boolean handle(Request request, Response response, Callback callback) { var runtimeInfo = operator.getRuntimeInfo(); - if (runtimeInfo.isStarted() && runtimeInfo.allEventSourcesAreHealthy()) { - sendMessage(response, 200, "healthy", callback); + var started = runtimeInfo.isStarted(); + Set staleInformers = + started ? resourceVersionHealthCheck.staleInformers(runtimeInfo) : Set.of(); + if (started && runtimeInfo.allEventSourcesAreHealthy()) { + var message = staleInformers.isEmpty() ? "healthy" : "healthy, stale: " + staleInformers; + sendMessage(response, 200, message, callback); } else { sendMessage(response, 503, "not healthy", callback); }