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); }