Skip to content
Open
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
46 changes: 46 additions & 0 deletions cmapi/src/cmapi/capacity/retention.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
"""How long a cluster's platform Prometheus keeps its samples, read through the cluster's Thanos Querier (#763).

docs/02, "Onboarding becomes shorter", step 2: "preflight: the Thanos Route answers, retention is at least 15 days". docs/02,
"Retention limit": "Platform Prometheus keeps 15 days by default, and the in-cluster Thanos Querier has no long-term store
behind it, so any window over 14 days silently returns less data." The 14-day window of usage.py (WINDOW_DAYS) is the reason.

The value is Prometheus's own gauge, read with the same query, the same Route and the same reader grants as the usage reads
(thanos.py): prometheus/tsdb/db.go, `prometheus_tsdb_retention_limit_seconds`, "How long to retain samples in storage", set
from the time retention (openshift/prometheus release-4.18, Prometheus 2.55.1, tsdb/db.go). 0 is no time limit:
`BeyondTimeRetention` returns at once when "Time retention is disabled" (`db.opts.RetentionDuration == 0`), which is how
Prometheus runs when only a size limit is set (cmd/prometheus/main.go applies the 15d default only when "neither this flag nor
storage.tsdb.retention.size is set").

Only the platform Prometheus counts: the series of job prometheus-k8s in openshift-monitoring (cluster-monitoring-operator
release-4.18, assets/prometheus-k8s/service-monitor.yaml and service.yaml; prometheus-operator sets `job` from the Service's
name). The Querier also answers the same gauge for the user-workload Prometheus and the Thanos Ruler, whose 24-hour default
says nothing of the platform metrics usage reads (measured on CRC 4.22.14, 2026-12-01: prometheus-k8s 1296000, the
user-workload Prometheus and Thanos Ruler 86400). The sources and the decisions: docs/reviews/2026-12-01-issue-763/README.md.
"""
from __future__ import annotations

import math

from cmapi.capacity.usage import MetricsUnavailable, sample
from cmapi.core.ports import MetricsSource

# docs/02, "Onboarding becomes shorter", step 2. No configuration names another value, so it is a constant (#763).
MIN_RETENTION_DAYS = 15
RETENTION_QUERY = 'prometheus_tsdb_retention_limit_seconds{namespace="openshift-monitoring", job="prometheus-k8s"}'


def platform_retention_seconds(metrics: MetricsSource, cluster_id: str) -> float:
"""The shortest time retention of the cluster's platform Prometheus replicas, in seconds, or math.inf when none has a time
limit. MetricsUnavailable when it cannot be read: the query fails, no replica reports the gauge, or a value is not a
number of seconds. Never a default: a retention that is not read is not assumed."""
series = metrics.query(cluster_id, RETENTION_QUERY)
if not series:
raise MetricsUnavailable(f"{cluster_id}: the Thanos Querier has no prometheus_tsdb_retention_limit_seconds of "
"job prometheus-k8s in openshift-monitoring")
seconds: list[float] = []
for s in series:
v = sample(s)
if v is None or v < 0:
raise MetricsUnavailable(f"{cluster_id}: a prometheus_tsdb_retention_limit_seconds that is not a number of seconds")
seconds.append(math.inf if v == 0 else v)
return min(seconds)
101 changes: 95 additions & 6 deletions cmapi/src/cmapi/ops/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"""
from __future__ import annotations

import math
from typing import Any, Callable

from sqlalchemy import select
Expand Down Expand Up @@ -288,16 +289,104 @@ def wait_import(sc: StepContext) -> StepResult:

@step("cluster-onboard", "preflight")
def preflight(sc: StepContext) -> StepResult:
"""docs/02, step 2. Built: the import's own checks, connected with no finding, which include the reader's grants for the
cluster's Thanos Querier when the instance reads usage (#724). Not built (#763): the retention of at least 15 days and the
root Application's sync; the outputs list them as not checked, so nobody reads them as passed."""
"""docs/02, step 2: "the Thanos Route answers, retention is at least 15 days, and the root Application exists and is
Synced", after the import's own checks (connected, no finding, which include the reader's Thanos grants when the instance
reads usage, #724). Each check passes, is a finding, or does not apply to this instance and cluster, with its reason under
notApplicable. A check that cannot be read is a finding, never a pass (#763; docs/reviews/2026-12-01-issue-763)."""
cid = sc.parameters["cluster-id"]
st = sc.ctx.registry.get(cid)
not_checked = ["Thanos retention of at least 15 days (#763)", "the root Application exists and is Synced (#763)"]
if st.status != "connected" or st.findings:
return StepResult.failed(f"{cid} is {st.status}: {'; '.join(st.findings) or 'no finding'}",
findings=list(st.findings), notChecked=not_checked)
return StepResult.done(checks=["import connected", "no import finding"], notChecked=not_checked)
findings=list(st.findings))
checks, findings = ["import connected", "no import finding"], []
not_applicable: dict[str, str] = {}
outputs: dict[str, Any] = {}
for name, check in (("thanosRetention", _retention), ("rootApplication", _root_application)):
outcome, text, facts = check(sc.ctx, cid, st)
outputs.update(facts)
if outcome == "check":
checks.append(text)
elif outcome == "finding":
findings.append(text)
else:
not_applicable[name] = text
outputs.update(checks=checks, notApplicable=not_applicable)
if findings:
return StepResult.failed("; ".join(findings), findings=findings, **outputs)
return StepResult.done(**outputs)


