feat(worker): supervise VPN connections and recover batched telemetry

This commit is contained in:
DCCONSTRUCTIONS
2026-11-10 01:10:37 +03:00
parent fe5900ff3b
commit ad5a929e06
46 changed files with 2996 additions and 640 deletions
+17
View File
@@ -241,3 +241,20 @@ See [the measured recovery audit](../../docs/audits/2026-09-25-worker-telemetry-
for exact acceptance, remaining cold-boot/clean-host gates and bounded test
entrypoints. The earlier LAN workflow remains a legacy explicit configuration;
it is not the current Worker 006 transport.
## MQTT batching — 2026-11-09
The Windows and Linux templates publish topic batches (`layout="batch"`). The
normalizer accepts both legacy single samples and Telegraf `{"metrics":[...]}`
messages, bounded to 512 samples and 1 MiB. Each metric keeps its original source
time; batching does not renew stale samples or change ACL/freshness rules.
Deploy the compatible normalizer before switching existing agents. A narrow
managed-Windows migration is `telegraf/Enable-NdcMissionCoreTelemetryBatch.ps1`;
its configuration backup and rollback preserve existing service credentials.
This avoids one synchronous QoS 1 round trip per metric on high-latency links.
The Worker 006 controlled benchmark and remaining real-LTE acceptance are recorded
in [Worker connections](../../docs/WORKER_CONNECTIONS.md). The current registry
owns all four channel supervisors; the older telemetry startup tool refuses to
replace a registry-managed tunnel.
@@ -29,6 +29,7 @@ PIPELINE_EVENT_MEASUREMENT: Final = "missioncore_pipeline_event"
QUERY_SCHEMA: Final = "missioncore.telemetry-query/v1"
SAFE_IDENTIFIER: Final = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$")
MAX_PAYLOAD_BYTES: Final = 1024 * 1024
MAX_MESSAGE_METRICS: Final = 512
MAX_TAGS: Final = 256
MAX_SERIES_KEY_BYTES: Final = 4096
LATEST_TTL_SECONDS: Final = 300
@@ -218,6 +219,28 @@ def _normalize(topic: str, payload: bytes) -> tuple[object, ...]:
)
def normalize_message(topic: str, payload: bytes) -> list[tuple]:
"""Accept both original single samples and Telegraf's topic batch envelope.
Validate the complete bounded message before admitting any of its samples.
Every sample retains its own source timestamp and series identity.
"""
if len(payload) > MAX_PAYLOAD_BYTES:
raise ValueError("telemetry message is too large")
document = json.loads(payload)
if not isinstance(document, dict) or "metrics" not in document:
return [_normalize(topic, payload)]
metrics = document["metrics"]
if (
set(document) != {"metrics"}
or not isinstance(metrics, list)
or not 1 <= len(metrics) <= MAX_MESSAGE_METRICS
or any(not isinstance(metric, dict) or "metrics" in metric for metric in metrics)
):
raise ValueError("invalid telemetry batch")
return [_normalize(topic, json.dumps(metric).encode("utf-8")) for metric in metrics]
class LatestTelemetry:
"""Bounded volatile latest-value cache; never a time-series archive."""
@@ -516,9 +539,9 @@ def main() -> None:
def on_message(_client, _userdata, message):
try:
row = _normalize(message.topic, message.payload)
if cache.put(row):
runtime_health.mark_ingested()
for row in normalize_message(message.topic, message.payload):
if cache.put(row):
runtime_health.mark_ingested()
except (ValueError, UnicodeDecodeError, TypeError, OverflowError):
# Never log rejected payloads or emit an unbounded line per bad sample.
return
@@ -0,0 +1,58 @@
[CmdletBinding()]
param([Parameter(Mandatory=$true)][string]$ExpectedNodeId)
# Narrow migration for existing managed agents; fresh installs use the templates.
$ErrorActionPreference='Stop'
$ProgressPreference='SilentlyContinue'
if ($env:COMPUTERNAME -cne $ExpectedNodeId) { throw 'Worker identity mismatch' }
$root='C:\ProgramData\NDC\MissionCore\telemetry-agent'
$config=Join-Path $root 'telegraf.conf'
$exe='C:\Program Files\NDC\Mission Core\Telegraf\telegraf.exe'
$service=Get-CimInstance Win32_Service -Filter "Name='telegraf'"
if (-not $service -or $service.PathName -notlike '*NDC\Mission Core\Telegraf\telegraf.exe*') { throw 'Managed agent required' }
if ($service.State -ne 'Running') { throw 'Running baseline required' }
if ((Get-Item $config -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Regular managed configuration required' }
$before=[IO.File]::ReadAllText($config)
$blocks=[regex]::Matches($before,'(?ms)^\[\[outputs\.mqtt\]\].*?(?=^\[\[|\z)')
if ($blocks.Count -ne 2) { throw 'Expected separate host and pipeline outputs' }
$after=$before
foreach ($block in $blocks) {
if ($block.Value -match '(?m)^\s*layout\s*=') {
if ($block.Value -notmatch '(?m)^\s*layout\s*=\s*"batch"\s*$') { throw 'Unexpected existing MQTT layout' }
continue
}
$after=$after.Replace($block.Value, $block.Value.Replace('[[outputs.mqtt]]', "[[outputs.mqtt]]`n layout = `"batch`""))
}
if ($after -eq $before) { @{changed=$false;mode='batch'} | ConvertTo-Json -Compress;exit 0 }
$baselineHash=(Get-FileHash $config -Algorithm SHA256).Hash
$scratch=Join-Path $root ('batch-update-'+[Guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory $scratch | Out-Null
$candidate=Join-Path $scratch 'telegraf.conf'
$backup=Join-Path $root ('telegraf-before-batch-'+$baselineHash.Substring(0,12)+'.conf')
$changed=$false
try {
foreach ($entry in (Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Services\telegraf').Environment) {
$name,$value=$entry -split '=',2
if ($name) { Set-Item "Env:$name" $value }
}
[IO.File]::WriteAllText($candidate,$after,[Text.UTF8Encoding]::new($false))
$probe=Start-Process $exe -ArgumentList @('--config',('"'+$candidate+'"'),'--test') -PassThru -NoNewWindow -RedirectStandardOutput (Join-Path $scratch 'out.log') -RedirectStandardError (Join-Path $scratch 'error.log')
$probeHandle=$probe.Handle
if (-not $probe.WaitForExit(30000)) { $probe.Kill();throw 'Agent validation timed out' }
if ($probe.ExitCode -ne 0) { throw 'Agent configuration validation failed' }
if ((Get-FileHash $config -Algorithm SHA256).Hash -ne $baselineHash) { throw 'Configuration changed during validation' }
if (-not (Test-Path $backup)) { Copy-Item $config $backup }
Stop-Service telegraf
(Get-Service telegraf).WaitForStatus([ServiceProcess.ServiceControllerStatus]::Stopped,[TimeSpan]::FromSeconds(20))
$changed=$true
Copy-Item $candidate $config -Force
Start-Service telegraf
(Get-Service telegraf).WaitForStatus([ServiceProcess.ServiceControllerStatus]::Running,[TimeSpan]::FromSeconds(20))
@{changed=$true;mode='batch';backup=$backup;sha256=(Get-FileHash $config -Algorithm SHA256).Hash}|ConvertTo-Json -Compress
} catch {
if ($changed) {
Stop-Service telegraf -ErrorAction SilentlyContinue
Copy-Item $backup $config -Force
}
if ((Get-Service telegraf).Status -eq 'Stopped') { Start-Service telegraf }
throw
} finally { Remove-Item $scratch -Recurse -Force }
@@ -29,6 +29,7 @@
total = true
[[outputs.mqtt]]
layout = "batch"
startup_error_behavior = "retry"
servers = ["tcp://${MISSIONCORE_MQTT_HOST}:${MISSIONCORE_MQTT_PORT}"]
topic = "mission-core/v1/contours/${MISSIONCORE_CONTOUR_ID}/agents/${MISSIONCORE_AGENT_ID}/host"
@@ -80,6 +80,7 @@
data_type = "string"
[[outputs.mqtt]]
layout = "batch"
startup_error_behavior = "retry"
servers = ["tcp://${MISSIONCORE_MQTT_HOST}:${MISSIONCORE_MQTT_PORT}"]
topic = "mission-core/v1/contours/${MISSIONCORE_CONTOUR_ID}/agents/${MISSIONCORE_AGENT_ID}/host"
@@ -91,6 +92,7 @@
namedrop = ["missioncore_pipeline", "missioncore_pipeline_event"]
[[outputs.mqtt]]
layout = "batch"
startup_error_behavior = "retry"
servers = ["tcp://${MISSIONCORE_MQTT_HOST}:${MISSIONCORE_MQTT_PORT}"]
topic = "mission-core/v1/contours/${MISSIONCORE_CONTOUR_ID}/agents/${MISSIONCORE_AGENT_ID}/pipeline"