feat(reporter): add rolling 24h drift/heal counters to state snapshot
This commit is contained in:
1 parent
8c7b0768b0
commit
469a30df6a
3 files changed
+121
-1
No files matched your search
@@ -32,6 +32,7 @@ The standard `crowdsec-firewall-bouncer` can occasionally experience "ghost" des
|
||||
- Persists structured heal history, including pre/post fingerprints and heal result.
|
||||
- Exposes lightweight node metrics in state (`uptime_seconds`, `checks_total`, `heals_total`, `heal_failures_total`).
|
||||
- Tracks drift activity counters (`drift_events_total`, `drift_heal_attempts_total`) for suppression/load visibility.
|
||||
- Exposes rolling 24h counters (`drift_events_24h`, `drift_heal_attempts_24h`, `heals_24h`, `heal_failures_24h`).
|
||||
- Default state path: `/root/threat-engine-agent/threat-agent-state.json`.
|
||||
|
||||
## 📂 Project Structure
|
||||
|
||||
+90
-1
@@ -36,6 +36,76 @@ class LocalStateReporter:
|
||||
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))),
|
||||
}
|
||||
return normalized
|
||||
|
||||
def _roll_24h_counters(
|
||||
self,
|
||||
previous,
|
||||
now_epoch,
|
||||
drift_events_increment,
|
||||
heal_result,
|
||||
):
|
||||
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,
|
||||
},
|
||||
)
|
||||
|
||||
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
|
||||
|
||||
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())
|
||||
|
||||
return (
|
||||
buckets,
|
||||
drift_events_24h,
|
||||
drift_heal_attempts_24h,
|
||||
heals_24h,
|
||||
heal_failures_24h,
|
||||
)
|
||||
|
||||
def update_status(
|
||||
self,
|
||||
is_synced,
|
||||
@@ -70,6 +140,7 @@ class LocalStateReporter:
|
||||
if effective_last_heal_timestamp is None:
|
||||
effective_last_heal_timestamp = datetime.now().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))
|
||||
@@ -86,7 +157,20 @@ class LocalStateReporter:
|
||||
if heal_result != "success":
|
||||
heal_failures_total += 1
|
||||
|
||||
uptime_seconds = max(0, int(time.time() - self.started_at_epoch))
|
||||
(
|
||||
rolling_24h_buckets,
|
||||
drift_events_24h,
|
||||
drift_heal_attempts_24h,
|
||||
heals_24h,
|
||||
heal_failures_24h,
|
||||
) = self._roll_24h_counters(
|
||||
previous=previous,
|
||||
now_epoch=now_epoch,
|
||||
drift_events_increment=drift_events_increment,
|
||||
heal_result=heal_result,
|
||||
)
|
||||
|
||||
uptime_seconds = max(0, int(now_epoch - self.started_at_epoch))
|
||||
status_data = {
|
||||
"node_name": self.node_name,
|
||||
"last_check": datetime.now().isoformat(),
|
||||
@@ -104,8 +188,13 @@ class LocalStateReporter:
|
||||
"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,
|
||||
"_rolling_24h_buckets": rolling_24h_buckets,
|
||||
}
|
||||
|
||||
try:
|
||||
|
||||
@@ -3,6 +3,7 @@ import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from datetime import datetime
|
||||
from unittest.mock import patch
|
||||
|
||||
from reporter import LocalStateReporter
|
||||
|
||||
@@ -79,6 +80,10 @@ class ReporterStateTests(unittest.TestCase):
|
||||
self.assertEqual(2, payload["checks_total"])
|
||||
self.assertEqual(1, payload["drift_events_total"])
|
||||
self.assertEqual(2, payload["drift_heal_attempts_total"])
|
||||
self.assertEqual(1, payload["drift_events_24h"])
|
||||
self.assertEqual(2, payload["drift_heal_attempts_24h"])
|
||||
self.assertEqual(2, payload["heals_24h"])
|
||||
self.assertEqual(1, payload["heal_failures_24h"])
|
||||
self.assertEqual(2, payload["heals_total"])
|
||||
self.assertEqual(1, payload["heal_failures_total"])
|
||||
self.assertEqual("success", payload["last_heal_result"])
|
||||
@@ -100,6 +105,31 @@ class ReporterStateTests(unittest.TestCase):
|
||||
|
||||
self.assertEqual(2, payload["drift_events_total"])
|
||||
self.assertEqual(1, payload["drift_heal_attempts_total"])
|
||||
self.assertEqual(2, payload["drift_events_24h"])
|
||||
self.assertEqual(1, payload["drift_heal_attempts_24h"])
|
||||
|
||||
@patch("reporter.time.time")
|
||||
def test_update_status_rolls_24h_window(self, time_mock):
|
||||
with tempfile.TemporaryDirectory() as tmp_dir:
|
||||
state_file = os.path.join(tmp_dir, "state.json")
|
||||
reporter = LocalStateReporter(state_file=state_file, node_name="n1")
|
||||
reporter.started_at_epoch = 0
|
||||
|
||||
# Initial write at hour 1000.
|
||||
time_mock.return_value = 1000 * 3600
|
||||
reporter.update_status(False, 1, drift_events_increment=1, heal_result="failed")
|
||||
|
||||
# New write 25 hours later; previous hour should be pruned from 24h view.
|
||||
time_mock.return_value = (1000 + 25) * 3600
|
||||
reporter.update_status(True, 1, checks_increment=1)
|
||||
|
||||
with open(state_file, "r") as f:
|
||||
payload = json.load(f)
|
||||
|
||||
self.assertEqual(0, payload["drift_events_24h"])
|
||||
self.assertEqual(0, payload["drift_heal_attempts_24h"])
|
||||
self.assertEqual(0, payload["heals_24h"])
|
||||
self.assertEqual(0, payload["heal_failures_24h"])
|
||||
|
||||
def test_update_status_preserves_last_heal_timestamp_when_no_new_heal(self):
|
||||
with tempfile.TemporaryDirectory() as tmp_dir:
|
||||
|
||||
Reference in new issue
Block a user