A LAPI range decision (e.g. 195.178.110.0/24) inserted into an nft set without the interval flag is stored as its bare network address. The string diff saw that as one missing and one extra entry, and every heal re-added the same address, so nodes stuck in DESYNC_DETECTED with the flap guard suppressing repeat heals. Pair such ranges with their network address, report them as unenforceable_ranges with a dedicated warning, and keep them out of the drift counts and fingerprint. The reporter records unenforceable_range_count and shows DEGRADED for a node that is otherwise in sync. Desync log lines now name the missing and extra values. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
277 lines
9.8 KiB
Python
277 lines
9.8 KiB
Python
# threat_engine_agent/reporter.py
|
|
|
|
import json
|
|
import os
|
|
import logging
|
|
import time
|
|
from datetime import datetime, timezone
|
|
|
|
class LocalStateReporter:
|
|
"""
|
|
Manages the health manifest on Triton.
|
|
Acts as the 'Black Box' recorder for Argus to query.
|
|
"""
|
|
def __init__(
|
|
self,
|
|
state_file="/root/threat-engine-agent/threat-agent-state.json",
|
|
node_name="unknown",
|
|
):
|
|
self.state_file = state_file
|
|
self.node_name = node_name
|
|
self.started_at_epoch = time.time()
|
|
# Ensure the directory is writable
|
|
os.makedirs(os.path.dirname(os.path.abspath(self.state_file)), exist_ok=True)
|
|
|
|
def _load_previous_state(self):
|
|
try:
|
|
with open(self.state_file, "r") as f:
|
|
data = json.load(f)
|
|
return data if isinstance(data, dict) else {}
|
|
except Exception:
|
|
return {}
|
|
|
|
def _get_int(self, payload, key, default=0):
|
|
try:
|
|
return int(payload.get(key, default))
|
|
except Exception:
|
|
return default
|
|
|
|
def _normalize_hourly_buckets(self, previous):
|
|
raw = previous.get("_rolling_24h_buckets", previous.get("rolling_24h_buckets", {}))
|
|
if not isinstance(raw, dict):
|
|
return {}
|
|
|
|
normalized = {}
|
|
for hour_key, metrics in raw.items():
|
|
try:
|
|
hour = int(hour_key)
|
|
except Exception:
|
|
continue
|
|
if not isinstance(metrics, dict):
|
|
continue
|
|
normalized[str(hour)] = {
|
|
"drift_events": max(0, int(metrics.get("drift_events", 0))),
|
|
"drift_heal_attempts": max(0, int(metrics.get("drift_heal_attempts", 0))),
|
|
"heals": max(0, int(metrics.get("heals", 0))),
|
|
"heal_failures": max(0, int(metrics.get("heal_failures", 0))),
|
|
"heals_suppressed": max(0, int(metrics.get("heals_suppressed", 0))),
|
|
}
|
|
return normalized
|
|
|
|
def _roll_24h_counters(
|
|
self,
|
|
previous,
|
|
now_epoch,
|
|
drift_events_increment,
|
|
heal_result,
|
|
heal_suppressed=False,
|
|
):
|
|
current_hour = int(now_epoch // 3600)
|
|
min_hour = current_hour - 23
|
|
buckets = self._normalize_hourly_buckets(previous)
|
|
|
|
# Prune data outside rolling 24-hour window.
|
|
buckets = {
|
|
hour_key: metrics
|
|
for hour_key, metrics in buckets.items()
|
|
if int(hour_key) >= min_hour
|
|
}
|
|
|
|
hour_key = str(current_hour)
|
|
bucket = buckets.setdefault(
|
|
hour_key,
|
|
{
|
|
"drift_events": 0,
|
|
"drift_heal_attempts": 0,
|
|
"heals": 0,
|
|
"heal_failures": 0,
|
|
"heals_suppressed": 0,
|
|
},
|
|
)
|
|
|
|
bucket["drift_events"] += max(0, int(drift_events_increment))
|
|
if heal_result is not None:
|
|
bucket["drift_heal_attempts"] += 1
|
|
bucket["heals"] += 1
|
|
if heal_result != "success":
|
|
bucket["heal_failures"] += 1
|
|
if heal_suppressed:
|
|
bucket["heals_suppressed"] += 1
|
|
|
|
drift_events_24h = sum(v["drift_events"] for v in buckets.values())
|
|
drift_heal_attempts_24h = sum(v["drift_heal_attempts"] for v in buckets.values())
|
|
heals_24h = sum(v["heals"] for v in buckets.values())
|
|
heal_failures_24h = sum(v["heal_failures"] for v in buckets.values())
|
|
heals_suppressed_24h = sum(v["heals_suppressed"] for v in buckets.values())
|
|
|
|
return (
|
|
buckets,
|
|
drift_events_24h,
|
|
drift_heal_attempts_24h,
|
|
heals_24h,
|
|
heal_failures_24h,
|
|
heals_suppressed_24h,
|
|
)
|
|
|
|
def update_status(
|
|
self,
|
|
is_synced,
|
|
ban_count,
|
|
last_error=None,
|
|
missing_count=0,
|
|
extra_count=0,
|
|
metadata_drift_count=0,
|
|
last_drift_fingerprint="",
|
|
last_heal_result=None,
|
|
last_heal_timestamp=None,
|
|
checks_increment=0,
|
|
drift_events_increment=0,
|
|
heal_result=None,
|
|
heal_suppressed=False,
|
|
unenforceable_range_count=0,
|
|
):
|
|
"""
|
|
Writes the current health snapshot to a JSON file.
|
|
|
|
heal_suppressed marks a drift the heal gate skipped because the same drift was
|
|
healed moments ago, so every drift event is either a heal attempt or a suppressed heal.
|
|
|
|
unenforceable_range_count is the number of LAPI range decisions the kernel holds
|
|
only as a single address. They are not drift a heal can fix, so a node that is
|
|
otherwise in sync reports DEGRADED rather than HEALTHY.
|
|
"""
|
|
previous = self._load_previous_state()
|
|
effective_heal_result = (
|
|
last_heal_result
|
|
if last_heal_result is not None
|
|
else previous.get("last_heal_result")
|
|
)
|
|
effective_last_heal_timestamp = (
|
|
last_heal_timestamp
|
|
if last_heal_timestamp is not None
|
|
else previous.get("last_heal_timestamp")
|
|
)
|
|
if heal_result is not None:
|
|
effective_heal_result = heal_result
|
|
effective_last_heal_timestamp = (
|
|
last_heal_timestamp
|
|
if last_heal_timestamp is not None
|
|
else datetime.now(timezone.utc).isoformat()
|
|
)
|
|
|
|
now_epoch = time.time()
|
|
checks_total = max(0, self._get_int(previous, "checks_total", 0))
|
|
checks_total += max(0, int(checks_increment))
|
|
drift_events_total = max(0, self._get_int(previous, "drift_events_total", 0))
|
|
drift_events_total += max(0, int(drift_events_increment))
|
|
|
|
heals_total = max(0, self._get_int(previous, "heals_total", 0))
|
|
heal_failures_total = max(0, self._get_int(previous, "heal_failures_total", 0))
|
|
drift_heal_attempts_total = max(
|
|
0, self._get_int(previous, "drift_heal_attempts_total", 0)
|
|
)
|
|
if heal_result is not None:
|
|
heals_total += 1
|
|
drift_heal_attempts_total += 1
|
|
if heal_result != "success":
|
|
heal_failures_total += 1
|
|
heals_suppressed_total = max(0, self._get_int(previous, "heals_suppressed_total", 0))
|
|
if heal_suppressed:
|
|
heals_suppressed_total += 1
|
|
|
|
(
|
|
rolling_24h_buckets,
|
|
drift_events_24h,
|
|
drift_heal_attempts_24h,
|
|
heals_24h,
|
|
heal_failures_24h,
|
|
heals_suppressed_24h,
|
|
) = self._roll_24h_counters(
|
|
previous=previous,
|
|
now_epoch=now_epoch,
|
|
drift_events_increment=drift_events_increment,
|
|
heal_result=heal_result,
|
|
heal_suppressed=heal_suppressed,
|
|
)
|
|
|
|
uptime_seconds = max(0, int(now_epoch - self.started_at_epoch))
|
|
status_data = {
|
|
"node_name": self.node_name,
|
|
"last_check": datetime.now(timezone.utc).isoformat(),
|
|
"status": self._status_label(is_synced, unenforceable_range_count),
|
|
"is_synced": is_synced,
|
|
"kernel_ban_count": ban_count,
|
|
"last_error": last_error,
|
|
"missing_count": missing_count,
|
|
"extra_count": extra_count,
|
|
"metadata_drift_count": metadata_drift_count,
|
|
"unenforceable_range_count": unenforceable_range_count,
|
|
"last_drift_fingerprint": last_drift_fingerprint,
|
|
"last_heal_result": effective_heal_result,
|
|
"last_heal_timestamp": effective_last_heal_timestamp,
|
|
"uptime_seconds": uptime_seconds,
|
|
"checks_total": checks_total,
|
|
"drift_events_total": drift_events_total,
|
|
"drift_heal_attempts_total": drift_heal_attempts_total,
|
|
"drift_events_24h": drift_events_24h,
|
|
"drift_heal_attempts_24h": drift_heal_attempts_24h,
|
|
"heals_24h": heals_24h,
|
|
"heal_failures_24h": heal_failures_24h,
|
|
"heals_total": heals_total,
|
|
"heal_failures_total": heal_failures_total,
|
|
"heals_suppressed_24h": heals_suppressed_24h,
|
|
"heals_suppressed_total": heals_suppressed_total,
|
|
"_rolling_24h_buckets": rolling_24h_buckets,
|
|
}
|
|
|
|
try:
|
|
# Atomic write: Write to a temp file then rename to avoid corruption
|
|
temp_file = f"{self.state_file}.tmp"
|
|
with open(temp_file, 'w') as f:
|
|
json.dump(status_data, f, indent=4)
|
|
os.replace(temp_file, self.state_file)
|
|
except Exception as e:
|
|
logging.error(f"Reporter: Failed to write state file: {e}")
|
|
|
|
@staticmethod
|
|
def _status_label(is_synced, unenforceable_range_count):
|
|
if not is_synced:
|
|
return "DESYNC_DETECTED"
|
|
if unenforceable_range_count:
|
|
return "DEGRADED"
|
|
return "HEALTHY"
|
|
|
|
def get_history_file(self):
|
|
base, _ = os.path.splitext(self.state_file)
|
|
return f"{base}.history"
|
|
|
|
def log_heal_event(
|
|
self,
|
|
kernel_count,
|
|
missing_count,
|
|
extra_count,
|
|
metadata_drift_count,
|
|
drift_fingerprint,
|
|
reason,
|
|
heal_result,
|
|
post_drift_fingerprint,
|
|
):
|
|
"""
|
|
Records a specific healing event in a persistent history log.
|
|
"""
|
|
history_file = self.get_history_file()
|
|
timestamp = datetime.now(timezone.utc).isoformat()
|
|
|
|
try:
|
|
with open(history_file, 'a') as f:
|
|
f.write(
|
|
f"{timestamp} - HEAL: reason={reason} "
|
|
f"kernel={kernel_count} missing={missing_count} "
|
|
f"extra={extra_count} metadata={metadata_drift_count} "
|
|
f"drift_fingerprint={drift_fingerprint} "
|
|
f"heal_result={heal_result} "
|
|
f"post_drift_fingerprint={post_drift_fingerprint}\n"
|
|
)
|
|
except Exception as e:
|
|
logging.error(f"Reporter: Failed to write to history log: {e}")
|