# One preflight check's result: ("check", what passed), ("finding", what is wrong) or ("notApplicable", why), and its facts.
Checked = tuple[str, str, dict[str, Any]]


def _retention(ctx: Any, cid: str, st: Any) -> Checked:
"""The Thanos Route answers and the platform Prometheus keeps at least MIN_RETENTION_DAYS (capacity/retention.py), read
as the usage reads are. An instance that reads no usage (capacity.yaml usage.source none) never reaches Thanos, and its
readers need no grant for it (#724), so there is nothing to check."""
from cmapi.capacity.retention import MIN_RETENTION_DAYS, platform_retention_seconds
from cmapi.capacity.usage import MetricsUnavailable

if not ctx.usage.configured:
return "notApplicable", "capacity.yaml usage.source is none: cmapi reads no Thanos Querier", {}
# `metrics` is not part of UsageSource: a configured source without it is a finding, never a check that does not apply.
metrics = getattr(ctx.usage, "metrics", None)
if metrics is None:
return "finding", "the Thanos retention cannot be read: the usage source has no metrics reader", {}
try:
seconds = platform_retention_seconds(metrics, cid)
except MetricsUnavailable as exc:
return "finding", f"the Thanos retention cannot be read: {exc}"[:300], {}
if seconds == math.inf:
return "check", "Thanos answers; platform Prometheus has no time retention limit", {"retentionDays": None}
days = seconds / 86400
# In seconds when not whole days, so a rounded figure never reads as the bound it misses (15 days less a second).
kept = f"{days:g} days" if seconds % 86400 == 0 else f"{seconds:.15g} seconds"
facts = {"retentionDays": days}
if seconds < MIN_RETENTION_DAYS * 86400:
return ("finding", f"platform Prometheus keeps {kept}, less than {MIN_RETENTION_DAYS} days: set prometheusK8s.retention "
f"to {MIN_RETENTION_DAYS}d or more in openshift-monitoring/cluster-monitoring-config", facts)
return "check", f"Thanos answers; platform Prometheus keeps {kept}", facts


def _root_application(ctx: Any, cid: str, st: Any) -> Checked:
"""The Argo CD root Application of integrations.yaml delivery.argocd exists and its status.sync.status is Synced. It is
the Application cmapi reads for this cluster: the gate in argocd mode, the signal in gitops mode with delivery.signal
argocd. In apply mode, or gitops with another signal, no Argo CD Application of cmapi's delivers the cluster."""
from cmapi.core.clients.kube import BadResponse, ClusterUnreachable, KubeError
from cmapi.core.sync import ArgoCdSignal, application_name
from cmapi.jobs.delivery import mode_of

mode, d = mode_of(ctx, cid), ctx.delivery
if mode == "apply":
return "notApplicable", f"delivery mode apply: the worker applies {cid}'s folders, and no Argo CD Application does", {}
if mode == "gitops" and d.signal != "argocd":
return "notApplicable", f"delivery mode gitops with delivery.signal {d.signal}: cmapi reads no Argo CD Application", {}
template = d.argocd_root_application
if application_name(template, cid, "a") != application_name(template, cid, "b"):
return ("notApplicable", f"delivery.argocd.rootApplication {template!r} names one Application per namespace, so the "
"cluster has no root Application", {})
ns, name = d.argocd_namespace, application_name(template, cid, "")
label, facts = f"root Application {ns}/{name}", {"rootApplication": {"namespace": ns, "name": name}}
client = st.client # once: the registry clears it when the cluster drops (#402)
if client is None:
return "finding", f"{label} cannot be read: {cid} is {st.status}", facts
try:
app = ArgoCdSignal(client, ns, name).status(cid)
except KubeError as exc:
if exc.status == 404:
return "finding", f"{label} does not exist", facts
if exc.status == 403:
return ("finding", f"{label} cannot be read: the reader may not get it (the baseline grants get on argoproj.io "
"applications)", facts)
return "finding", f"{label} cannot be read: {exc}"[:300], facts
except (ClusterUnreachable, BadResponse, AttributeError, KeyError, TypeError) as exc:
# AttributeError, KeyError, TypeError: a status of another shape, which is no Synced Application either.
return "finding", f"{label} cannot be read: {type(exc).__name__}: {exc}"[:300], facts
facts["rootApplication"].update(sync=app.sync, health=app.health)
if app.sync != "Synced":
return "finding", f"{label} is {app.sync} (health {app.health}), not Synced", facts
return "check", f"{label} is Synced (health {app.health})", facts


@step("cluster-onboard", "propose-registry")
Expand Down
3 changes: 2 additions & 1 deletion cmapi/src/cmapi/ops/templates/cluster-onboard.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# docs/02, "Onboarding becomes shorter", and its template (config/operations/cluster-onboard.yaml). The steps that the build
# has: wait-import (the baseline's import Secret appears and connects) and preflight (the import's checks). propose-registry
# has: wait-import (the baseline's import Secret appears and connects) and preflight (the import's checks, the Thanos retention
# and the root Application, #763). propose-registry
# needs POST /api/v1/admin/clusters:propose and smoke-test a namespace made and removed, which are not built: each refuses with
# its issue, after the steps before it ran. A cluster that clusters.yaml already names skips propose-registry and wait-request.
# docs/02's onExit: cleanup is left out: the bootstrap left cluster-onboard for the baseline, so no step makes anything to
Expand Down
Loading