From 8bf6571ce2bf7fa825b422f1795af549a2ffe218 Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Thu, 8 Oct 2026 10:54:35 +0300 Subject: [PATCH] Keep operator telemetry live-only with bounded volatile state --- AGENTS.md | 6 + deploy/telemetry-plane/.env.example | 4 - deploy/telemetry-plane/README.md | 80 ++- deploy/telemetry-plane/compose.yaml | 91 +--- .../telemetry-plane/mosquitto/mosquitto.conf | 13 +- deploy/telemetry-plane/normalizer/Dockerfile | 4 +- .../telemetry-plane/normalizer/normalizer.py | 493 ++++++++---------- deploy/telemetry-plane/prepare.py | 30 +- .../timescale/001_telemetry.sql | 43 -- .../timescale/002_roles_and_retention.sh | 31 -- scripts/manage_telemetry_startup.py | 4 +- tests/test_telemetry_normalizer_contract.py | 179 +++++-- tests/test_telemetry_plane_prepare.py | 19 +- tests/test_telemetry_startup.py | 23 +- 14 files changed, 450 insertions(+), 570 deletions(-) delete mode 100644 deploy/telemetry-plane/timescale/001_telemetry.sql delete mode 100644 deploy/telemetry-plane/timescale/002_roles_and_retention.sh diff --git a/AGENTS.md b/AGENTS.md index 6a7e440a..4a8b6ad1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -29,6 +29,12 @@ and the boundary between Mission Core and vendor-specific integration code. - Other repositories, platform worktrees, infrastructure, DOC, workspace bridge, Site/SEO, BIM Viewer, Device Core, Design Guideline, and Gaussian Pipeline are separate ownership boundaries. Mission Core cleanup must not alter them. +- Operator telemetry is live-only: bounded latest values in RAM, expiry and a + daily reset. Do not reintroduce a local time-series database or persistent raw + monitoring history on the Mac. Diagnostic logs must rotate. Future historical + monitoring requires an explicitly provisioned separate service; simulation + evidence and recordings have a separate lifecycle and must not be deleted as + part of telemetry cleanup. ## Non-negotiable safety boundaries diff --git a/deploy/telemetry-plane/.env.example b/deploy/telemetry-plane/.env.example index f0c807d4..08a4ce8c 100644 --- a/deploy/telemetry-plane/.env.example +++ b/deploy/telemetry-plane/.env.example @@ -1,9 +1,5 @@ MISSIONCORE_MQTT_BIND_ADDRESS=127.0.0.1 MISSIONCORE_MQTT_PORT=1883 MISSIONCORE_TELEMETRY_QUERY_PORT=18030 -MISSIONCORE_DB_NAME=missioncore_telemetry -MISSIONCORE_DB_USER=missioncore_ingest -MISSIONCORE_DB_PASSWORD=replace-with-a-random-local-secret -MISSIONCORE_DB_INGEST_PASSWORD=replace-with-a-separate-ingest-secret MISSIONCORE_MQTT_INGEST_USER=missioncore-ingest MISSIONCORE_MQTT_INGEST_PASSWORD=replace-with-a-random-local-secret diff --git a/deploy/telemetry-plane/README.md b/deploy/telemetry-plane/README.md index a6b3cd36..2a7b6185 100644 --- a/deploy/telemetry-plane/README.md +++ b/deploy/telemetry-plane/README.md @@ -2,54 +2,45 @@ Portable local-only telemetry infrastructure for compute contours. -One Docker Compose project, `ndc-mission-core-telemetry`, owns three long-running -containers and one bounded bootstrap job: +The operator contour is **live-only**. One Compose project, +`ndc-mission-core-telemetry`, owns two services: the authenticated Mosquitto broker +and the normalizer/query adapter. There is no local telemetry database, named data +volume, raw metric archive, or SQL retention job. -- `ndc-mission-core-mqtt-broker` — Eclipse Mosquitto `2.1.2-alpine`; -- `ndc-mission-core-telemetry-timescaledb` — TimescaleDB HA OSS - `pg16.14-ts2.28.2-all-oss`; -- `ndc-mission-core-telemetry-bootstrap` — one-shot database role/bootstrap job; -- `ndc-mission-core-telemetry-normalizer` — Mission Core telemetry normalizer. +Each new sample replaces the previous value for the same contour, agent, +measurement and series. The existing `/v1/contours/.../agents/.../latest` response +contract is preserved. Split Telegraf fields at the same timestamp are merged; +out-of-order older samples cannot replace newer state. -The Telegraf configuration templates cover Windows and Linux, but the agent runs as a -host service rather than inside this Compose project. This preserves access to native -Windows performance counters, Docker Desktop and NVIDIA telemetry. +The cache lives only in RAM. Values expire after five minutes (the Core UI asks +for at most 30-second-old values). Limits are 512 series per agent, 20,000 total, +and 16 MiB of accounted entries including a fixed overhead allowance, within the +256 MiB container memory ceiling. Oldest entries are evicted on capacity pressure; +health exposes capacity, eviction and stale-input counters. This is bounded local +monitoring, not a claim of acceptance for hundreds of workers. -The normalizer exposes a read-only normalized telemetry adapter on -`127.0.0.1:18030`. Mission Core reads this adapter; the browser never receives MQTT or -Timescale credentials, and Timescale is not published on a host port. -The normalizer uses a separate `missioncore_normalizer` database role with only -`SELECT`, `INSERT`, `UPDATE`, and bounded retention `DELETE` on the telemetry -hypertable. Raw telemetry older than 30 days is removed in batches of at most -1000 rows per minute, on a separate connection/thread (2s statement / 250ms lock -deadline). Retention never runs inside the MQTT callback. This stays compatible -with the Apache-licensed Timescale image without -depending on the Timescale License retention scheduler. +A background sweep clears the entire cache at the UTC date boundary, including +when no messages arrive; restart also starts empty. Routine HTTP polls and message +payloads are not logged. Both services rotate their diagnostic Docker logs at +5 MiB × 2 files per service. MQTT persistence/retained messages are disabled, +offline sessions are not replayed, and queues are bounded. Authentication, agent +ACLs, loopback query access and the existing Worker connection are unchanged. -The 1 GiB database container explicitly sets 128 MiB shared buffers and 64 MiB -maintenance memory. The HA image's automatic tuning sees the Docker VM instead -of this container limit; do not inherit its multi-GiB defaults. +`/health` reports `storage_ready` and `storage.backend=memory`; it no longer claims +a database is reachable. Startup reconciliation uses that contract and can start +only broker + normalizer. Long-term monitoring, if requested later, belongs to a +separate explicitly provisioned service with time/size retention budgets. -For a memory-constrained local repair, `compose.source.yaml` mounts the reviewed -normalizer source read-only into the **existing** image. Set -`MISSIONCORE_NORMALIZER_SOURCE` to the absolute `normalizer.py` path, pass both -Compose files and the existing private `--env-file` / `--project-directory`, and -use `up -d --no-deps --no-build normalizer`. This is an explicit local source -override, not a rebuilt portable image. Normal restart/reboot retains the mount. +For migration from the retired SQL deployment: qualify the live adapter first, +then remove only the exact Mission Core Timescale/bootstrap containers and the +`ndc-mission-core-telemetry-timescale-data` volume, with owner authorization for +history deletion. The old `ndc-mission-core-mqtt-data` volume is also obsolete. +Do not use global Docker pruning or remove the Docker disk image. Simulation +recordings, evidence, local application databases and Worker artifacts are separate +and are not part of this migration. -The stack is one deployment contour, not one multi-process container. Keeping broker, -normalizer and database in separate containers preserves independent health checks, -least-privilege boundaries and rollback while Compose provides one operator lifecycle: - -```bash -docker compose ps -docker compose up -d -docker compose down -``` - -All NODE.DC-owned Docker objects use the lowercase `ndc-` namespace. Docker names are -case-sensitive identifiers, so the product prefix is normalized to lowercase while the -product name remains NODE.DC in operator-facing copy. +The optional `compose.source.yaml` provides a read-only source override for a +bounded local repair; normal releases use the built normalizer image. This directory does not contain credentials. Copy `.env.example` to `.env`, generate unique passwords and build the ACL/password files before starting the stack. @@ -101,10 +92,7 @@ network: ndc-mission-core-telemetry containers: ndc-mission-core-mqtt-broker ndc-mission-core-telemetry-normalizer - ndc-mission-core-telemetry-timescaledb -volumes: - ndc-mission-core-mqtt-data - ndc-mission-core-telemetry-timescale-data +volumes: none (volatile tmpfs only) ``` `prepare.py` passes passwords to `mosquitto_passwd` through stdin. Secrets are not placed diff --git a/deploy/telemetry-plane/compose.yaml b/deploy/telemetry-plane/compose.yaml index e190853d..b1c1fb4d 100644 --- a/deploy/telemetry-plane/compose.yaml +++ b/deploy/telemetry-plane/compose.yaml @@ -10,6 +10,11 @@ services: image: eclipse-mosquitto:2.1.2-alpine container_name: ndc-mission-core-mqtt-broker restart: unless-stopped + logging: + driver: local + options: + max-size: "5m" + max-file: "2" read_only: true security_opt: - no-new-privileges:true @@ -33,9 +38,10 @@ services: - ./mosquitto/mosquitto.conf:/mosquitto/config/mosquitto.conf:ro - ./runtime/mosquitto/passwords:/mosquitto/config/passwords:ro - ./runtime/mosquitto/acl:/mosquitto/config/acl:ro - - broker-data:/mosquitto/data tmpfs: - /tmp:size=16m,noexec,nosuid + - /mosquitto/data:size=1m,noexec,nosuid + - /mosquitto/log:size=1m,noexec,nosuid healthcheck: test: - CMD-SHELL @@ -47,67 +53,18 @@ services: timeout: 4s retries: 6 - timescale: - image: timescale/timescaledb-ha:pg16.14-ts2.28.2-all-oss - # The HA image auto-tunes for the Docker VM, not this 1 GiB container. - command: ["postgres", "-c", "shared_buffers=128MB", "-c", "work_mem=4MB", "-c", "maintenance_work_mem=64MB", "-c", "effective_cache_size=512MB", "-c", "max_parallel_workers_per_gather=0", "-c", "max_connections=32"] - container_name: ndc-mission-core-telemetry-timescaledb - restart: unless-stopped - security_opt: - - no-new-privileges:true - mem_limit: 1024m - pids_limit: 256 - labels: - <<: *ndc-labels - com.nodedc.role: telemetry-database - environment: - POSTGRES_DB: "${MISSIONCORE_DB_NAME}" - POSTGRES_USER: "${MISSIONCORE_DB_USER}" - POSTGRES_PASSWORD: "${MISSIONCORE_DB_PASSWORD}" - volumes: - - timescale-data:/home/postgres/pgdata/data - - ./timescale/001_telemetry.sql:/docker-entrypoint-initdb.d/001_telemetry.sql:ro - healthcheck: - test: ["CMD-SHELL", "pg_isready -U ${MISSIONCORE_DB_USER} -d ${MISSIONCORE_DB_NAME}"] - interval: 10s - timeout: 5s - retries: 10 - - database-bootstrap: - image: timescale/timescaledb-ha:pg16.14-ts2.28.2-all-oss - container_name: ndc-mission-core-telemetry-bootstrap - restart: "no" - read_only: true - security_opt: - - no-new-privileges:true - cap_drop: - - ALL - mem_limit: 128m - pids_limit: 64 - labels: - <<: *ndc-labels - com.nodedc.role: telemetry-database-bootstrap - depends_on: - timescale: - condition: service_healthy - environment: - MISSIONCORE_DB_NAME: "${MISSIONCORE_DB_NAME}" - MISSIONCORE_DB_ADMIN_USER: "${MISSIONCORE_DB_USER}" - MISSIONCORE_DB_ADMIN_PASSWORD: "${MISSIONCORE_DB_PASSWORD}" - MISSIONCORE_DB_INGEST_PASSWORD: "${MISSIONCORE_DB_INGEST_PASSWORD}" - volumes: - - ./timescale/002_roles_and_retention.sh:/bootstrap.sh:ro - tmpfs: - - /tmp:size=16m,noexec,nosuid - entrypoint: ["/bin/sh", "/bootstrap.sh"] - normalizer: - image: nodedc/mission-core-telemetry-normalizer:local + image: ndc-mission-core-telemetry-normalizer:live-v1 container_name: ndc-mission-core-telemetry-normalizer build: - context: ../.. - dockerfile: deploy/telemetry-plane/normalizer/Dockerfile + context: ./normalizer + dockerfile: Dockerfile restart: unless-stopped + logging: + driver: local + options: + max-size: "5m" + max-file: "2" read_only: true security_opt: - no-new-privileges:true @@ -121,10 +78,6 @@ services: depends_on: broker: condition: service_healthy - timescale: - condition: service_healthy - database-bootstrap: - condition: service_completed_successfully ports: - "127.0.0.1:${MISSIONCORE_TELEMETRY_QUERY_PORT:-18030}:18030" environment: @@ -132,8 +85,6 @@ services: MISSIONCORE_MQTT_PORT: "1883" MISSIONCORE_MQTT_USERNAME: "${MISSIONCORE_MQTT_INGEST_USER}" MISSIONCORE_MQTT_PASSWORD: "${MISSIONCORE_MQTT_INGEST_PASSWORD}" - MISSIONCORE_DATABASE_DSN: >- - postgresql://missioncore_normalizer:${MISSIONCORE_DB_INGEST_PASSWORD}@timescale:5432/${MISSIONCORE_DB_NAME} MISSIONCORE_QUERY_HOST: "0.0.0.0" MISSIONCORE_QUERY_PORT: "18030" tmpfs: @@ -150,18 +101,6 @@ services: timeout: 4s retries: 6 -volumes: - broker-data: - name: ndc-mission-core-mqtt-data - labels: - <<: *ndc-labels - com.nodedc.role: mqtt-storage - timescale-data: - name: ndc-mission-core-telemetry-timescale-data - labels: - <<: *ndc-labels - com.nodedc.role: telemetry-storage - networks: default: name: ndc-mission-core-telemetry diff --git a/deploy/telemetry-plane/mosquitto/mosquitto.conf b/deploy/telemetry-plane/mosquitto/mosquitto.conf index bbf63e53..6e749050 100644 --- a/deploy/telemetry-plane/mosquitto/mosquitto.conf +++ b/deploy/telemetry-plane/mosquitto/mosquitto.conf @@ -1,5 +1,12 @@ -persistence true -persistence_location /mosquitto/data/ +# Live telemetry only: never write MQTT messages/session history to disk. +persistence false +retain_available false +# Health probe waits 3s; without retained messages SYS must publish within that. +sys_interval 1 +max_queued_messages 200 +max_queued_bytes 1048576 +message_size_limit 1048576 +persistent_client_expiration 1d listener 1883 0.0.0.0 allow_anonymous false @@ -7,5 +14,5 @@ password_file /mosquitto/config/passwords acl_file /mosquitto/config/acl log_dest stdout -connection_messages true +connection_messages false log_timestamp true diff --git a/deploy/telemetry-plane/normalizer/Dockerfile b/deploy/telemetry-plane/normalizer/Dockerfile index 4b44ad35..f44a4cfd 100644 --- a/deploy/telemetry-plane/normalizer/Dockerfile +++ b/deploy/telemetry-plane/normalizer/Dockerfile @@ -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"] diff --git a/deploy/telemetry-plane/normalizer/normalizer.py b/deploy/telemetry-plane/normalizer/normalizer.py index 98bea50f..ccffe423 100644 --- a/deploy/telemetry-plane/normalizer/normalizer.py +++ b/deploy/telemetry-plane/normalizer/normalizer.py @@ -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[-a-z0-9]+)/agents/" - r"(?P[-a-z0-9]+)/latest", + r"/v1/contours/(?P[-a-z0-9]+)/agents/(?P[-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) diff --git a/deploy/telemetry-plane/prepare.py b/deploy/telemetry-plane/prepare.py index 2a207e8e..5592857e 100644 --- a/deploy/telemetry-plane/prepare.py +++ b/deploy/telemetry-plane/prepare.py @@ -24,9 +24,7 @@ PLACEHOLDER: Final = "replace-with-" AGENT_REGISTRY_SCHEMA: Final = "missioncore.telemetry-agent-credential-registry/v1" AGENT_PAYLOAD_SCHEMA: Final = "missioncore.telemetry-agent-provisioning-payload/v1" AGENT_BUNDLE_SCHEMA: Final = "missioncore.telemetry-agent-bundle/v1" -SAFE_IDENTIFIER: Final = re.compile( - r"^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$" -) +SAFE_IDENTIFIER: Final = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$") SAFE_INTERVAL: Final = re.compile(r"^[1-9][0-9]{0,2}s$") WINDOWS_BUNDLE_FILES: Final = ( "Install-NdcMissionCoreTelemetryRecovery.ps1", @@ -62,10 +60,6 @@ def _initialize_environment(bind_address: str, *, overwrite: bool = False) -> No "MISSIONCORE_MQTT_BIND_ADDRESS": normalized_bind_address, "MISSIONCORE_MQTT_PORT": "1883", "MISSIONCORE_TELEMETRY_QUERY_PORT": "18030", - "MISSIONCORE_DB_NAME": "missioncore_telemetry", - "MISSIONCORE_DB_USER": "missioncore_ingest", - "MISSIONCORE_DB_PASSWORD": secrets.token_urlsafe(36), - "MISSIONCORE_DB_INGEST_PASSWORD": secrets.token_urlsafe(36), "MISSIONCORE_MQTT_INGEST_USER": "missioncore-ingest", "MISSIONCORE_MQTT_INGEST_PASSWORD": secrets.token_urlsafe(36), } @@ -91,17 +85,6 @@ def _environment() -> dict[str, str]: def _migrate_environment() -> None: values = _environment() - additions: dict[str, str] = {} - if "MISSIONCORE_DB_INGEST_PASSWORD" not in values: - additions["MISSIONCORE_DB_INGEST_PASSWORD"] = secrets.token_urlsafe(36) - if additions: - with ENV_PATH.open("a", encoding="utf-8", newline="\n") as stream: - for name, value in additions.items(): - stream.write(f"{name}={value}\n") - stream.flush() - os.fsync(stream.fileno()) - os.chmod(ENV_PATH, 0o600) - values.update(additions) _migrate_legacy_worker(values) @@ -301,12 +284,12 @@ def _private_mqtt_host(value: str) -> None: try: address = ipaddress.ip_address(value) except ValueError: - if not value.endswith(".local") or len(value) > 253 or any( - SAFE_IDENTIFIER.fullmatch(label) is None for label in value[:-6].split(".") + if ( + not value.endswith(".local") + or len(value) > 253 + or any(SAFE_IDENTIFIER.fullmatch(label) is None for label in value[:-6].split(".")) ): - raise RuntimeError( - "MQTT host must be a private IP or stable .local hostname" - ) from None + raise RuntimeError("MQTT host must be a private IP or stable .local hostname") from None else: if not address.is_private or address.is_unspecified or address.is_multicast: raise RuntimeError("MQTT host must be a private IP or stable .local hostname") @@ -391,7 +374,6 @@ def _prepare_plane() -> None: agents = _read_agent_registry() ingest_user = _required(values, "MISSIONCORE_MQTT_INGEST_USER") ingest_password = _required(values, "MISSIONCORE_MQTT_INGEST_PASSWORD") - _required(values, "MISSIONCORE_DB_PASSWORD") RUNTIME.mkdir(mode=0o700, parents=True, exist_ok=True) password_path = RUNTIME / "passwords" _prepare_password_entries(password_path, ingest_user, ingest_password, agents) diff --git a/deploy/telemetry-plane/timescale/001_telemetry.sql b/deploy/telemetry-plane/timescale/001_telemetry.sql deleted file mode 100644 index a36082db..00000000 --- a/deploy/telemetry-plane/timescale/001_telemetry.sql +++ /dev/null @@ -1,43 +0,0 @@ -CREATE EXTENSION IF NOT EXISTS timescaledb; - -CREATE TABLE IF NOT EXISTS contour_telemetry_samples ( - observed_at TIMESTAMPTZ NOT NULL, - ingested_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - contour_id TEXT NOT NULL, - agent_id TEXT NOT NULL, - node_id TEXT NOT NULL, - kind TEXT NOT NULL, - measurement TEXT NOT NULL, - series_key TEXT NOT NULL DEFAULT '', - source_schema TEXT NOT NULL, - source_topic TEXT NOT NULL, - lab_id TEXT, - run_id TEXT, - request_id TEXT, - frame_index BIGINT, - payload JSONB NOT NULL, - PRIMARY KEY ( - observed_at, - contour_id, - agent_id, - kind, - measurement, - series_key - ) -); - -SELECT create_hypertable( - 'contour_telemetry_samples', - by_range('observed_at'), - if_not_exists => TRUE -); - -CREATE INDEX IF NOT EXISTS contour_telemetry_latest_idx - ON contour_telemetry_samples ( - contour_id, - agent_id, - kind, - measurement, - series_key, - observed_at DESC - ); diff --git a/deploy/telemetry-plane/timescale/002_roles_and_retention.sh b/deploy/telemetry-plane/timescale/002_roles_and_retention.sh deleted file mode 100644 index ddebccc9..00000000 --- a/deploy/telemetry-plane/timescale/002_roles_and_retention.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh -set -eu - -export PGPASSWORD="${MISSIONCORE_DB_ADMIN_PASSWORD}" - -psql \ - --host timescale \ - --username "${MISSIONCORE_DB_ADMIN_USER}" \ - --dbname "${MISSIONCORE_DB_NAME}" \ - --set ON_ERROR_STOP=1 \ - --set database_name="${MISSIONCORE_DB_NAME}" \ - --set ingest_password="${MISSIONCORE_DB_INGEST_PASSWORD}" <<'SQL' -DO $roles$ -BEGIN - IF NOT EXISTS ( - SELECT 1 FROM pg_roles WHERE rolname = 'missioncore_normalizer' - ) THEN - CREATE ROLE missioncore_normalizer LOGIN; - END IF; -END -$roles$; - -ALTER ROLE missioncore_normalizer PASSWORD :'ingest_password'; -GRANT CONNECT ON DATABASE :"database_name" TO missioncore_normalizer; -GRANT USAGE ON SCHEMA public TO missioncore_normalizer; -GRANT SELECT, INSERT, UPDATE, DELETE ON contour_telemetry_samples - TO missioncore_normalizer; - -DELETE FROM contour_telemetry_samples -WHERE observed_at < CURRENT_TIMESTAMP - INTERVAL '30 days'; -SQL diff --git a/scripts/manage_telemetry_startup.py b/scripts/manage_telemetry_startup.py index d00abd3b..86cb87ae 100644 --- a/scripts/manage_telemetry_startup.py +++ b/scripts/manage_telemetry_startup.py @@ -42,7 +42,8 @@ def receiver_ready(): return ( d.get("ok") is True and d.get("mqtt_connected") is True - and d.get("database_reachable") is True + and d.get("storage_ready") is True + and d.get("storage", {}).get("backend") == "memory" ) except (OSError, ValueError): return False @@ -99,7 +100,6 @@ def reconcile(stack: Path): "--wait-timeout", "45", "broker", - "timescale", "normalizer", ], 60, diff --git a/tests/test_telemetry_normalizer_contract.py b/tests/test_telemetry_normalizer_contract.py index 2877f219..e9068ba4 100644 --- a/tests/test_telemetry_normalizer_contract.py +++ b/tests/test_telemetry_normalizer_contract.py @@ -10,13 +10,7 @@ import pytest import yaml REPOSITORY_ROOT = Path(__file__).resolve().parents[1] -NORMALIZER_PATH = ( - REPOSITORY_ROOT - / "deploy" - / "telemetry-plane" - / "normalizer" - / "normalizer.py" -) +NORMALIZER_PATH = REPOSITORY_ROOT / "deploy" / "telemetry-plane" / "normalizer" / "normalizer.py" COMPOSE_PATH = REPOSITORY_ROOT / "deploy" / "telemetry-plane" / "compose.yaml" NORMALIZER_SOURCE = NORMALIZER_PATH.read_text(encoding="utf-8") @@ -117,29 +111,25 @@ def test_normalizer_keeps_same_measurement_series_distinct() -> None: assert rows[1][6] == '{"interface":"Wi-Fi"}' -def test_telegraf_upsert_merges_split_fields_in_one_series() -> None: - assert "contour_telemetry_samples.payload -> 'fields'" in NORMALIZER_SOURCE - assert "EXCLUDED.payload -> 'fields'" in NORMALIZER_SOURCE - - -def test_normalizer_enforces_oss_compatible_bounded_retention() -> None: - assert "DELETE FROM contour_telemetry_samples" in NORMALIZER_SOURCE - assert "INTERVAL '30 days'" in NORMALIZER_SOURCE - assert "RETENTION_INTERVAL_SECONDS" in NORMALIZER_SOURCE - assert "ORDER BY observed_at LIMIT %s" in NORMALIZER_SOURCE - assert "statement_timeout = '2s'" in NORMALIZER_SOURCE - assert "samples.tableoid = expired.tableoid" in NORMALIZER_SOURCE - assert "target=_retention_loop" in NORMALIZER_SOURCE - callback = NORMALIZER_SOURCE.split(" def on_message(", 1)[1] - assert "DELETE FROM" not in callback - - -def test_telegraf_network_recovery_and_database_memory_are_bounded() -> None: +def test_telegraf_network_recovery_and_no_persistent_storage() -> None: compose = yaml.safe_load(COMPOSE_PATH.read_text()) - assert "shared_buffers=128MB" in compose["services"]["timescale"]["command"] + assert set(compose["services"]) == {"broker", "normalizer"} + assert not compose.get("volumes") + broker = compose["services"]["broker"] + assert any(mount.startswith("/mosquitto/data:") for mount in broker["tmpfs"]) + assert any(mount.startswith("/mosquitto/log:") for mount in broker["tmpfs"]) + config = (COMPOSE_PATH.parent / "mosquitto/mosquitto.conf").read_text() + assert "persistence false" in config and "retain_available false" in config + assert "max_queued_bytes 1048576" in config + assert "MISSIONCORE_DATABASE_DSN" not in compose["services"]["normalizer"]["environment"] + for service in compose["services"].values(): + assert service["logging"]["options"] == {"max-size": "5m", "max-file": "2"} for platform, outputs in (("windows", 2), ("linux", 1)): - template = (REPOSITORY_ROOT / "deploy/telemetry-plane/telegraf" / - f"mission-core-{platform}.conf.tmpl").read_text() + template = ( + REPOSITORY_ROOT + / "deploy/telemetry-plane/telegraf" + / f"mission-core-{platform}.conf.tmpl" + ).read_text() assert template.count('startup_error_behavior = "retry"') == outputs assert "metric_buffer_limit = 2000" in template @@ -247,10 +237,7 @@ def test_normalizer_rejects_oversized_payload_and_series_identity() -> None: "name": "cpu", "tags": { "node_id": "DESKTOP-OPJ8J04", - **{ - f"tag-{index}": str(index) - for index in range(normalizer.MAX_TAGS + 1) - }, + **{f"tag-{index}": str(index) for index in range(normalizer.MAX_TAGS + 1)}, }, "fields": {"usage_active": 12.5}, "timestamp": 1_785_179_600, @@ -291,14 +278,9 @@ def test_telemetry_plane_uses_the_ndc_docker_namespace() -> None: assert document["name"] == "ndc-mission-core-telemetry" services = document["services"] - assert { - service["container_name"] - for service in services.values() - } == { + assert {service["container_name"] for service in services.values()} == { "ndc-mission-core-mqtt-broker", - "ndc-mission-core-telemetry-bootstrap", "ndc-mission-core-telemetry-normalizer", - "ndc-mission-core-telemetry-timescaledb", } for service in services.values(): assert service["container_name"].startswith("ndc-") @@ -308,10 +290,117 @@ def test_telemetry_plane_uses_the_ndc_docker_namespace() -> None: assert services["broker"]["cap_drop"] == ["ALL"] assert set(services["broker"]["cap_add"]) == {"CHOWN", "SETGID", "SETUID"} assert document["networks"]["default"]["name"] == "ndc-mission-core-telemetry" - assert { - volume["name"] - for volume in document["volumes"].values() - } == { - "ndc-mission-core-mqtt-data", - "ndc-mission-core-telemetry-timescale-data", - } + assert not document.get("volumes") + + +def _cache_fixture(**limits): + from datetime import timedelta + + normalizer = _normalizer() + clock = [datetime(2026, 10, 8, 12, tzinfo=UTC)] + cache = normalizer.LatestTelemetry(clock=lambda: clock[0], **limits) + + def row(*, seconds=0, agent="worker-006", series="total", fields=None): + return normalizer._normalize( + f"mission-core/v1/contours/worker-006/agents/{agent}/host", + json.dumps( + { + "name": "cpu", + "tags": {"node_id": "test-node", "cpu": series}, + "fields": fields or {"usage_active": 12.5}, + "timestamp": (clock[0] + timedelta(seconds=seconds)).timestamp(), + } + ).encode(), + ) + + return cache, clock, row + + +def test_latest_cache_replaces_history_and_merges_only_same_timestamp(): + cache, clock, row = _cache_fixture() + from datetime import timedelta + + assert cache.put(row(fields={"a": 1})) + assert cache.put(row(fields={"b": 2})) + assert cache.latest("worker-006", "worker-006", 30)[0]["payload"]["fields"] == {"a": 1, "b": 2} + clock[0] += timedelta(seconds=2) + assert cache.put(row(fields={"a": 3})) + assert not cache.put(row(seconds=-1, fields={"a": 0})) + assert cache.latest("worker-006", "worker-006", 30)[0]["payload"]["fields"] == {"a": 3} + assert cache.snapshot()["samples"] == 1 + + +def test_cache_freshness_expiry_and_daily_reset_without_new_input(): + from datetime import timedelta + + cache, clock, row = _cache_fixture() + assert not cache.put(row(seconds=-301)) + assert not cache.put(row(seconds=31)) + assert cache.put(row()) + clock[0] += timedelta(seconds=31) + assert cache.latest("worker-006", "worker-006", 30) == [] + assert cache.snapshot()["samples"] == 1 + clock[0] += timedelta(seconds=275) + cache.maintenance() + assert cache.snapshot()["samples"] == 0 + assert cache.snapshot()["accounted_bytes"] == 0 + clock[0] = clock[0].replace(hour=23, minute=59, second=59) + assert cache.put(row()) + clock[0] += timedelta(seconds=2) + cache.maintenance() + assert cache.snapshot()["samples"] == 0 + assert cache.snapshot()["daily_resets"] == 1 + assert cache.snapshot()["accounted_bytes"] == 0 + + +def test_cache_bounds_agent_cardinality_total_and_bytes(): + cache, clock, row = _cache_fixture(max_samples=4, max_agent_samples=2) + for n in range(3): + assert cache.put(row(series=str(n))) + assert cache.snapshot()["samples"] == 2 + for n in range(3): + assert cache.put(row(agent=f"worker-{n}", series="x")) + assert cache.snapshot()["samples"] == 4 + assert cache.snapshot()["evictions"] == 2 + assert cache.latest("worker-006", "unrelated-agent", 30) == [] + small, _, small_row = _cache_fixture(max_bytes=1600) + assert small.put(small_row()) + assert not small.put(small_row(fields={"big": "x" * 2000})) + assert small.snapshot()["samples"] == 1 # Oversize must not erase the good value. + for n in range(4): + assert small.put(small_row(series=str(n))) + assert small.snapshot()["accounted_bytes"] <= 1600 + assert small.snapshot()["evictions"] >= 3 + + +def test_normalizer_http_contract_and_no_history_after_restart(): + from threading import Thread + from urllib.request import urlopen + + normalizer = _normalizer() + cache, _, row = _cache_fixture() + cache.put(row()) + health = normalizer.TelemetryRuntimeHealth() + health.set_mqtt(True) + server = normalizer.TelemetryQueryServer(("127.0.0.1", 0), cache, health) + thread = Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + base = f"http://127.0.0.1:{server.server_port}" + with urlopen(base + "/health") as response: + doc = json.load(response) + assert doc["ok"] and doc["storage_ready"] + assert doc["storage"]["backend"] == "memory" + assert doc["storage"]["persistent_history"] is False + with urlopen( + base + "/v1/contours/worker-006/agents/worker-006/latest?max_age_seconds=30" + ) as response: + doc = json.load(response) + assert doc["schema_version"] == "missioncore.telemetry-query/v1" + assert len(doc["samples"]) == 1 + assert doc["samples"][0]["payload"]["fields"]["usage_active"] == 12.5 + assert normalizer.LatestTelemetry().snapshot()["samples"] == 0 + finally: + server.shutdown() + server.server_close() + thread.join(timeout=2) diff --git a/tests/test_telemetry_plane_prepare.py b/tests/test_telemetry_plane_prepare.py index da9e4b30..0f2df8a7 100644 --- a/tests/test_telemetry_plane_prepare.py +++ b/tests/test_telemetry_plane_prepare.py @@ -12,12 +12,7 @@ import pytest def _prepare_module() -> ModuleType: - path = ( - Path(__file__).resolve().parents[1] - / "deploy" - / "telemetry-plane" - / "prepare.py" - ) + path = Path(__file__).resolve().parents[1] / "deploy" / "telemetry-plane" / "prepare.py" specification = importlib.util.spec_from_file_location( "mission_core_telemetry_prepare", path, @@ -48,8 +43,6 @@ def _write_environment(path: Path) -> None: path.write_text( "MISSIONCORE_MQTT_BIND_ADDRESS=192.168.68.52\n" "MISSIONCORE_MQTT_PORT=1883\n" - "MISSIONCORE_DB_PASSWORD=db-secret\n" - "MISSIONCORE_DB_INGEST_PASSWORD=db-ingest-secret\n" "MISSIONCORE_MQTT_INGEST_USER=missioncore-ingest\n" "MISSIONCORE_MQTT_INGEST_PASSWORD=mqtt-ingest-secret\n", encoding="utf-8", @@ -65,16 +58,14 @@ def test_initialize_environment_generates_only_plane_secrets( prepare._initialize_environment("192.0.2.15") values = dict( - line.split("=", 1) - for line in prepare.ENV_PATH.read_text(encoding="utf-8").splitlines() + line.split("=", 1) for line in prepare.ENV_PATH.read_text(encoding="utf-8").splitlines() ) assert values["MISSIONCORE_MQTT_BIND_ADDRESS"] == "192.0.2.15" generated = { - values["MISSIONCORE_DB_PASSWORD"], - values["MISSIONCORE_DB_INGEST_PASSWORD"], values["MISSIONCORE_MQTT_INGEST_PASSWORD"], } - assert len(generated) == 3 + assert len(generated) == 1 + assert not any(name.startswith("MISSIONCORE_DB_") for name in values) assert all(len(secret) >= 40 for secret in generated) assert not any("WORKER_006" in name for name in values) assert stat.S_IMODE(prepare.ENV_PATH.stat().st_mode) == 0o600 @@ -112,7 +103,7 @@ def test_migration_moves_legacy_worker_to_private_registry( prepare._migrate_environment() assert "MISSIONCORE_DB_PASSWORD=keep-me" in first_env - assert "MISSIONCORE_DB_INGEST_PASSWORD=" in first_env + assert "MISSIONCORE_DB_INGEST_PASSWORD=" not in first_env assert prepare.ENV_PATH.read_text(encoding="utf-8") == first_env assert prepare.AGENT_REGISTRY_PATH.read_bytes() == first_registry assert prepare._read_agent_registry() == ( diff --git a/tests/test_telemetry_startup.py b/tests/test_telemetry_startup.py index d2246ced..8afc21d3 100644 --- a/tests/test_telemetry_startup.py +++ b/tests/test_telemetry_startup.py @@ -132,7 +132,7 @@ def test_old_lan_binding_is_reconciled_even_when_receiver_healthy(monkeypatch, t monkeypatch.setattr(manager, "command", run) assert manager.reconcile(tmp_path) == "ready" - assert calls[-1][-3:] == ["broker", "timescale", "normalizer"] + assert calls[-1][-2:] == ["broker", "normalizer"] assert "--no-build" in calls[-1] and "--pull" in calls[-1] and "never" in calls[-1] @@ -144,3 +144,24 @@ def test_failed_compose_reports_waiting_without_ready(monkeypatch, tmp_path): lambda args, timeout: subprocess.CompletedProcess(args, int("up" in args)), ) assert manager.reconcile(tmp_path) == "waiting-for-receiver" + + +def test_readiness_accepts_memory_receiver_and_rejects_retired_database(monkeypatch): + import io + + documents = [ + {"ok": True, "mqtt_connected": True, "database_reachable": True}, + { + "ok": True, + "mqtt_connected": True, + "storage_ready": True, + "storage": {"backend": "memory"}, + }, + ] + monkeypatch.setattr( + manager.urllib.request, + "urlopen", + lambda *args, **kwargs: io.BytesIO(json.dumps(documents.pop(0)).encode()), + ) + assert not manager.receiver_ready() + assert manager.receiver_ready()