Keep operator telemetry live-only with bounded volatile state
This commit is contained in:
@@ -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)
|
||||
|
||||
@@ -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() == (
|
||||
|
||||
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user