Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 22 additions & 12 deletions docs/content/en/docs/documentation/operations/health-probes.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> 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

Expand Down
Original file line number Diff line number Diff line change
@@ -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.
*
* <p>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<String, Observation> observations = new HashMap<>();
private Set<String> 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) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I guess this is purely for test seam.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Correct, it's a package-private seam purely for the test — InformerResourceVersionHealthCheckTest is in the same package and injects a controllable LongSupplier so tests don't need real sleeps to exercise the timeout. It isn't used anywhere else (verified via a repo-wide search). Added a one-line comment above it to make that explicit rather than changing the API shape, since it's already package-private and not part of the public surface.

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<String> staleInformers(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added. InformerResourceVersionHealthCheck now logs a WARN the moment an informer's key enters the stale set, and an INFO when it recovers (resource version advances again while healthy), instead of logging on every probe request — so the logs show when the condition started and ended without being noisy. Covered by two new unit tests (logsWhenAnInformerBecomesStaleAndRecovers, doesNotLogRecoveryWhenAStaleInformerBecomesUnhealthy) that capture the Log4j2 output.

I also wired the check into the operations sample's HealthHandler (purely for logging on every probe request, consistent with the doc's caution against failing a liveness probe on a quiet-cluster false positive), and documented both in health-probes.md.

Map<String, ? extends InformerHealthIndicator> informers) {
Objects.requireNonNull(informers);
observations.keySet().retainAll(informers.keySet());
var now = ticker.getAsLong();
Set<String> 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<String> staleInformers(RuntimeInfo runtimeInfo) {
return staleInformers(collectInformerHealthIndicators(runtimeInfo));
}

private static Map<String, InformerHealthIndicator> collectInformerHealthIndicators(
RuntimeInfo runtimeInfo) {
Map<String, InformerHealthIndicator> 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<String> 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)) {
Comment thread
csviri marked this conversation as resolved.
Resolved
log.info(
"Informer resource version health check: '{}' resource version advanced again,"
+ " no longer stale",
key);
}
}
}

private record Observation(
InformerHealthIndicator informer, String resourceVersion, long since) {}
}
Loading