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