Keep operator telemetry live-only with bounded volatile state

This commit is contained in:
DCCONSTRUCTIONS
2026-10-08 10:54:35 +03:00
parent 15a60e7e31
commit 8bf6571ce2
14 changed files with 450 additions and 570 deletions
+2 -2
View File
@@ -1,8 +1,8 @@
FROM python:3.12-slim
WORKDIR /app
RUN pip install --no-cache-dir "paho-mqtt>=2.1,<3" "psycopg[binary]>=3.2,<4"
COPY deploy/telemetry-plane/normalizer/normalizer.py /app/normalizer.py
RUN pip install --no-cache-dir "paho-mqtt==2.1.0"
COPY normalizer.py /app/normalizer.py
USER 65532:65532
ENTRYPOINT ["python", "/app/normalizer.py"]
+214 -279
View File
@@ -1,11 +1,11 @@
from __future__ import annotations
import contextlib
import json
import os
import re
import threading
import time
from collections import OrderedDict
from datetime import UTC, datetime
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
@@ -31,8 +31,10 @@ SAFE_IDENTIFIER: Final = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$")
MAX_PAYLOAD_BYTES: Final = 1024 * 1024
MAX_TAGS: Final = 256
MAX_SERIES_KEY_BYTES: Final = 4096
RETENTION_INTERVAL_SECONDS: Final = 60
RETENTION_BATCH_ROWS: Final = 1000
LATEST_TTL_SECONDS: Final = 300
MAX_LATEST_SAMPLES: Final = 20_000
MAX_AGENT_SAMPLES: Final = 512
MAX_CACHE_BYTES: Final = 16 * 1024 * 1024
ALLOWED_TELEMETRY_TAGS: Final = frozenset(
{
"agent_id",
@@ -133,9 +135,7 @@ def _sanitize_tags(document: dict[str, Any]) -> dict[str, Any]:
if len(tags) > MAX_TAGS:
raise ValueError("telemetry payload contains too many tags")
sanitized = {
str(name): str(value)
for name, value in tags.items()
if name in ALLOWED_TELEMETRY_TAGS
str(name): str(value) for name, value in tags.items() if name in ALLOWED_TELEMETRY_TAGS
}
return {**document, "tags": sanitized}
@@ -197,11 +197,7 @@ def _normalize(topic: str, payload: bytes) -> tuple[object, ...]:
node_id = document.get("node_id") or _tag_text(document, "node_id")
if not node_id:
node_id = _tag_text(document, "host")
if (
not isinstance(node_id, str)
or not node_id.strip()
or len(node_id.strip()) > 128
):
if not isinstance(node_id, str) or not node_id.strip() or len(node_id.strip()) > 128:
raise ValueError("node_id is required")
observed_at = _timestamp(observed_value)
return (
@@ -222,27 +218,163 @@ def _normalize(topic: str, payload: bytes) -> tuple[object, ...]:
)
class TelemetryQueryServer(ThreadingHTTPServer):
daemon_threads = True
class LatestTelemetry:
"""Bounded volatile latest-value cache; never a time-series archive."""
def __init__(
self,
server_address: tuple[str, int],
dsn: str,
runtime_health: TelemetryRuntimeHealth,
*,
clock=None,
ttl_seconds=LATEST_TTL_SECONDS,
max_samples=MAX_LATEST_SAMPLES,
max_agent_samples=MAX_AGENT_SAMPLES,
max_bytes=MAX_CACHE_BYTES,
) -> None:
super().__init__(server_address, TelemetryQueryHandler)
self.dsn = dsn
self.runtime_health = runtime_health
self._clock = clock or (lambda: datetime.now(UTC))
self._ttl = ttl_seconds
self._max_samples = max_samples
self._max_agent_samples = max_agent_samples
self._max_bytes = max_bytes
self._lock = threading.Lock()
self._entries: OrderedDict = OrderedDict()
self._agents: dict = {}
self._bytes = 0
self._day = self._clock().date()
self._next_sweep = 0.0
self._evictions = 0
self._rejected = 0
self._daily_resets = 0
def _remove(self, key) -> None:
row, _ingested, size = self._entries.pop(key)
agent = key[:2]
self._agents[agent].pop(key)
if not self._agents[agent]:
del self._agents[agent]
self._bytes -= size
def _maintain(self, now: datetime) -> None:
if now.date() != self._day:
self._entries.clear()
self._agents.clear()
self._bytes = 0
self._day = now.date()
self._daily_resets += 1
self._next_sweep = 0.0
if now.timestamp() >= self._next_sweep:
cutoff = now.timestamp() - self._ttl
for key, (row, _ingested, _size) in list(self._entries.items()):
if row[0].timestamp() < cutoff:
self._remove(key)
self._next_sweep = now.timestamp() + 5
def maintenance(self) -> None:
with self._lock:
self._maintain(self._clock())
def put(self, row: tuple) -> bool:
with self._lock:
now = self._clock()
self._maintain(now)
age = (now - row[0]).total_seconds()
if age > self._ttl or age < -30:
self._rejected += 1
return False
key = (row[1], row[2], row[4], row[5], row[6])
agent = key[:2]
previous = self._entries.get(key)
if previous:
old = previous[0]
if old[0] > row[0]:
return False
if old[0] == row[0] and old[7] == row[7] == TELEGRAF_SCHEMA:
# Telegraf can split fields of a single timestamp across messages.
previous_payload = json.loads(old[13])
payload = json.loads(row[13])
payload["fields"] = {
**previous_payload.get("fields", {}),
**payload.get("fields", {}),
}
row = (
*row[:13],
json.dumps(payload, separators=(",", ":"), ensure_ascii=False),
)
# Count retained strings as UTF-8, plus a conservative fixed entry charge.
# Both entry count and container RSS also have independent hard limits.
size = sum(len(str(value).encode("utf-8")) for value in row) + 512
if size > self._max_bytes:
self._rejected += 1
return False
if previous:
self._remove(key)
while len(self._agents.get(agent, {})) >= self._max_agent_samples:
self._remove(next(iter(self._agents[agent])))
self._evictions += 1
while self._entries and (
len(self._entries) >= self._max_samples or self._bytes + size > self._max_bytes
):
self._remove(next(iter(self._entries)))
self._evictions += 1
self._entries[key] = (row, now, size)
self._agents.setdefault(agent, OrderedDict())[key] = None
self._bytes += size
return True
def latest(self, contour_id: str, agent_id: str, max_age_seconds: int) -> list:
with self._lock:
now = self._clock()
self._maintain(now)
entries = [self._entries[key] for key in self._agents.get((contour_id, agent_id), {})]
samples = []
for row, ingested, _size in entries:
if (now - row[0]).total_seconds() > min(max_age_seconds, self._ttl):
continue
samples.append(
{
"observed_at_utc": row[0].isoformat().replace("+00:00", "Z"),
"ingested_at_utc": ingested.isoformat().replace("+00:00", "Z"),
"node_id": row[3],
"kind": row[4],
"measurement": row[5],
"series_key": row[6],
"source_schema": row[7],
"lab_id": row[9],
"run_id": row[10],
"request_id": row[11],
"frame_index": row[12],
"payload": json.loads(row[13]),
}
)
return sorted(
samples,
key=lambda sample: (sample["kind"], sample["measurement"], sample["series_key"]),
)
def snapshot(self) -> dict:
with self._lock:
self._maintain(self._clock())
return {
"backend": "memory",
"persistent_history": False,
"samples": len(self._entries),
"agents": len(self._agents),
"accounted_bytes": self._bytes,
"max_bytes": self._max_bytes,
"max_samples": self._max_samples,
"max_agent_samples": self._max_agent_samples,
"ttl_seconds": self._ttl,
"daily_reset_timezone": "UTC",
"reset_day": self._day.isoformat(),
"daily_resets": self._daily_resets,
"evictions": self._evictions,
"rejected_samples": self._rejected,
}
class TelemetryRuntimeHealth:
"""Thread-safe health of the actual MQTT-to-database ingestion path."""
def __init__(self) -> None:
self._lock = threading.Lock()
self._mqtt_connected = False
self._database_connected = False
self._last_ingested_at_utc: str | None = None
self._last_error: str | None = None
@@ -251,341 +383,145 @@ class TelemetryRuntimeHealth:
self._mqtt_connected = connected
self._last_error = error
def set_database(self, connected: bool, error: str | None = None) -> None:
with self._lock:
self._database_connected = connected
self._last_error = error
def mark_ingested(self) -> None:
with self._lock:
self._database_connected = True
self._last_ingested_at_utc = (
datetime.now(UTC).isoformat(timespec="seconds").replace("+00:00", "Z")
)
self._last_ingested_at_utc = datetime.now(UTC).isoformat().replace("+00:00", "Z")
self._last_error = None
def snapshot(self) -> dict[str, object]:
with self._lock:
return {
"mqtt_connected": self._mqtt_connected,
"database_connected": self._database_connected,
"last_ingested_at_utc": self._last_ingested_at_utc,
"last_error": self._last_error,
}
class TelemetryQueryServer(ThreadingHTTPServer):
daemon_threads = True
def __init__(self, server_address, cache, runtime_health) -> None:
super().__init__(server_address, TelemetryQueryHandler)
self.cache = cache
self.runtime_health = runtime_health
class TelemetryQueryHandler(BaseHTTPRequestHandler):
server: TelemetryQueryServer
def do_GET(self) -> None: # noqa: N802 - stdlib HTTP handler contract
def do_GET(self) -> None: # noqa: N802
parsed = urlparse(self.path)
if parsed.path == "/health":
self._health()
runtime = self.server.runtime_health.snapshot()
ok = runtime["mqtt_connected"] is True
self._json(
HTTPStatus.OK if ok else HTTPStatus.SERVICE_UNAVAILABLE,
{
"ok": ok,
"schema_version": QUERY_SCHEMA,
"storage_ready": True,
"storage": self.server.cache.snapshot(),
**runtime,
},
)
return
match = re.fullmatch(
r"/v1/contours/(?P<contour>[-a-z0-9]+)/agents/"
r"(?P<agent>[-a-z0-9]+)/latest",
r"/v1/contours/(?P<contour>[-a-z0-9]+)/agents/(?P<agent>[-a-z0-9]+)/latest",
parsed.path,
)
if match is None:
self._json(HTTPStatus.NOT_FOUND, {"detail": "not found"})
return
query = parse_qs(parsed.query)
try:
max_age_seconds = int(query.get("max_age_seconds", ["120"])[0])
max_age_seconds = int(parse_qs(parsed.query).get("max_age_seconds", ["120"])[0])
except ValueError:
self._json(HTTPStatus.BAD_REQUEST, {"detail": "invalid max_age_seconds"})
return
max_age_seconds = 0
if not 1 <= max_age_seconds <= 86_400:
self._json(HTTPStatus.BAD_REQUEST, {"detail": "invalid max_age_seconds"})
return
self._latest(
match.group("contour"),
match.group("agent"),
max_age_seconds=max_age_seconds,
)
def log_message(self, format: str, *args: object) -> None:
print(f"telemetry query: {format % args}", flush=True)
def _health(self) -> None:
import psycopg # type: ignore[import-not-found]
database_reachable = False
try:
with (
psycopg.connect(self.server.dsn) as connection,
connection.cursor() as cursor,
):
cursor.execute("SELECT 1")
cursor.fetchone()
database_reachable = True
except psycopg.Error:
database_reachable = False
runtime = self.server.runtime_health.snapshot()
ok = (
database_reachable
and runtime["mqtt_connected"] is True
and runtime["database_connected"] is True
)
self._json(
HTTPStatus.OK if ok else HTTPStatus.SERVICE_UNAVAILABLE,
{
"ok": ok,
"schema_version": QUERY_SCHEMA,
"database_reachable": database_reachable,
**runtime,
},
)
def _latest(
self,
contour_id: str,
agent_id: str,
*,
max_age_seconds: int,
) -> None:
import psycopg # type: ignore[import-not-found]
if (
SAFE_IDENTIFIER.fullmatch(contour_id) is None
or SAFE_IDENTIFIER.fullmatch(agent_id) is None
):
contour, agent = match.group("contour"), match.group("agent")
if SAFE_IDENTIFIER.fullmatch(contour) is None or SAFE_IDENTIFIER.fullmatch(agent) is None:
self._json(HTTPStatus.BAD_REQUEST, {"detail": "invalid identifier"})
return
try:
with (
psycopg.connect(self.server.dsn) as connection,
connection.cursor() as cursor,
):
cursor.execute(
"""
SELECT DISTINCT ON (kind, measurement, series_key)
observed_at, ingested_at, node_id, kind, measurement,
series_key, source_schema, lab_id, run_id, request_id,
frame_index, payload
FROM contour_telemetry_samples
WHERE contour_id = %s
AND agent_id = %s
AND observed_at >= NOW() - (%s * INTERVAL '1 second')
ORDER BY kind, measurement, series_key, observed_at DESC
""",
(contour_id, agent_id, max_age_seconds),
)
rows = cursor.fetchall()
except psycopg.Error:
self._json(
HTTPStatus.SERVICE_UNAVAILABLE,
{"detail": "telemetry database unavailable"},
)
return
samples = [
{
"observed_at_utc": row[0].astimezone(UTC).isoformat().replace("+00:00", "Z"),
"ingested_at_utc": row[1].astimezone(UTC).isoformat().replace("+00:00", "Z"),
"node_id": row[2],
"kind": row[3],
"measurement": row[4],
"series_key": row[5],
"source_schema": row[6],
"lab_id": row[7],
"run_id": row[8],
"request_id": row[9],
"frame_index": row[10],
"payload": row[11],
}
for row in rows
]
self._json(
HTTPStatus.OK,
{
"schema_version": QUERY_SCHEMA,
"contour_id": contour_id,
"agent_id": agent_id,
"samples": samples,
"contour_id": contour,
"agent_id": agent,
"samples": self.server.cache.latest(contour, agent, max_age_seconds),
},
)
def log_message(self, format: str, *args: object) -> None:
# Polls/health checks must not become another on-disk telemetry history.
pass
def _json(self, status: HTTPStatus, document: dict[str, object]) -> None:
body = json.dumps(
document,
ensure_ascii=False,
separators=(",", ":"),
).encode("utf-8")
body = json.dumps(document, ensure_ascii=False, separators=(",", ":")).encode()
self.send_response(status.value)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def _start_query_server(
dsn: str,
runtime_health: TelemetryRuntimeHealth,
) -> ThreadingHTTPServer:
def _start_query_server(cache, runtime_health) -> ThreadingHTTPServer:
host = os.environ.get("MISSIONCORE_QUERY_HOST", "0.0.0.0")
port = int(os.environ.get("MISSIONCORE_QUERY_PORT", "18030"))
server = TelemetryQueryServer((host, port), dsn, runtime_health)
thread = threading.Thread(
target=server.serve_forever,
name="telemetry-query",
daemon=True,
)
thread.start()
server = TelemetryQueryServer((host, port), cache, runtime_health)
threading.Thread(target=server.serve_forever, name="telemetry-query", daemon=True).start()
return server
def _retention_batch(connection: Any) -> int:
"""Preserve the existing 30-day policy without an unbounded startup DELETE."""
with connection.transaction(), connection.cursor() as cursor:
cursor.execute("SET LOCAL statement_timeout = '2s'")
cursor.execute("SET LOCAL lock_timeout = '250ms'")
cursor.execute(
"""
WITH expired AS (
SELECT tableoid, ctid FROM contour_telemetry_samples
WHERE observed_at < CURRENT_TIMESTAMP - INTERVAL '30 days'
ORDER BY observed_at LIMIT %s
)
DELETE FROM contour_telemetry_samples AS samples USING expired
WHERE samples.tableoid = expired.tableoid AND samples.ctid = expired.ctid
""",
(RETENTION_BATCH_ROWS,),
)
return cursor.rowcount
def _retention_loop(dsn: str) -> None:
import psycopg # type: ignore[import-not-found]
def _maintenance_loop(cache: LatestTelemetry) -> None:
while True:
# Neither a retention timeout nor database recovery blocks MQTT I/O.
time.sleep(RETENTION_INTERVAL_SECONDS)
try:
with psycopg.connect(dsn, connect_timeout=3) as connection:
_retention_batch(connection)
except psycopg.Error:
print("telemetry retention deferred", flush=True)
time.sleep(1)
cache.maintenance()
def main() -> None:
import paho.mqtt.client as mqtt
import psycopg # type: ignore[import-not-found]
from paho.mqtt import MQTTException
from paho.mqtt.enums import CallbackAPIVersion
dsn = _required("MISSIONCORE_DATABASE_DSN")
host = _required("MISSIONCORE_MQTT_HOST")
port = int(os.environ.get("MISSIONCORE_MQTT_PORT", "1883"))
username = _required("MISSIONCORE_MQTT_USERNAME")
password = _required("MISSIONCORE_MQTT_PASSWORD")
cache = LatestTelemetry()
runtime_health = TelemetryRuntimeHealth()
connection = psycopg.connect(dsn, autocommit=True)
threading.Thread(
target=_retention_loop, args=(dsn,), name="telemetry-retention", daemon=True
target=_maintenance_loop, args=(cache,), name="telemetry-expiry", daemon=True
).start()
runtime_health.set_database(True)
_start_query_server(dsn, runtime_health)
_start_query_server(cache, runtime_health)
# No offline replay queue: this receiver serves current state, not history.
client = mqtt.Client(
callback_api_version=CallbackAPIVersion.VERSION2,
client_id="ndc-mission-core-telemetry-normalizer",
clean_session=False,
clean_session=True,
)
client.username_pw_set(username, password)
def on_connect(
connected_client: Any,
_userdata: object,
_flags: Any,
reason_code: Any,
_properties: Any,
) -> None:
def on_connect(connected_client, _userdata, _flags, reason_code, _properties):
if reason_code.is_failure:
runtime_health.set_mqtt(False, f"MQTT connection rejected: {reason_code}")
raise RuntimeError(f"MQTT connection rejected: {reason_code}")
runtime_health.set_mqtt(False, "MQTT connection rejected")
return
connected_client.subscribe(TOPIC, qos=1)
runtime_health.set_mqtt(True)
def on_disconnect(
_connected_client: Any,
_userdata: object,
_disconnect_flags: Any,
reason_code: Any,
_properties: Any,
) -> None:
runtime_health.set_mqtt(False, f"MQTT disconnected: {reason_code}")
def on_disconnect(_client, _userdata, _flags, reason_code, _properties):
runtime_health.set_mqtt(False, "MQTT disconnected")
def on_message(_client: Any, _userdata: object, message: Any) -> None:
nonlocal connection
def on_message(_client, _userdata, message):
try:
row = _normalize(message.topic, message.payload)
except (ValueError, UnicodeDecodeError, json.JSONDecodeError) as exc:
print(f"telemetry sample rejected: {exc}", flush=True)
return
for attempt in range(2):
try:
with connection.cursor() as cursor:
cursor.execute(
"""
INSERT INTO contour_telemetry_samples (
observed_at, contour_id, agent_id, node_id, kind, measurement,
series_key, source_schema, source_topic, lab_id, run_id,
request_id, frame_index, payload
)
VALUES (
%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s,
%s::jsonb
)
ON CONFLICT (
observed_at, contour_id, agent_id, kind, measurement, series_key
)
DO UPDATE SET
ingested_at = NOW(),
node_id = EXCLUDED.node_id,
series_key = EXCLUDED.series_key,
source_schema = EXCLUDED.source_schema,
source_topic = EXCLUDED.source_topic,
lab_id = EXCLUDED.lab_id,
run_id = EXCLUDED.run_id,
request_id = EXCLUDED.request_id,
frame_index = EXCLUDED.frame_index,
payload = CASE
WHEN contour_telemetry_samples.source_schema = %s
AND EXCLUDED.source_schema = %s
THEN EXCLUDED.payload || jsonb_build_object(
'fields',
COALESCE(
contour_telemetry_samples.payload -> 'fields',
'{}'::jsonb
) || COALESCE(
EXCLUDED.payload -> 'fields',
'{}'::jsonb
)
)
ELSE EXCLUDED.payload
END
""",
(*row, TELEGRAF_SCHEMA, TELEGRAF_SCHEMA),
)
if cache.put(row):
runtime_health.mark_ingested()
return
except psycopg.Error as exc:
runtime_health.set_database(False, f"database ingestion failed: {exc}")
with contextlib.suppress(psycopg.Error):
connection.close()
if attempt == 0:
try:
connection = psycopg.connect(dsn, autocommit=True)
runtime_health.set_database(True)
except psycopg.Error as reconnect_error:
runtime_health.set_database(
False,
f"database reconnect failed: {reconnect_error}",
)
break
else:
break
print("telemetry sample rejected: database unavailable", flush=True)
except (ValueError, UnicodeDecodeError, TypeError, OverflowError):
# Never log rejected payloads or emit an unbounded line per bad sample.
return
client.on_connect = on_connect
client.on_disconnect = on_disconnect
@@ -594,9 +530,8 @@ def main() -> None:
try:
client.connect(host, port, keepalive=30)
client.loop_forever(retry_first_connection=True)
except (OSError, MQTTException, psycopg.Error) as exc:
runtime_health.set_mqtt(False, f"MQTT reconnecting: {exc}")
print(f"telemetry normalizer reconnecting: {exc}", flush=True)
except (OSError, MQTTException):
runtime_health.set_mqtt(False, "MQTT reconnecting")
time.sleep(3)