косметический коммит
This commit is contained in:
parent
5d4fa901a5
commit
3f3cdab741
23
README.md
23
README.md
|
|
@ -3,6 +3,7 @@
|
|||
Легковесный Linux-агент для сбора событий, нормализации, хранения в памяти, обработки команд и отправки исходящих сообщений.
|
||||
|
||||
Проект ориентирован на системный запуск под Linux и использует:
|
||||
|
||||
- collectors для источников событий;
|
||||
- единый канонический формат `EventEnvelope` на protobuf v1;
|
||||
- bounded in-memory cache и outbox;
|
||||
|
|
@ -33,7 +34,12 @@
|
|||
### Установка
|
||||
|
||||
```bash
|
||||
# Для сборки systemd-python необходимы dev-пакеты Linux
|
||||
sudo apt-get install -y libsystemd-dev pkg-config python3-dev build-essential
|
||||
cd /opt/wf-agent2
|
||||
source .venv/bin/activate
|
||||
python -m pip install -e .
|
||||
python -m pip install systemd-python dbus-next
|
||||
```
|
||||
|
||||
### Проверка конфигурации
|
||||
|
|
@ -121,6 +127,7 @@ Sender loops
|
|||
Collectors отвечают за источник данных и lifecycle соединения.
|
||||
|
||||
Общие обязанности:
|
||||
|
||||
- `start()` / `stop()`;
|
||||
- `health()` / `stats()`;
|
||||
- reconnect и recovery;
|
||||
|
|
@ -128,6 +135,7 @@ Collectors отвечают за источник данных и lifecycle со
|
|||
- отправка нормализованного `EventEnvelope` в `Director`.
|
||||
|
||||
Реализованные collectors:
|
||||
|
||||
- `JournalCollector` - systemd journal;
|
||||
- `DbusCollector` - D-Bus сигналы;
|
||||
- `WpaCtrlCollector` - `wpa_supplicant` `ctrl_iface`;
|
||||
|
|
@ -138,23 +146,28 @@ Collectors отвечают за источник данных и lifecycle со
|
|||
Pipeline одинаков по смыслу для всех collectors.
|
||||
|
||||
1. Prefilter
|
||||
|
||||
- ранний отсев шума;
|
||||
- минимизация нагрузки на CPU и память.
|
||||
|
||||
2. Validation
|
||||
|
||||
- проверка структуры сырого события;
|
||||
- reject или downgrade malformed records.
|
||||
|
||||
3. Normalization
|
||||
|
||||
- перевод в канонический `EventEnvelope`;
|
||||
- заполнение hot fields и source-specific payload.
|
||||
|
||||
4. Marking
|
||||
|
||||
- добавление workflow tags, labels, routing hints, severity overrides.
|
||||
|
||||
### Director
|
||||
|
||||
`Director` решает, куда попадёт canonical event:
|
||||
|
||||
- в cache;
|
||||
- в outbox;
|
||||
- в derivator-interest path.
|
||||
|
|
@ -164,11 +177,13 @@ Pipeline одинаков по смыслу для всех collectors.
|
|||
### Cache
|
||||
|
||||
Cache состоит из:
|
||||
|
||||
- bounded ring buffer;
|
||||
- payload store;
|
||||
- secondary indexes.
|
||||
|
||||
Индексы строятся по:
|
||||
|
||||
- interface;
|
||||
- event type;
|
||||
- source kind;
|
||||
|
|
@ -199,6 +214,7 @@ CLI / Scheduler / Derivator
|
|||
Executors выполняют control actions, а не ingestion.
|
||||
|
||||
Реализованные executors:
|
||||
|
||||
- `WpaCtrlExecutor` - команды для `wpa_supplicant`;
|
||||
- `SystemExecutor` - системные действия, например `system.set_regdomain`.
|
||||
|
||||
|
|
@ -223,11 +239,13 @@ Sender управляет тем, когда и как outbox draining прои
|
|||
Transport отвечает за физическую доставку.
|
||||
|
||||
Поддержаны sender modes:
|
||||
|
||||
- `none`
|
||||
- `strict_priority`
|
||||
- `buffered`
|
||||
|
||||
Поддержаны transports:
|
||||
|
||||
- `drop`
|
||||
- `webhook`
|
||||
|
||||
|
|
@ -282,6 +300,7 @@ WEBHOOK_TOKEN=secret-token
|
|||
### TOML
|
||||
|
||||
Главные секции:
|
||||
|
||||
- `[agent]` - общие параметры;
|
||||
- `[cache]` - размер ring buffer и payload arena;
|
||||
- `[outbox]` - bounded queue;
|
||||
|
|
@ -364,6 +383,7 @@ WantedBy=multi-user.target
|
|||
#### JournalCollector
|
||||
|
||||
Нужен доступ к systemd journal:
|
||||
|
||||
- обычно через группу `systemd-journal`;
|
||||
- либо запуск от root;
|
||||
- либо через policy, если используется более строгая модель доступа.
|
||||
|
|
@ -376,6 +396,7 @@ WantedBy=multi-user.target
|
|||
|
||||
Нужен доступ к unix socket `wpa_supplicant ctrl_iface`.
|
||||
Часто это означает:
|
||||
|
||||
- принадлежность к `netdev` или специальной группе;
|
||||
- корректные права на socket directory;
|
||||
- иногда запуск от root, если локальная политика ограничивает доступ.
|
||||
|
|
@ -384,6 +405,7 @@ WantedBy=multi-user.target
|
|||
|
||||
Команды вроде `system.set_regdomain` обычно требуют привилегий уровня root или `CAP_NET_ADMIN`.
|
||||
Для production лучше использовать либо:
|
||||
|
||||
- отдельный privileged service;
|
||||
- либо минимальный sudo/polkit policy на конкретное действие.
|
||||
|
||||
|
|
@ -467,6 +489,7 @@ python -m compileall src tests
|
|||
## Состояние проекта
|
||||
|
||||
Проект уже содержит:
|
||||
|
||||
- collectors, pipeline и supervisor;
|
||||
- cache core и outbox;
|
||||
- command model, policy, queue и coordinator;
|
||||
|
|
|
|||
|
|
@ -2,6 +2,9 @@
|
|||
name = "wf-agent2"
|
||||
log_level = "INFO"
|
||||
|
||||
[control]
|
||||
socket_path = "/run/wf-agent2/control.sock"
|
||||
|
||||
[cache]
|
||||
capacity_events = 50000
|
||||
payload_arena_bytes = 67108864
|
||||
|
|
@ -52,7 +55,7 @@ auth_mode = "none"
|
|||
token = ""
|
||||
|
||||
[executors.wpa_ctrl]
|
||||
enabled = false
|
||||
enabled = true
|
||||
interface = "wlp3s0"
|
||||
ctrl_path = "/run/wpa_supplicant"
|
||||
source_name = "wpa-ctrl://wlp3s0"
|
||||
|
|
@ -71,7 +74,7 @@ source_kind = "journal"
|
|||
profile = "system"
|
||||
|
||||
[[collectors.journal.filters]]
|
||||
name = "wpa-supplicant"
|
||||
name = "wpa_supplicant"
|
||||
field = "_SYSTEMD_UNIT"
|
||||
op = "in"
|
||||
value = ["wpa_supplicant.service", "NetworkManager.service"]
|
||||
|
|
|
|||
451
src/agent/app.py
451
src/agent/app.py
|
|
@ -2,26 +2,54 @@
|
|||
|
||||
from __future__ import annotations
|
||||
|
||||
import signal
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any, Mapping
|
||||
|
||||
from .core.clock import now_mono_ns
|
||||
|
||||
from .cache import CacheAPI, build_default_cache
|
||||
from .cache.snapshot import CacheSnapshot
|
||||
from .collectors import CollectorSupervisor
|
||||
from .collectors import (
|
||||
CollectorSupervisor,
|
||||
DbusCollector,
|
||||
JournalCollector,
|
||||
NavigationCollector,
|
||||
WpaCtrlCollector,
|
||||
)
|
||||
from .commands import CommandCoordinator, CommandRequest, CommandSubmissionResult
|
||||
from .commands.models import CommandOriginKind, CommandTargetKind
|
||||
from .control import ControlDispatcher, ControlServer, ControlService
|
||||
from .core.clock import now_mono_ns
|
||||
from .core.enums import SourceKind
|
||||
from .derivator import DerivatorPollResult, DerivatorWorker, WifiScanSummaryWorkflow, WifiScanSummaryWorkflowConfig
|
||||
from .derivator import (
|
||||
DerivatorPollResult,
|
||||
DerivatorWorker,
|
||||
WifiScanSummaryWorkflow,
|
||||
WifiScanSummaryWorkflowConfig,
|
||||
)
|
||||
from .executors import ExecutorRouter, SystemExecutor, WpaCtrlExecutor
|
||||
from .scheduler import Scheduler, SchedulerJob, SchedulerJobKind, SchedulerRegistry, SchedulerState, SchedulerStats
|
||||
from .sender import DropTransport, OutboxQueue, SenderLoopBase, SenderLoopResult, SenderRuntimeConfig, TransportResult, WebhookTransport, build_sender_loop
|
||||
from .scheduler import (
|
||||
Scheduler,
|
||||
SchedulerJob,
|
||||
SchedulerJobKind,
|
||||
SchedulerRegistry,
|
||||
SchedulerState,
|
||||
SchedulerStats,
|
||||
)
|
||||
from .sender import (
|
||||
DropTransport,
|
||||
OutboxQueue,
|
||||
SenderLoopBase,
|
||||
SenderLoopResult,
|
||||
SenderRuntimeConfig,
|
||||
TransportResult,
|
||||
WebhookTransport,
|
||||
build_sender_loop,
|
||||
)
|
||||
from .sender.sender_types import SenderType, TransportType
|
||||
from .settings import Settings, load_settings
|
||||
|
||||
|
||||
DEFAULT_CACHE_CAPACITY_EVENTS = 50_000
|
||||
DEFAULT_CACHE_PAYLOAD_BYTES = 64 * 1024 * 1024
|
||||
DEFAULT_OUTBOX_CAPACITY_ITEMS = 5_000
|
||||
|
|
@ -33,8 +61,14 @@ def _build_cache(settings: Settings) -> CacheAPI:
|
|||
cache_section = settings.config.get("cache", {})
|
||||
if not isinstance(cache_section, dict):
|
||||
cache_section = {}
|
||||
ring_capacity = int(cache_section.get("capacity_events", DEFAULT_CACHE_CAPACITY_EVENTS) or DEFAULT_CACHE_CAPACITY_EVENTS)
|
||||
payload_capacity_bytes = int(cache_section.get("payload_arena_bytes", DEFAULT_CACHE_PAYLOAD_BYTES) or DEFAULT_CACHE_PAYLOAD_BYTES)
|
||||
ring_capacity = int(
|
||||
cache_section.get("capacity_events", DEFAULT_CACHE_CAPACITY_EVENTS)
|
||||
or DEFAULT_CACHE_CAPACITY_EVENTS
|
||||
)
|
||||
payload_capacity_bytes = int(
|
||||
cache_section.get("payload_arena_bytes", DEFAULT_CACHE_PAYLOAD_BYTES)
|
||||
or DEFAULT_CACHE_PAYLOAD_BYTES
|
||||
)
|
||||
return build_default_cache(
|
||||
ring_capacity=max(1, ring_capacity),
|
||||
payload_capacity_items=max(1, ring_capacity),
|
||||
|
|
@ -46,10 +80,22 @@ def _build_outbox(settings: Settings) -> OutboxQueue:
|
|||
outbox_section = settings.config.get("outbox", {})
|
||||
if not isinstance(outbox_section, dict):
|
||||
outbox_section = {}
|
||||
capacity_items = int(outbox_section.get("capacity_items", DEFAULT_OUTBOX_CAPACITY_ITEMS) or DEFAULT_OUTBOX_CAPACITY_ITEMS)
|
||||
capacity_items = int(
|
||||
outbox_section.get("capacity_items", DEFAULT_OUTBOX_CAPACITY_ITEMS)
|
||||
or DEFAULT_OUTBOX_CAPACITY_ITEMS
|
||||
)
|
||||
return OutboxQueue(max(1, capacity_items))
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class AgentRuntimeState:
|
||||
stop_requested: bool = False
|
||||
started: bool = False
|
||||
tick_total: int = 0
|
||||
last_tick_mono_ns: int = 0
|
||||
last_error: str = ""
|
||||
|
||||
|
||||
@dataclass(slots=True, frozen=True)
|
||||
class CollectorSummary:
|
||||
name: str
|
||||
|
|
@ -66,22 +112,61 @@ class CollectorSummary:
|
|||
last_error: str | None = None
|
||||
|
||||
|
||||
@dataclass(slots=True, frozen=True)
|
||||
@dataclass(slots=True)
|
||||
class AgentApplication:
|
||||
"""Loaded runtime state used by the CLI entrypoint."""
|
||||
|
||||
settings: Settings
|
||||
collector_supervisor: CollectorSupervisor = field(default_factory=CollectorSupervisor)
|
||||
cache: CacheAPI = field(default_factory=lambda: build_default_cache(
|
||||
ring_capacity=DEFAULT_CACHE_CAPACITY_EVENTS,
|
||||
payload_capacity_items=DEFAULT_CACHE_CAPACITY_EVENTS,
|
||||
payload_capacity_bytes=DEFAULT_CACHE_PAYLOAD_BYTES,
|
||||
))
|
||||
outbox: OutboxQueue = field(default_factory=lambda: OutboxQueue(DEFAULT_OUTBOX_CAPACITY_ITEMS))
|
||||
collector_supervisor: CollectorSupervisor = field(
|
||||
default_factory=CollectorSupervisor
|
||||
)
|
||||
cache: CacheAPI = field(
|
||||
default_factory=lambda: build_default_cache(
|
||||
ring_capacity=DEFAULT_CACHE_CAPACITY_EVENTS,
|
||||
payload_capacity_items=DEFAULT_CACHE_CAPACITY_EVENTS,
|
||||
payload_capacity_bytes=DEFAULT_CACHE_PAYLOAD_BYTES,
|
||||
)
|
||||
)
|
||||
outbox: OutboxQueue = field(
|
||||
default_factory=lambda: OutboxQueue(DEFAULT_OUTBOX_CAPACITY_ITEMS)
|
||||
)
|
||||
sender_loop: SenderLoopBase | None = field(default=None, repr=False, compare=False)
|
||||
derivator_worker: DerivatorWorker | None = field(default=None, repr=False, compare=False)
|
||||
derivator_worker: DerivatorWorker | None = field(
|
||||
default=None, repr=False, compare=False
|
||||
)
|
||||
scheduler_runtime: Scheduler | None = field(default=None, repr=False, compare=False)
|
||||
command_coordinator_runtime: CommandCoordinator | None = field(default=None, repr=False, compare=False)
|
||||
command_coordinator_runtime: CommandCoordinator | None = field(
|
||||
default=None, repr=False, compare=False
|
||||
)
|
||||
runtime_state: AgentRuntimeState = field(
|
||||
default_factory=AgentRuntimeState, repr=False, compare=False
|
||||
)
|
||||
control_server_runtime: ControlServer | None = field(
|
||||
default=None, repr=False, compare=False
|
||||
)
|
||||
|
||||
def control_socket_path(self) -> str:
|
||||
control_section = self.settings.config.get("control", {})
|
||||
if not isinstance(control_section, dict):
|
||||
control_section = {}
|
||||
return str(
|
||||
control_section.get("socket_path", "/run/wf-agent2/control.sock")
|
||||
or "/run/wf-agent2/control.sock"
|
||||
)
|
||||
|
||||
def _ensure_control_server(self) -> ControlServer:
|
||||
server = self.control_server_runtime
|
||||
if server is not None:
|
||||
return server
|
||||
service = ControlService(self)
|
||||
dispatcher = ControlDispatcher(service)
|
||||
server = ControlServer(
|
||||
dispatcher,
|
||||
socket_path=self.control_socket_path(),
|
||||
daemon_user="wifi-agent",
|
||||
)
|
||||
self.control_server_runtime = server
|
||||
return server
|
||||
|
||||
@property
|
||||
def config_path(self) -> Path:
|
||||
|
|
@ -132,6 +217,11 @@ class AgentApplication:
|
|||
"sender_last_error": sender_status["last_error"],
|
||||
"outbox_depth": outbox_stats.size,
|
||||
"outbox_capacity": outbox_stats.capacity,
|
||||
"runtime_started": self.runtime_state.started,
|
||||
"runtime_stop_requested": self.runtime_state.stop_requested,
|
||||
"runtime_tick_total": self.runtime_state.tick_total,
|
||||
"runtime_last_tick_mono_ns": self.runtime_state.last_tick_mono_ns,
|
||||
"runtime_last_error": self.runtime_state.last_error,
|
||||
}
|
||||
|
||||
def collector_config_sections(self) -> dict[str, Any]:
|
||||
|
|
@ -190,7 +280,9 @@ class AgentApplication:
|
|||
ssid: str | None = None,
|
||||
limit: int | None = None,
|
||||
) -> CacheSnapshot:
|
||||
interface_id = self.cache.interner.intern(interface_name) if interface_name else None
|
||||
interface_id = (
|
||||
self.cache.interner.intern(interface_name) if interface_name else None
|
||||
)
|
||||
event_type_id = self.cache.interner.intern(event_type) if event_type else None
|
||||
ssid_id = self.cache.interner.intern(ssid) if ssid else None
|
||||
source_kind_value = _coerce_source_kind(source_kind)
|
||||
|
|
@ -217,13 +309,29 @@ class AgentApplication:
|
|||
"transport_type": sender_config.transport_type.value,
|
||||
"supported": not sender_config.validate(),
|
||||
"queue_depth": self.outbox.stats().size,
|
||||
"retry_pending_total": sender_stats.retry_pending_total if sender_stats is not None else 0,
|
||||
"retry_scheduled_total": sender_stats.retry_scheduled_total if sender_stats is not None else 0,
|
||||
"retry_promoted_total": sender_stats.retry_promoted_total if sender_stats is not None else 0,
|
||||
"retry_expired_total": sender_stats.retry_expired_total if sender_stats is not None else 0,
|
||||
"last_batch_size": sender_stats.last_batch_size if sender_stats is not None else 0,
|
||||
"last_transport_status_code": sender_stats.last_transport_status_code if sender_stats is not None else 0,
|
||||
"last_transport_reason": sender_stats.last_transport_reason if sender_stats is not None else "",
|
||||
"retry_pending_total": (
|
||||
sender_stats.retry_pending_total if sender_stats is not None else 0
|
||||
),
|
||||
"retry_scheduled_total": (
|
||||
sender_stats.retry_scheduled_total if sender_stats is not None else 0
|
||||
),
|
||||
"retry_promoted_total": (
|
||||
sender_stats.retry_promoted_total if sender_stats is not None else 0
|
||||
),
|
||||
"retry_expired_total": (
|
||||
sender_stats.retry_expired_total if sender_stats is not None else 0
|
||||
),
|
||||
"last_batch_size": (
|
||||
sender_stats.last_batch_size if sender_stats is not None else 0
|
||||
),
|
||||
"last_transport_status_code": (
|
||||
sender_stats.last_transport_status_code
|
||||
if sender_stats is not None
|
||||
else 0
|
||||
),
|
||||
"last_transport_reason": (
|
||||
sender_stats.last_transport_reason if sender_stats is not None else ""
|
||||
),
|
||||
"last_error": sender_stats.last_error if sender_stats is not None else "",
|
||||
}
|
||||
|
||||
|
|
@ -239,13 +347,29 @@ class AgentApplication:
|
|||
"queue_depth": outbox_stats.size,
|
||||
"queue_capacity": outbox_stats.capacity,
|
||||
"queue_fill_ratio": outbox_stats.fill_ratio,
|
||||
"retry_pending_total": sender_stats.retry_pending_total if sender_stats is not None else 0,
|
||||
"retry_scheduled_total": sender_stats.retry_scheduled_total if sender_stats is not None else 0,
|
||||
"retry_promoted_total": sender_stats.retry_promoted_total if sender_stats is not None else 0,
|
||||
"retry_expired_total": sender_stats.retry_expired_total if sender_stats is not None else 0,
|
||||
"last_batch_size": sender_stats.last_batch_size if sender_stats is not None else 0,
|
||||
"last_transport_status_code": sender_stats.last_transport_status_code if sender_stats is not None else 0,
|
||||
"last_transport_reason": sender_stats.last_transport_reason if sender_stats is not None else "",
|
||||
"retry_pending_total": (
|
||||
sender_stats.retry_pending_total if sender_stats is not None else 0
|
||||
),
|
||||
"retry_scheduled_total": (
|
||||
sender_stats.retry_scheduled_total if sender_stats is not None else 0
|
||||
),
|
||||
"retry_promoted_total": (
|
||||
sender_stats.retry_promoted_total if sender_stats is not None else 0
|
||||
),
|
||||
"retry_expired_total": (
|
||||
sender_stats.retry_expired_total if sender_stats is not None else 0
|
||||
),
|
||||
"last_batch_size": (
|
||||
sender_stats.last_batch_size if sender_stats is not None else 0
|
||||
),
|
||||
"last_transport_status_code": (
|
||||
sender_stats.last_transport_status_code
|
||||
if sender_stats is not None
|
||||
else 0
|
||||
),
|
||||
"last_transport_reason": (
|
||||
sender_stats.last_transport_reason if sender_stats is not None else ""
|
||||
),
|
||||
"last_error": sender_stats.last_error if sender_stats is not None else "",
|
||||
}
|
||||
|
||||
|
|
@ -283,7 +407,9 @@ class AgentApplication:
|
|||
"last_error": state.stats.last_error,
|
||||
}
|
||||
|
||||
def derivator_run_once(self, *, now_mono_ns_value: int | None = None) -> DerivatorPollResult:
|
||||
def derivator_run_once(
|
||||
self, *, now_mono_ns_value: int | None = None
|
||||
) -> DerivatorPollResult:
|
||||
worker = self._ensure_derivator_worker()
|
||||
return worker.run_once(now_mono_ns_value=now_mono_ns_value)
|
||||
|
||||
|
|
@ -292,7 +418,7 @@ class AgentApplication:
|
|||
if scheduler is not None:
|
||||
return scheduler
|
||||
scheduler = self._build_scheduler(self.settings)
|
||||
object.__setattr__(self, "scheduler_runtime", scheduler)
|
||||
self.scheduler_runtime = scheduler
|
||||
return scheduler
|
||||
|
||||
def scheduler_state(self) -> SchedulerState:
|
||||
|
|
@ -339,7 +465,9 @@ class AgentApplication:
|
|||
"due": name in state.due_job_names,
|
||||
}
|
||||
|
||||
def task_enable(self, name: str, *, now_mono_ns_value: int | None = None) -> SchedulerJob:
|
||||
def task_enable(
|
||||
self, name: str, *, now_mono_ns_value: int | None = None
|
||||
) -> SchedulerJob:
|
||||
scheduler = self.scheduler()
|
||||
job = scheduler.registry.enable(name)
|
||||
if job is None:
|
||||
|
|
@ -358,7 +486,9 @@ class AgentApplication:
|
|||
raise KeyError(name)
|
||||
return job
|
||||
|
||||
def task_run_once(self, name: str, *, now_mono_ns_value: int | None = None) -> CommandSubmissionResult:
|
||||
def task_run_once(
|
||||
self, name: str, *, now_mono_ns_value: int | None = None
|
||||
) -> CommandSubmissionResult:
|
||||
scheduler = self.scheduler()
|
||||
now = now_mono_ns() if now_mono_ns_value is None else now_mono_ns_value
|
||||
request = scheduler.run_once(name, now_mono_ns_value=now)
|
||||
|
|
@ -369,21 +499,29 @@ class AgentApplication:
|
|||
if coordinator is not None:
|
||||
return coordinator
|
||||
coordinator = self._build_command_coordinator(self.settings)
|
||||
object.__setattr__(self, "command_coordinator_runtime", coordinator)
|
||||
self.command_coordinator_runtime = coordinator
|
||||
return coordinator
|
||||
|
||||
def submit_command(self, request: CommandRequest, *, now_mono_ns_value: int | None = None) -> CommandSubmissionResult:
|
||||
def submit_command(
|
||||
self, request: CommandRequest, *, now_mono_ns_value: int | None = None
|
||||
) -> CommandSubmissionResult:
|
||||
coordinator = self.command_coordinator()
|
||||
if request.origin_kind == CommandOriginKind.SCHEDULER:
|
||||
return coordinator.submit_scheduler(request, now_mono_ns_value=now_mono_ns_value)
|
||||
return coordinator.submit_scheduler(
|
||||
request, now_mono_ns_value=now_mono_ns_value
|
||||
)
|
||||
if request.origin_kind == CommandOriginKind.DERIVATOR:
|
||||
return coordinator.submit_derivator(request, now_mono_ns_value=now_mono_ns_value)
|
||||
return coordinator.submit_derivator(
|
||||
request, now_mono_ns_value=now_mono_ns_value
|
||||
)
|
||||
return coordinator.submit_cli(request, now_mono_ns_value=now_mono_ns_value)
|
||||
|
||||
def command_state(self):
|
||||
return self.command_coordinator().state()
|
||||
|
||||
def sender_test(self, *, payload: Mapping[str, Any] | None = None) -> TransportResult:
|
||||
def sender_test(
|
||||
self, *, payload: Mapping[str, Any] | None = None
|
||||
) -> TransportResult:
|
||||
sender_config = self.sender_config()
|
||||
transport = self._build_transport(sender_config)
|
||||
payload = payload or {
|
||||
|
|
@ -430,12 +568,144 @@ class AgentApplication:
|
|||
"collector_supervisor_errors_total": supervisor_stats.errors_total,
|
||||
}
|
||||
|
||||
def register_collectors_from_config(self) -> tuple[str, ...]:
|
||||
registered: list[str] = []
|
||||
for name, config in self.collector_config_sections().items():
|
||||
if not isinstance(config, Mapping):
|
||||
continue
|
||||
collector = self._build_collector_from_config(name, config)
|
||||
if collector is None:
|
||||
continue
|
||||
self.collector_supervisor.register(collector, replace_existing=True)
|
||||
registered.append(name)
|
||||
return tuple(registered)
|
||||
|
||||
def _build_collector_from_config(self, name: str, config: Mapping[str, Any]):
|
||||
source_kind = str(config.get("source_kind", name) or name).strip().lower()
|
||||
|
||||
if source_kind == "journal":
|
||||
return JournalCollector.from_toml(self.settings.config, collector_name=name)
|
||||
if source_kind == "dbus":
|
||||
return DbusCollector.from_toml(self.settings.config, collector_name=name)
|
||||
if source_kind == "wpa_ctrl":
|
||||
return WpaCtrlCollector.from_toml(self.settings.config, collector_name=name)
|
||||
if source_kind == "navigation":
|
||||
return NavigationCollector.from_toml(
|
||||
self.settings.config, collector_name=name
|
||||
)
|
||||
|
||||
return None
|
||||
|
||||
def start_runtime(self) -> None:
|
||||
if self.runtime_state.started:
|
||||
return
|
||||
|
||||
self.register_collectors_from_config()
|
||||
self.scheduler()
|
||||
self.command_coordinator()
|
||||
self._sender_loop_or_none()
|
||||
self._ensure_derivator_worker()
|
||||
|
||||
self.collector_supervisor.start_enabled()
|
||||
self.runtime_state.started = True
|
||||
|
||||
def _poll_collectors(
|
||||
self, *, now_mono_ns_value: int | None = None, limit_per_collector: int = 64
|
||||
) -> None:
|
||||
for collector in self.collector_supervisor.collectors.values():
|
||||
if not collector.identity.enabled:
|
||||
continue
|
||||
if not collector.is_running():
|
||||
continue
|
||||
try:
|
||||
collector.drain_pending(
|
||||
limit=limit_per_collector,
|
||||
now_mono_ns_value=now_mono_ns_value,
|
||||
)
|
||||
except Exception as exc:
|
||||
self.runtime_state.last_error = str(exc)
|
||||
|
||||
def tick_runtime(self, *, now_mono_ns_value: int | None = None) -> None:
|
||||
now = now_mono_ns() if now_mono_ns_value is None else now_mono_ns_value
|
||||
|
||||
self._poll_collectors(now_mono_ns_value=now)
|
||||
|
||||
scheduler = self.scheduler()
|
||||
try:
|
||||
emitted = scheduler.tick(now_mono_ns_value=now)
|
||||
except TypeError:
|
||||
emitted = scheduler.tick(now)
|
||||
|
||||
if emitted:
|
||||
for request in emitted:
|
||||
self.submit_command(request, now_mono_ns_value=now)
|
||||
|
||||
worker = self._ensure_derivator_worker()
|
||||
state = worker.state()
|
||||
if state.enabled:
|
||||
try:
|
||||
self.derivator_run_once(now_mono_ns_value=now)
|
||||
except Exception as exc:
|
||||
self.runtime_state.last_error = str(exc)
|
||||
|
||||
sender = self._sender_loop_or_none()
|
||||
if sender is not None:
|
||||
try:
|
||||
sender.flush_now()
|
||||
except Exception as exc:
|
||||
self.runtime_state.last_error = str(exc)
|
||||
|
||||
try:
|
||||
self.collector_supervisor.watchdog_check()
|
||||
except Exception as exc:
|
||||
self.runtime_state.last_error = str(exc)
|
||||
|
||||
self.runtime_state.tick_total += 1
|
||||
self.runtime_state.last_tick_mono_ns = now
|
||||
|
||||
def stop_runtime(self) -> None:
|
||||
self.runtime_state.stop_requested = True
|
||||
try:
|
||||
self.collector_supervisor.stop_all()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def run_forever(self, *, tick_interval_ms: int = 200) -> int:
|
||||
self.start_runtime()
|
||||
control_server = self._ensure_control_server()
|
||||
control_server.start()
|
||||
|
||||
def _request_stop(signum, frame):
|
||||
self.runtime_state.stop_requested = True
|
||||
|
||||
old_sigterm = signal.getsignal(signal.SIGTERM)
|
||||
old_sigint = signal.getsignal(signal.SIGINT)
|
||||
|
||||
signal.signal(signal.SIGTERM, _request_stop)
|
||||
signal.signal(signal.SIGINT, _request_stop)
|
||||
|
||||
try:
|
||||
while not self.runtime_state.stop_requested:
|
||||
try:
|
||||
self.tick_runtime()
|
||||
except Exception as exc:
|
||||
self.runtime_state.last_error = str(exc)
|
||||
time.sleep(max(0.01, tick_interval_ms / 1000.0))
|
||||
return 0
|
||||
finally:
|
||||
try:
|
||||
control_server.stop()
|
||||
finally:
|
||||
self.stop_runtime()
|
||||
signal.signal(signal.SIGTERM, old_sigterm)
|
||||
signal.signal(signal.SIGINT, old_sigint)
|
||||
|
||||
def _ensure_sender_loop(self) -> SenderLoopBase:
|
||||
sender = self._sender_loop_or_none()
|
||||
if sender is not None:
|
||||
return sender
|
||||
sender = self._build_sender_loop(self.sender_config())
|
||||
object.__setattr__(self, "sender_loop", sender)
|
||||
self.sender_loop = sender
|
||||
return sender
|
||||
|
||||
def _ensure_derivator_worker(self) -> DerivatorWorker:
|
||||
|
|
@ -443,7 +713,7 @@ class AgentApplication:
|
|||
if worker is not None:
|
||||
return worker
|
||||
worker = self._build_derivator_worker(self.settings)
|
||||
object.__setattr__(self, "derivator_worker", worker)
|
||||
self.derivator_worker = worker
|
||||
return worker
|
||||
|
||||
def _sender_loop_or_none(self) -> SenderLoopBase | None:
|
||||
|
|
@ -454,7 +724,7 @@ class AgentApplication:
|
|||
sender = self._build_sender_loop(self.sender_config())
|
||||
except ValueError:
|
||||
return None
|
||||
object.__setattr__(self, "sender_loop", sender)
|
||||
self.sender_loop = sender
|
||||
return sender
|
||||
|
||||
def _build_sender_loop(self, sender_config: SenderRuntimeConfig) -> SenderLoopBase:
|
||||
|
|
@ -464,7 +734,9 @@ class AgentApplication:
|
|||
transport = WebhookTransport(sender_config.webhook)
|
||||
else:
|
||||
transport = DropTransport()
|
||||
return build_sender_loop(sender_config, cache=self.cache, outbox=self.outbox, transport=transport)
|
||||
return build_sender_loop(
|
||||
sender_config, cache=self.cache, outbox=self.outbox, transport=transport
|
||||
)
|
||||
|
||||
def _build_transport(self, sender_config: SenderRuntimeConfig):
|
||||
if sender_config.transport_type == TransportType.WEBHOOK:
|
||||
|
|
@ -476,9 +748,18 @@ class AgentApplication:
|
|||
if not isinstance(derivator_section, dict):
|
||||
derivator_section = {}
|
||||
workflows = _build_derivator_workflows(derivator_section)
|
||||
worker_name = str(derivator_section.get("name", DEFAULT_DERIVATOR_NAME) or DEFAULT_DERIVATOR_NAME)
|
||||
poll_interval_raw = derivator_section.get("poll_interval_ms", DEFAULT_DERIVATOR_POLL_INTERVAL_MS)
|
||||
poll_interval_ms = DEFAULT_DERIVATOR_POLL_INTERVAL_MS if poll_interval_raw is None else int(poll_interval_raw)
|
||||
worker_name = str(
|
||||
derivator_section.get("name", DEFAULT_DERIVATOR_NAME)
|
||||
or DEFAULT_DERIVATOR_NAME
|
||||
)
|
||||
poll_interval_raw = derivator_section.get(
|
||||
"poll_interval_ms", DEFAULT_DERIVATOR_POLL_INTERVAL_MS
|
||||
)
|
||||
poll_interval_ms = (
|
||||
DEFAULT_DERIVATOR_POLL_INTERVAL_MS
|
||||
if poll_interval_raw is None
|
||||
else int(poll_interval_raw)
|
||||
)
|
||||
enabled = bool(derivator_section.get("enabled", True))
|
||||
return DerivatorWorker(
|
||||
self.cache,
|
||||
|
|
@ -506,7 +787,9 @@ class AgentApplication:
|
|||
executors_section = {}
|
||||
wpa_section = executors_section.get("wpa_ctrl")
|
||||
if isinstance(wpa_section, dict) and bool(wpa_section.get("enabled", True)):
|
||||
executor = WpaCtrlExecutor.from_toml(settings.config, executor_name="wpa_ctrl")
|
||||
executor = WpaCtrlExecutor.from_toml(
|
||||
settings.config, executor_name="wpa_ctrl"
|
||||
)
|
||||
router.register(
|
||||
executor,
|
||||
command_prefixes=("wpa.",),
|
||||
|
|
@ -514,7 +797,9 @@ class AgentApplication:
|
|||
name=executor.identity.name,
|
||||
)
|
||||
system_section = executors_section.get("system")
|
||||
if isinstance(system_section, dict) and bool(system_section.get("enabled", True)):
|
||||
if isinstance(system_section, dict) and bool(
|
||||
system_section.get("enabled", True)
|
||||
):
|
||||
executor = SystemExecutor.from_toml(settings.config, executor_name="system")
|
||||
router.register(
|
||||
executor,
|
||||
|
|
@ -542,7 +827,9 @@ class AgentApplication:
|
|||
source_kind=source_kind,
|
||||
description=description if isinstance(description, str) else None,
|
||||
profile=profile if isinstance(profile, str) else None,
|
||||
interface_name=interface_name if isinstance(interface_name, str) else None,
|
||||
interface_name=(
|
||||
interface_name if isinstance(interface_name, str) else None
|
||||
),
|
||||
has_runtime_state=False,
|
||||
)
|
||||
health = runtime_state.health
|
||||
|
|
@ -617,8 +904,16 @@ def _build_derivator_workflows(derivator_section: Mapping[str, Any]) -> tuple[An
|
|||
for raw_workflow in workflows_section:
|
||||
if not isinstance(raw_workflow, dict):
|
||||
continue
|
||||
workflow_name = str(raw_workflow.get("workflow_name", raw_workflow.get("name", "wifi_scan_summary")) or "wifi_scan_summary")
|
||||
if workflow_name != "wifi_scan_summary" and str(raw_workflow.get("name", "")) != "wifi_scan_summary":
|
||||
workflow_name = str(
|
||||
raw_workflow.get(
|
||||
"workflow_name", raw_workflow.get("name", "wifi_scan_summary")
|
||||
)
|
||||
or "wifi_scan_summary"
|
||||
)
|
||||
if (
|
||||
workflow_name != "wifi_scan_summary"
|
||||
and str(raw_workflow.get("name", "")) != "wifi_scan_summary"
|
||||
):
|
||||
continue
|
||||
workflows.append(
|
||||
WifiScanSummaryWorkflow(
|
||||
|
|
@ -626,17 +921,39 @@ def _build_derivator_workflows(derivator_section: Mapping[str, Any]) -> tuple[An
|
|||
name=str(raw_workflow.get("name", workflow_name) or workflow_name),
|
||||
workflow_name=workflow_name,
|
||||
min_wifi_records=int(raw_workflow.get("min_wifi_records", 1) or 1),
|
||||
type_prefixes=_string_tuple(raw_workflow.get("type_prefixes", ("wifi.",))),
|
||||
source_kinds=_derivator_source_kinds(raw_workflow.get("source_kinds", ())),
|
||||
follow_up_command_type=str(raw_workflow.get("follow_up_command_type", "") or ""),
|
||||
follow_up_command_target_kind=_coerce_command_target_kind(raw_workflow.get("follow_up_command_target_kind")),
|
||||
follow_up_command_target_id=str(raw_workflow.get("follow_up_command_target_id", "") or ""),
|
||||
follow_up_command_min_disconnects=int(raw_workflow.get("follow_up_command_min_disconnects", 1) or 1),
|
||||
follow_up_command_priority=int(raw_workflow.get("follow_up_command_priority", 0) or 0),
|
||||
follow_up_command_exclusive_key=str(raw_workflow.get("follow_up_command_exclusive_key", "") or ""),
|
||||
follow_up_command_dedup_key=str(raw_workflow.get("follow_up_command_dedup_key", "") or ""),
|
||||
follow_up_command_cooldown_key=str(raw_workflow.get("follow_up_command_cooldown_key", "") or ""),
|
||||
follow_up_command_args=raw_workflow.get("follow_up_command_args", {}),
|
||||
type_prefixes=_string_tuple(
|
||||
raw_workflow.get("type_prefixes", ("wifi.",))
|
||||
),
|
||||
source_kinds=_derivator_source_kinds(
|
||||
raw_workflow.get("source_kinds", ())
|
||||
),
|
||||
follow_up_command_type=str(
|
||||
raw_workflow.get("follow_up_command_type", "") or ""
|
||||
),
|
||||
follow_up_command_target_kind=_coerce_command_target_kind(
|
||||
raw_workflow.get("follow_up_command_target_kind")
|
||||
),
|
||||
follow_up_command_target_id=str(
|
||||
raw_workflow.get("follow_up_command_target_id", "") or ""
|
||||
),
|
||||
follow_up_command_min_disconnects=int(
|
||||
raw_workflow.get("follow_up_command_min_disconnects", 1) or 1
|
||||
),
|
||||
follow_up_command_priority=int(
|
||||
raw_workflow.get("follow_up_command_priority", 0) or 0
|
||||
),
|
||||
follow_up_command_exclusive_key=str(
|
||||
raw_workflow.get("follow_up_command_exclusive_key", "") or ""
|
||||
),
|
||||
follow_up_command_dedup_key=str(
|
||||
raw_workflow.get("follow_up_command_dedup_key", "") or ""
|
||||
),
|
||||
follow_up_command_cooldown_key=str(
|
||||
raw_workflow.get("follow_up_command_cooldown_key", "") or ""
|
||||
),
|
||||
follow_up_command_args=raw_workflow.get(
|
||||
"follow_up_command_args", {}
|
||||
),
|
||||
)
|
||||
)
|
||||
)
|
||||
|
|
|
|||
|
|
@ -24,8 +24,12 @@ class CacheAPI:
|
|||
indexes: SecondaryIndexes
|
||||
interner: StringInterner = field(default_factory=StringInterner)
|
||||
|
||||
def append(self, record: EventRecord, payload: bytes | bytearray | memoryview | None = None) -> EventRecord:
|
||||
stored = record if payload is None else self.payload_store.attach(record, payload)
|
||||
def append(
|
||||
self, record: EventRecord, payload: bytes | bytearray | memoryview | None = None
|
||||
) -> EventRecord:
|
||||
stored = (
|
||||
record if payload is None else self.payload_store.attach(record, payload)
|
||||
)
|
||||
stored = self.ring_buffer.append(stored)
|
||||
self.indexes.add(stored)
|
||||
return stored
|
||||
|
|
@ -34,10 +38,14 @@ class CacheAPI:
|
|||
return [self.append(record) for record in records]
|
||||
|
||||
def recent_head(self, limit: int | None = None) -> CacheSnapshot:
|
||||
return self._snapshot(self.ring_buffer.head(limit), filters=CacheFilterSnapshot(limit=limit))
|
||||
return self._snapshot(
|
||||
self.ring_buffer.head(limit), filters=CacheFilterSnapshot(limit=limit)
|
||||
)
|
||||
|
||||
def recent_tail(self, limit: int | None = None) -> CacheSnapshot:
|
||||
return self._snapshot(self.ring_buffer.tail(limit), filters=CacheFilterSnapshot(limit=limit))
|
||||
return self._snapshot(
|
||||
self.ring_buffer.tail(limit), filters=CacheFilterSnapshot(limit=limit)
|
||||
)
|
||||
|
||||
def head(self, limit: int | None = None) -> CacheSnapshot:
|
||||
return self.recent_head(limit)
|
||||
|
|
@ -69,7 +77,9 @@ class CacheAPI:
|
|||
return self.ring_buffer.get(seq_no)
|
||||
|
||||
def stats(self) -> CacheSnapshot:
|
||||
return self._snapshot(self.ring_buffer.snapshot(), filters=CacheFilterSnapshot())
|
||||
return self._snapshot(
|
||||
self.ring_buffer.snapshot(), filters=CacheFilterSnapshot()
|
||||
)
|
||||
|
||||
def snapshot(
|
||||
self,
|
||||
|
|
@ -81,7 +91,10 @@ class CacheAPI:
|
|||
ssid_id: int | StringId | None = None,
|
||||
recent: str = "tail",
|
||||
) -> CacheSnapshot:
|
||||
if any(value is not None for value in (interface_id, event_type_id, source_kind, ssid_id)):
|
||||
if any(
|
||||
value is not None
|
||||
for value in (interface_id, event_type_id, source_kind, ssid_id)
|
||||
):
|
||||
return self.find(
|
||||
interface_id=interface_id,
|
||||
event_type_id=event_type_id,
|
||||
|
|
@ -97,13 +110,33 @@ class CacheAPI:
|
|||
candidates: list[set[int]] = []
|
||||
live = self.ring_buffer.get
|
||||
if filters.interface_id is not None:
|
||||
candidates.append(set(self.indexes.iter_seq_nos_by_interface(filters.interface_id, is_live=live)))
|
||||
candidates.append(
|
||||
set(
|
||||
self.indexes.iter_seq_nos_by_interface(
|
||||
filters.interface_id, is_live=live
|
||||
)
|
||||
)
|
||||
)
|
||||
if filters.event_type_id is not None:
|
||||
candidates.append(set(self.indexes.iter_seq_nos_by_event_type(filters.event_type_id, is_live=live)))
|
||||
candidates.append(
|
||||
set(
|
||||
self.indexes.iter_seq_nos_by_event_type(
|
||||
filters.event_type_id, is_live=live
|
||||
)
|
||||
)
|
||||
)
|
||||
if filters.source_kind is not None:
|
||||
candidates.append(set(self.indexes.iter_seq_nos_by_source_kind(filters.source_kind, is_live=live)))
|
||||
candidates.append(
|
||||
set(
|
||||
self.indexes.iter_seq_nos_by_source_kind(
|
||||
filters.source_kind, is_live=live
|
||||
)
|
||||
)
|
||||
)
|
||||
if filters.ssid_id is not None:
|
||||
candidates.append(set(self.indexes.iter_seq_nos_by_ssid(filters.ssid_id, is_live=live)))
|
||||
candidates.append(
|
||||
set(self.indexes.iter_seq_nos_by_ssid(filters.ssid_id, is_live=live))
|
||||
)
|
||||
|
||||
if not candidates:
|
||||
return [int(record.seq_no) for record in self.ring_buffer]
|
||||
|
|
@ -113,7 +146,9 @@ class CacheAPI:
|
|||
seq_nos &= candidate
|
||||
return sorted(seq_nos)
|
||||
|
||||
def _records_from_seq_nos(self, seq_nos: Sequence[int], *, limit: int | None = None) -> list[EventRecord]:
|
||||
def _records_from_seq_nos(
|
||||
self, seq_nos: Sequence[int], *, limit: int | None = None
|
||||
) -> list[EventRecord]:
|
||||
if limit is not None and limit >= 0:
|
||||
seq_nos = seq_nos[:limit]
|
||||
records: list[EventRecord] = []
|
||||
|
|
@ -123,7 +158,9 @@ class CacheAPI:
|
|||
records.append(record)
|
||||
return records
|
||||
|
||||
def _snapshot(self, records: Sequence[EventRecord], *, filters: CacheFilterSnapshot) -> CacheSnapshot:
|
||||
def _snapshot(
|
||||
self, records: Sequence[EventRecord], *, filters: CacheFilterSnapshot
|
||||
) -> CacheSnapshot:
|
||||
return snapshot_from_records(
|
||||
list(records),
|
||||
interner=self.interner,
|
||||
|
|
|
|||
|
|
@ -61,7 +61,9 @@ class SecondaryIndexes:
|
|||
*,
|
||||
is_live: SeqNoLiveCheck | None = None,
|
||||
) -> Iterator[int]:
|
||||
yield from self._iter_live(self._by_interface, int(interface_id), is_live=is_live)
|
||||
yield from self._iter_live(
|
||||
self._by_interface, int(interface_id), is_live=is_live
|
||||
)
|
||||
|
||||
def iter_seq_nos_by_event_type(
|
||||
self,
|
||||
|
|
@ -69,7 +71,9 @@ class SecondaryIndexes:
|
|||
*,
|
||||
is_live: SeqNoLiveCheck | None = None,
|
||||
) -> Iterator[int]:
|
||||
yield from self._iter_live(self._by_event_type, int(event_type_id), is_live=is_live)
|
||||
yield from self._iter_live(
|
||||
self._by_event_type, int(event_type_id), is_live=is_live
|
||||
)
|
||||
|
||||
def iter_seq_nos_by_source_kind(
|
||||
self,
|
||||
|
|
@ -77,7 +81,9 @@ class SecondaryIndexes:
|
|||
*,
|
||||
is_live: SeqNoLiveCheck | None = None,
|
||||
) -> Iterator[int]:
|
||||
yield from self._iter_live(self._by_source_kind, int(source_kind), is_live=is_live)
|
||||
yield from self._iter_live(
|
||||
self._by_source_kind, int(source_kind), is_live=is_live
|
||||
)
|
||||
|
||||
def iter_seq_nos_by_ssid(
|
||||
self,
|
||||
|
|
@ -92,20 +98,32 @@ class SecondaryIndexes:
|
|||
interface_id: int | InterfaceId,
|
||||
buffer: RingBuffer,
|
||||
) -> list[EventRecord]:
|
||||
return self._records_from_seq_nos(self.iter_seq_nos_by_interface(interface_id, is_live=buffer.get), buffer)
|
||||
return self._records_from_seq_nos(
|
||||
self.iter_seq_nos_by_interface(interface_id, is_live=buffer.get), buffer
|
||||
)
|
||||
|
||||
def query_records_by_event_type(
|
||||
self,
|
||||
event_type_id: int | EventTypeId,
|
||||
buffer: RingBuffer,
|
||||
) -> list[EventRecord]:
|
||||
return self._records_from_seq_nos(self.iter_seq_nos_by_event_type(event_type_id, is_live=buffer.get), buffer)
|
||||
return self._records_from_seq_nos(
|
||||
self.iter_seq_nos_by_event_type(event_type_id, is_live=buffer.get), buffer
|
||||
)
|
||||
|
||||
def query_records_by_source_kind(self, source_kind: int, buffer: RingBuffer) -> list[EventRecord]:
|
||||
return self._records_from_seq_nos(self.iter_seq_nos_by_source_kind(source_kind, is_live=buffer.get), buffer)
|
||||
def query_records_by_source_kind(
|
||||
self, source_kind: int, buffer: RingBuffer
|
||||
) -> list[EventRecord]:
|
||||
return self._records_from_seq_nos(
|
||||
self.iter_seq_nos_by_source_kind(source_kind, is_live=buffer.get), buffer
|
||||
)
|
||||
|
||||
def query_records_by_ssid(self, ssid_id: int | StringId, buffer: RingBuffer) -> list[EventRecord]:
|
||||
return self._records_from_seq_nos(self.iter_seq_nos_by_ssid(ssid_id, is_live=buffer.get), buffer)
|
||||
def query_records_by_ssid(
|
||||
self, ssid_id: int | StringId, buffer: RingBuffer
|
||||
) -> list[EventRecord]:
|
||||
return self._records_from_seq_nos(
|
||||
self.iter_seq_nos_by_ssid(ssid_id, is_live=buffer.get), buffer
|
||||
)
|
||||
|
||||
def stats(self) -> IndexStats:
|
||||
return IndexStats(
|
||||
|
|
@ -121,7 +139,12 @@ class SecondaryIndexes:
|
|||
|
||||
def prune_stale(self, buffer: RingBuffer) -> int:
|
||||
pruned = 0
|
||||
for mapping in (self._by_interface, self._by_event_type, self._by_source_kind, self._by_ssid):
|
||||
for mapping in (
|
||||
self._by_interface,
|
||||
self._by_event_type,
|
||||
self._by_source_kind,
|
||||
self._by_ssid,
|
||||
):
|
||||
pruned += self._prune_mapping(mapping, buffer.get)
|
||||
return pruned
|
||||
|
||||
|
|
@ -131,7 +154,12 @@ class SecondaryIndexes:
|
|||
mapping.setdefault(key, deque()).append(seq_no)
|
||||
|
||||
def _remove_from_all(self, seq_no: int) -> None:
|
||||
for mapping in (self._by_interface, self._by_event_type, self._by_source_kind, self._by_ssid):
|
||||
for mapping in (
|
||||
self._by_interface,
|
||||
self._by_event_type,
|
||||
self._by_source_kind,
|
||||
self._by_ssid,
|
||||
):
|
||||
self._remove_from_mapping(mapping, seq_no)
|
||||
|
||||
def _remove_from_mapping(self, mapping: dict[int, Deque[int]], seq_no: int) -> None:
|
||||
|
|
@ -153,7 +181,9 @@ class SecondaryIndexes:
|
|||
seq_nos = mapping.get(key)
|
||||
if not seq_nos:
|
||||
return
|
||||
self._prune_deque(seq_nos, lambda value: False if is_live is None else not is_live(value))
|
||||
self._prune_deque(
|
||||
seq_nos, lambda value: False if is_live is None else not is_live(value)
|
||||
)
|
||||
if not seq_nos:
|
||||
del mapping[key]
|
||||
return
|
||||
|
|
@ -161,7 +191,9 @@ class SecondaryIndexes:
|
|||
if is_live is None or is_live(seq_no):
|
||||
yield seq_no
|
||||
|
||||
def _records_from_seq_nos(self, seq_nos: Iterable[int], buffer: RingBuffer) -> list[EventRecord]:
|
||||
def _records_from_seq_nos(
|
||||
self, seq_nos: Iterable[int], buffer: RingBuffer
|
||||
) -> list[EventRecord]:
|
||||
records: list[EventRecord] = []
|
||||
for seq_no in seq_nos:
|
||||
record = buffer.get(seq_no)
|
||||
|
|
@ -169,7 +201,9 @@ class SecondaryIndexes:
|
|||
records.append(record)
|
||||
return records
|
||||
|
||||
def _prune_mapping(self, mapping: dict[int, Deque[int]], is_live: SeqNoLiveCheck) -> int:
|
||||
def _prune_mapping(
|
||||
self, mapping: dict[int, Deque[int]], is_live: SeqNoLiveCheck
|
||||
) -> int:
|
||||
removed = 0
|
||||
empty_keys: list[int] = []
|
||||
for key, seq_nos in mapping.items():
|
||||
|
|
|
|||
|
|
@ -113,7 +113,9 @@ class PayloadStore:
|
|||
return entry
|
||||
return None
|
||||
|
||||
def attach(self, record: EventRecord, payload: bytes | bytearray | memoryview) -> EventRecord:
|
||||
def attach(
|
||||
self, record: EventRecord, payload: bytes | bytearray | memoryview
|
||||
) -> EventRecord:
|
||||
entry = self.put(payload)
|
||||
return replace(record, payload_ref=entry.payload_ref, payload_len=entry.size)
|
||||
|
||||
|
|
@ -175,9 +177,15 @@ class PayloadStore:
|
|||
yield entry
|
||||
|
||||
|
||||
def attach_payload(record: EventRecord, payload_ref: int | PayloadRef, payload_len: int) -> EventRecord:
|
||||
return replace(record, payload_ref=PayloadRef(int(payload_ref)), payload_len=payload_len)
|
||||
def attach_payload(
|
||||
record: EventRecord, payload_ref: int | PayloadRef, payload_len: int
|
||||
) -> EventRecord:
|
||||
return replace(
|
||||
record, payload_ref=PayloadRef(int(payload_ref)), payload_len=payload_len
|
||||
)
|
||||
|
||||
|
||||
def extend(store: PayloadStore, payloads: Iterable[bytes | bytearray | memoryview]) -> list[PayloadEntry]:
|
||||
def extend(
|
||||
store: PayloadStore, payloads: Iterable[bytes | bytearray | memoryview]
|
||||
) -> list[PayloadEntry]:
|
||||
return [store.put(payload) for payload in payloads]
|
||||
|
|
|
|||
|
|
@ -76,7 +76,9 @@ class CacheSnapshot:
|
|||
records: tuple[CacheRecordSnapshot, ...]
|
||||
|
||||
|
||||
def record_to_snapshot(record: EventRecord, *, interner: StringInterner | None = None) -> CacheRecordSnapshot:
|
||||
def record_to_snapshot(
|
||||
record: EventRecord, *, interner: StringInterner | None = None
|
||||
) -> CacheRecordSnapshot:
|
||||
interner = StringInterner() if interner is None else interner
|
||||
return CacheRecordSnapshot(
|
||||
seq_no=int(record.seq_no),
|
||||
|
|
@ -112,7 +114,9 @@ def snapshot_from_records(
|
|||
) -> CacheSnapshot:
|
||||
interner = StringInterner() if interner is None else interner
|
||||
filters = CacheFilterSnapshot() if filters is None else filters
|
||||
ring_stats = ring_stats or RingBufferStats(capacity=0, size=0, next_seq_no=1, overwrite_count=0)
|
||||
ring_stats = ring_stats or RingBufferStats(
|
||||
capacity=0, size=0, next_seq_no=1, overwrite_count=0
|
||||
)
|
||||
payload_stats = payload_stats or PayloadStoreStats(
|
||||
capacity_items=0,
|
||||
capacity_bytes=0,
|
||||
|
|
@ -158,7 +162,9 @@ def snapshot_from_records(
|
|||
generated_wall_ns=generated_wall_ns,
|
||||
filters=filters,
|
||||
stats=stats,
|
||||
records=tuple(record_to_snapshot(record, interner=interner) for record in records),
|
||||
records=tuple(
|
||||
record_to_snapshot(record, interner=interner) for record in records
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
|
|
@ -173,5 +179,7 @@ def _format_wall_ns(value: int) -> str:
|
|||
if value <= 0:
|
||||
return ""
|
||||
seconds, nanos = divmod(value, 1_000_000_000)
|
||||
dt = datetime.fromtimestamp(seconds, tz=timezone.utc).replace(microsecond=nanos // 1000)
|
||||
dt = datetime.fromtimestamp(seconds, tz=timezone.utc).replace(
|
||||
microsecond=nanos // 1000
|
||||
)
|
||||
return dt.isoformat().replace("+00:00", "Z")
|
||||
|
|
|
|||
698
src/agent/cli.py
698
src/agent/cli.py
File diff suppressed because it is too large
Load Diff
|
|
@ -115,7 +115,9 @@ class CollectorBase(ABC):
|
|||
return self._identity
|
||||
|
||||
def state(self) -> CollectorState:
|
||||
return CollectorState(identity=self._identity, health=self._health, stats=self._stats)
|
||||
return CollectorState(
|
||||
identity=self._identity, health=self._health, stats=self._stats
|
||||
)
|
||||
|
||||
def health(self) -> CollectorHealth:
|
||||
self._touch_health()
|
||||
|
|
@ -131,7 +133,10 @@ class CollectorBase(ABC):
|
|||
return self._health.pipeline_state
|
||||
|
||||
def is_running(self) -> bool:
|
||||
return self._health.lifecycle_state in {CollectorLifecycleState.CONNECTED, CollectorLifecycleState.RUNNING}
|
||||
return self._health.lifecycle_state in {
|
||||
CollectorLifecycleState.CONNECTED,
|
||||
CollectorLifecycleState.RUNNING,
|
||||
}
|
||||
|
||||
@abstractmethod
|
||||
def start(self) -> None:
|
||||
|
|
@ -146,16 +151,24 @@ class CollectorBase(ABC):
|
|||
"""Reload collector configuration if supported."""
|
||||
|
||||
def _set_lifecycle_state(self, state: CollectorLifecycleState) -> None:
|
||||
self._health = replace(self._health, lifecycle_state=state, last_transition_mono_ns=now_mono_ns())
|
||||
self._health = replace(
|
||||
self._health, lifecycle_state=state, last_transition_mono_ns=now_mono_ns()
|
||||
)
|
||||
|
||||
def _set_connection_state(self, state: CollectorConnectionState) -> None:
|
||||
self._health = replace(self._health, connection_state=state, last_transition_mono_ns=now_mono_ns())
|
||||
self._health = replace(
|
||||
self._health, connection_state=state, last_transition_mono_ns=now_mono_ns()
|
||||
)
|
||||
|
||||
def _set_pipeline_state(self, state: CollectorPipelineState) -> None:
|
||||
self._health = replace(self._health, pipeline_state=state, last_transition_mono_ns=now_mono_ns())
|
||||
self._health = replace(
|
||||
self._health, pipeline_state=state, last_transition_mono_ns=now_mono_ns()
|
||||
)
|
||||
|
||||
def _mark_healthy(self, healthy: bool) -> None:
|
||||
self._health = replace(self._health, healthy=healthy, last_checked_mono_ns=now_mono_ns())
|
||||
self._health = replace(
|
||||
self._health, healthy=healthy, last_checked_mono_ns=now_mono_ns()
|
||||
)
|
||||
|
||||
def _record_error(self, message: str | Exception) -> None:
|
||||
error_text = str(message)
|
||||
|
|
@ -172,12 +185,17 @@ class CollectorBase(ABC):
|
|||
)
|
||||
|
||||
def _clear_error(self) -> None:
|
||||
self._health = replace(self._health, last_error=None, last_checked_mono_ns=now_mono_ns())
|
||||
self._health = replace(
|
||||
self._health, last_error=None, last_checked_mono_ns=now_mono_ns()
|
||||
)
|
||||
|
||||
def _increment_stats(self, **counters: int) -> None:
|
||||
if not counters:
|
||||
return
|
||||
values: dict[str, Any] = {key: getattr(self._stats, key) + int(delta) for key, delta in counters.items()}
|
||||
values: dict[str, Any] = {
|
||||
key: getattr(self._stats, key) + int(delta)
|
||||
for key, delta in counters.items()
|
||||
}
|
||||
self._stats = replace(self._stats, **values)
|
||||
|
||||
def _touch_health(self) -> None:
|
||||
|
|
@ -185,18 +203,23 @@ class CollectorBase(ABC):
|
|||
|
||||
def _mark_started(self) -> None:
|
||||
now = now_mono_ns()
|
||||
self._stats = replace(self._stats, start_total=self._stats.start_total + 1, last_start_mono_ns=now)
|
||||
self._stats = replace(
|
||||
self._stats, start_total=self._stats.start_total + 1, last_start_mono_ns=now
|
||||
)
|
||||
self._health = replace(
|
||||
self._health,
|
||||
healthy=self._health.connection_state == CollectorConnectionState.CONNECTED
|
||||
and self._health.pipeline_state in {CollectorPipelineState.IDLE, CollectorPipelineState.ACTIVE},
|
||||
and self._health.pipeline_state
|
||||
in {CollectorPipelineState.IDLE, CollectorPipelineState.ACTIVE},
|
||||
lifecycle_state=CollectorLifecycleState.RUNNING,
|
||||
last_transition_mono_ns=now,
|
||||
)
|
||||
|
||||
def _mark_stopped(self) -> None:
|
||||
now = now_mono_ns()
|
||||
self._stats = replace(self._stats, stop_total=self._stats.stop_total + 1, last_stop_mono_ns=now)
|
||||
self._stats = replace(
|
||||
self._stats, stop_total=self._stats.stop_total + 1, last_stop_mono_ns=now
|
||||
)
|
||||
self._health = replace(
|
||||
self._health,
|
||||
healthy=False,
|
||||
|
|
|
|||
|
|
@ -15,21 +15,22 @@ from .base import (
|
|||
CollectorLifecycleState,
|
||||
CollectorPipelineState,
|
||||
)
|
||||
from .pipeline import CollectorPipeline, CollectorPipelineContext, CollectorPipelineOutcome, CollectorRawEvent
|
||||
|
||||
from .pipeline import (
|
||||
CollectorPipeline,
|
||||
CollectorPipelineContext,
|
||||
CollectorPipelineOutcome,
|
||||
CollectorRawEvent,
|
||||
)
|
||||
|
||||
DbusSink = Callable[[events_pb2.EventEnvelope], None]
|
||||
|
||||
|
||||
class DbusBackend(Protocol):
|
||||
def connect(self, config: "DbusCollectorConfig") -> None:
|
||||
...
|
||||
def connect(self, config: "DbusCollectorConfig") -> None: ...
|
||||
|
||||
def read(self) -> "DbusSignal | None":
|
||||
...
|
||||
def read(self) -> "DbusSignal | None": ...
|
||||
|
||||
def close(self) -> None:
|
||||
...
|
||||
def close(self) -> None: ...
|
||||
|
||||
|
||||
@dataclass(slots=True, frozen=True)
|
||||
|
|
@ -53,7 +54,9 @@ class DbusSignal:
|
|||
headers = {}
|
||||
args = data.get("args_json", data.get("args", ()))
|
||||
return cls(
|
||||
bus_name=str(data.get("bus_name", data.get("service", data.get("sender", ""))) or ""),
|
||||
bus_name=str(
|
||||
data.get("bus_name", data.get("service", data.get("sender", ""))) or ""
|
||||
),
|
||||
object_path=str(data.get("object_path", data.get("path", "")) or ""),
|
||||
interface=str(data.get("interface", "") or ""),
|
||||
member=str(data.get("member", data.get("signal", "")) or ""),
|
||||
|
|
@ -62,8 +65,12 @@ class DbusSignal:
|
|||
message=str(data.get("message", "") or ""),
|
||||
args_json=_normalize_args(args),
|
||||
headers=dict(headers),
|
||||
realtime_ns=int(data.get("realtime_ns", data.get("__REALTIME_TIMESTAMP", 0)) or 0),
|
||||
monotonic_ns=int(data.get("monotonic_ns", data.get("__MONOTONIC_TIMESTAMP", 0)) or 0),
|
||||
realtime_ns=int(
|
||||
data.get("realtime_ns", data.get("__REALTIME_TIMESTAMP", 0)) or 0
|
||||
),
|
||||
monotonic_ns=int(
|
||||
data.get("monotonic_ns", data.get("__MONOTONIC_TIMESTAMP", 0)) or 0
|
||||
),
|
||||
)
|
||||
|
||||
@classmethod
|
||||
|
|
@ -141,9 +148,11 @@ class DbusSubscription:
|
|||
)
|
||||
|
||||
def matches(self, signal: DbusSignal) -> bool:
|
||||
if self.service and not _matches_any(signal, self.service, 'service'):
|
||||
if self.service and not _matches_any(signal, self.service, "service"):
|
||||
return False
|
||||
if self.service_prefix and not _matches_prefix(signal, self.service_prefix, 'service'):
|
||||
if self.service_prefix and not _matches_prefix(
|
||||
signal, self.service_prefix, "service"
|
||||
):
|
||||
return False
|
||||
if self.path and signal.object_path != self.path:
|
||||
return False
|
||||
|
|
@ -151,7 +160,9 @@ class DbusSubscription:
|
|||
return False
|
||||
if self.interface and signal.interface != self.interface:
|
||||
return False
|
||||
if self.interface_prefix and not signal.interface.startswith(self.interface_prefix):
|
||||
if self.interface_prefix and not signal.interface.startswith(
|
||||
self.interface_prefix
|
||||
):
|
||||
return False
|
||||
if self.member and signal.member != self.member:
|
||||
return False
|
||||
|
|
@ -179,7 +190,9 @@ class DbusCollectorConfig:
|
|||
drop_unmatched: bool = True
|
||||
|
||||
@classmethod
|
||||
def from_toml(cls, data: Mapping[str, Any], *, collector_name: str | None = None) -> "DbusCollectorConfig":
|
||||
def from_toml(
|
||||
cls, data: Mapping[str, Any], *, collector_name: str | None = None
|
||||
) -> "DbusCollectorConfig":
|
||||
section = _select_collector_section(data, collector_name)
|
||||
if not isinstance(section, Mapping):
|
||||
section = {}
|
||||
|
|
@ -188,15 +201,32 @@ class DbusCollectorConfig:
|
|||
name=str(collector_name or section.get("name", "dbus")),
|
||||
enabled=bool(section.get("enabled", True)),
|
||||
bus=str(section.get("bus", section.get("bus_type", "system")) or "system"),
|
||||
source_name=str(section.get("source_name", section.get("source", "system-dbus")) or "system-dbus"),
|
||||
subscriptions=tuple(DbusSubscription.from_toml(item) for item in subscriptions),
|
||||
source_name=str(
|
||||
section.get("source_name", section.get("source", "system-dbus"))
|
||||
or "system-dbus"
|
||||
),
|
||||
subscriptions=tuple(
|
||||
DbusSubscription.from_toml(item) for item in subscriptions
|
||||
),
|
||||
drop_unmatched=bool(section.get("drop_unmatched", True)),
|
||||
)
|
||||
|
||||
|
||||
class FakeDbusBackend:
|
||||
def __init__(self, signals: Iterable[DbusSignal | Mapping[str, Any]] | None = None, *, fail_first_read: bool = False) -> None:
|
||||
self._signals: list[DbusSignal] = [signal if isinstance(signal, DbusSignal) else DbusSignal.from_mapping(signal) for signal in (signals or ())]
|
||||
def __init__(
|
||||
self,
|
||||
signals: Iterable[DbusSignal | Mapping[str, Any]] | None = None,
|
||||
*,
|
||||
fail_first_read: bool = False,
|
||||
) -> None:
|
||||
self._signals: list[DbusSignal] = [
|
||||
(
|
||||
signal
|
||||
if isinstance(signal, DbusSignal)
|
||||
else DbusSignal.from_mapping(signal)
|
||||
)
|
||||
for signal in (signals or ())
|
||||
]
|
||||
self._position = 0
|
||||
self._connected = False
|
||||
self._fail_first_read = fail_first_read
|
||||
|
|
@ -230,7 +260,11 @@ class FakeDbusBackend:
|
|||
self.close_calls += 1
|
||||
|
||||
def append(self, signal: DbusSignal | Mapping[str, Any]) -> DbusSignal:
|
||||
dbus_signal = signal if isinstance(signal, DbusSignal) else DbusSignal.from_mapping(signal)
|
||||
dbus_signal = (
|
||||
signal
|
||||
if isinstance(signal, DbusSignal)
|
||||
else DbusSignal.from_mapping(signal)
|
||||
)
|
||||
self._signals.append(dbus_signal)
|
||||
return dbus_signal
|
||||
|
||||
|
|
@ -250,7 +284,11 @@ class SystemBusDbusBackend:
|
|||
raise RuntimeError("dbus-next bindings are not available") from exc
|
||||
|
||||
async def _connect() -> None:
|
||||
bus_type = BusType.SYSTEM if config.bus.strip().lower() != "session" else BusType.SESSION
|
||||
bus_type = (
|
||||
BusType.SYSTEM
|
||||
if config.bus.strip().lower() != "session"
|
||||
else BusType.SESSION
|
||||
)
|
||||
bus = MessageBus(bus_type=bus_type)
|
||||
await bus.connect()
|
||||
bus.add_message_handler(self._make_handler(MessageType))
|
||||
|
|
@ -347,7 +385,10 @@ class DbusCollector(CollectorBase):
|
|||
self._clear_error()
|
||||
|
||||
def stop(self) -> None:
|
||||
if not self._connected and self.connection_state() == CollectorConnectionState.STOPPED:
|
||||
if (
|
||||
not self._connected
|
||||
and self.connection_state() == CollectorConnectionState.STOPPED
|
||||
):
|
||||
return
|
||||
self._set_lifecycle_state(CollectorLifecycleState.STOPPING)
|
||||
self._set_connection_state(CollectorConnectionState.STOPPING)
|
||||
|
|
@ -364,7 +405,9 @@ class DbusCollector(CollectorBase):
|
|||
self._mark_healthy(True)
|
||||
self._clear_error()
|
||||
|
||||
def poll_once(self, *, now_mono_ns_value: int | None = None) -> CollectorPipelineOutcome | None:
|
||||
def poll_once(
|
||||
self, *, now_mono_ns_value: int | None = None
|
||||
) -> CollectorPipelineOutcome | None:
|
||||
if not self._connected:
|
||||
return None
|
||||
try:
|
||||
|
|
@ -377,12 +420,18 @@ class DbusCollector(CollectorBase):
|
|||
self._mark_healthy(True)
|
||||
return None
|
||||
|
||||
raw_event = self._signal_to_raw_event(signal, now_mono_ns_value=now_mono_ns_value)
|
||||
raw_event = self._signal_to_raw_event(
|
||||
signal, now_mono_ns_value=now_mono_ns_value
|
||||
)
|
||||
context = self._build_context(signal)
|
||||
self._increment_stats(events_received_total=1)
|
||||
|
||||
matched_subscription = self._match_subscription(signal)
|
||||
if self.config.subscriptions and matched_subscription is None and self.config.drop_unmatched:
|
||||
if (
|
||||
self.config.subscriptions
|
||||
and matched_subscription is None
|
||||
and self.config.drop_unmatched
|
||||
):
|
||||
self._increment_stats(events_prefilter_dropped_total=1)
|
||||
self._set_pipeline_state(CollectorPipelineState.IDLE)
|
||||
self._mark_healthy(True)
|
||||
|
|
@ -396,7 +445,9 @@ class DbusCollector(CollectorBase):
|
|||
|
||||
outcome = self.pipeline.process(raw_event, context=context)
|
||||
if outcome.accepted:
|
||||
self._increment_stats(events_normalized_total=1, events_marked_total=1, events_emitted_total=1)
|
||||
self._increment_stats(
|
||||
events_normalized_total=1, events_marked_total=1, events_emitted_total=1
|
||||
)
|
||||
self._set_pipeline_state(CollectorPipelineState.ACTIVE)
|
||||
self._mark_healthy(True)
|
||||
self._clear_error()
|
||||
|
|
@ -411,7 +462,9 @@ class DbusCollector(CollectorBase):
|
|||
self._mark_healthy(True)
|
||||
return outcome
|
||||
|
||||
def drain_pending(self, *, limit: int | None = None, now_mono_ns_value: int | None = None) -> list[CollectorPipelineOutcome]:
|
||||
def drain_pending(
|
||||
self, *, limit: int | None = None, now_mono_ns_value: int | None = None
|
||||
) -> list[CollectorPipelineOutcome]:
|
||||
outcomes: list[CollectorPipelineOutcome] = []
|
||||
processed = 0
|
||||
while self._connected and (limit is None or processed < limit):
|
||||
|
|
@ -457,12 +510,20 @@ class DbusCollector(CollectorBase):
|
|||
return subscription
|
||||
return None
|
||||
|
||||
def _signal_to_raw_event(self, signal: DbusSignal, *, now_mono_ns_value: int | None = None) -> CollectorRawEvent:
|
||||
def _signal_to_raw_event(
|
||||
self, signal: DbusSignal, *, now_mono_ns_value: int | None = None
|
||||
) -> CollectorRawEvent:
|
||||
subscription = self._match_subscription(signal)
|
||||
event_type_prefix = subscription.event_type_prefix_for(signal) if subscription is not None else _dbus_event_type_prefix(signal)
|
||||
event_type_prefix = (
|
||||
subscription.event_type_prefix_for(signal)
|
||||
if subscription is not None
|
||||
else _dbus_event_type_prefix(signal)
|
||||
)
|
||||
member_token = _normalize_token(signal.member or "signal")
|
||||
event_type = f"{event_type_prefix}.{member_token}"
|
||||
payload_headers = {f"header.{key}": value for key, value in signal.headers.items()}
|
||||
payload_headers = {
|
||||
f"header.{key}": value for key, value in signal.headers.items()
|
||||
}
|
||||
payload = {
|
||||
"bus_type": self.config.bus,
|
||||
"bus_name": signal.bus_name,
|
||||
|
|
@ -500,7 +561,11 @@ class DbusCollector(CollectorBase):
|
|||
**payload_headers,
|
||||
},
|
||||
payload=payload,
|
||||
labels={"collector": self.config.name, "bus": self.config.bus, "service": signal.bus_name or self.config.source_name},
|
||||
labels={
|
||||
"collector": self.config.name,
|
||||
"bus": self.config.bus,
|
||||
"service": signal.bus_name or self.config.source_name,
|
||||
},
|
||||
tags=(),
|
||||
)
|
||||
|
||||
|
|
@ -560,7 +625,11 @@ def _dbus_signal_severity(signal: DbusSignal) -> Severity:
|
|||
|
||||
|
||||
def _dbus_event_type_prefix(signal: DbusSignal) -> str:
|
||||
text = " ".join(filter(None, [signal.bus_name, signal.interface, signal.object_path, signal.member])).lower()
|
||||
text = " ".join(
|
||||
filter(
|
||||
None, [signal.bus_name, signal.interface, signal.object_path, signal.member]
|
||||
)
|
||||
).lower()
|
||||
if "wpa_supplicant" in text:
|
||||
return "wifi.raw.dbus"
|
||||
if "networkmanager" in text:
|
||||
|
|
@ -576,14 +645,29 @@ def _normalize_token(value: str) -> str:
|
|||
token = token.replace("__", "_")
|
||||
return token or "signal"
|
||||
|
||||
|
||||
def _candidate_values(signal: DbusSignal, field: str) -> tuple[str, ...]:
|
||||
if field == "service":
|
||||
return tuple(value for value in (signal.bus_name, signal.sender, signal.destination) if value)
|
||||
return tuple(
|
||||
value
|
||||
for value in (signal.bus_name, signal.sender, signal.destination)
|
||||
if value
|
||||
)
|
||||
if field == "sender":
|
||||
return tuple(value for value in (signal.sender, signal.bus_name, signal.destination) if value)
|
||||
return tuple(
|
||||
value
|
||||
for value in (signal.sender, signal.bus_name, signal.destination)
|
||||
if value
|
||||
)
|
||||
if field == "destination":
|
||||
return tuple(value for value in (signal.destination, signal.bus_name, signal.sender) if value)
|
||||
return tuple(value for value in (signal.bus_name, signal.sender, signal.destination) if value)
|
||||
return tuple(
|
||||
value
|
||||
for value in (signal.destination, signal.bus_name, signal.sender)
|
||||
if value
|
||||
)
|
||||
return tuple(
|
||||
value for value in (signal.bus_name, signal.sender, signal.destination) if value
|
||||
)
|
||||
|
||||
|
||||
def _matches_any(signal: DbusSignal, expected: str, field: str) -> bool:
|
||||
|
|
@ -591,7 +675,9 @@ def _matches_any(signal: DbusSignal, expected: str, field: str) -> bool:
|
|||
|
||||
|
||||
def _matches_prefix(signal: DbusSignal, expected: str, field: str) -> bool:
|
||||
return any(candidate.startswith(expected) for candidate in _candidate_values(signal, field))
|
||||
return any(
|
||||
candidate.startswith(expected) for candidate in _candidate_values(signal, field)
|
||||
)
|
||||
|
||||
|
||||
def _subscription_list(section: Mapping[str, Any]) -> list[Mapping[str, Any]]:
|
||||
|
|
@ -607,7 +693,9 @@ def _subscription_list(section: Mapping[str, Any]) -> list[Mapping[str, Any]]:
|
|||
return []
|
||||
|
||||
|
||||
def _select_collector_section(data: Mapping[str, Any], collector_name: str | None) -> Mapping[str, Any]:
|
||||
def _select_collector_section(
|
||||
data: Mapping[str, Any], collector_name: str | None
|
||||
) -> Mapping[str, Any]:
|
||||
if collector_name is not None:
|
||||
collectors = data.get("collectors")
|
||||
if isinstance(collectors, Mapping):
|
||||
|
|
@ -619,4 +707,4 @@ def _select_collector_section(data: Mapping[str, Any], collector_name: str | Non
|
|||
section = next(iter(collectors.values()))
|
||||
if isinstance(section, Mapping):
|
||||
return section
|
||||
return data
|
||||
return data
|
||||
|
|
|
|||
|
|
@ -14,21 +14,22 @@ from .base import (
|
|||
CollectorLifecycleState,
|
||||
CollectorPipelineState,
|
||||
)
|
||||
from .pipeline import CollectorPipeline, CollectorPipelineContext, CollectorPipelineOutcome, CollectorRawEvent
|
||||
|
||||
from .pipeline import (
|
||||
CollectorPipeline,
|
||||
CollectorPipelineContext,
|
||||
CollectorPipelineOutcome,
|
||||
CollectorRawEvent,
|
||||
)
|
||||
|
||||
JournalSink = Callable[[events_pb2.EventEnvelope], None]
|
||||
|
||||
|
||||
class JournalBackend(Protocol):
|
||||
def connect(self, config: "JournalCollectorConfig") -> None:
|
||||
...
|
||||
def connect(self, config: "JournalCollectorConfig") -> None: ...
|
||||
|
||||
def read(self) -> "JournalEntry | None":
|
||||
...
|
||||
def read(self) -> "JournalEntry | None": ...
|
||||
|
||||
def close(self) -> None:
|
||||
...
|
||||
def close(self) -> None: ...
|
||||
|
||||
|
||||
@dataclass(slots=True, frozen=True)
|
||||
|
|
@ -44,14 +45,31 @@ class JournalEntry:
|
|||
def from_mapping(cls, data: Mapping[str, Any]) -> "JournalEntry":
|
||||
fields = data.get("fields")
|
||||
if not isinstance(fields, Mapping):
|
||||
fields = {key: value for key, value in data.items() if key not in {"message", "cursor", "realtime_ns", "monotonic_ns", "source_name"}}
|
||||
fields = {
|
||||
key: value
|
||||
for key, value in data.items()
|
||||
if key
|
||||
not in {
|
||||
"message",
|
||||
"cursor",
|
||||
"realtime_ns",
|
||||
"monotonic_ns",
|
||||
"source_name",
|
||||
}
|
||||
}
|
||||
return cls(
|
||||
message=str(data.get("message", data.get("MESSAGE", "")) or ""),
|
||||
fields=dict(fields),
|
||||
cursor=str(data.get("cursor", data.get("_CURSOR", "")) or ""),
|
||||
realtime_ns=int(data.get("realtime_ns", data.get("__REALTIME_TIMESTAMP", 0)) or 0),
|
||||
monotonic_ns=int(data.get("monotonic_ns", data.get("__MONOTONIC_TIMESTAMP", 0)) or 0),
|
||||
source_name=str(data.get("source_name", data.get("SYSLOG_IDENTIFIER", "")) or ""),
|
||||
realtime_ns=int(
|
||||
data.get("realtime_ns", data.get("__REALTIME_TIMESTAMP", 0)) or 0
|
||||
),
|
||||
monotonic_ns=int(
|
||||
data.get("monotonic_ns", data.get("__MONOTONIC_TIMESTAMP", 0)) or 0
|
||||
),
|
||||
source_name=str(
|
||||
data.get("source_name", data.get("SYSLOG_IDENTIFIER", "")) or ""
|
||||
),
|
||||
)
|
||||
|
||||
def as_mapping(self) -> dict[str, Any]:
|
||||
|
|
@ -81,7 +99,9 @@ class JournalCollectorConfig:
|
|||
max_priority: int | None = None
|
||||
|
||||
@classmethod
|
||||
def from_toml(cls, data: Mapping[str, Any], *, collector_name: str | None = None) -> "JournalCollectorConfig":
|
||||
def from_toml(
|
||||
cls, data: Mapping[str, Any], *, collector_name: str | None = None
|
||||
) -> "JournalCollectorConfig":
|
||||
section = _select_collector_section(data, collector_name)
|
||||
if not isinstance(section, Mapping):
|
||||
section = {}
|
||||
|
|
@ -90,7 +110,9 @@ class JournalCollectorConfig:
|
|||
enabled=bool(section.get("enabled", True)),
|
||||
mode=str(section.get("mode", "tail") or "tail"),
|
||||
cursor=str(section.get("cursor", "") or ""),
|
||||
source_name=str(section.get("source_name", "systemd-journal") or "systemd-journal"),
|
||||
source_name=str(
|
||||
section.get("source_name", "systemd-journal") or "systemd-journal"
|
||||
),
|
||||
unit_allowlist=_string_tuple(section.get("unit_allowlist", ())),
|
||||
comm_allowlist=_string_tuple(section.get("comm_allowlist", ())),
|
||||
exe_allowlist=_string_tuple(section.get("exe_allowlist", ())),
|
||||
|
|
@ -100,8 +122,20 @@ class JournalCollectorConfig:
|
|||
|
||||
|
||||
class FakeJournalBackend:
|
||||
def __init__(self, entries: Iterable[JournalEntry | Mapping[str, Any]] | None = None, *, fail_first_read: bool = False) -> None:
|
||||
self._entries: list[JournalEntry] = [entry if isinstance(entry, JournalEntry) else JournalEntry.from_mapping(entry) for entry in (entries or ())]
|
||||
def __init__(
|
||||
self,
|
||||
entries: Iterable[JournalEntry | Mapping[str, Any]] | None = None,
|
||||
*,
|
||||
fail_first_read: bool = False,
|
||||
) -> None:
|
||||
self._entries: list[JournalEntry] = [
|
||||
(
|
||||
entry
|
||||
if isinstance(entry, JournalEntry)
|
||||
else JournalEntry.from_mapping(entry)
|
||||
)
|
||||
for entry in (entries or ())
|
||||
]
|
||||
self._position = 0
|
||||
self._connected = False
|
||||
self._fail_first_read = fail_first_read
|
||||
|
|
@ -141,7 +175,11 @@ class FakeJournalBackend:
|
|||
self.close_calls += 1
|
||||
|
||||
def append(self, entry: JournalEntry | Mapping[str, Any]) -> JournalEntry:
|
||||
journal_entry = entry if isinstance(entry, JournalEntry) else JournalEntry.from_mapping(entry)
|
||||
journal_entry = (
|
||||
entry
|
||||
if isinstance(entry, JournalEntry)
|
||||
else JournalEntry.from_mapping(entry)
|
||||
)
|
||||
self._entries.append(journal_entry)
|
||||
return journal_entry
|
||||
|
||||
|
|
@ -255,7 +293,10 @@ class JournalCollector(CollectorBase):
|
|||
self._clear_error()
|
||||
|
||||
def stop(self) -> None:
|
||||
if not self._connected and self.connection_state() == CollectorConnectionState.STOPPED:
|
||||
if (
|
||||
not self._connected
|
||||
and self.connection_state() == CollectorConnectionState.STOPPED
|
||||
):
|
||||
return
|
||||
self._set_lifecycle_state(CollectorLifecycleState.STOPPING)
|
||||
self._set_connection_state(CollectorConnectionState.STOPPING)
|
||||
|
|
@ -273,7 +314,9 @@ class JournalCollector(CollectorBase):
|
|||
self._mark_healthy(True)
|
||||
self._clear_error()
|
||||
|
||||
def poll_once(self, *, now_mono_ns_value: int | None = None) -> CollectorPipelineOutcome | None:
|
||||
def poll_once(
|
||||
self, *, now_mono_ns_value: int | None = None
|
||||
) -> CollectorPipelineOutcome | None:
|
||||
if not self._connected:
|
||||
return None
|
||||
try:
|
||||
|
|
@ -324,7 +367,9 @@ class JournalCollector(CollectorBase):
|
|||
self._mark_healthy(True)
|
||||
return outcome
|
||||
|
||||
def drain_pending(self, *, limit: int | None = None, now_mono_ns_value: int | None = None) -> list[CollectorPipelineOutcome]:
|
||||
def drain_pending(
|
||||
self, *, limit: int | None = None, now_mono_ns_value: int | None = None
|
||||
) -> list[CollectorPipelineOutcome]:
|
||||
outcomes: list[CollectorPipelineOutcome] = []
|
||||
processed = 0
|
||||
while self._connected and (limit is None or processed < limit):
|
||||
|
|
@ -376,9 +421,19 @@ class JournalCollector(CollectorBase):
|
|||
comm = str(fields.get("_COMM", "") or "")
|
||||
exe = str(fields.get("_EXE", "") or "")
|
||||
event_type = _journal_event_type(unit=unit, comm=comm, severity=severity)
|
||||
source_name = entry.source_name or str(fields.get("SYSLOG_IDENTIFIER", unit or comm or self.config.source_name) or self.config.source_name)
|
||||
observed_wall_ns = int(fields.get("__REALTIME_TIMESTAMP", entry.realtime_ns or 0) or 0)
|
||||
observed_mono_ns = int(fields.get("__MONOTONIC_TIMESTAMP", entry.monotonic_ns or observed_wall_ns or 0) or 0)
|
||||
source_name = entry.source_name or str(
|
||||
fields.get("SYSLOG_IDENTIFIER", unit or comm or self.config.source_name)
|
||||
or self.config.source_name
|
||||
)
|
||||
observed_wall_ns = int(
|
||||
fields.get("__REALTIME_TIMESTAMP", entry.realtime_ns or 0) or 0
|
||||
)
|
||||
observed_mono_ns = int(
|
||||
fields.get(
|
||||
"__MONOTONIC_TIMESTAMP", entry.monotonic_ns or observed_wall_ns or 0
|
||||
)
|
||||
or 0
|
||||
)
|
||||
if now_mono_ns_value is not None and observed_mono_ns <= 0:
|
||||
observed_mono_ns = int(now_mono_ns_value)
|
||||
return CollectorRawEvent(
|
||||
|
|
@ -396,7 +451,9 @@ class JournalCollector(CollectorBase):
|
|||
correlation_id=str(fields.get("CORRELATION_ID", "") or ""),
|
||||
causation_id=str(fields.get("CAUSATION_ID", "") or ""),
|
||||
parent_event_id=str(fields.get("PARENT_EVENT_ID", "") or ""),
|
||||
normalized_event_code=str(fields.get("CODE", message or event_type) or event_type),
|
||||
normalized_event_code=str(
|
||||
fields.get("CODE", message or event_type) or event_type
|
||||
),
|
||||
normalized_reason=str(fields.get("MESSAGE", message or "") or message),
|
||||
fields=fields,
|
||||
payload=None,
|
||||
|
|
@ -409,7 +466,11 @@ class JournalCollector(CollectorBase):
|
|||
return CollectorPipelineContext(
|
||||
collector_name=self.config.name,
|
||||
source_kind=SourceKind.JOURNAL,
|
||||
source_name=entry.source_name or str(fields.get("SYSLOG_IDENTIFIER", self.config.source_name) or self.config.source_name),
|
||||
source_name=entry.source_name
|
||||
or str(
|
||||
fields.get("SYSLOG_IDENTIFIER", self.config.source_name)
|
||||
or self.config.source_name
|
||||
),
|
||||
labels={"source": "journal", "collector": self.config.name},
|
||||
metadata={"mode": self.config.mode, "cursor": entry.cursor},
|
||||
)
|
||||
|
|
@ -480,7 +541,9 @@ def _string_tuple(value: Any) -> tuple[str, ...]:
|
|||
return (text,) if text else ()
|
||||
|
||||
|
||||
def _select_collector_section(data: Mapping[str, Any], collector_name: str | None) -> Mapping[str, Any]:
|
||||
def _select_collector_section(
|
||||
data: Mapping[str, Any], collector_name: str | None
|
||||
) -> Mapping[str, Any]:
|
||||
collectors = data.get("collectors")
|
||||
if collector_name is not None and isinstance(collectors, Mapping):
|
||||
section = collectors.get(collector_name, {})
|
||||
|
|
@ -504,4 +567,4 @@ def _create_systemd_reader() -> Any:
|
|||
except Exception as exc: # pragma: no cover - optional dependency path
|
||||
raise RuntimeError("systemd journal bindings are not available") from exc
|
||||
_SYSTEMD_JOURNAL_MODULE = systemd_journal
|
||||
return _SYSTEMD_JOURNAL_MODULE.Reader()
|
||||
return _SYSTEMD_JOURNAL_MODULE.Reader()
|
||||
|
|
|
|||
|
|
@ -41,17 +41,25 @@ class MarkRule:
|
|||
set_values = {}
|
||||
condition = _rule_condition_from_mapping(data)
|
||||
labels = _collect_flat_mapping(add, "labels")
|
||||
workflow_tags = _sequence_from_any(add.get("workflow_tags", data.get("workflow_tags", ())))
|
||||
workflow_tags = _sequence_from_any(
|
||||
add.get("workflow_tags", data.get("workflow_tags", ()))
|
||||
)
|
||||
return cls(
|
||||
condition=condition,
|
||||
name=str(data.get("name", "")),
|
||||
add_workflow_tags=tuple(str(item) for item in workflow_tags if item is not None),
|
||||
add_workflow_tags=tuple(
|
||||
str(item) for item in workflow_tags if item is not None
|
||||
),
|
||||
add_labels={str(key): str(value) for key, value in labels.items()},
|
||||
set_cache_enabled=_select_bool(add, set_values, "routing", "cache_enabled"),
|
||||
set_outbox_enabled=_select_bool(add, set_values, "routing", "outbox_enabled"),
|
||||
set_outbox_enabled=_select_bool(
|
||||
add, set_values, "routing", "outbox_enabled"
|
||||
),
|
||||
set_priority=_select_int(add, set_values, "routing", "priority"),
|
||||
set_severity=add.get("severity", set_values.get("severity")),
|
||||
set_event_type=_optional_str(set_values.get("event_type", data.get("event_type"))),
|
||||
set_event_type=_optional_str(
|
||||
set_values.get("event_type", data.get("event_type"))
|
||||
),
|
||||
set_subject=_optional_str(set_values.get("subject", data.get("subject"))),
|
||||
)
|
||||
|
||||
|
|
@ -90,7 +98,9 @@ class Marker:
|
|||
envelope.trace.workflow_tags.append(tag)
|
||||
workflow_tags_added.append(tag)
|
||||
if rule.add_labels:
|
||||
flattened = {str(key): str(value) for key, value in rule.add_labels.items()}
|
||||
flattened = {
|
||||
str(key): str(value) for key, value in rule.add_labels.items()
|
||||
}
|
||||
envelope.attributes.labels.update(flattened)
|
||||
labels_added.update(flattened)
|
||||
if rule.set_cache_enabled is not None:
|
||||
|
|
@ -115,11 +125,17 @@ class Marker:
|
|||
)
|
||||
|
||||
|
||||
def _select_bool(add: Mapping[str, Any], set_values: Mapping[str, Any], parent: str, key: str) -> bool | None:
|
||||
def _select_bool(
|
||||
add: Mapping[str, Any], set_values: Mapping[str, Any], parent: str, key: str
|
||||
) -> bool | None:
|
||||
candidate = None
|
||||
if parent in add and isinstance(add[parent], Mapping):
|
||||
candidate = add[parent].get(key)
|
||||
if candidate is None and parent in set_values and isinstance(set_values[parent], Mapping):
|
||||
if (
|
||||
candidate is None
|
||||
and parent in set_values
|
||||
and isinstance(set_values[parent], Mapping)
|
||||
):
|
||||
candidate = set_values[parent].get(key)
|
||||
if candidate is None and key in add:
|
||||
candidate = add[key]
|
||||
|
|
@ -130,11 +146,17 @@ def _select_bool(add: Mapping[str, Any], set_values: Mapping[str, Any], parent:
|
|||
return bool(candidate)
|
||||
|
||||
|
||||
def _select_int(add: Mapping[str, Any], set_values: Mapping[str, Any], parent: str, key: str) -> int | None:
|
||||
def _select_int(
|
||||
add: Mapping[str, Any], set_values: Mapping[str, Any], parent: str, key: str
|
||||
) -> int | None:
|
||||
candidate = None
|
||||
if parent in add and isinstance(add[parent], Mapping):
|
||||
candidate = add[parent].get(key)
|
||||
if candidate is None and parent in set_values and isinstance(set_values[parent], Mapping):
|
||||
if (
|
||||
candidate is None
|
||||
and parent in set_values
|
||||
and isinstance(set_values[parent], Mapping)
|
||||
):
|
||||
candidate = set_values[parent].get(key)
|
||||
if candidate is None and key in add:
|
||||
candidate = add[key]
|
||||
|
|
|
|||
|
|
@ -15,21 +15,22 @@ from .base import (
|
|||
CollectorLifecycleState,
|
||||
CollectorPipelineState,
|
||||
)
|
||||
from .pipeline import CollectorPipeline, CollectorPipelineContext, CollectorPipelineOutcome, CollectorRawEvent
|
||||
|
||||
from .pipeline import (
|
||||
CollectorPipeline,
|
||||
CollectorPipelineContext,
|
||||
CollectorPipelineOutcome,
|
||||
CollectorRawEvent,
|
||||
)
|
||||
|
||||
NavigationSink = Callable[[events_pb2.EventEnvelope], None]
|
||||
|
||||
|
||||
class NavigationAdapter(Protocol):
|
||||
def connect(self, config: "NavigationCollectorConfig") -> None:
|
||||
...
|
||||
def connect(self, config: "NavigationCollectorConfig") -> None: ...
|
||||
|
||||
def read(self) -> "NavigationObservation | None":
|
||||
...
|
||||
def read(self) -> "NavigationObservation | None": ...
|
||||
|
||||
def close(self) -> None:
|
||||
...
|
||||
def close(self) -> None: ...
|
||||
|
||||
|
||||
@dataclass(slots=True, frozen=True)
|
||||
|
|
@ -58,14 +59,24 @@ class NavigationObservation:
|
|||
if not isinstance(details, Mapping):
|
||||
details = {}
|
||||
combined = {**dict(payload), **dict(details)}
|
||||
event_class = str(data.get("event_class", data.get("class", combined.get("event_class", combined.get("class", "")))) or "")
|
||||
event_class = str(
|
||||
data.get(
|
||||
"event_class",
|
||||
data.get(
|
||||
"class", combined.get("event_class", combined.get("class", ""))
|
||||
),
|
||||
)
|
||||
or ""
|
||||
)
|
||||
event_type = str(data.get("event_type", combined.get("event_type", "")) or "")
|
||||
if not event_type:
|
||||
event_type = _navigation_event_type_from_class(event_class)
|
||||
message = str(data.get("message", data.get("summary", event_type)) or "")
|
||||
return cls(
|
||||
robot_id=str(data.get("robot_id", combined.get("robot_id", "")) or ""),
|
||||
mission_id=str(data.get("mission_id", combined.get("mission_id", "")) or ""),
|
||||
mission_id=str(
|
||||
data.get("mission_id", combined.get("mission_id", "")) or ""
|
||||
),
|
||||
event_class=event_class,
|
||||
event_type=event_type,
|
||||
message=message,
|
||||
|
|
@ -74,10 +85,16 @@ class NavigationObservation:
|
|||
y=_coerce_float(data.get("y", combined.get("y", 0.0))),
|
||||
z=_coerce_float(data.get("z", combined.get("z", 0.0))),
|
||||
yaw=_coerce_float(data.get("yaw", combined.get("yaw", 0.0))),
|
||||
source_name=str(data.get("source_name", combined.get("source_name", "")) or ""),
|
||||
source_name=str(
|
||||
data.get("source_name", combined.get("source_name", "")) or ""
|
||||
),
|
||||
details=dict(combined),
|
||||
realtime_ns=int(data.get("realtime_ns", data.get("__REALTIME_TIMESTAMP", 0)) or 0),
|
||||
monotonic_ns=int(data.get("monotonic_ns", data.get("__MONOTONIC_TIMESTAMP", 0)) or 0),
|
||||
realtime_ns=int(
|
||||
data.get("realtime_ns", data.get("__REALTIME_TIMESTAMP", 0)) or 0
|
||||
),
|
||||
monotonic_ns=int(
|
||||
data.get("monotonic_ns", data.get("__MONOTONIC_TIMESTAMP", 0)) or 0
|
||||
),
|
||||
)
|
||||
|
||||
def as_mapping(self) -> dict[str, Any]:
|
||||
|
|
@ -126,19 +143,26 @@ class NavigationCollectorConfig:
|
|||
drop_unmatched: bool = True
|
||||
|
||||
@classmethod
|
||||
def from_toml(cls, data: Mapping[str, Any], *, collector_name: str | None = None) -> "NavigationCollectorConfig":
|
||||
def from_toml(
|
||||
cls, data: Mapping[str, Any], *, collector_name: str | None = None
|
||||
) -> "NavigationCollectorConfig":
|
||||
section = _select_collector_section(data, collector_name)
|
||||
if not isinstance(section, Mapping):
|
||||
section = {}
|
||||
adapter = str(section.get("adapter", "stub") or "stub")
|
||||
source_name = str(section.get("source_name", f"navigation://{adapter}") or f"navigation://{adapter}")
|
||||
source_name = str(
|
||||
section.get("source_name", f"navigation://{adapter}")
|
||||
or f"navigation://{adapter}"
|
||||
)
|
||||
return cls(
|
||||
name=str(collector_name or section.get("name", "navigation")),
|
||||
enabled=bool(section.get("enabled", True)),
|
||||
adapter=adapter,
|
||||
source_name=source_name,
|
||||
robot_allowlist=_string_tuple(section.get("robot_allowlist", ())),
|
||||
event_class_allowlist=_string_tuple(section.get("event_class_allowlist", ())),
|
||||
event_class_allowlist=_string_tuple(
|
||||
section.get("event_class_allowlist", ())
|
||||
),
|
||||
frame_allowlist=_string_tuple(section.get("frame_allowlist", ())),
|
||||
drop_unmatched=bool(section.get("drop_unmatched", True)),
|
||||
)
|
||||
|
|
@ -152,7 +176,11 @@ class FakeNavigationBackend:
|
|||
fail_first_read: bool = False,
|
||||
) -> None:
|
||||
self._observations: list[NavigationObservation] = [
|
||||
observation if isinstance(observation, NavigationObservation) else NavigationObservation.from_mapping(observation)
|
||||
(
|
||||
observation
|
||||
if isinstance(observation, NavigationObservation)
|
||||
else NavigationObservation.from_mapping(observation)
|
||||
)
|
||||
for observation in (observations or ())
|
||||
]
|
||||
self._position = 0
|
||||
|
|
@ -187,8 +215,14 @@ class FakeNavigationBackend:
|
|||
self._connected = False
|
||||
self.close_calls += 1
|
||||
|
||||
def append(self, observation: NavigationObservation | Mapping[str, Any]) -> NavigationObservation:
|
||||
sample = observation if isinstance(observation, NavigationObservation) else NavigationObservation.from_mapping(observation)
|
||||
def append(
|
||||
self, observation: NavigationObservation | Mapping[str, Any]
|
||||
) -> NavigationObservation:
|
||||
sample = (
|
||||
observation
|
||||
if isinstance(observation, NavigationObservation)
|
||||
else NavigationObservation.from_mapping(observation)
|
||||
)
|
||||
self._observations.append(sample)
|
||||
return sample
|
||||
|
||||
|
|
@ -250,7 +284,9 @@ class SystemNavigationBackend:
|
|||
return result
|
||||
if isinstance(result, Mapping):
|
||||
return NavigationObservation.from_mapping(result)
|
||||
return NavigationObservation.from_mapping({"event_type": str(result), "message": str(result)})
|
||||
return NavigationObservation.from_mapping(
|
||||
{"event_type": str(result), "message": str(result)}
|
||||
)
|
||||
|
||||
def close(self) -> None:
|
||||
backend = self._backend
|
||||
|
|
@ -266,7 +302,13 @@ class SystemNavigationBackend:
|
|||
|
||||
def _load_backend(self) -> Any:
|
||||
module = _load_navigation_module(self.adapter_path)
|
||||
for attr in ("NavigationAdapter", "NavigationBackend", "Adapter", "Client", "NavigationClient"):
|
||||
for attr in (
|
||||
"NavigationAdapter",
|
||||
"NavigationBackend",
|
||||
"Adapter",
|
||||
"Client",
|
||||
"NavigationClient",
|
||||
):
|
||||
candidate = getattr(module, attr, None)
|
||||
if candidate is None:
|
||||
continue
|
||||
|
|
@ -314,7 +356,9 @@ class NavigationCollector(CollectorBase):
|
|||
backend: NavigationAdapter | None = None,
|
||||
director_sink: NavigationSink | None = None,
|
||||
) -> "NavigationCollector":
|
||||
config = NavigationCollectorConfig.from_toml(data, collector_name=collector_name)
|
||||
config = NavigationCollectorConfig.from_toml(
|
||||
data, collector_name=collector_name
|
||||
)
|
||||
pipeline = CollectorPipeline.from_toml(data, collector_name=collector_name)
|
||||
return cls(config, pipeline, backend=backend, director_sink=director_sink)
|
||||
|
||||
|
|
@ -339,7 +383,10 @@ class NavigationCollector(CollectorBase):
|
|||
self._clear_error()
|
||||
|
||||
def stop(self) -> None:
|
||||
if not self._connected and self.connection_state() == CollectorConnectionState.STOPPED:
|
||||
if (
|
||||
not self._connected
|
||||
and self.connection_state() == CollectorConnectionState.STOPPED
|
||||
):
|
||||
return
|
||||
self._set_lifecycle_state(CollectorLifecycleState.STOPPING)
|
||||
self._set_connection_state(CollectorConnectionState.STOPPING)
|
||||
|
|
@ -356,7 +403,9 @@ class NavigationCollector(CollectorBase):
|
|||
self._mark_healthy(True)
|
||||
self._clear_error()
|
||||
|
||||
def poll_once(self, *, now_mono_ns_value: int | None = None) -> CollectorPipelineOutcome | None:
|
||||
def poll_once(
|
||||
self, *, now_mono_ns_value: int | None = None
|
||||
) -> CollectorPipelineOutcome | None:
|
||||
if not self._connected:
|
||||
return None
|
||||
try:
|
||||
|
|
@ -369,7 +418,9 @@ class NavigationCollector(CollectorBase):
|
|||
self._mark_healthy(True)
|
||||
return None
|
||||
|
||||
raw_event = self._observation_to_raw_event(observation, now_mono_ns_value=now_mono_ns_value)
|
||||
raw_event = self._observation_to_raw_event(
|
||||
observation, now_mono_ns_value=now_mono_ns_value
|
||||
)
|
||||
context = self._build_context(observation)
|
||||
self._increment_stats(events_received_total=1)
|
||||
|
||||
|
|
@ -388,7 +439,9 @@ class NavigationCollector(CollectorBase):
|
|||
|
||||
outcome = self.pipeline.process(raw_event, context=context)
|
||||
if outcome.accepted:
|
||||
self._increment_stats(events_normalized_total=1, events_marked_total=1, events_emitted_total=1)
|
||||
self._increment_stats(
|
||||
events_normalized_total=1, events_marked_total=1, events_emitted_total=1
|
||||
)
|
||||
self._set_pipeline_state(CollectorPipelineState.ACTIVE)
|
||||
self._mark_healthy(True)
|
||||
self._clear_error()
|
||||
|
|
@ -403,7 +456,9 @@ class NavigationCollector(CollectorBase):
|
|||
self._mark_healthy(True)
|
||||
return outcome
|
||||
|
||||
def drain_pending(self, *, limit: int | None = None, now_mono_ns_value: int | None = None) -> list[CollectorPipelineOutcome]:
|
||||
def drain_pending(
|
||||
self, *, limit: int | None = None, now_mono_ns_value: int | None = None
|
||||
) -> list[CollectorPipelineOutcome]:
|
||||
outcomes: list[CollectorPipelineOutcome] = []
|
||||
processed = 0
|
||||
while self._connected and (limit is None or processed < limit):
|
||||
|
|
@ -441,24 +496,33 @@ class NavigationCollector(CollectorBase):
|
|||
self._set_pipeline_state(CollectorPipelineState.ERROR)
|
||||
self.reconnect()
|
||||
|
||||
def _source_prefilter_reason(self, observation: NavigationObservation) -> str | None:
|
||||
def _source_prefilter_reason(
|
||||
self, observation: NavigationObservation
|
||||
) -> str | None:
|
||||
if not self.config.drop_unmatched:
|
||||
return None
|
||||
if self.config.robot_allowlist and _normalize_nav_token(observation.robot_id) not in {
|
||||
_normalize_nav_token(value) for value in self.config.robot_allowlist
|
||||
}:
|
||||
if self.config.robot_allowlist and _normalize_nav_token(
|
||||
observation.robot_id
|
||||
) not in {_normalize_nav_token(value) for value in self.config.robot_allowlist}:
|
||||
return f"robot not allowed: {observation.robot_id or '<empty>'}"
|
||||
if self.config.event_class_allowlist and _normalize_nav_token(_navigation_class(observation)) not in {
|
||||
if self.config.event_class_allowlist and _normalize_nav_token(
|
||||
_navigation_class(observation)
|
||||
) not in {
|
||||
_normalize_nav_token(value) for value in self.config.event_class_allowlist
|
||||
}:
|
||||
return f"event class not allowed: {observation.event_class or _navigation_class(observation)}"
|
||||
if self.config.frame_allowlist and _normalize_nav_token(observation.frame_id) not in {
|
||||
_normalize_nav_token(value) for value in self.config.frame_allowlist
|
||||
}:
|
||||
if self.config.frame_allowlist and _normalize_nav_token(
|
||||
observation.frame_id
|
||||
) not in {_normalize_nav_token(value) for value in self.config.frame_allowlist}:
|
||||
return f"frame not allowed: {observation.frame_id or '<empty>'}"
|
||||
return None
|
||||
|
||||
def _observation_to_raw_event(self, observation: NavigationObservation, *, now_mono_ns_value: int | None = None) -> CollectorRawEvent:
|
||||
def _observation_to_raw_event(
|
||||
self,
|
||||
observation: NavigationObservation,
|
||||
*,
|
||||
now_mono_ns_value: int | None = None,
|
||||
) -> CollectorRawEvent:
|
||||
event_type = _navigation_event_type(observation)
|
||||
event_class = _navigation_class(observation)
|
||||
observed_mono_ns = observation.monotonic_ns or (now_mono_ns_value or 0)
|
||||
|
|
@ -493,7 +557,9 @@ class NavigationCollector(CollectorBase):
|
|||
tags=(),
|
||||
)
|
||||
|
||||
def _build_context(self, observation: NavigationObservation) -> CollectorPipelineContext:
|
||||
def _build_context(
|
||||
self, observation: NavigationObservation
|
||||
) -> CollectorPipelineContext:
|
||||
labels = {
|
||||
"source": "navigation",
|
||||
"collector": self.config.name,
|
||||
|
|
@ -583,7 +649,9 @@ def _string_tuple(value: Any) -> tuple[str, ...]:
|
|||
return (text,) if text else ()
|
||||
|
||||
|
||||
def _select_collector_section(data: Mapping[str, Any], collector_name: str | None) -> Mapping[str, Any]:
|
||||
def _select_collector_section(
|
||||
data: Mapping[str, Any], collector_name: str | None
|
||||
) -> Mapping[str, Any]:
|
||||
collectors = data.get("collectors")
|
||||
if collector_name is not None and isinstance(collectors, Mapping):
|
||||
section = collectors.get(collector_name, {})
|
||||
|
|
@ -601,9 +669,14 @@ _NAVIGATION_MODULE: Any | None = None
|
|||
|
||||
def _load_navigation_module(adapter_path: str) -> Any:
|
||||
global _NAVIGATION_MODULE
|
||||
if _NAVIGATION_MODULE is None or getattr(_NAVIGATION_MODULE, "__name__", None) != adapter_path:
|
||||
if (
|
||||
_NAVIGATION_MODULE is None
|
||||
or getattr(_NAVIGATION_MODULE, "__name__", None) != adapter_path
|
||||
):
|
||||
try:
|
||||
_NAVIGATION_MODULE = importlib.import_module(adapter_path)
|
||||
except Exception as exc: # pragma: no cover - optional dependency path
|
||||
raise RuntimeError(f"navigation adapter '{adapter_path}' is not available") from exc
|
||||
raise RuntimeError(
|
||||
f"navigation adapter '{adapter_path}' is not available"
|
||||
) from exc
|
||||
return _NAVIGATION_MODULE
|
||||
|
|
|
|||
|
|
@ -47,7 +47,9 @@ class Normalizer:
|
|||
validation_result: ValidationResult | None = None,
|
||||
) -> NormalizationResult:
|
||||
source_kind = _coerce_source_kind(
|
||||
raw.source_kind if raw.source_kind != SourceKind.UNSPECIFIED else context.source_kind
|
||||
raw.source_kind
|
||||
if raw.source_kind != SourceKind.UNSPECIFIED
|
||||
else context.source_kind
|
||||
)
|
||||
event_kind = _coerce_event_kind(raw.event_kind)
|
||||
payload_kind = _coerce_payload_kind(raw.payload_kind, source_kind)
|
||||
|
|
@ -55,11 +57,17 @@ class Normalizer:
|
|||
|
||||
payload_field, payload_message = self._build_payload(raw, context, payload_kind)
|
||||
severity = _coerce_severity(raw.severity)
|
||||
if validation_result is not None and validation_result.downgraded and severity < Severity.ERROR:
|
||||
if (
|
||||
validation_result is not None
|
||||
and validation_result.downgraded
|
||||
and severity < Severity.ERROR
|
||||
):
|
||||
severity = Severity.ERROR
|
||||
|
||||
envelope = make_event_envelope(
|
||||
id=str(raw.fields.get("id", raw.normalized_event_code or raw.event_type or "")),
|
||||
id=str(
|
||||
raw.fields.get("id", raw.normalized_event_code or raw.event_type or "")
|
||||
),
|
||||
source=raw.source_name or context.source_name or raw.collector_name,
|
||||
type=raw.event_type,
|
||||
subject=raw.subject,
|
||||
|
|
@ -91,7 +99,9 @@ class Normalizer:
|
|||
envelope.attributes.labels.setdefault("profile", context.profile)
|
||||
if context.site_id:
|
||||
envelope.attributes.labels.setdefault("site_id", context.site_id)
|
||||
return NormalizationResult(envelope=envelope, payload_field=payload_field, payload_kind=payload_kind)
|
||||
return NormalizationResult(
|
||||
envelope=envelope, payload_field=payload_field, payload_kind=payload_kind
|
||||
)
|
||||
|
||||
def _build_payload(
|
||||
self,
|
||||
|
|
@ -109,19 +119,32 @@ class Normalizer:
|
|||
comm=str(fields.get("_COMM", "")),
|
||||
exe=str(fields.get("_EXE", "")),
|
||||
)
|
||||
message.fields.update({str(key): _stringify(value) for key, value in fields.items()})
|
||||
message.fields.update(
|
||||
{str(key): _stringify(value) for key, value in fields.items()}
|
||||
)
|
||||
return "raw_journal", message
|
||||
if payload_kind == PayloadKind.DBUS:
|
||||
message = events_pb2.RawDbusPayload(
|
||||
bus_type=str(payload.get("bus_type", fields.get("bus_type", ""))),
|
||||
bus_name=str(raw.source_name or context.source_name or ""),
|
||||
object_path=str(fields.get("object_path", payload.get("object_path", ""))),
|
||||
object_path=str(
|
||||
fields.get("object_path", payload.get("object_path", ""))
|
||||
),
|
||||
interface=str(fields.get("interface", payload.get("interface", ""))),
|
||||
member=str(fields.get("member", payload.get("member", ""))),
|
||||
)
|
||||
message.headers.update({str(key): _stringify(value) for key, value in fields.items() if key.startswith("header.")})
|
||||
message.headers.update(
|
||||
{
|
||||
str(key): _stringify(value)
|
||||
for key, value in fields.items()
|
||||
if key.startswith("header.")
|
||||
}
|
||||
)
|
||||
message.args_json.extend(
|
||||
_stringify(value) for value in _sequence_from_any(payload.get("args_json", fields.get("args_json", [])))
|
||||
_stringify(value)
|
||||
for value in _sequence_from_any(
|
||||
payload.get("args_json", fields.get("args_json", []))
|
||||
)
|
||||
)
|
||||
return "raw_dbus", message
|
||||
if payload_kind == PayloadKind.WPA_CTRL:
|
||||
|
|
@ -130,13 +153,17 @@ class Normalizer:
|
|||
event_line=str(raw.message or fields.get("event_line", "")),
|
||||
event_name=str(raw.event_type or fields.get("event_name", "")),
|
||||
)
|
||||
message.key_values.update({str(key): _stringify(value) for key, value in fields.items()})
|
||||
message.key_values.update(
|
||||
{str(key): _stringify(value) for key, value in fields.items()}
|
||||
)
|
||||
return "raw_wpa", message
|
||||
if payload_kind == PayloadKind.NAVIGATION:
|
||||
payload_map = {str(key): value for key, value in payload.items()}
|
||||
message = events_pb2.NavigationPayload(
|
||||
robot_id=str(payload_map.get("robot_id", fields.get("robot_id", ""))),
|
||||
mission_id=str(payload_map.get("mission_id", fields.get("mission_id", ""))),
|
||||
mission_id=str(
|
||||
payload_map.get("mission_id", fields.get("mission_id", ""))
|
||||
),
|
||||
x=float(payload_map.get("x", fields.get("x", 0.0)) or 0.0),
|
||||
y=float(payload_map.get("y", fields.get("y", 0.0)) or 0.0),
|
||||
z=float(payload_map.get("z", fields.get("z", 0.0)) or 0.0),
|
||||
|
|
@ -146,20 +173,34 @@ class Normalizer:
|
|||
return "navigation", message
|
||||
if payload_kind == PayloadKind.DERIVED:
|
||||
message = events_pb2.DerivedEventPayload(
|
||||
derivation_name=str(payload.get("derivation_name", fields.get("derivation_name", ""))),
|
||||
workflow_name=str(payload.get("workflow_name", fields.get("workflow_name", ""))),
|
||||
derivation_name=str(
|
||||
payload.get("derivation_name", fields.get("derivation_name", ""))
|
||||
),
|
||||
workflow_name=str(
|
||||
payload.get("workflow_name", fields.get("workflow_name", ""))
|
||||
),
|
||||
summary=str(payload.get("summary", raw.message or "")),
|
||||
confidence=float(payload.get("confidence", fields.get("confidence", 0.0)) or 0.0),
|
||||
confidence=float(
|
||||
payload.get("confidence", fields.get("confidence", 0.0)) or 0.0
|
||||
),
|
||||
)
|
||||
return "derived", message
|
||||
if payload_kind == PayloadKind.COMMAND_RESULT:
|
||||
message = events_pb2.CommandResultPayload(
|
||||
command_id=str(payload.get("command_id", fields.get("command_id", ""))),
|
||||
command_type=str(payload.get("command_type", fields.get("command_type", ""))),
|
||||
origin_kind=str(payload.get("origin_kind", fields.get("origin_kind", ""))),
|
||||
target_kind=str(payload.get("target_kind", fields.get("target_kind", ""))),
|
||||
command_type=str(
|
||||
payload.get("command_type", fields.get("command_type", ""))
|
||||
),
|
||||
origin_kind=str(
|
||||
payload.get("origin_kind", fields.get("origin_kind", ""))
|
||||
),
|
||||
target_kind=str(
|
||||
payload.get("target_kind", fields.get("target_kind", ""))
|
||||
),
|
||||
target_id=str(payload.get("target_id", fields.get("target_id", ""))),
|
||||
result_state=str(payload.get("result_state", fields.get("result_state", ""))),
|
||||
result_state=str(
|
||||
payload.get("result_state", fields.get("result_state", ""))
|
||||
),
|
||||
message=str(payload.get("message", raw.message or "")),
|
||||
)
|
||||
return "command_result", message
|
||||
|
|
|
|||
|
|
@ -146,7 +146,9 @@ class CollectorPipelineConfig:
|
|||
collector_name: str | None = None,
|
||||
) -> "CollectorPipelineConfig":
|
||||
section = _select_collector_section(data, collector_name)
|
||||
pipeline_section = section.get("pipeline", section) if isinstance(section, Mapping) else {}
|
||||
pipeline_section = (
|
||||
section.get("pipeline", section) if isinstance(section, Mapping) else {}
|
||||
)
|
||||
|
||||
from .marking import MarkRule
|
||||
from .prefilter import FilterRule
|
||||
|
|
@ -155,15 +157,23 @@ class CollectorPipelineConfig:
|
|||
return cls(
|
||||
enabled=bool(pipeline_section.get("enabled", section.get("enabled", True))),
|
||||
prefilter_rules=tuple(
|
||||
FilterRule.from_toml(item) for item in _as_rule_list(pipeline_section, "filters", "prefilters")
|
||||
FilterRule.from_toml(item)
|
||||
for item in _as_rule_list(pipeline_section, "filters", "prefilters")
|
||||
),
|
||||
validation_rules=tuple(
|
||||
ValidationRule.from_toml(item)
|
||||
for item in _as_rule_list(pipeline_section, "validations", "validators")
|
||||
),
|
||||
mark_rules=tuple(MarkRule.from_toml(item) for item in _as_rule_list(pipeline_section, "marks", "mark_rules")),
|
||||
default_cache_enabled=bool(pipeline_section.get("default_cache_enabled", True)),
|
||||
default_outbox_enabled=bool(pipeline_section.get("default_outbox_enabled", False)),
|
||||
mark_rules=tuple(
|
||||
MarkRule.from_toml(item)
|
||||
for item in _as_rule_list(pipeline_section, "marks", "mark_rules")
|
||||
),
|
||||
default_cache_enabled=bool(
|
||||
pipeline_section.get("default_cache_enabled", True)
|
||||
),
|
||||
default_outbox_enabled=bool(
|
||||
pipeline_section.get("default_outbox_enabled", False)
|
||||
),
|
||||
default_priority=int(pipeline_section.get("default_priority", 0)),
|
||||
)
|
||||
|
||||
|
|
@ -201,7 +211,10 @@ class CollectorPipeline:
|
|||
collector_name: str | None = None,
|
||||
context: CollectorPipelineContext | None = None,
|
||||
) -> "CollectorPipeline":
|
||||
return cls(CollectorPipelineConfig.from_toml(data, collector_name=collector_name), context=context)
|
||||
return cls(
|
||||
CollectorPipelineConfig.from_toml(data, collector_name=collector_name),
|
||||
context=context,
|
||||
)
|
||||
|
||||
def process(
|
||||
self,
|
||||
|
|
@ -210,13 +223,16 @@ class CollectorPipeline:
|
|||
context: CollectorPipelineContext | None = None,
|
||||
) -> CollectorPipelineOutcome:
|
||||
effective_context = self._resolve_context(raw_event, context)
|
||||
self.stats = replace(self.stats, events_received_total=self.stats.events_received_total + 1)
|
||||
self.stats = replace(
|
||||
self.stats, events_received_total=self.stats.events_received_total + 1
|
||||
)
|
||||
|
||||
prefilter_result = self.prefilter.evaluate(raw_event, effective_context)
|
||||
if not prefilter_result.accepted:
|
||||
self.stats = replace(
|
||||
self.stats,
|
||||
events_prefilter_dropped_total=self.stats.events_prefilter_dropped_total + 1,
|
||||
events_prefilter_dropped_total=self.stats.events_prefilter_dropped_total
|
||||
+ 1,
|
||||
)
|
||||
return CollectorPipelineOutcome(
|
||||
accepted=False,
|
||||
|
|
@ -231,7 +247,8 @@ class CollectorPipeline:
|
|||
if not validation_result.valid and not validation_result.downgraded:
|
||||
self.stats = replace(
|
||||
self.stats,
|
||||
events_validation_failed_total=self.stats.events_validation_failed_total + 1,
|
||||
events_validation_failed_total=self.stats.events_validation_failed_total
|
||||
+ 1,
|
||||
)
|
||||
return CollectorPipelineOutcome(
|
||||
accepted=False,
|
||||
|
|
@ -248,13 +265,24 @@ class CollectorPipeline:
|
|||
effective_context,
|
||||
validation_result=validation_result,
|
||||
)
|
||||
self.stats = replace(self.stats, events_normalized_total=self.stats.events_normalized_total + 1)
|
||||
self.stats = replace(
|
||||
self.stats, events_normalized_total=self.stats.events_normalized_total + 1
|
||||
)
|
||||
|
||||
marking_result = self.marker.apply(normalization_result.envelope, raw_event, effective_context)
|
||||
self.stats = replace(self.stats, events_marked_total=self.stats.events_marked_total + 1)
|
||||
self.stats = replace(self.stats, events_emitted_total=self.stats.events_emitted_total + 1)
|
||||
marking_result = self.marker.apply(
|
||||
normalization_result.envelope, raw_event, effective_context
|
||||
)
|
||||
self.stats = replace(
|
||||
self.stats, events_marked_total=self.stats.events_marked_total + 1
|
||||
)
|
||||
self.stats = replace(
|
||||
self.stats, events_emitted_total=self.stats.events_emitted_total + 1
|
||||
)
|
||||
if validation_result.downgraded:
|
||||
self.stats = replace(self.stats, events_downgraded_total=self.stats.events_downgraded_total + 1)
|
||||
self.stats = replace(
|
||||
self.stats,
|
||||
events_downgraded_total=self.stats.events_downgraded_total + 1,
|
||||
)
|
||||
|
||||
return CollectorPipelineOutcome(
|
||||
accepted=True,
|
||||
|
|
@ -285,7 +313,9 @@ class CollectorPipeline:
|
|||
)
|
||||
|
||||
|
||||
def _select_collector_section(data: Mapping[str, Any], collector_name: str | None) -> Mapping[str, Any]:
|
||||
def _select_collector_section(
|
||||
data: Mapping[str, Any], collector_name: str | None
|
||||
) -> Mapping[str, Any]:
|
||||
if collector_name is not None:
|
||||
collectors = data.get("collectors")
|
||||
if isinstance(collectors, Mapping):
|
||||
|
|
@ -352,7 +382,9 @@ def _coerce_event_kind(value: EventKind | int | str | None) -> EventKind:
|
|||
return getattr(EventKind, normalized, EventKind.UNSPECIFIED)
|
||||
|
||||
|
||||
def _coerce_payload_kind(value: PayloadKind | int | str | None, source_kind: SourceKind) -> PayloadKind:
|
||||
def _coerce_payload_kind(
|
||||
value: PayloadKind | int | str | None, source_kind: SourceKind
|
||||
) -> PayloadKind:
|
||||
if isinstance(value, PayloadKind):
|
||||
return value
|
||||
if value is None or value == "":
|
||||
|
|
@ -387,7 +419,9 @@ def _coerce_datetime(value: int) -> datetime | None:
|
|||
return datetime.fromtimestamp(seconds, tz=timezone.utc)
|
||||
|
||||
|
||||
def _lookup_value(raw: CollectorRawEvent, context: CollectorPipelineContext, field: str) -> Any:
|
||||
def _lookup_value(
|
||||
raw: CollectorRawEvent, context: CollectorPipelineContext, field: str
|
||||
) -> Any:
|
||||
raw_mapping = raw.as_mapping()
|
||||
context_mapping = context.as_mapping()
|
||||
if field in raw_mapping:
|
||||
|
|
@ -442,7 +476,9 @@ def _has_value(value: Any) -> bool:
|
|||
return True
|
||||
|
||||
|
||||
def _condition_matches(condition: RuleCondition, raw: CollectorRawEvent, context: CollectorPipelineContext) -> bool:
|
||||
def _condition_matches(
|
||||
condition: RuleCondition, raw: CollectorRawEvent, context: CollectorPipelineContext
|
||||
) -> bool:
|
||||
value = _lookup_value(raw, context, condition.field)
|
||||
op = condition.op.strip().lower()
|
||||
expected = condition.value
|
||||
|
|
@ -451,40 +487,67 @@ def _condition_matches(condition: RuleCondition, raw: CollectorRawEvent, context
|
|||
if value is None:
|
||||
return False
|
||||
if op in {"eq", "=="}:
|
||||
return _normalize_string(value, case_sensitive=condition.case_sensitive) == _normalize_string(
|
||||
expected, case_sensitive=condition.case_sensitive
|
||||
)
|
||||
return _normalize_string(
|
||||
value, case_sensitive=condition.case_sensitive
|
||||
) == _normalize_string(expected, case_sensitive=condition.case_sensitive)
|
||||
if op in {"ne", "!="}:
|
||||
return _normalize_string(value, case_sensitive=condition.case_sensitive) != _normalize_string(
|
||||
expected, case_sensitive=condition.case_sensitive
|
||||
)
|
||||
return _normalize_string(
|
||||
value, case_sensitive=condition.case_sensitive
|
||||
) != _normalize_string(expected, case_sensitive=condition.case_sensitive)
|
||||
if op == "in":
|
||||
if isinstance(expected, Sequence) and not isinstance(expected, (str, bytes, bytearray)):
|
||||
candidate = _normalize_string(value, case_sensitive=condition.case_sensitive)
|
||||
return any(candidate == _normalize_string(item, case_sensitive=condition.case_sensitive) for item in expected)
|
||||
return _normalize_string(value, case_sensitive=condition.case_sensitive) in _normalize_string(
|
||||
expected, case_sensitive=condition.case_sensitive
|
||||
)
|
||||
if isinstance(expected, Sequence) and not isinstance(
|
||||
expected, (str, bytes, bytearray)
|
||||
):
|
||||
candidate = _normalize_string(
|
||||
value, case_sensitive=condition.case_sensitive
|
||||
)
|
||||
return any(
|
||||
candidate
|
||||
== _normalize_string(item, case_sensitive=condition.case_sensitive)
|
||||
for item in expected
|
||||
)
|
||||
return _normalize_string(
|
||||
value, case_sensitive=condition.case_sensitive
|
||||
) in _normalize_string(expected, case_sensitive=condition.case_sensitive)
|
||||
if op == "not_in":
|
||||
if isinstance(expected, Sequence) and not isinstance(expected, (str, bytes, bytearray)):
|
||||
candidate = _normalize_string(value, case_sensitive=condition.case_sensitive)
|
||||
return all(candidate != _normalize_string(item, case_sensitive=condition.case_sensitive) for item in expected)
|
||||
return _normalize_string(value, case_sensitive=condition.case_sensitive) not in _normalize_string(
|
||||
expected, case_sensitive=condition.case_sensitive
|
||||
)
|
||||
if isinstance(expected, Sequence) and not isinstance(
|
||||
expected, (str, bytes, bytearray)
|
||||
):
|
||||
candidate = _normalize_string(
|
||||
value, case_sensitive=condition.case_sensitive
|
||||
)
|
||||
return all(
|
||||
candidate
|
||||
!= _normalize_string(item, case_sensitive=condition.case_sensitive)
|
||||
for item in expected
|
||||
)
|
||||
return _normalize_string(
|
||||
value, case_sensitive=condition.case_sensitive
|
||||
) not in _normalize_string(expected, case_sensitive=condition.case_sensitive)
|
||||
if op == "prefix":
|
||||
return _normalize_string(value, case_sensitive=condition.case_sensitive).startswith(
|
||||
return _normalize_string(
|
||||
value, case_sensitive=condition.case_sensitive
|
||||
).startswith(
|
||||
_normalize_string(expected, case_sensitive=condition.case_sensitive)
|
||||
)
|
||||
if op == "suffix":
|
||||
return _normalize_string(value, case_sensitive=condition.case_sensitive).endswith(
|
||||
_normalize_string(expected, case_sensitive=condition.case_sensitive)
|
||||
)
|
||||
return _normalize_string(
|
||||
value, case_sensitive=condition.case_sensitive
|
||||
).endswith(_normalize_string(expected, case_sensitive=condition.case_sensitive))
|
||||
if op == "contains":
|
||||
candidate = _normalize_string(value, case_sensitive=condition.case_sensitive)
|
||||
if isinstance(expected, Sequence) and not isinstance(expected, (str, bytes, bytearray)):
|
||||
return any(_normalize_string(item, case_sensitive=condition.case_sensitive) in candidate for item in expected)
|
||||
return _normalize_string(expected, case_sensitive=condition.case_sensitive) in candidate
|
||||
if isinstance(expected, Sequence) and not isinstance(
|
||||
expected, (str, bytes, bytearray)
|
||||
):
|
||||
return any(
|
||||
_normalize_string(item, case_sensitive=condition.case_sensitive)
|
||||
in candidate
|
||||
for item in expected
|
||||
)
|
||||
return (
|
||||
_normalize_string(expected, case_sensitive=condition.case_sensitive)
|
||||
in candidate
|
||||
)
|
||||
if op in {"lte", "<="}:
|
||||
return float(value) <= float(expected)
|
||||
if op in {"gte", ">="}:
|
||||
|
|
|
|||
|
|
@ -6,7 +6,13 @@ from dataclasses import dataclass
|
|||
from enum import Enum
|
||||
from typing import Any, Mapping
|
||||
|
||||
from .pipeline import CollectorPipelineContext, CollectorRawEvent, RuleCondition, _condition_matches, _rule_condition_from_mapping
|
||||
from .pipeline import (
|
||||
CollectorPipelineContext,
|
||||
CollectorRawEvent,
|
||||
RuleCondition,
|
||||
_condition_matches,
|
||||
_rule_condition_from_mapping,
|
||||
)
|
||||
|
||||
|
||||
class FilterAction(str, Enum):
|
||||
|
|
@ -43,17 +49,38 @@ class Prefilter:
|
|||
def __init__(self, rules: tuple[FilterRule, ...] = ()) -> None:
|
||||
self.rules = rules
|
||||
|
||||
def evaluate(self, raw: CollectorRawEvent, context: CollectorPipelineContext) -> PrefilterResult:
|
||||
def evaluate(
|
||||
self, raw: CollectorRawEvent, context: CollectorPipelineContext
|
||||
) -> PrefilterResult:
|
||||
matched_keep: FilterRule | None = None
|
||||
keep_rules_present = any(rule.action is FilterAction.KEEP for rule in self.rules)
|
||||
keep_rules_present = any(
|
||||
rule.action is FilterAction.KEEP for rule in self.rules
|
||||
)
|
||||
for rule in self.rules:
|
||||
if not _condition_matches(rule.condition, raw, context):
|
||||
continue
|
||||
if rule.action is FilterAction.DROP:
|
||||
return PrefilterResult(False, rule.action, rule.name or rule.condition.field, rule.reason or "dropped")
|
||||
return PrefilterResult(
|
||||
False,
|
||||
rule.action,
|
||||
rule.name or rule.condition.field,
|
||||
rule.reason or "dropped",
|
||||
)
|
||||
matched_keep = rule
|
||||
if keep_rules_present:
|
||||
if matched_keep is None:
|
||||
return PrefilterResult(False, FilterAction.DROP, None, "no keep rule matched")
|
||||
return PrefilterResult(True, FilterAction.KEEP, matched_keep.name or matched_keep.condition.field, matched_keep.reason or None)
|
||||
return PrefilterResult(True, FilterAction.KEEP, matched_keep.name if matched_keep else None, matched_keep.reason if matched_keep else None)
|
||||
return PrefilterResult(
|
||||
False, FilterAction.DROP, None, "no keep rule matched"
|
||||
)
|
||||
return PrefilterResult(
|
||||
True,
|
||||
FilterAction.KEEP,
|
||||
matched_keep.name or matched_keep.condition.field,
|
||||
matched_keep.reason or None,
|
||||
)
|
||||
return PrefilterResult(
|
||||
True,
|
||||
FilterAction.KEEP,
|
||||
matched_keep.name if matched_keep else None,
|
||||
matched_keep.reason if matched_keep else None,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -81,21 +81,28 @@ class CollectorSupervisorState:
|
|||
class CollectorSupervisor:
|
||||
"""Manage enabled collectors and expose an aggregate state view."""
|
||||
|
||||
def __init__(self, collectors: Iterable[CollectorBase] | Mapping[str, CollectorBase] | None = None) -> None:
|
||||
def __init__(
|
||||
self,
|
||||
collectors: Iterable[CollectorBase] | Mapping[str, CollectorBase] | None = None,
|
||||
) -> None:
|
||||
self.collectors: dict[str, CollectorBase] = {}
|
||||
self._stats = CollectorSupervisorStats()
|
||||
self._last_error: str | None = None
|
||||
if collectors is not None:
|
||||
self.register_many(collectors)
|
||||
|
||||
def register(self, collector: CollectorBase, *, replace_existing: bool = False) -> None:
|
||||
def register(
|
||||
self, collector: CollectorBase, *, replace_existing: bool = False
|
||||
) -> None:
|
||||
name = collector.identity.name
|
||||
if not replace_existing and name in self.collectors:
|
||||
raise ValueError(f"collector already registered: {name}")
|
||||
self.collectors[name] = collector
|
||||
self._recalculate_stats()
|
||||
|
||||
def register_many(self, collectors: Iterable[CollectorBase] | Mapping[str, CollectorBase]) -> None:
|
||||
def register_many(
|
||||
self, collectors: Iterable[CollectorBase] | Mapping[str, CollectorBase]
|
||||
) -> None:
|
||||
if isinstance(collectors, Mapping):
|
||||
for name, collector in collectors.items():
|
||||
if collector.identity.name != name:
|
||||
|
|
@ -208,7 +215,9 @@ class CollectorSupervisor:
|
|||
return CollectorSupervisorState(
|
||||
health=self.health(),
|
||||
stats=self._stats,
|
||||
collectors={name: collector.state() for name, collector in self.collectors.items()},
|
||||
collectors={
|
||||
name: collector.state() for name, collector in self.collectors.items()
|
||||
},
|
||||
)
|
||||
|
||||
def summary(self) -> dict[str, Any]:
|
||||
|
|
@ -252,7 +261,9 @@ class CollectorSupervisor:
|
|||
if health.last_error:
|
||||
self._last_error = health.last_error
|
||||
|
||||
def _build_health(self, states: Mapping[str, CollectorState], checked_mono_ns: int) -> CollectorSupervisorHealth:
|
||||
def _build_health(
|
||||
self, states: Mapping[str, CollectorState], checked_mono_ns: int
|
||||
) -> CollectorSupervisorHealth:
|
||||
collectors_total = len(states)
|
||||
enabled_total = 0
|
||||
active_total = 0
|
||||
|
|
@ -280,7 +291,10 @@ class CollectorSupervisor:
|
|||
unhealthy_total += 1
|
||||
if health.last_error:
|
||||
last_error = health.last_error
|
||||
if health.lifecycle_state in {CollectorLifecycleState.CONNECTED, CollectorLifecycleState.RUNNING}:
|
||||
if health.lifecycle_state in {
|
||||
CollectorLifecycleState.CONNECTED,
|
||||
CollectorLifecycleState.RUNNING,
|
||||
}:
|
||||
running_total += 1
|
||||
if (
|
||||
health.lifecycle_state == CollectorLifecycleState.STOPPED
|
||||
|
|
@ -311,15 +325,24 @@ class CollectorSupervisor:
|
|||
)
|
||||
|
||||
def _collector_is_active(self, health: CollectorHealth) -> bool:
|
||||
return health.lifecycle_state not in {CollectorLifecycleState.INIT, CollectorLifecycleState.STOPPED}
|
||||
return health.lifecycle_state not in {
|
||||
CollectorLifecycleState.INIT,
|
||||
CollectorLifecycleState.STOPPED,
|
||||
}
|
||||
|
||||
def _watchdog_reason(self, health: CollectorHealth) -> str:
|
||||
if health.last_error:
|
||||
return health.last_error
|
||||
if health.lifecycle_state == CollectorLifecycleState.STOPPED:
|
||||
return "collector stopped"
|
||||
if health.connection_state in {CollectorConnectionState.DISCONNECTED, CollectorConnectionState.RECONNECTING}:
|
||||
if health.connection_state in {
|
||||
CollectorConnectionState.DISCONNECTED,
|
||||
CollectorConnectionState.RECONNECTING,
|
||||
}:
|
||||
return f"connection {health.connection_state.name.lower()}"
|
||||
if health.pipeline_state in {CollectorPipelineState.ERROR, CollectorPipelineState.DEGRADED}:
|
||||
if health.pipeline_state in {
|
||||
CollectorPipelineState.ERROR,
|
||||
CollectorPipelineState.DEGRADED,
|
||||
}:
|
||||
return f"pipeline {health.pipeline_state.name.lower()}"
|
||||
return "collector unhealthy"
|
||||
|
|
|
|||
|
|
@ -5,7 +5,13 @@ from __future__ import annotations
|
|||
from dataclasses import dataclass
|
||||
from typing import Any, Mapping
|
||||
|
||||
from .pipeline import CollectorPipelineContext, CollectorRawEvent, RuleCondition, _condition_matches, _rule_condition_from_mapping
|
||||
from .pipeline import (
|
||||
CollectorPipelineContext,
|
||||
CollectorRawEvent,
|
||||
RuleCondition,
|
||||
_condition_matches,
|
||||
_rule_condition_from_mapping,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(slots=True, frozen=True)
|
||||
|
|
@ -49,7 +55,9 @@ class Validator:
|
|||
def __init__(self, rules: tuple[ValidationRule, ...] = ()) -> None:
|
||||
self.rules = rules
|
||||
|
||||
def validate(self, raw: CollectorRawEvent, context: CollectorPipelineContext) -> ValidationResult:
|
||||
def validate(
|
||||
self, raw: CollectorRawEvent, context: CollectorPipelineContext
|
||||
) -> ValidationResult:
|
||||
issues: list[ValidationIssue] = []
|
||||
downgraded = False
|
||||
for rule in self.rules:
|
||||
|
|
@ -59,7 +67,8 @@ class Validator:
|
|||
ValidationIssue(
|
||||
rule=rule.name or rule.condition.field,
|
||||
field=rule.condition.field,
|
||||
message=rule.message or f"validation failed for {rule.condition.field}",
|
||||
message=rule.message
|
||||
or f"validation failed for {rule.condition.field}",
|
||||
severity=rule.severity,
|
||||
on_fail=rule.on_fail,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -15,24 +15,24 @@ from .base import (
|
|||
CollectorLifecycleState,
|
||||
CollectorPipelineState,
|
||||
)
|
||||
from .pipeline import CollectorPipeline, CollectorPipelineContext, CollectorPipelineOutcome, CollectorRawEvent
|
||||
|
||||
from .pipeline import (
|
||||
CollectorPipeline,
|
||||
CollectorPipelineContext,
|
||||
CollectorPipelineOutcome,
|
||||
CollectorRawEvent,
|
||||
)
|
||||
|
||||
WpaSink = Callable[[events_pb2.EventEnvelope], None]
|
||||
|
||||
|
||||
class WpaCtrlBackend(Protocol):
|
||||
def connect(self, config: "WpaCtrlCollectorConfig") -> None:
|
||||
...
|
||||
def connect(self, config: "WpaCtrlCollectorConfig") -> None: ...
|
||||
|
||||
def read(self) -> "WpaCtrlEvent | None":
|
||||
...
|
||||
def read(self) -> "WpaCtrlEvent | None": ...
|
||||
|
||||
def close(self) -> None:
|
||||
...
|
||||
def close(self) -> None: ...
|
||||
|
||||
def query(self, command: str, *, iface: str | None = None) -> str | None:
|
||||
...
|
||||
def query(self, command: str, *, iface: str | None = None) -> str | None: ...
|
||||
|
||||
|
||||
@dataclass(slots=True, frozen=True)
|
||||
|
|
@ -54,20 +54,42 @@ class WpaCtrlEvent:
|
|||
key_values = {
|
||||
key: value
|
||||
for key, value in data.items()
|
||||
if key not in {"interface_name", "event_line", "event_name", "event", "message", "key_values", "fields", "realtime_ns", "monotonic_ns"}
|
||||
if key
|
||||
not in {
|
||||
"interface_name",
|
||||
"event_line",
|
||||
"event_name",
|
||||
"event",
|
||||
"message",
|
||||
"key_values",
|
||||
"fields",
|
||||
"realtime_ns",
|
||||
"monotonic_ns",
|
||||
}
|
||||
}
|
||||
event_line = str(data.get("event_line", data.get("line", data.get("message", ""))) or "")
|
||||
event_line = str(
|
||||
data.get("event_line", data.get("line", data.get("message", ""))) or ""
|
||||
)
|
||||
event_name = str(data.get("event_name", data.get("event", "")) or "")
|
||||
if not event_name and event_line:
|
||||
event_name = _derive_wpa_event_name(event_line)
|
||||
return cls(
|
||||
interface_name=str(data.get("interface_name", data.get("interface", data.get("ifname", ""))) or ""),
|
||||
interface_name=str(
|
||||
data.get(
|
||||
"interface_name", data.get("interface", data.get("ifname", ""))
|
||||
)
|
||||
or ""
|
||||
),
|
||||
event_line=event_line,
|
||||
event_name=event_name,
|
||||
message=str(data.get("message", event_line or event_name) or ""),
|
||||
key_values=dict(key_values),
|
||||
realtime_ns=int(data.get("realtime_ns", data.get("__REALTIME_TIMESTAMP", 0)) or 0),
|
||||
monotonic_ns=int(data.get("monotonic_ns", data.get("__MONOTONIC_TIMESTAMP", 0)) or 0),
|
||||
realtime_ns=int(
|
||||
data.get("realtime_ns", data.get("__REALTIME_TIMESTAMP", 0)) or 0
|
||||
),
|
||||
monotonic_ns=int(
|
||||
data.get("monotonic_ns", data.get("__MONOTONIC_TIMESTAMP", 0)) or 0
|
||||
),
|
||||
)
|
||||
|
||||
def as_mapping(self) -> dict[str, Any]:
|
||||
|
|
@ -116,7 +138,9 @@ class WpaCtrlFilterRule:
|
|||
if self.event_prefix:
|
||||
expected_prefix = _normalize_wpa_text(self.event_prefix)
|
||||
expected_token_prefix = _normalize_wpa_event_token(self.event_prefix)
|
||||
if not normalized_event.startswith(expected_prefix) and not token.startswith(expected_token_prefix):
|
||||
if not normalized_event.startswith(
|
||||
expected_prefix
|
||||
) and not token.startswith(expected_token_prefix):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
|
@ -135,22 +159,36 @@ class WpaCtrlCollectorConfig:
|
|||
telemetry_on_start: bool = False
|
||||
|
||||
@classmethod
|
||||
def from_toml(cls, data: Mapping[str, Any], *, collector_name: str | None = None) -> "WpaCtrlCollectorConfig":
|
||||
def from_toml(
|
||||
cls, data: Mapping[str, Any], *, collector_name: str | None = None
|
||||
) -> "WpaCtrlCollectorConfig":
|
||||
section = _select_collector_section(data, collector_name)
|
||||
if not isinstance(section, Mapping):
|
||||
section = {}
|
||||
interface = str(section.get("interface", section.get("ifname", "")) or "")
|
||||
source_name = str(section.get("source_name", f"wpa-ctrl://{interface or 'wpa'}") or f"wpa-ctrl://{interface or 'wpa'}")
|
||||
source_name = str(
|
||||
section.get("source_name", f"wpa-ctrl://{interface or 'wpa'}")
|
||||
or f"wpa-ctrl://{interface or 'wpa'}"
|
||||
)
|
||||
return cls(
|
||||
name=str(collector_name or section.get("name", "wpa_ctrl")),
|
||||
enabled=bool(section.get("enabled", True)),
|
||||
interface=interface,
|
||||
ctrl_path=str(section.get("ctrl_path", section.get("socket", "/run/wpa_supplicant")) or "/run/wpa_supplicant"),
|
||||
ctrl_path=str(
|
||||
section.get("ctrl_path", section.get("socket", "/run/wpa_supplicant"))
|
||||
or "/run/wpa_supplicant"
|
||||
),
|
||||
source_name=source_name,
|
||||
filters=tuple(WpaCtrlFilterRule.from_toml(item) for item in _filter_list(section)),
|
||||
filters=tuple(
|
||||
WpaCtrlFilterRule.from_toml(item) for item in _filter_list(section)
|
||||
),
|
||||
drop_unmatched=bool(section.get("drop_unmatched", True)),
|
||||
signal_poll_min_interval_ms=int(section.get("signal_poll_min_interval_ms", 0) or 0),
|
||||
telemetry_commands=_string_tuple(section.get("telemetry_commands", section.get("commands", ()))),
|
||||
signal_poll_min_interval_ms=int(
|
||||
section.get("signal_poll_min_interval_ms", 0) or 0
|
||||
),
|
||||
telemetry_commands=_string_tuple(
|
||||
section.get("telemetry_commands", section.get("commands", ()))
|
||||
),
|
||||
telemetry_on_start=bool(section.get("telemetry_on_start", False)),
|
||||
)
|
||||
|
||||
|
|
@ -162,7 +200,14 @@ class FakeWpaCtrlBackend:
|
|||
*,
|
||||
fail_first_read: bool = False,
|
||||
) -> None:
|
||||
self._events: list[WpaCtrlEvent] = [event if isinstance(event, WpaCtrlEvent) else WpaCtrlEvent.from_mapping(event) for event in (events or ())]
|
||||
self._events: list[WpaCtrlEvent] = [
|
||||
(
|
||||
event
|
||||
if isinstance(event, WpaCtrlEvent)
|
||||
else WpaCtrlEvent.from_mapping(event)
|
||||
)
|
||||
for event in (events or ())
|
||||
]
|
||||
self._position = 0
|
||||
self._connected = False
|
||||
self._fail_first_read = fail_first_read
|
||||
|
|
@ -207,7 +252,11 @@ class FakeWpaCtrlBackend:
|
|||
self.close_calls += 1
|
||||
|
||||
def append(self, event: WpaCtrlEvent | Mapping[str, Any]) -> WpaCtrlEvent:
|
||||
wpa_event = event if isinstance(event, WpaCtrlEvent) else WpaCtrlEvent.from_mapping(event)
|
||||
wpa_event = (
|
||||
event
|
||||
if isinstance(event, WpaCtrlEvent)
|
||||
else WpaCtrlEvent.from_mapping(event)
|
||||
)
|
||||
self._events.append(wpa_event)
|
||||
return wpa_event
|
||||
|
||||
|
|
@ -225,11 +274,19 @@ class SystemWpaCtrlBackend:
|
|||
|
||||
def connect(self, config: WpaCtrlCollectorConfig) -> None:
|
||||
module = _load_wpa_ctrl_module()
|
||||
backend_cls = getattr(module, "WpaCtrl", None) or getattr(module, "Ctrl", None) or getattr(module, "WpaCtrlClient", None)
|
||||
backend_cls = (
|
||||
getattr(module, "WpaCtrl", None)
|
||||
or getattr(module, "Ctrl", None)
|
||||
or getattr(module, "WpaCtrlClient", None)
|
||||
)
|
||||
if backend_cls is None:
|
||||
raise RuntimeError("wpa ctrl bindings are not available")
|
||||
try:
|
||||
self._backend = backend_cls(config.ctrl_path, config.interface) if config.interface else backend_cls(config.ctrl_path)
|
||||
self._backend = (
|
||||
backend_cls(config.ctrl_path, config.interface)
|
||||
if config.interface
|
||||
else backend_cls(config.ctrl_path)
|
||||
)
|
||||
except TypeError:
|
||||
self._backend = backend_cls(config.ctrl_path)
|
||||
self._connected = True
|
||||
|
|
@ -246,7 +303,9 @@ class SystemWpaCtrlBackend:
|
|||
return None
|
||||
if isinstance(result, Mapping):
|
||||
return WpaCtrlEvent.from_mapping(result)
|
||||
return WpaCtrlEvent.from_mapping({"event_line": str(result), "message": str(result)})
|
||||
return WpaCtrlEvent.from_mapping(
|
||||
{"event_line": str(result), "message": str(result)}
|
||||
)
|
||||
return None
|
||||
|
||||
def query(self, command: str, *, iface: str | None = None) -> str | None:
|
||||
|
|
@ -314,7 +373,10 @@ class WpaCtrlCollector(CollectorBase):
|
|||
director_sink: WpaSink | None = None,
|
||||
) -> "WpaCtrlCollector":
|
||||
config = WpaCtrlCollectorConfig.from_toml(data, collector_name=collector_name)
|
||||
pipeline = CollectorPipeline.from_toml(_pipeline_toml_without_custom_filters(data, collector_name), collector_name=collector_name)
|
||||
pipeline = CollectorPipeline.from_toml(
|
||||
_pipeline_toml_without_custom_filters(data, collector_name),
|
||||
collector_name=collector_name,
|
||||
)
|
||||
return cls(config, pipeline, backend=backend, director_sink=director_sink)
|
||||
|
||||
def start(self) -> None:
|
||||
|
|
@ -340,7 +402,10 @@ class WpaCtrlCollector(CollectorBase):
|
|||
self.collect_telemetry()
|
||||
|
||||
def stop(self) -> None:
|
||||
if not self._connected and self.connection_state() == CollectorConnectionState.STOPPED:
|
||||
if (
|
||||
not self._connected
|
||||
and self.connection_state() == CollectorConnectionState.STOPPED
|
||||
):
|
||||
return
|
||||
self._set_lifecycle_state(CollectorLifecycleState.STOPPING)
|
||||
self._set_connection_state(CollectorConnectionState.STOPPING)
|
||||
|
|
@ -357,7 +422,9 @@ class WpaCtrlCollector(CollectorBase):
|
|||
self._mark_healthy(True)
|
||||
self._clear_error()
|
||||
|
||||
def poll_once(self, *, now_mono_ns_value: int | None = None) -> CollectorPipelineOutcome | None:
|
||||
def poll_once(
|
||||
self, *, now_mono_ns_value: int | None = None
|
||||
) -> CollectorPipelineOutcome | None:
|
||||
if not self._connected:
|
||||
return None
|
||||
try:
|
||||
|
|
@ -385,7 +452,9 @@ class WpaCtrlCollector(CollectorBase):
|
|||
outcomes: list[CollectorPipelineOutcome] = []
|
||||
for command in chosen_commands:
|
||||
try:
|
||||
response = self.backend.query(command, iface=self.config.interface or None)
|
||||
response = self.backend.query(
|
||||
command, iface=self.config.interface or None
|
||||
)
|
||||
except Exception as exc:
|
||||
self._handle_backend_error(exc)
|
||||
break
|
||||
|
|
@ -405,7 +474,9 @@ class WpaCtrlCollector(CollectorBase):
|
|||
outcomes.append(outcome)
|
||||
return outcomes
|
||||
|
||||
def drain_pending(self, *, limit: int | None = None, now_mono_ns_value: int | None = None) -> list[CollectorPipelineOutcome]:
|
||||
def drain_pending(
|
||||
self, *, limit: int | None = None, now_mono_ns_value: int | None = None
|
||||
) -> list[CollectorPipelineOutcome]:
|
||||
outcomes: list[CollectorPipelineOutcome] = []
|
||||
processed = 0
|
||||
while self._connected and (limit is None or processed < limit):
|
||||
|
|
@ -443,10 +514,18 @@ class WpaCtrlCollector(CollectorBase):
|
|||
self._set_pipeline_state(CollectorPipelineState.ERROR)
|
||||
self.reconnect()
|
||||
|
||||
def _process_event(self, event: WpaCtrlEvent, *, now_mono_ns_value: int | None = None) -> CollectorPipelineOutcome | None:
|
||||
event_name = _derive_wpa_event_name(event.event_name or event.event_line or event.message)
|
||||
source_prefilter_reason = self._source_prefilter_reason(event, event_name, now_mono_ns_value=now_mono_ns_value)
|
||||
raw_event = self._event_to_raw_event(event, event_name, now_mono_ns_value=now_mono_ns_value)
|
||||
def _process_event(
|
||||
self, event: WpaCtrlEvent, *, now_mono_ns_value: int | None = None
|
||||
) -> CollectorPipelineOutcome | None:
|
||||
event_name = _derive_wpa_event_name(
|
||||
event.event_name or event.event_line or event.message
|
||||
)
|
||||
source_prefilter_reason = self._source_prefilter_reason(
|
||||
event, event_name, now_mono_ns_value=now_mono_ns_value
|
||||
)
|
||||
raw_event = self._event_to_raw_event(
|
||||
event, event_name, now_mono_ns_value=now_mono_ns_value
|
||||
)
|
||||
context = self._build_context(event, event_name)
|
||||
self._increment_stats(events_received_total=1)
|
||||
|
||||
|
|
@ -464,7 +543,9 @@ class WpaCtrlCollector(CollectorBase):
|
|||
|
||||
outcome = self.pipeline.process(raw_event, context=context)
|
||||
if outcome.accepted:
|
||||
self._increment_stats(events_normalized_total=1, events_marked_total=1, events_emitted_total=1)
|
||||
self._increment_stats(
|
||||
events_normalized_total=1, events_marked_total=1, events_emitted_total=1
|
||||
)
|
||||
self._set_pipeline_state(CollectorPipelineState.ACTIVE)
|
||||
self._mark_healthy(True)
|
||||
self._clear_error()
|
||||
|
|
@ -479,12 +560,20 @@ class WpaCtrlCollector(CollectorBase):
|
|||
self._mark_healthy(True)
|
||||
return outcome
|
||||
|
||||
def _event_to_raw_event(self, event: WpaCtrlEvent, event_name: str, *, now_mono_ns_value: int | None = None) -> CollectorRawEvent:
|
||||
def _event_to_raw_event(
|
||||
self,
|
||||
event: WpaCtrlEvent,
|
||||
event_name: str,
|
||||
*,
|
||||
now_mono_ns_value: int | None = None,
|
||||
) -> CollectorRawEvent:
|
||||
observed_mono_ns = event.monotonic_ns or (now_mono_ns_value or 0)
|
||||
fields = event.as_mapping()
|
||||
fields.setdefault("event_name", event_name)
|
||||
fields.setdefault("event_line", event.event_line or event_name)
|
||||
fields.setdefault("interface_name", event.interface_name or self.config.interface)
|
||||
fields.setdefault(
|
||||
"interface_name", event.interface_name or self.config.interface
|
||||
)
|
||||
return CollectorRawEvent(
|
||||
collector_name=self.config.name,
|
||||
source_kind=SourceKind.WPA_CTRL,
|
||||
|
|
@ -502,11 +591,16 @@ class WpaCtrlCollector(CollectorBase):
|
|||
normalized_reason=event.message or event.event_line or event_name,
|
||||
fields=fields,
|
||||
payload=None,
|
||||
labels={"collector": self.config.name, "interface": event.interface_name or self.config.interface or ""},
|
||||
labels={
|
||||
"collector": self.config.name,
|
||||
"interface": event.interface_name or self.config.interface or "",
|
||||
},
|
||||
tags=(),
|
||||
)
|
||||
|
||||
def _build_context(self, event: WpaCtrlEvent, event_name: str) -> CollectorPipelineContext:
|
||||
def _build_context(
|
||||
self, event: WpaCtrlEvent, event_name: str
|
||||
) -> CollectorPipelineContext:
|
||||
labels = {
|
||||
"source": "wpa_ctrl",
|
||||
"collector": self.config.name,
|
||||
|
|
@ -531,18 +625,24 @@ class WpaCtrlCollector(CollectorBase):
|
|||
) -> str | None:
|
||||
if _is_forced_keep_wpa_event(event_name):
|
||||
if _wpa_event_token(event_name) == "signal_poll":
|
||||
self._last_signal_poll_mono_ns = event.monotonic_ns or (now_mono_ns_value or self._last_signal_poll_mono_ns)
|
||||
self._last_signal_poll_mono_ns = event.monotonic_ns or (
|
||||
now_mono_ns_value or self._last_signal_poll_mono_ns
|
||||
)
|
||||
return None
|
||||
|
||||
normalized_name = _normalize_wpa_text(event_name)
|
||||
if self.config.filters:
|
||||
matched_keep = None
|
||||
keep_rules_present = any(rule.action == "keep" for rule in self.config.filters)
|
||||
keep_rules_present = any(
|
||||
rule.action == "keep" for rule in self.config.filters
|
||||
)
|
||||
for rule in self.config.filters:
|
||||
if not rule.matches(event_name):
|
||||
continue
|
||||
if rule.action == "drop":
|
||||
return rule.reason or rule.name or f"dropped event: {normalized_name}"
|
||||
return (
|
||||
rule.reason or rule.name or f"dropped event: {normalized_name}"
|
||||
)
|
||||
matched_keep = rule
|
||||
if keep_rules_present and matched_keep is None:
|
||||
return f"no keep rule matched: {normalized_name}"
|
||||
|
|
@ -594,12 +694,21 @@ def _normalize_wpa_event_token(value: str) -> str:
|
|||
|
||||
def _is_forced_keep_wpa_event(event_name: str) -> bool:
|
||||
token = _wpa_event_token(event_name)
|
||||
return token.startswith("disconnect") or token.endswith("failed") or token.endswith("failure") or token in {"terminating", "auth_rejected", "assoc_rejected"}
|
||||
return (
|
||||
token.startswith("disconnect")
|
||||
or token.endswith("failed")
|
||||
or token.endswith("failure")
|
||||
or token in {"terminating", "auth_rejected", "assoc_rejected"}
|
||||
)
|
||||
|
||||
|
||||
def _wpa_event_severity(event_name: str) -> Severity:
|
||||
token = _wpa_event_token(event_name)
|
||||
if token.startswith("disconnect") or token.endswith("failed") or token.endswith("failure"):
|
||||
if (
|
||||
token.startswith("disconnect")
|
||||
or token.endswith("failed")
|
||||
or token.endswith("failure")
|
||||
):
|
||||
return Severity.WARNING
|
||||
if token in {"signal_poll", "scan_results", "status"}:
|
||||
return Severity.INFO
|
||||
|
|
@ -637,7 +746,9 @@ def _string_tuple(value: Any) -> tuple[str, ...]:
|
|||
return (text,) if text else ()
|
||||
|
||||
|
||||
def _select_collector_section(data: Mapping[str, Any], collector_name: str | None) -> Mapping[str, Any]:
|
||||
def _select_collector_section(
|
||||
data: Mapping[str, Any], collector_name: str | None
|
||||
) -> Mapping[str, Any]:
|
||||
collectors = data.get("collectors")
|
||||
if collector_name is not None and isinstance(collectors, Mapping):
|
||||
section = collectors.get(collector_name, {})
|
||||
|
|
@ -650,7 +761,9 @@ def _select_collector_section(data: Mapping[str, Any], collector_name: str | Non
|
|||
return data
|
||||
|
||||
|
||||
def _pipeline_toml_without_custom_filters(data: Mapping[str, Any], collector_name: str | None) -> Mapping[str, Any]:
|
||||
def _pipeline_toml_without_custom_filters(
|
||||
data: Mapping[str, Any], collector_name: str | None
|
||||
) -> Mapping[str, Any]:
|
||||
if not isinstance(data, Mapping):
|
||||
return {}
|
||||
root = dict(data)
|
||||
|
|
|
|||
|
|
@ -21,7 +21,13 @@ from .policy import (
|
|||
CommandPolicyConfig,
|
||||
CommandPolicyState,
|
||||
)
|
||||
from .queue import CommandQueue, CommandQueueStats, QueueEnqueueResult, QueueOverflowPolicy, QueuedCommand
|
||||
from .queue import (
|
||||
CommandQueue,
|
||||
CommandQueueStats,
|
||||
QueueEnqueueResult,
|
||||
QueueOverflowPolicy,
|
||||
QueuedCommand,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"CommandOriginKind",
|
||||
|
|
|
|||
|
|
@ -24,11 +24,9 @@ from .queue import CommandQueue, CommandQueueStats, QueueEnqueueResult, QueuedCo
|
|||
|
||||
|
||||
class CommandExecutorRouter(Protocol):
|
||||
def supports(self, request: CommandRequest) -> bool:
|
||||
...
|
||||
def supports(self, request: CommandRequest) -> bool: ...
|
||||
|
||||
def execute(self, request: CommandRequest) -> CommandResult:
|
||||
...
|
||||
def execute(self, request: CommandRequest) -> CommandResult: ...
|
||||
|
||||
|
||||
CommandResultSink = Callable[[CommandResult], None]
|
||||
|
|
@ -78,7 +76,11 @@ class CommandSubmissionResult:
|
|||
|
||||
@property
|
||||
def accepted(self) -> bool:
|
||||
return self.admission.accepted and self.queue_result is not None and self.queue_result.accepted
|
||||
return (
|
||||
self.admission.accepted
|
||||
and self.queue_result is not None
|
||||
and self.queue_result.accepted
|
||||
)
|
||||
|
||||
@property
|
||||
def emitted_count(self) -> int:
|
||||
|
|
@ -107,7 +109,9 @@ class CommandCoordinator:
|
|||
self._last_result: CommandResult | None = None
|
||||
self._last_error: str | None = None
|
||||
|
||||
def submit(self, request: CommandRequest, *, now_mono_ns_value: int | None = None) -> CommandSubmissionResult:
|
||||
def submit(
|
||||
self, request: CommandRequest, *, now_mono_ns_value: int | None = None
|
||||
) -> CommandSubmissionResult:
|
||||
now = now_mono_ns() if now_mono_ns_value is None else now_mono_ns_value
|
||||
self._stats = replace(
|
||||
self._stats,
|
||||
|
|
@ -116,10 +120,16 @@ class CommandCoordinator:
|
|||
last_transition_mono_ns=now,
|
||||
)
|
||||
|
||||
admission = self.policy.evaluate(request, self.policy_state, now_mono_ns_value=now)
|
||||
admission = self.policy.evaluate(
|
||||
request, self.policy_state, now_mono_ns_value=now
|
||||
)
|
||||
if not admission.accepted:
|
||||
result = self._emit_result(self._result_from_admission(admission, now_mono_ns_value=now))
|
||||
self._bump_admission_stats(admission, result=result, queue_result=None, now_mono_ns_value=now)
|
||||
result = self._emit_result(
|
||||
self._result_from_admission(admission, now_mono_ns_value=now)
|
||||
)
|
||||
self._bump_admission_stats(
|
||||
admission, result=result, queue_result=None, now_mono_ns_value=now
|
||||
)
|
||||
return CommandSubmissionResult(
|
||||
request=request,
|
||||
admission=admission,
|
||||
|
|
@ -127,9 +137,13 @@ class CommandCoordinator:
|
|||
emitted=(result,),
|
||||
)
|
||||
|
||||
queue_result = self.queue.enqueue(admission.effective_request, enqueued_mono_ns=now)
|
||||
queue_result = self.queue.enqueue(
|
||||
admission.effective_request, enqueued_mono_ns=now
|
||||
)
|
||||
if not queue_result.accepted or queue_result.queued is None:
|
||||
queue_rejected = self._emit_result(self._result_from_queue_rejection(admission, queue_result))
|
||||
queue_rejected = self._emit_result(
|
||||
self._result_from_queue_rejection(admission, queue_result)
|
||||
)
|
||||
self._bump_admission_stats(
|
||||
admission,
|
||||
result=queue_rejected,
|
||||
|
|
@ -144,7 +158,9 @@ class CommandCoordinator:
|
|||
queue_result=queue_result,
|
||||
)
|
||||
|
||||
self.policy.observe_acceptance(admission, self.policy_state, now_mono_ns_value=now)
|
||||
self.policy.observe_acceptance(
|
||||
admission, self.policy_state, now_mono_ns_value=now
|
||||
)
|
||||
self._bump_admission_stats(
|
||||
admission,
|
||||
result=None,
|
||||
|
|
@ -166,13 +182,19 @@ class CommandCoordinator:
|
|||
dispatched=dispatched,
|
||||
)
|
||||
|
||||
def submit_cli(self, request: CommandRequest, *, now_mono_ns_value: int | None = None) -> CommandSubmissionResult:
|
||||
def submit_cli(
|
||||
self, request: CommandRequest, *, now_mono_ns_value: int | None = None
|
||||
) -> CommandSubmissionResult:
|
||||
return self.submit(request, now_mono_ns_value=now_mono_ns_value)
|
||||
|
||||
def submit_scheduler(self, request: CommandRequest, *, now_mono_ns_value: int | None = None) -> CommandSubmissionResult:
|
||||
def submit_scheduler(
|
||||
self, request: CommandRequest, *, now_mono_ns_value: int | None = None
|
||||
) -> CommandSubmissionResult:
|
||||
return self.submit(request, now_mono_ns_value=now_mono_ns_value)
|
||||
|
||||
def submit_derivator(self, request: CommandRequest, *, now_mono_ns_value: int | None = None) -> CommandSubmissionResult:
|
||||
def submit_derivator(
|
||||
self, request: CommandRequest, *, now_mono_ns_value: int | None = None
|
||||
) -> CommandSubmissionResult:
|
||||
return self.submit(request, now_mono_ns_value=now_mono_ns_value)
|
||||
|
||||
def dispatch_pending(
|
||||
|
|
@ -210,7 +232,9 @@ class CommandCoordinator:
|
|||
finished_mono_ns=now,
|
||||
)
|
||||
)
|
||||
self.policy.observe_result(expired, self.policy_state, now_mono_ns_value=now)
|
||||
self.policy.observe_result(
|
||||
expired, self.policy_state, now_mono_ns_value=now
|
||||
)
|
||||
self._record_result(expired, now_mono_ns_value=now)
|
||||
results.append(expired)
|
||||
continue
|
||||
|
|
@ -231,9 +255,13 @@ class CommandCoordinator:
|
|||
self._record_result(started, now_mono_ns_value=now)
|
||||
results.append(started)
|
||||
|
||||
final_result = self._dispatch_request(request, attempt_no=queued.attempt_no, now_mono_ns_value=now)
|
||||
final_result = self._dispatch_request(
|
||||
request, attempt_no=queued.attempt_no, now_mono_ns_value=now
|
||||
)
|
||||
final_result = self._emit_result(final_result)
|
||||
self.policy.observe_result(final_result, self.policy_state, now_mono_ns_value=now)
|
||||
self.policy.observe_result(
|
||||
final_result, self.policy_state, now_mono_ns_value=now
|
||||
)
|
||||
self._record_result(final_result, now_mono_ns_value=now)
|
||||
results.append(final_result)
|
||||
return results
|
||||
|
|
@ -244,7 +272,10 @@ class CommandCoordinator:
|
|||
queue=self.queue.stats(),
|
||||
stats=self._stats,
|
||||
pending_command_ids=tuple(item.command_id for item in self.queue.items()),
|
||||
active_command_ids=tuple(request.command_id for request in self.policy_state.active_exclusive.values()),
|
||||
active_command_ids=tuple(
|
||||
request.command_id
|
||||
for request in self.policy_state.active_exclusive.values()
|
||||
),
|
||||
last_result=self._last_result,
|
||||
last_error=self._last_error,
|
||||
)
|
||||
|
|
@ -344,33 +375,49 @@ class CommandCoordinator:
|
|||
|
||||
def _emit_result(self, result: CommandResult) -> CommandResult:
|
||||
self._last_result = result
|
||||
self._stats = replace(self._stats, emitted_total=self._stats.emitted_total + 1, last_result_mono_ns=now_mono_ns())
|
||||
self._stats = replace(
|
||||
self._stats,
|
||||
emitted_total=self._stats.emitted_total + 1,
|
||||
last_result_mono_ns=now_mono_ns(),
|
||||
)
|
||||
if self.sink is not None:
|
||||
self.sink(result)
|
||||
return result
|
||||
|
||||
def _record_result(self, result: CommandResult, *, now_mono_ns_value: int) -> None:
|
||||
if result.state == CommandState.STARTED:
|
||||
self._stats = replace(self._stats, started_total=self._stats.started_total + 1)
|
||||
self._stats = replace(
|
||||
self._stats, started_total=self._stats.started_total + 1
|
||||
)
|
||||
return
|
||||
if result.state == CommandState.SUCCEEDED:
|
||||
self._stats = replace(self._stats, succeeded_total=self._stats.succeeded_total + 1)
|
||||
self._stats = replace(
|
||||
self._stats, succeeded_total=self._stats.succeeded_total + 1
|
||||
)
|
||||
return
|
||||
if result.state == CommandState.FAILED:
|
||||
self._stats = replace(self._stats, failed_total=self._stats.failed_total + 1)
|
||||
self._stats = replace(
|
||||
self._stats, failed_total=self._stats.failed_total + 1
|
||||
)
|
||||
self._last_error = result.message or result.state.name.lower()
|
||||
self._stats = replace(self._stats, last_error_mono_ns=now_mono_ns_value)
|
||||
return
|
||||
if result.state == CommandState.REJECTED:
|
||||
self._stats = replace(self._stats, rejected_total=self._stats.rejected_total + 1)
|
||||
self._stats = replace(
|
||||
self._stats, rejected_total=self._stats.rejected_total + 1
|
||||
)
|
||||
self._last_error = result.message or result.state.name.lower()
|
||||
self._stats = replace(self._stats, last_error_mono_ns=now_mono_ns_value)
|
||||
return
|
||||
if result.state == CommandState.DEFERRED:
|
||||
self._stats = replace(self._stats, deferred_total=self._stats.deferred_total + 1)
|
||||
self._stats = replace(
|
||||
self._stats, deferred_total=self._stats.deferred_total + 1
|
||||
)
|
||||
return
|
||||
if result.state == CommandState.SUPPRESSED:
|
||||
self._stats = replace(self._stats, suppressed_total=self._stats.suppressed_total + 1)
|
||||
self._stats = replace(
|
||||
self._stats, suppressed_total=self._stats.suppressed_total + 1
|
||||
)
|
||||
return
|
||||
|
||||
def _bump_admission_stats(
|
||||
|
|
|
|||
|
|
@ -93,7 +93,12 @@ class CommandRequest:
|
|||
return replace(self, deadline_mono_ns=int(deadline_mono_ns))
|
||||
|
||||
def key(self) -> tuple[str, str, str, str]:
|
||||
return (self.command_type, self.origin_id, self.target_kind.name, self.target_id)
|
||||
return (
|
||||
self.command_type,
|
||||
self.origin_id,
|
||||
self.target_kind.name,
|
||||
self.target_id,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(slots=True, frozen=True)
|
||||
|
|
@ -162,7 +167,9 @@ class CommandResult:
|
|||
return 0
|
||||
return max(0, self.finished_mono_ns - self.started_mono_ns)
|
||||
|
||||
def finished(self, *, state: CommandState, success: bool, message: str = "") -> "CommandResult":
|
||||
def finished(
|
||||
self, *, state: CommandState, success: bool, message: str = ""
|
||||
) -> "CommandResult":
|
||||
return replace(
|
||||
self,
|
||||
state=state,
|
||||
|
|
|
|||
|
|
@ -48,7 +48,9 @@ class CommandPolicyConfig:
|
|||
priority_collector=int(section.get("default_priority_collector", 40)),
|
||||
priority_default=int(section.get("default_priority_default", 0)),
|
||||
dedup_window_ns=_duration_to_ns(section.get("dedup_window_ms", 5000)),
|
||||
cooldown_window_ns=_duration_to_ns(section.get("cooldown_window_ms", 30000)),
|
||||
cooldown_window_ns=_duration_to_ns(
|
||||
section.get("cooldown_window_ms", 30000)
|
||||
),
|
||||
)
|
||||
|
||||
def priority_for_origin(self, origin_kind: CommandOriginKind) -> int:
|
||||
|
|
@ -75,7 +77,9 @@ class CommandPolicyState:
|
|||
|
||||
def snapshot(self) -> dict[str, Any]:
|
||||
return {
|
||||
"active_exclusive": {key: value.command_id for key, value in self.active_exclusive.items()},
|
||||
"active_exclusive": {
|
||||
key: value.command_id for key, value in self.active_exclusive.items()
|
||||
},
|
||||
"dedup_seen": dict(self.dedup_seen_mono_ns),
|
||||
"cooldown_until": dict(self.cooldown_until_mono_ns),
|
||||
"known_requests": list(self.known_requests),
|
||||
|
|
@ -136,7 +140,11 @@ class CommandPolicy:
|
|||
)
|
||||
|
||||
effective_priority = self.resolve_priority(request)
|
||||
effective_request = request if request.priority == effective_priority else request.with_priority(effective_priority)
|
||||
effective_request = (
|
||||
request
|
||||
if request.priority == effective_priority
|
||||
else request.with_priority(effective_priority)
|
||||
)
|
||||
|
||||
if effective_request.expired(now):
|
||||
return self._admission(
|
||||
|
|
@ -257,16 +265,26 @@ class CommandPolicy:
|
|||
)
|
||||
if result.state.is_terminal:
|
||||
exclusive_key = request.exclusive_key.strip()
|
||||
if exclusive_key and state.active_exclusive.get(exclusive_key, None) is not None:
|
||||
if state.active_exclusive[exclusive_key].command_id == request.command_id:
|
||||
if (
|
||||
exclusive_key
|
||||
and state.active_exclusive.get(exclusive_key, None) is not None
|
||||
):
|
||||
if (
|
||||
state.active_exclusive[exclusive_key].command_id
|
||||
== request.command_id
|
||||
):
|
||||
state.active_exclusive.pop(exclusive_key, None)
|
||||
cooldown_key = request.cooldown_key.strip()
|
||||
if cooldown_key:
|
||||
state.cooldown_until_mono_ns[cooldown_key] = now + self.config.cooldown_window_ns
|
||||
state.cooldown_until_mono_ns[cooldown_key] = (
|
||||
now + self.config.cooldown_window_ns
|
||||
)
|
||||
state.known_requests.pop(request.command_id, None)
|
||||
state.last_transition_mono_ns = now
|
||||
|
||||
def prune(self, state: CommandPolicyState, *, now_mono_ns_value: int | None = None) -> None:
|
||||
def prune(
|
||||
self, state: CommandPolicyState, *, now_mono_ns_value: int | None = None
|
||||
) -> None:
|
||||
now = now_mono_ns() if now_mono_ns_value is None else now_mono_ns_value
|
||||
dedup_window = self.config.dedup_window_ns
|
||||
for key, seen in list(state.dedup_seen_mono_ns.items()):
|
||||
|
|
@ -281,7 +299,11 @@ class CommandPolicy:
|
|||
state.last_transition_mono_ns = now
|
||||
|
||||
def resolve_priority(self, request: CommandRequest) -> int:
|
||||
return request.priority if request.priority > 0 else self.config.priority_for_origin(request.origin_kind)
|
||||
return (
|
||||
request.priority
|
||||
if request.priority > 0
|
||||
else self.config.priority_for_origin(request.origin_kind)
|
||||
)
|
||||
|
||||
def _validate_request(self, request: CommandRequest) -> str | None:
|
||||
if not request.command_id.strip():
|
||||
|
|
@ -292,7 +314,10 @@ class CommandPolicy:
|
|||
return "origin_kind is required"
|
||||
if request.target_kind == CommandTargetKind.UNSPECIFIED:
|
||||
return "target_kind is required"
|
||||
if request.target_kind != CommandTargetKind.GLOBAL and not request.target_id.strip():
|
||||
if (
|
||||
request.target_kind != CommandTargetKind.GLOBAL
|
||||
and not request.target_id.strip()
|
||||
):
|
||||
return "target_id is required"
|
||||
return None
|
||||
|
||||
|
|
|
|||
|
|
@ -40,7 +40,9 @@ class QueuedCommand:
|
|||
return max(0, monotonic_ns() - self.enqueued_mono_ns)
|
||||
|
||||
def sort_key(self) -> tuple[int, int, int, int]:
|
||||
deadline_rank = self.deadline_mono_ns if self.deadline_mono_ns > 0 else 2**63 - 1
|
||||
deadline_rank = (
|
||||
self.deadline_mono_ns if self.deadline_mono_ns > 0 else 2**63 - 1
|
||||
)
|
||||
return (-self.priority, deadline_rank, self.enqueued_mono_ns, self.sequence_no)
|
||||
|
||||
|
||||
|
|
@ -119,7 +121,9 @@ class CommandQueue:
|
|||
worst = self._items[-1]
|
||||
if queued.sort_key() >= worst.sort_key():
|
||||
self._rejected_total += 1
|
||||
return QueueEnqueueResult(False, None, "lower priority than queued items", ())
|
||||
return QueueEnqueueResult(
|
||||
False, None, "lower priority than queued items", ()
|
||||
)
|
||||
|
||||
self._items.pop()
|
||||
self._evicted_total += 1
|
||||
|
|
|
|||
|
|
@ -8,7 +8,11 @@ from google.protobuf.message import Message
|
|||
from google.protobuf.timestamp_pb2 import Timestamp
|
||||
|
||||
from ..proto_generated import events_pb2
|
||||
from ..proto_helpers import DEFAULT_DATACONTENTTYPE, DEFAULT_SPECVERSION, make_event_envelope
|
||||
from ..proto_helpers import (
|
||||
DEFAULT_DATACONTENTTYPE,
|
||||
DEFAULT_SPECVERSION,
|
||||
make_event_envelope,
|
||||
)
|
||||
from .clock import now_mono_ns, now_wall_ns
|
||||
from .enums import EventFlagBits, EventKind, PayloadKind, Severity, SourceKind
|
||||
from .ids import (
|
||||
|
|
@ -44,9 +48,15 @@ def event_envelope_to_record(
|
|||
payload_len = payload_msg.ByteSize() if payload_msg is not None else 0
|
||||
|
||||
route = envelope.routing
|
||||
flags = _encode_flags(route.cache_enabled, route.outbox_enabled, payload_field is not None)
|
||||
host_id = interner.intern(envelope.host.host_id if envelope.HasField("host") else "")
|
||||
interface_id = interner.intern(_interface_name_from_envelope(envelope, payload_field))
|
||||
flags = _encode_flags(
|
||||
route.cache_enabled, route.outbox_enabled, payload_field is not None
|
||||
)
|
||||
host_id = interner.intern(
|
||||
envelope.host.host_id if envelope.HasField("host") else ""
|
||||
)
|
||||
interface_id = interner.intern(
|
||||
_interface_name_from_envelope(envelope, payload_field)
|
||||
)
|
||||
event_type_id = interner.intern(envelope.type)
|
||||
source_instance_id = interner.intern(envelope.source)
|
||||
normalized_ssid_id = int(interner.intern(envelope.normalized_ssid))
|
||||
|
|
@ -61,9 +71,11 @@ def event_envelope_to_record(
|
|||
)
|
||||
parent_seq_no = _string_to_id(
|
||||
interner,
|
||||
envelope.trace.parent_event_ids[0]
|
||||
if envelope.HasField("trace") and envelope.trace.parent_event_ids
|
||||
else "",
|
||||
(
|
||||
envelope.trace.parent_event_ids[0]
|
||||
if envelope.HasField("trace") and envelope.trace.parent_event_ids
|
||||
else ""
|
||||
),
|
||||
)
|
||||
|
||||
return EventRecord(
|
||||
|
|
@ -77,13 +89,23 @@ def event_envelope_to_record(
|
|||
flags=int(flags),
|
||||
event_type_id=EventTypeId(event_type_id),
|
||||
source_instance_id=SourceInstanceId(source_instance_id),
|
||||
observed_mono_ns=observed_mono_ns if observed_mono_ns is not None else now_mono_ns(),
|
||||
observed_wall_ns=_timestamp_to_ns(envelope.time) if envelope.HasField("time") else now_wall_ns(),
|
||||
ingested_mono_ns=ingested_mono_ns if ingested_mono_ns is not None else now_mono_ns(),
|
||||
observed_mono_ns=(
|
||||
observed_mono_ns if observed_mono_ns is not None else now_mono_ns()
|
||||
),
|
||||
observed_wall_ns=(
|
||||
_timestamp_to_ns(envelope.time)
|
||||
if envelope.HasField("time")
|
||||
else now_wall_ns()
|
||||
),
|
||||
ingested_mono_ns=(
|
||||
ingested_mono_ns if ingested_mono_ns is not None else now_mono_ns()
|
||||
),
|
||||
host_id=HostId(host_id),
|
||||
interface_id=InterfaceId(interface_id),
|
||||
workflow_mask=WorkflowMask(
|
||||
_workflow_mask_from_tags(envelope.trace.workflow_tags) if envelope.HasField("trace") else 0
|
||||
_workflow_mask_from_tags(envelope.trace.workflow_tags)
|
||||
if envelope.HasField("trace")
|
||||
else 0
|
||||
),
|
||||
normalized_ssid_id=normalized_ssid_id,
|
||||
normalized_bssid=_parse_bssid(envelope.normalized_bssid),
|
||||
|
|
@ -107,9 +129,15 @@ def event_record_to_envelope(
|
|||
payload: Message | None = None,
|
||||
) -> events_pb2.EventEnvelope:
|
||||
interner = StringInterner() if interner is None else interner
|
||||
payload_field = _infer_payload_field_from_kind(record.payload_kind) if payload is not None else None
|
||||
payload_field = (
|
||||
_infer_payload_field_from_kind(record.payload_kind)
|
||||
if payload is not None
|
||||
else None
|
||||
)
|
||||
host = events_pb2.HostContext(host_id=interner.resolve(record.host_id))
|
||||
network = events_pb2.NetworkContext(interface_name=interner.resolve(record.interface_id))
|
||||
network = events_pb2.NetworkContext(
|
||||
interface_name=interner.resolve(record.interface_id)
|
||||
)
|
||||
trace = events_pb2.TraceContext(
|
||||
correlation_id=interner.resolve(record.correlation_id),
|
||||
causation_id=interner.resolve(record.causation_id),
|
||||
|
|
@ -121,7 +149,8 @@ def event_record_to_envelope(
|
|||
id=interner.resolve(record.event_id),
|
||||
source=interner.resolve(record.source_instance_id),
|
||||
type=interner.resolve(record.event_type_id),
|
||||
subject=interner.resolve(record.interface_id) or interner.resolve(record.host_id),
|
||||
subject=interner.resolve(record.interface_id)
|
||||
or interner.resolve(record.host_id),
|
||||
time=_ns_to_timestamp(record.observed_wall_ns),
|
||||
event_kind=int(record.event_kind),
|
||||
source_kind=int(record.source_kind),
|
||||
|
|
@ -154,7 +183,9 @@ def batch_envelope_to_records(
|
|||
*,
|
||||
interner: StringInterner | None = None,
|
||||
) -> list[EventRecord]:
|
||||
return [event_envelope_to_record(event, interner=interner) for event in batch.events]
|
||||
return [
|
||||
event_envelope_to_record(event, interner=interner) for event in batch.events
|
||||
]
|
||||
|
||||
|
||||
def records_to_batch_envelope(
|
||||
|
|
@ -162,7 +193,11 @@ def records_to_batch_envelope(
|
|||
*,
|
||||
interner: StringInterner | None = None,
|
||||
) -> events_pb2.BatchEnvelope:
|
||||
return events_pb2.BatchEnvelope(events=[event_record_to_envelope(record, interner=interner) for record in records])
|
||||
return events_pb2.BatchEnvelope(
|
||||
events=[
|
||||
event_record_to_envelope(record, interner=interner) for record in records
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def _coerce_enum(enum_cls, value: int):
|
||||
|
|
@ -204,7 +239,9 @@ def _infer_payload_field_from_kind(kind: PayloadKind) -> str | None:
|
|||
return None
|
||||
|
||||
|
||||
def _encode_flags(cache_enabled: bool, outbox_enabled: bool, has_payload: bool) -> EventFlagBits:
|
||||
def _encode_flags(
|
||||
cache_enabled: bool, outbox_enabled: bool, has_payload: bool
|
||||
) -> EventFlagBits:
|
||||
flags = EventFlagBits(0)
|
||||
if cache_enabled:
|
||||
flags |= EventFlagBits.CACHE_ENABLED
|
||||
|
|
@ -223,7 +260,9 @@ def _workflow_mask_from_tags(tags: Iterable[str]) -> int:
|
|||
return mask
|
||||
|
||||
|
||||
def _interface_name_from_envelope(envelope: events_pb2.EventEnvelope, payload_field: str | None) -> str:
|
||||
def _interface_name_from_envelope(
|
||||
envelope: events_pb2.EventEnvelope, payload_field: str | None
|
||||
) -> str:
|
||||
if envelope.HasField("network") and envelope.network.interface_name:
|
||||
return envelope.network.interface_name
|
||||
if payload_field == "raw_wpa":
|
||||
|
|
|
|||
|
|
@ -12,8 +12,7 @@ from ..proto_generated import events_pb2
|
|||
|
||||
|
||||
class DerivatorSink(Protocol):
|
||||
def __call__(self, envelope: events_pb2.EventEnvelope) -> None:
|
||||
...
|
||||
def __call__(self, envelope: events_pb2.EventEnvelope) -> None: ...
|
||||
|
||||
|
||||
class DerivationWorkflow(Protocol):
|
||||
|
|
@ -26,8 +25,7 @@ class DerivationWorkflow(Protocol):
|
|||
interner: StringInterner,
|
||||
now_mono_ns: int,
|
||||
worker_name: str,
|
||||
) -> Sequence[events_pb2.EventEnvelope]:
|
||||
...
|
||||
) -> Sequence[events_pb2.EventEnvelope]: ...
|
||||
|
||||
|
||||
class CommandInitiatingWorkflow(Protocol):
|
||||
|
|
@ -40,13 +38,13 @@ class CommandInitiatingWorkflow(Protocol):
|
|||
interner: StringInterner,
|
||||
now_mono_ns: int,
|
||||
worker_name: str,
|
||||
) -> Sequence[CommandRequest]:
|
||||
...
|
||||
) -> Sequence[CommandRequest]: ...
|
||||
|
||||
|
||||
class CommandCoordinatorSink(Protocol):
|
||||
def submit_derivator(self, request: CommandRequest, *, now_mono_ns_value: int | None = None) -> Any:
|
||||
...
|
||||
def submit_derivator(
|
||||
self, request: CommandRequest, *, now_mono_ns_value: int | None = None
|
||||
) -> Any: ...
|
||||
|
||||
|
||||
@dataclass(slots=True, frozen=True)
|
||||
|
|
|
|||
|
|
@ -54,7 +54,9 @@ class WifiScanSummaryWorkflow:
|
|||
now_mono_ns: int,
|
||||
worker_name: str,
|
||||
) -> Sequence[events_pb2.EventEnvelope]:
|
||||
wifi_records, scan_total, signal_total, disconnect_total, connected_total = self._summarize_wifi_window(window, interner)
|
||||
wifi_records, scan_total, signal_total, disconnect_total, connected_total = (
|
||||
self._summarize_wifi_window(window, interner)
|
||||
)
|
||||
if len(wifi_records) < self.config.min_wifi_records:
|
||||
return ()
|
||||
|
||||
|
|
@ -76,8 +78,14 @@ class WifiScanSummaryWorkflow:
|
|||
"disconnected_count": int(disconnect_total),
|
||||
}
|
||||
)
|
||||
confidence = min(0.99, 0.60 + 0.10 * min(len(wifi_records), 3) + 0.05 * min(scan_total, 3))
|
||||
severity = common_pb2.SEVERITY_INFO if disconnect_total == 0 else common_pb2.SEVERITY_WARNING
|
||||
confidence = min(
|
||||
0.99, 0.60 + 0.10 * min(len(wifi_records), 3) + 0.05 * min(scan_total, 3)
|
||||
)
|
||||
severity = (
|
||||
common_pb2.SEVERITY_INFO
|
||||
if disconnect_total == 0
|
||||
else common_pb2.SEVERITY_WARNING
|
||||
)
|
||||
envelope = make_event_envelope(
|
||||
id=f"{self.name}-{window.end_seq_no}",
|
||||
source=f"derivator://{worker_name}/{self.name}",
|
||||
|
|
@ -86,9 +94,15 @@ class WifiScanSummaryWorkflow:
|
|||
event_kind=common_pb2.EVENT_KIND_DERIVED,
|
||||
source_kind=common_pb2.SOURCE_KIND_APPLICATION,
|
||||
severity=severity,
|
||||
routing=events_pb2.RoutingDirectives(cache_enabled=True, outbox_enabled=False, priority=5),
|
||||
trace=events_pb2.TraceContext(workflow_tags=["wifi", self.config.workflow_name]),
|
||||
attributes=common_pb2.AttributeMap(labels={"workflow": self.config.workflow_name, "source": "derivator"}),
|
||||
routing=events_pb2.RoutingDirectives(
|
||||
cache_enabled=True, outbox_enabled=False, priority=5
|
||||
),
|
||||
trace=events_pb2.TraceContext(
|
||||
workflow_tags=["wifi", self.config.workflow_name]
|
||||
),
|
||||
attributes=common_pb2.AttributeMap(
|
||||
labels={"workflow": self.config.workflow_name, "source": "derivator"}
|
||||
),
|
||||
normalized_event_code=self.config.workflow_name,
|
||||
normalized_reason=summary,
|
||||
payload=events_pb2.DerivedEventPayload(
|
||||
|
|
@ -110,10 +124,14 @@ class WifiScanSummaryWorkflow:
|
|||
now_mono_ns: int,
|
||||
worker_name: str,
|
||||
) -> Sequence[CommandRequest]:
|
||||
wifi_records, scan_total, signal_total, disconnect_total, connected_total = self._summarize_wifi_window(window, interner)
|
||||
wifi_records, scan_total, signal_total, disconnect_total, connected_total = (
|
||||
self._summarize_wifi_window(window, interner)
|
||||
)
|
||||
if len(wifi_records) < self.config.min_wifi_records:
|
||||
return ()
|
||||
if disconnect_total < max(0, int(self.config.follow_up_command_min_disconnects)):
|
||||
if disconnect_total < max(
|
||||
0, int(self.config.follow_up_command_min_disconnects)
|
||||
):
|
||||
return ()
|
||||
|
||||
command_type = self.config.follow_up_command_type.strip()
|
||||
|
|
@ -138,7 +156,10 @@ class WifiScanSummaryWorkflow:
|
|||
"disconnected_count": int(disconnect_total),
|
||||
}
|
||||
)
|
||||
dedup_key = self.config.follow_up_command_dedup_key.strip() or f"{command_type}:{target_id or target_kind.name.lower()}"
|
||||
dedup_key = (
|
||||
self.config.follow_up_command_dedup_key.strip()
|
||||
or f"{command_type}:{target_id or target_kind.name.lower()}"
|
||||
)
|
||||
cooldown_key = self.config.follow_up_command_cooldown_key.strip() or dedup_key
|
||||
exclusive_key = self.config.follow_up_command_exclusive_key.strip()
|
||||
causation_event_id = str(wifi_records[-1].event_id) if wifi_records else ""
|
||||
|
|
@ -167,11 +188,38 @@ class WifiScanSummaryWorkflow:
|
|||
window: DerivatorWindow,
|
||||
interner: StringInterner,
|
||||
) -> tuple[tuple[EventRecord, ...], int, int, int, int]:
|
||||
wifi_records = tuple(record for record in window.records if self._is_wifi_record(record, interner))
|
||||
scan_total = sum(1 for record in wifi_records if _contains_any(_type_name(record, interner), ("scan", "scan_results", "scan-result")))
|
||||
signal_total = sum(1 for record in wifi_records if _contains_any(_type_name(record, interner), ("signal_poll", "signal-poll")))
|
||||
disconnect_total = sum(1 for record in wifi_records if _contains_any(_type_name(record, interner), ("disconnect", "disconnected", "link_lost")))
|
||||
connected_total = sum(1 for record in wifi_records if _contains_any(_type_name(record, interner), ("connect", "connected")))
|
||||
wifi_records = tuple(
|
||||
record
|
||||
for record in window.records
|
||||
if self._is_wifi_record(record, interner)
|
||||
)
|
||||
scan_total = sum(
|
||||
1
|
||||
for record in wifi_records
|
||||
if _contains_any(
|
||||
_type_name(record, interner), ("scan", "scan_results", "scan-result")
|
||||
)
|
||||
)
|
||||
signal_total = sum(
|
||||
1
|
||||
for record in wifi_records
|
||||
if _contains_any(
|
||||
_type_name(record, interner), ("signal_poll", "signal-poll")
|
||||
)
|
||||
)
|
||||
disconnect_total = sum(
|
||||
1
|
||||
for record in wifi_records
|
||||
if _contains_any(
|
||||
_type_name(record, interner),
|
||||
("disconnect", "disconnected", "link_lost"),
|
||||
)
|
||||
)
|
||||
connected_total = sum(
|
||||
1
|
||||
for record in wifi_records
|
||||
if _contains_any(_type_name(record, interner), ("connect", "connected"))
|
||||
)
|
||||
return wifi_records, scan_total, signal_total, disconnect_total, connected_total
|
||||
|
||||
def _is_wifi_record(self, record: EventRecord, interner: StringInterner) -> bool:
|
||||
|
|
|
|||
|
|
@ -45,7 +45,9 @@ class DerivatorWorker:
|
|||
self.sink = sink
|
||||
self.command_coordinator = command_coordinator
|
||||
self.workflows = tuple(workflows or ())
|
||||
self.config = DerivatorWorkerConfig(name=name, enabled=enabled, poll_interval_ms=max(0, int(poll_interval_ms)))
|
||||
self.config = DerivatorWorkerConfig(
|
||||
name=name, enabled=enabled, poll_interval_ms=max(0, int(poll_interval_ms))
|
||||
)
|
||||
self.interner = interner if interner is not None else cache.interner
|
||||
self._cursor_seq_no = 1
|
||||
self._last_poll_mono_ns = 0
|
||||
|
|
@ -86,27 +88,45 @@ class DerivatorWorker:
|
|||
now = monotonic_ns() if now_mono_ns_value is None else now_mono_ns_value
|
||||
if self._last_poll_mono_ns <= 0:
|
||||
return True
|
||||
return (now - self._last_poll_mono_ns) >= self.config.poll_interval_ms * 1_000_000
|
||||
return (
|
||||
now - self._last_poll_mono_ns
|
||||
) >= self.config.poll_interval_ms * 1_000_000
|
||||
|
||||
def poll_once(self, *, now_mono_ns_value: int | None = None) -> DerivatorPollResult:
|
||||
now = monotonic_ns() if now_mono_ns_value is None else now_mono_ns_value
|
||||
if not self.config.enabled:
|
||||
self._stats = replace(self._stats, skipped_total=self._stats.skipped_total + 1, last_error="disabled")
|
||||
self._stats = replace(
|
||||
self._stats,
|
||||
skipped_total=self._stats.skipped_total + 1,
|
||||
last_error="disabled",
|
||||
)
|
||||
self._last_error = "disabled"
|
||||
return DerivatorPollResult(polled=False, skipped=True, reason="disabled")
|
||||
if not self.poll_due(now):
|
||||
self._stats = replace(self._stats, skipped_total=self._stats.skipped_total + 1, last_error="not due")
|
||||
self._stats = replace(
|
||||
self._stats,
|
||||
skipped_total=self._stats.skipped_total + 1,
|
||||
last_error="not due",
|
||||
)
|
||||
self._last_error = "not due"
|
||||
return DerivatorPollResult(polled=False, skipped=True, reason="not due")
|
||||
|
||||
self._last_poll_mono_ns = now
|
||||
self._current_poll_mono_ns = now
|
||||
self._stats = replace(self._stats, poll_total=self._stats.poll_total + 1, last_poll_mono_ns=now)
|
||||
self._stats = replace(
|
||||
self._stats, poll_total=self._stats.poll_total + 1, last_poll_mono_ns=now
|
||||
)
|
||||
window = self._collect_window(now)
|
||||
if window.is_empty:
|
||||
self._stats = replace(self._stats, skipped_total=self._stats.skipped_total + 1, last_error="no new records")
|
||||
self._stats = replace(
|
||||
self._stats,
|
||||
skipped_total=self._stats.skipped_total + 1,
|
||||
last_error="no new records",
|
||||
)
|
||||
self._last_error = "no new records"
|
||||
return DerivatorPollResult(polled=True, skipped=True, reason="no new records", window=window)
|
||||
return DerivatorPollResult(
|
||||
polled=True, skipped=True, reason="no new records", window=window
|
||||
)
|
||||
|
||||
derived_envelopes = tuple(self.process_window(window))
|
||||
emitted_total = 0
|
||||
|
|
@ -143,7 +163,9 @@ class DerivatorWorker:
|
|||
def run_once(self, *, now_mono_ns_value: int | None = None) -> DerivatorPollResult:
|
||||
return self.poll_once(now_mono_ns_value=now_mono_ns_value)
|
||||
|
||||
def process_window(self, window: DerivatorWindow) -> Sequence[events_pb2.EventEnvelope]:
|
||||
def process_window(
|
||||
self, window: DerivatorWindow
|
||||
) -> Sequence[events_pb2.EventEnvelope]:
|
||||
envelopes: list[events_pb2.EventEnvelope] = []
|
||||
for workflow in self.workflows:
|
||||
derived = workflow.derive(
|
||||
|
|
@ -170,7 +192,9 @@ class DerivatorWorker:
|
|||
worker_name=self.config.name,
|
||||
)
|
||||
for request in commands or ():
|
||||
self.command_coordinator.submit_derivator(request, now_mono_ns_value=self._current_poll_mono_ns)
|
||||
self.command_coordinator.submit_derivator(
|
||||
request, now_mono_ns_value=self._current_poll_mono_ns
|
||||
)
|
||||
|
||||
def _collect_window(self, now_mono_ns_value: int) -> DerivatorWindow:
|
||||
high_seq_no = int(self.cache.ring_buffer.next_seq_no) - 1
|
||||
|
|
@ -186,7 +210,11 @@ class DerivatorWorker:
|
|||
|
||||
retained_start = max(1, high_seq_no - int(self.cache.ring_buffer.capacity) + 1)
|
||||
scan_start = max(requested_start, retained_start)
|
||||
missing = list(range(requested_start, scan_start)) if scan_start > requested_start else []
|
||||
missing = (
|
||||
list(range(requested_start, scan_start))
|
||||
if scan_start > requested_start
|
||||
else []
|
||||
)
|
||||
records: list[EventRecord] = []
|
||||
for seq_no in range(scan_start, high_seq_no + 1):
|
||||
record = self.cache.get(seq_no)
|
||||
|
|
|
|||
|
|
@ -1,7 +1,12 @@
|
|||
"""Event routing director."""
|
||||
|
||||
from .director import Director, DirectorOutcome, DirectorSink, DirectorState
|
||||
from .policies import DirectorPolicyConfig, DirectorPolicyState, DirectorRouteHints, DirectorRoutingState
|
||||
from .policies import (
|
||||
DirectorPolicyConfig,
|
||||
DirectorPolicyState,
|
||||
DirectorRouteHints,
|
||||
DirectorRoutingState,
|
||||
)
|
||||
from .routing import DirectorRouteDecision, DirectorRouteStats, route_envelope
|
||||
|
||||
__all__ = [
|
||||
|
|
@ -16,4 +21,4 @@ __all__ = [
|
|||
"DirectorSink",
|
||||
"DirectorState",
|
||||
"route_envelope",
|
||||
]
|
||||
]
|
||||
|
|
|
|||
|
|
@ -14,8 +14,7 @@ from .routing import DirectorRouteDecision, DirectorRouteStats, route_envelope
|
|||
|
||||
|
||||
class DirectorSink(Protocol):
|
||||
def __call__(self, record: EventRecord) -> None:
|
||||
...
|
||||
def __call__(self, record: EventRecord) -> None: ...
|
||||
|
||||
|
||||
@dataclass(slots=True, frozen=True)
|
||||
|
|
@ -51,7 +50,11 @@ class Director:
|
|||
self.outbox_sink = outbox_sink
|
||||
self.derivator_sink = derivator_sink
|
||||
self.policy = DirectorPolicyConfig() if policy is None else policy
|
||||
self.interner = interner if interner is not None else (cache.interner if cache is not None else StringInterner())
|
||||
self.interner = (
|
||||
interner
|
||||
if interner is not None
|
||||
else (cache.interner if cache is not None else StringInterner())
|
||||
)
|
||||
self._stats = DirectorRouteStats()
|
||||
self._last_decision: DirectorRouteDecision | None = None
|
||||
self._last_error: str | None = None
|
||||
|
|
@ -64,7 +67,9 @@ class Director:
|
|||
) -> DirectorOutcome:
|
||||
now = now_mono_ns() if now_mono_ns_value is None else now_mono_ns_value
|
||||
decision = route_envelope(envelope, policy=self.policy)
|
||||
record = event_envelope_to_record(envelope, interner=self.interner, observed_mono_ns=now, ingested_mono_ns=now)
|
||||
record = event_envelope_to_record(
|
||||
envelope, interner=self.interner, observed_mono_ns=now, ingested_mono_ns=now
|
||||
)
|
||||
cached_record: EventRecord | None = None
|
||||
|
||||
if decision.cache and self.cache is not None:
|
||||
|
|
@ -79,7 +84,8 @@ class Director:
|
|||
self._stats,
|
||||
cache_total=self._stats.cache_total + (1 if decision.cache else 0),
|
||||
outbox_total=self._stats.outbox_total + (1 if decision.outbox else 0),
|
||||
derivator_interest_total=self._stats.derivator_interest_total + (1 if decision.derivator_interest else 0),
|
||||
derivator_interest_total=self._stats.derivator_interest_total
|
||||
+ (1 if decision.derivator_interest else 0),
|
||||
routed_total=self._stats.routed_total + 1,
|
||||
dropped_total=self._stats.dropped_total + (1 if not decision.any else 0),
|
||||
last_route_mono_ns=now,
|
||||
|
|
@ -95,7 +101,12 @@ class Director:
|
|||
derivator_interest_applied=decision.derivator_interest,
|
||||
)
|
||||
|
||||
def ingest(self, envelope: events_pb2.EventEnvelope, *, now_mono_ns_value: int | None = None) -> DirectorOutcome:
|
||||
def ingest(
|
||||
self,
|
||||
envelope: events_pb2.EventEnvelope,
|
||||
*,
|
||||
now_mono_ns_value: int | None = None,
|
||||
) -> DirectorOutcome:
|
||||
return self.route(envelope, now_mono_ns_value=now_mono_ns_value)
|
||||
|
||||
def state(self) -> DirectorState:
|
||||
|
|
@ -119,5 +130,7 @@ class Director:
|
|||
"derivator_interest_type_prefixes": self.policy.derivator_interest_type_prefixes,
|
||||
"derivator_interest_subject_prefixes": self.policy.derivator_interest_subject_prefixes,
|
||||
"derivator_interest_label_keys": self.policy.derivator_interest_label_keys,
|
||||
"derivator_interest_source_kinds": tuple(kind.name for kind in self.policy.derivator_interest_source_kinds),
|
||||
}
|
||||
"derivator_interest_source_kinds": tuple(
|
||||
kind.name for kind in self.policy.derivator_interest_source_kinds
|
||||
),
|
||||
}
|
||||
|
|
|
|||
|
|
@ -46,15 +46,30 @@ class DirectorPolicyConfig:
|
|||
if not isinstance(interest, Mapping):
|
||||
interest = {}
|
||||
return cls(
|
||||
outbox_severity_threshold=_coerce_severity(routing.get("outbox_severity_threshold", routing.get("severity_threshold", Severity.WARNING))),
|
||||
outbox_control_type_prefixes=_string_tuple(routing.get("outbox_control_type_prefixes", ("control.command.",))),
|
||||
outbox_severity_threshold=_coerce_severity(
|
||||
routing.get(
|
||||
"outbox_severity_threshold",
|
||||
routing.get("severity_threshold", Severity.WARNING),
|
||||
)
|
||||
),
|
||||
outbox_control_type_prefixes=_string_tuple(
|
||||
routing.get("outbox_control_type_prefixes", ("control.command.",))
|
||||
),
|
||||
outbox_derived_enabled=bool(routing.get("outbox_derived_enabled", True)),
|
||||
outbox_control_enabled=bool(routing.get("outbox_control_enabled", True)),
|
||||
derivator_interest_tags=_string_tuple(interest.get("workflow_tags", interest.get("tags", ()))),
|
||||
derivator_interest_type_prefixes=_string_tuple(interest.get("type_prefixes", interest.get("event_type_prefixes", ()))),
|
||||
derivator_interest_subject_prefixes=_string_tuple(interest.get("subject_prefixes", ())),
|
||||
derivator_interest_tags=_string_tuple(
|
||||
interest.get("workflow_tags", interest.get("tags", ()))
|
||||
),
|
||||
derivator_interest_type_prefixes=_string_tuple(
|
||||
interest.get("type_prefixes", interest.get("event_type_prefixes", ()))
|
||||
),
|
||||
derivator_interest_subject_prefixes=_string_tuple(
|
||||
interest.get("subject_prefixes", ())
|
||||
),
|
||||
derivator_interest_label_keys=_string_tuple(interest.get("label_keys", ())),
|
||||
derivator_interest_source_kinds=_source_kind_tuple(interest.get("source_kinds", ())),
|
||||
derivator_interest_source_kinds=_source_kind_tuple(
|
||||
interest.get("source_kinds", ())
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
|
|
@ -121,4 +136,4 @@ def _coerce_severity(value: Any) -> Severity:
|
|||
return Severity[key]
|
||||
except KeyError:
|
||||
pass
|
||||
return Severity.WARNING
|
||||
return Severity.WARNING
|
||||
|
|
|
|||
|
|
@ -67,14 +67,22 @@ def _should_outbox(
|
|||
if envelope.routing.outbox_enabled:
|
||||
return True, "routing.outbox_enabled"
|
||||
|
||||
severity = Severity(int(envelope.severity)) if int(envelope.severity) in Severity._value2member_map_ else Severity.UNSPECIFIED
|
||||
severity = (
|
||||
Severity(int(envelope.severity))
|
||||
if int(envelope.severity) in Severity._value2member_map_
|
||||
else Severity.UNSPECIFIED
|
||||
)
|
||||
if severity >= policy.outbox_severity_threshold:
|
||||
return True, f"severity>={policy.outbox_severity_threshold.name.lower()}"
|
||||
|
||||
if policy.outbox_derived_enabled and int(envelope.event_kind) == int(EventKind.DERIVED):
|
||||
if policy.outbox_derived_enabled and int(envelope.event_kind) == int(
|
||||
EventKind.DERIVED
|
||||
):
|
||||
return True, "event_kind=derived"
|
||||
|
||||
if policy.outbox_control_enabled and int(envelope.source_kind) == int(SourceKind.CONTROL):
|
||||
if policy.outbox_control_enabled and int(envelope.source_kind) == int(
|
||||
SourceKind.CONTROL
|
||||
):
|
||||
if _matches_prefix(envelope.type, policy.outbox_control_type_prefixes):
|
||||
return True, "source_kind=control"
|
||||
|
||||
|
|
@ -103,11 +111,18 @@ def _should_interest(
|
|||
if any(key in labels for key in policy.derivator_interest_label_keys):
|
||||
return True, "label_key"
|
||||
|
||||
if int(envelope.source_kind) in {int(kind) for kind in policy.derivator_interest_source_kinds}:
|
||||
if int(envelope.source_kind) in {
|
||||
int(kind) for kind in policy.derivator_interest_source_kinds
|
||||
}:
|
||||
if int(envelope.severity) >= int(Severity.WARNING):
|
||||
return True, "source_kind+severity"
|
||||
if int(envelope.source_kind) == int(SourceKind.CONTROL) and envelope.type.startswith("control.command."):
|
||||
if any(envelope.type.endswith(suffix) for suffix in ("failed", "rejected", "deferred", "suppressed")):
|
||||
if int(envelope.source_kind) == int(
|
||||
SourceKind.CONTROL
|
||||
) and envelope.type.startswith("control.command."):
|
||||
if any(
|
||||
envelope.type.endswith(suffix)
|
||||
for suffix in ("failed", "rejected", "deferred", "suppressed")
|
||||
):
|
||||
return True, "control_command_failure"
|
||||
|
||||
return False, None
|
||||
|
|
@ -125,4 +140,4 @@ def _intersects(values: Iterable[str], prefixes: Iterable[str]) -> bool:
|
|||
for value in values:
|
||||
if value in wanted:
|
||||
return True
|
||||
return False
|
||||
return False
|
||||
|
|
|
|||
|
|
@ -105,7 +105,9 @@ class ExecutorBase(ABC):
|
|||
return self._identity
|
||||
|
||||
def state(self) -> ExecutorState:
|
||||
return ExecutorState(identity=self._identity, health=self._health, stats=self._stats)
|
||||
return ExecutorState(
|
||||
identity=self._identity, health=self._health, stats=self._stats
|
||||
)
|
||||
|
||||
def health(self) -> ExecutorHealth:
|
||||
self._touch_health()
|
||||
|
|
@ -115,7 +117,10 @@ class ExecutorBase(ABC):
|
|||
return self._stats
|
||||
|
||||
def is_running(self) -> bool:
|
||||
return self._health.lifecycle_state in {ExecutorLifecycleState.CONNECTED, ExecutorLifecycleState.RUNNING}
|
||||
return self._health.lifecycle_state in {
|
||||
ExecutorLifecycleState.CONNECTED,
|
||||
ExecutorLifecycleState.RUNNING,
|
||||
}
|
||||
|
||||
@abstractmethod
|
||||
def supports(self, request: CommandRequest) -> bool:
|
||||
|
|
@ -126,24 +131,40 @@ class ExecutorBase(ABC):
|
|||
"""Execute *request* and return a command result."""
|
||||
|
||||
def _set_lifecycle_state(self, state: ExecutorLifecycleState) -> None:
|
||||
self._health = replace(self._health, lifecycle_state=state, last_transition_mono_ns=now_mono_ns())
|
||||
self._health = replace(
|
||||
self._health, lifecycle_state=state, last_transition_mono_ns=now_mono_ns()
|
||||
)
|
||||
|
||||
def _set_connection_state(self, state: ExecutorConnectionState) -> None:
|
||||
self._health = replace(self._health, connection_state=state, last_transition_mono_ns=now_mono_ns())
|
||||
self._health = replace(
|
||||
self._health, connection_state=state, last_transition_mono_ns=now_mono_ns()
|
||||
)
|
||||
|
||||
def _set_pipeline_state(self, state: ExecutorPipelineState) -> None:
|
||||
self._health = replace(self._health, pipeline_state=state, last_transition_mono_ns=now_mono_ns())
|
||||
self._health = replace(
|
||||
self._health, pipeline_state=state, last_transition_mono_ns=now_mono_ns()
|
||||
)
|
||||
|
||||
def _mark_healthy(self, healthy: bool) -> None:
|
||||
self._health = replace(self._health, healthy=healthy, last_checked_mono_ns=now_mono_ns())
|
||||
self._health = replace(
|
||||
self._health, healthy=healthy, last_checked_mono_ns=now_mono_ns()
|
||||
)
|
||||
|
||||
def _record_execute(self) -> None:
|
||||
now = now_mono_ns()
|
||||
self._stats = replace(self._stats, execute_total=self._stats.execute_total + 1, last_execute_mono_ns=now)
|
||||
self._stats = replace(
|
||||
self._stats,
|
||||
execute_total=self._stats.execute_total + 1,
|
||||
last_execute_mono_ns=now,
|
||||
)
|
||||
|
||||
def _record_success(self) -> None:
|
||||
now = now_mono_ns()
|
||||
self._stats = replace(self._stats, success_total=self._stats.success_total + 1, last_success_mono_ns=now)
|
||||
self._stats = replace(
|
||||
self._stats,
|
||||
success_total=self._stats.success_total + 1,
|
||||
last_success_mono_ns=now,
|
||||
)
|
||||
self._health = replace(self._health, healthy=True, last_checked_mono_ns=now)
|
||||
|
||||
def _record_failure(self, message: str | Exception) -> None:
|
||||
|
|
@ -163,7 +184,11 @@ class ExecutorBase(ABC):
|
|||
|
||||
def _record_reject(self, message: str | Exception) -> None:
|
||||
now = now_mono_ns()
|
||||
self._stats = replace(self._stats, reject_total=self._stats.reject_total + 1, last_error_mono_ns=now)
|
||||
self._stats = replace(
|
||||
self._stats,
|
||||
reject_total=self._stats.reject_total + 1,
|
||||
last_error_mono_ns=now,
|
||||
)
|
||||
self._health = replace(
|
||||
self._health,
|
||||
healthy=False,
|
||||
|
|
|
|||
|
|
@ -23,14 +23,27 @@ class ExecutorRoute:
|
|||
return False
|
||||
if self.command_types and request.command_type in self.command_types:
|
||||
return True
|
||||
if self.command_prefixes and any(request.command_type.startswith(prefix) for prefix in self.command_prefixes):
|
||||
if self.command_prefixes and any(
|
||||
request.command_type.startswith(prefix) for prefix in self.command_prefixes
|
||||
):
|
||||
return True
|
||||
return False
|
||||
|
||||
def specificity(self, request: CommandRequest) -> tuple[int, int, int, int]:
|
||||
exact_match = 1 if request.command_type in self.command_types else 0
|
||||
prefix_length = max((len(prefix) for prefix in self.command_prefixes if request.command_type.startswith(prefix)), default=0)
|
||||
target_match = 1 if not self.target_kinds or request.target_kind in self.target_kinds else 0
|
||||
prefix_length = max(
|
||||
(
|
||||
len(prefix)
|
||||
for prefix in self.command_prefixes
|
||||
if request.command_type.startswith(prefix)
|
||||
),
|
||||
default=0,
|
||||
)
|
||||
target_match = (
|
||||
1
|
||||
if not self.target_kinds or request.target_kind in self.target_kinds
|
||||
else 0
|
||||
)
|
||||
return (exact_match, prefix_length, target_match, self.priority)
|
||||
|
||||
|
||||
|
|
@ -100,7 +113,11 @@ class ExecutorRouter:
|
|||
name=name or executor.identity.name,
|
||||
)
|
||||
self._routes.append(route)
|
||||
self._stats = replace(self._stats, routes_total=len(self._routes), registries_total=self._stats.registries_total + 1)
|
||||
self._stats = replace(
|
||||
self._stats,
|
||||
routes_total=len(self._routes),
|
||||
registries_total=self._stats.registries_total + 1,
|
||||
)
|
||||
return route
|
||||
|
||||
def unregister(self, executor_name: str) -> ExecutorRoute | None:
|
||||
|
|
@ -112,11 +129,23 @@ class ExecutorRouter:
|
|||
return None
|
||||
|
||||
def resolve(self, request: CommandRequest) -> ExecutorRouteMatch | None:
|
||||
self._stats = replace(self._stats, resolve_total=self._stats.resolve_total + 1, last_resolve_mono_ns=_now())
|
||||
candidates = [route for route in self._routes if route.matches(request) and route.executor.supports(request)]
|
||||
self._stats = replace(
|
||||
self._stats,
|
||||
resolve_total=self._stats.resolve_total + 1,
|
||||
last_resolve_mono_ns=_now(),
|
||||
)
|
||||
candidates = [
|
||||
route
|
||||
for route in self._routes
|
||||
if route.matches(request) and route.executor.supports(request)
|
||||
]
|
||||
if not candidates:
|
||||
self._last_error = f"unsupported command: {request.command_type}"
|
||||
self._stats = replace(self._stats, unsupported_total=self._stats.unsupported_total + 1, last_error_mono_ns=_now())
|
||||
self._stats = replace(
|
||||
self._stats,
|
||||
unsupported_total=self._stats.unsupported_total + 1,
|
||||
last_error_mono_ns=_now(),
|
||||
)
|
||||
return None
|
||||
candidates.sort(key=lambda route: route.specificity(request), reverse=True)
|
||||
match = ExecutorRouteMatch(route=candidates[0], request=request)
|
||||
|
|
@ -127,7 +156,11 @@ class ExecutorRouter:
|
|||
return self.resolve(request) is not None
|
||||
|
||||
def execute(self, request: CommandRequest) -> CommandResult:
|
||||
self._stats = replace(self._stats, execute_total=self._stats.execute_total + 1, last_execute_mono_ns=_now())
|
||||
self._stats = replace(
|
||||
self._stats,
|
||||
execute_total=self._stats.execute_total + 1,
|
||||
last_execute_mono_ns=_now(),
|
||||
)
|
||||
match = self.resolve(request)
|
||||
if match is None:
|
||||
return CommandResult.from_request(
|
||||
|
|
@ -167,7 +200,9 @@ class ExecutorRouter:
|
|||
|
||||
def state(self) -> ExecutorRouterState:
|
||||
return ExecutorRouterState(
|
||||
routes=tuple(route.name or route.executor.identity.name for route in self._routes),
|
||||
routes=tuple(
|
||||
route.name or route.executor.identity.name for route in self._routes
|
||||
),
|
||||
stats=self._stats,
|
||||
unsupported_total=self._stats.unsupported_total,
|
||||
last_match=self._last_match,
|
||||
|
|
@ -182,4 +217,3 @@ def _now() -> int:
|
|||
from ..core.clock import now_mono_ns
|
||||
|
||||
return now_mono_ns()
|
||||
|
||||
|
|
|
|||
|
|
@ -10,7 +10,12 @@ from typing import Any, Callable, Mapping, Protocol
|
|||
|
||||
from google.protobuf import json_format, struct_pb2
|
||||
|
||||
from ..commands.models import CommandRequest, CommandResult, CommandState, CommandTargetKind
|
||||
from ..commands.models import (
|
||||
CommandRequest,
|
||||
CommandResult,
|
||||
CommandState,
|
||||
CommandTargetKind,
|
||||
)
|
||||
from ..core.enums import Severity
|
||||
from ..proto_generated import common_pb2, events_pb2
|
||||
from ..proto_helpers import make_event_envelope
|
||||
|
|
@ -22,19 +27,15 @@ from .base import (
|
|||
ExecutorPipelineState,
|
||||
)
|
||||
|
||||
|
||||
SystemResultSink = Callable[[events_pb2.EventEnvelope], None]
|
||||
|
||||
|
||||
class SystemCommandBackend(Protocol):
|
||||
def connect(self, config: "SystemExecutorConfig") -> None:
|
||||
...
|
||||
def connect(self, config: "SystemExecutorConfig") -> None: ...
|
||||
|
||||
def request(self, command_line: str) -> str | None:
|
||||
...
|
||||
def request(self, command_line: str) -> str | None: ...
|
||||
|
||||
def close(self) -> None:
|
||||
...
|
||||
def close(self) -> None: ...
|
||||
|
||||
|
||||
@dataclass(slots=True, frozen=True)
|
||||
|
|
@ -46,7 +47,9 @@ class SystemExecutorConfig:
|
|||
extra_actions: tuple[str, ...] = ()
|
||||
|
||||
@classmethod
|
||||
def from_toml(cls, data: Mapping[str, Any], *, executor_name: str | None = None) -> "SystemExecutorConfig":
|
||||
def from_toml(
|
||||
cls, data: Mapping[str, Any], *, executor_name: str | None = None
|
||||
) -> "SystemExecutorConfig":
|
||||
section = _select_executor_section(data, executor_name)
|
||||
if not isinstance(section, Mapping):
|
||||
section = {}
|
||||
|
|
@ -54,7 +57,9 @@ class SystemExecutorConfig:
|
|||
return cls(
|
||||
name=str(executor_name or section.get("name", "system")),
|
||||
enabled=bool(section.get("enabled", True)),
|
||||
source_name=str(section.get("source_name", "system://local") or "system://local"),
|
||||
source_name=str(
|
||||
section.get("source_name", "system://local") or "system://local"
|
||||
),
|
||||
allow_set_regdomain=bool(section.get("allow_set_regdomain", True)),
|
||||
extra_actions=_string_tuple(extra_actions),
|
||||
)
|
||||
|
|
@ -87,8 +92,14 @@ class FakeSystemBackend:
|
|||
raise RuntimeError("system backend is not connected")
|
||||
self.request_calls += 1
|
||||
response_queue = self._responses.get(command_line)
|
||||
response = self.default_response if response_queue is None or not response_queue else response_queue.pop(0)
|
||||
self.calls.append(SystemCommandCall(command_line=command_line, response=response))
|
||||
response = (
|
||||
self.default_response
|
||||
if response_queue is None or not response_queue
|
||||
else response_queue.pop(0)
|
||||
)
|
||||
self.calls.append(
|
||||
SystemCommandCall(command_line=command_line, response=response)
|
||||
)
|
||||
return response
|
||||
|
||||
def close(self) -> None:
|
||||
|
|
@ -182,7 +193,10 @@ class SystemExecutor(ExecutorBase):
|
|||
success=False,
|
||||
message=f"unsupported command: {request.command_type}",
|
||||
executor_name=self.identity.name,
|
||||
).with_details(reason="unsupported", supported_actions=["set_regdomain", *self.config.extra_actions])
|
||||
).with_details(
|
||||
reason="unsupported",
|
||||
supported_actions=["set_regdomain", *self.config.extra_actions],
|
||||
)
|
||||
self._emit_result(result)
|
||||
return result
|
||||
|
||||
|
|
@ -268,10 +282,16 @@ class SystemExecutor(ExecutorBase):
|
|||
def _emit_result(self, result: CommandResult) -> None:
|
||||
if self.result_sink is None:
|
||||
return
|
||||
self.result_sink(system_command_result_to_envelope(result, source_name=self.config.source_name))
|
||||
self.result_sink(
|
||||
system_command_result_to_envelope(
|
||||
result, source_name=self.config.source_name
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def system_command_result_to_envelope(result: CommandResult, *, source_name: str) -> events_pb2.EventEnvelope:
|
||||
def system_command_result_to_envelope(
|
||||
result: CommandResult, *, source_name: str
|
||||
) -> events_pb2.EventEnvelope:
|
||||
details = struct_pb2.Struct()
|
||||
if result.details:
|
||||
json_format.ParseDict(dict(result.details), details)
|
||||
|
|
@ -301,7 +321,9 @@ def system_command_result_to_envelope(result: CommandResult, *, source_name: str
|
|||
correlation_id=result.correlation_id,
|
||||
causation_id=result.causation_event_id,
|
||||
),
|
||||
routing=events_pb2.RoutingDirectives(cache_enabled=True, outbox_enabled=True, priority=0),
|
||||
routing=events_pb2.RoutingDirectives(
|
||||
cache_enabled=True, outbox_enabled=True, priority=0
|
||||
),
|
||||
)
|
||||
envelope.attributes.labels["executor"] = "system"
|
||||
return envelope
|
||||
|
|
@ -316,7 +338,9 @@ def _system_command_suffix(command_type: str) -> str:
|
|||
|
||||
def _build_command_line(action: str, args: Mapping[str, Any]) -> str:
|
||||
if action == "set_regdomain":
|
||||
country = _stringify(args.get("country", args.get("country_code", args.get("regdomain", ""))))
|
||||
country = _stringify(
|
||||
args.get("country", args.get("country_code", args.get("regdomain", "")))
|
||||
)
|
||||
if not country:
|
||||
raise ValueError("country is required for system.set_regdomain")
|
||||
return f"iw reg set {country}"
|
||||
|
|
@ -347,7 +371,11 @@ def _response_indicates_success(response: str | None) -> bool:
|
|||
text = response.strip().upper()
|
||||
if not text:
|
||||
return True
|
||||
return not (text.startswith("FAIL") or text.startswith("ERROR") or text.startswith("UNKNOWN"))
|
||||
return not (
|
||||
text.startswith("FAIL")
|
||||
or text.startswith("ERROR")
|
||||
or text.startswith("UNKNOWN")
|
||||
)
|
||||
|
||||
|
||||
def _result_message(response: str | None, success: bool) -> str:
|
||||
|
|
@ -369,7 +397,9 @@ def _result_severity(state: CommandState) -> Severity:
|
|||
return Severity.DEBUG
|
||||
|
||||
|
||||
def _select_executor_section(data: Mapping[str, Any], executor_name: str | None) -> Mapping[str, Any]:
|
||||
def _select_executor_section(
|
||||
data: Mapping[str, Any], executor_name: str | None
|
||||
) -> Mapping[str, Any]:
|
||||
executors = data.get("executors")
|
||||
if executor_name is not None and isinstance(executors, Mapping):
|
||||
section = executors.get(executor_name, {})
|
||||
|
|
|
|||
|
|
@ -8,7 +8,12 @@ from typing import Any, Callable, Mapping, Protocol
|
|||
|
||||
from google.protobuf import json_format, struct_pb2
|
||||
|
||||
from ..commands.models import CommandRequest, CommandResult, CommandState, CommandTargetKind
|
||||
from ..commands.models import (
|
||||
CommandRequest,
|
||||
CommandResult,
|
||||
CommandState,
|
||||
CommandTargetKind,
|
||||
)
|
||||
from ..core.enums import Severity
|
||||
from ..proto_generated import common_pb2, events_pb2
|
||||
from ..proto_helpers import make_event_envelope
|
||||
|
|
@ -20,19 +25,15 @@ from .base import (
|
|||
ExecutorPipelineState,
|
||||
)
|
||||
|
||||
|
||||
WpaCtrlResultSink = Callable[[events_pb2.EventEnvelope], None]
|
||||
|
||||
|
||||
class WpaCtrlCommandBackend(Protocol):
|
||||
def connect(self, config: "WpaCtrlExecutorConfig") -> None:
|
||||
...
|
||||
def connect(self, config: "WpaCtrlExecutorConfig") -> None: ...
|
||||
|
||||
def request(self, command_line: str) -> str | None:
|
||||
...
|
||||
def request(self, command_line: str) -> str | None: ...
|
||||
|
||||
def close(self) -> None:
|
||||
...
|
||||
def close(self) -> None: ...
|
||||
|
||||
|
||||
@dataclass(slots=True, frozen=True)
|
||||
|
|
@ -44,7 +45,9 @@ class WpaCtrlExecutorConfig:
|
|||
source_name: str = ""
|
||||
|
||||
@classmethod
|
||||
def from_toml(cls, data: Mapping[str, Any], *, executor_name: str | None = None) -> "WpaCtrlExecutorConfig":
|
||||
def from_toml(
|
||||
cls, data: Mapping[str, Any], *, executor_name: str | None = None
|
||||
) -> "WpaCtrlExecutorConfig":
|
||||
section = _select_executor_section(data, executor_name)
|
||||
if not isinstance(section, Mapping):
|
||||
section = {}
|
||||
|
|
@ -56,7 +59,10 @@ class WpaCtrlExecutorConfig:
|
|||
name=str(executor_name or section.get("name", "wpa_ctrl")),
|
||||
enabled=bool(section.get("enabled", True)),
|
||||
interface=interface,
|
||||
ctrl_path=str(section.get("ctrl_path", section.get("socket", "/run/wpa_supplicant")) or "/run/wpa_supplicant"),
|
||||
ctrl_path=str(
|
||||
section.get("ctrl_path", section.get("socket", "/run/wpa_supplicant"))
|
||||
or "/run/wpa_supplicant"
|
||||
),
|
||||
source_name=source_name,
|
||||
)
|
||||
|
||||
|
|
@ -88,8 +94,14 @@ class FakeWpaCtrlBackend:
|
|||
raise RuntimeError("wpa ctrl backend is not connected")
|
||||
self.request_calls += 1
|
||||
response_queue = self._responses.get(command_line)
|
||||
response = self.default_response if response_queue is None or not response_queue else response_queue.pop(0)
|
||||
self.calls.append(WpaCtrlCommandCall(command_line=command_line, response=response))
|
||||
response = (
|
||||
self.default_response
|
||||
if response_queue is None or not response_queue
|
||||
else response_queue.pop(0)
|
||||
)
|
||||
self.calls.append(
|
||||
WpaCtrlCommandCall(command_line=command_line, response=response)
|
||||
)
|
||||
return response
|
||||
|
||||
def close(self) -> None:
|
||||
|
|
@ -115,7 +127,11 @@ class SystemWpaCtrlBackend:
|
|||
if candidate is None:
|
||||
raise RuntimeError("wpa ctrl bindings are not available")
|
||||
try:
|
||||
backend = candidate(config.ctrl_path, config.interface) if config.interface else candidate(config.ctrl_path)
|
||||
backend = (
|
||||
candidate(config.ctrl_path, config.interface)
|
||||
if config.interface
|
||||
else candidate(config.ctrl_path)
|
||||
)
|
||||
except TypeError:
|
||||
backend = candidate(config.ctrl_path)
|
||||
self._backend = backend
|
||||
|
|
@ -186,7 +202,11 @@ class WpaCtrlExecutor(ExecutorBase):
|
|||
return False
|
||||
if not request.command_type.startswith("wpa."):
|
||||
return False
|
||||
if self.config.interface and request.target_id and request.target_id != self.config.interface:
|
||||
if (
|
||||
self.config.interface
|
||||
and request.target_id
|
||||
and request.target_id != self.config.interface
|
||||
):
|
||||
return False
|
||||
return _wpa_command_suffix(request.command_type) in _SUPPORTED_COMMAND_SUFFIXES
|
||||
|
||||
|
|
@ -200,7 +220,10 @@ class WpaCtrlExecutor(ExecutorBase):
|
|||
success=False,
|
||||
message=f"unsupported command: {request.command_type}",
|
||||
executor_name=self.identity.name,
|
||||
).with_details(reason="unsupported", supported_commands=list(_SUPPORTED_COMMAND_SUFFIXES))
|
||||
).with_details(
|
||||
reason="unsupported",
|
||||
supported_commands=list(_SUPPORTED_COMMAND_SUFFIXES),
|
||||
)
|
||||
self._emit_result(result)
|
||||
return result
|
||||
|
||||
|
|
@ -215,7 +238,11 @@ class WpaCtrlExecutor(ExecutorBase):
|
|||
success=False,
|
||||
message=str(exc),
|
||||
executor_name=self.identity.name,
|
||||
).with_details(reason="connect_failed", interface=self.config.interface, source_name=self.config.source_name)
|
||||
).with_details(
|
||||
reason="connect_failed",
|
||||
interface=self.config.interface,
|
||||
source_name=self.config.source_name,
|
||||
)
|
||||
self._emit_result(result)
|
||||
return result
|
||||
|
||||
|
|
@ -288,7 +315,13 @@ class WpaCtrlExecutor(ExecutorBase):
|
|||
def _emit_result(self, result: CommandResult) -> None:
|
||||
if self.result_sink is None:
|
||||
return
|
||||
self.result_sink(command_result_to_envelope(result, source_name=self.config.source_name, interface=self.config.interface))
|
||||
self.result_sink(
|
||||
command_result_to_envelope(
|
||||
result,
|
||||
source_name=self.config.source_name,
|
||||
interface=self.config.interface,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def command_result_to_envelope(
|
||||
|
|
@ -327,7 +360,9 @@ def command_result_to_envelope(
|
|||
correlation_id=result.correlation_id,
|
||||
causation_id=result.causation_event_id,
|
||||
),
|
||||
routing=events_pb2.RoutingDirectives(cache_enabled=True, outbox_enabled=True, priority=0),
|
||||
routing=events_pb2.RoutingDirectives(
|
||||
cache_enabled=True, outbox_enabled=True, priority=0
|
||||
),
|
||||
)
|
||||
if interface:
|
||||
envelope.network.interface_name = interface
|
||||
|
|
@ -425,7 +460,11 @@ def _response_indicates_success(response: str | None) -> bool:
|
|||
text = response.strip().upper()
|
||||
if not text:
|
||||
return True
|
||||
return not (text.startswith("FAIL") or text.startswith("ERROR") or text.startswith("UNKNOWN"))
|
||||
return not (
|
||||
text.startswith("FAIL")
|
||||
or text.startswith("ERROR")
|
||||
or text.startswith("UNKNOWN")
|
||||
)
|
||||
|
||||
|
||||
def _result_message(response: str | None, success: bool) -> str:
|
||||
|
|
@ -447,7 +486,9 @@ def _result_severity(state: CommandState) -> Severity:
|
|||
return Severity.DEBUG
|
||||
|
||||
|
||||
def _select_executor_section(data: Mapping[str, Any], executor_name: str | None) -> Mapping[str, Any]:
|
||||
def _select_executor_section(
|
||||
data: Mapping[str, Any], executor_name: str | None
|
||||
) -> Mapping[str, Any]:
|
||||
executors = data.get("executors")
|
||||
if executor_name is not None and isinstance(executors, Mapping):
|
||||
section = executors.get(executor_name, {})
|
||||
|
|
|
|||
|
|
@ -3,10 +3,16 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from google.protobuf import descriptor_pb2 as _descriptor_pb2
|
||||
from google.protobuf import struct_pb2 as _struct_pb2 # noqa: F401 - load dependency into pool
|
||||
from google.protobuf import timestamp_pb2 as _timestamp_pb2 # noqa: F401 - load dependency into pool
|
||||
from google.protobuf import (
|
||||
struct_pb2 as _struct_pb2,
|
||||
) # noqa: F401 - load dependency into pool
|
||||
from google.protobuf import (
|
||||
timestamp_pb2 as _timestamp_pb2,
|
||||
) # noqa: F401 - load dependency into pool
|
||||
|
||||
from . import common_pb2 as _common_pb2 # noqa: F401 - ensure shared descriptors are loaded
|
||||
from . import (
|
||||
common_pb2 as _common_pb2,
|
||||
) # noqa: F401 - ensure shared descriptors are loaded
|
||||
from ._runtime import message_class as _message_class
|
||||
from ._runtime import register_file as _register_file
|
||||
|
||||
|
|
|
|||
|
|
@ -13,4 +13,4 @@ __all__ = [
|
|||
"SchedulerState",
|
||||
"SchedulerStats",
|
||||
"SchedulerTickResult",
|
||||
]
|
||||
]
|
||||
|
|
|
|||
|
|
@ -47,7 +47,9 @@ def _target_kind_from_value(value: Any) -> CommandTargetKind:
|
|||
if isinstance(value, CommandTargetKind):
|
||||
return value
|
||||
if isinstance(value, str):
|
||||
return _TARGET_KIND_BY_ALIAS.get(value.strip().lower(), CommandTargetKind.UNSPECIFIED)
|
||||
return _TARGET_KIND_BY_ALIAS.get(
|
||||
value.strip().lower(), CommandTargetKind.UNSPECIFIED
|
||||
)
|
||||
return CommandTargetKind.UNSPECIFIED
|
||||
|
||||
|
||||
|
|
@ -93,7 +95,9 @@ class SchedulerJob:
|
|||
name = _string_or_default(data.get("name"))
|
||||
if not name:
|
||||
raise ValueError("scheduler job name is required")
|
||||
kind = _job_kind_from_value(data.get("type", data.get("kind", SchedulerJobKind.INTERVAL.value)))
|
||||
kind = _job_kind_from_value(
|
||||
data.get("type", data.get("kind", SchedulerJobKind.INTERVAL.value))
|
||||
)
|
||||
enabled = bool(data.get("enabled", True))
|
||||
executor = _string_or_default(data.get("executor"))
|
||||
command = _string_or_default(data.get("command"))
|
||||
|
|
@ -101,18 +105,32 @@ class SchedulerJob:
|
|||
if not command_type:
|
||||
prefix = _command_prefix_from_executor(executor) if executor else ""
|
||||
command_type = f"{prefix}.{command}" if prefix and command else command
|
||||
target_kind = _target_kind_from_value(data.get("target_kind", data.get("target_kind_name")))
|
||||
target_kind = _target_kind_from_value(
|
||||
data.get("target_kind", data.get("target_kind_name"))
|
||||
)
|
||||
if target_kind == CommandTargetKind.UNSPECIFIED and executor:
|
||||
target_kind = _target_kind_from_executor(executor)
|
||||
target_id = _string_or_default(
|
||||
data.get("target_id", data.get("target", data.get("interface", data.get("name"))))
|
||||
data.get(
|
||||
"target_id", data.get("target", data.get("interface", data.get("name")))
|
||||
)
|
||||
)
|
||||
interval_ms = int(data.get("interval_ms", data.get("every_ms", 0)) or 0)
|
||||
has_initial_delay = "initial_delay_ms" in data or "delay_ms" in data
|
||||
initial_delay_ms = int(data.get("initial_delay_ms", data.get("delay_ms", 0)) or 0)
|
||||
if kind == SchedulerJobKind.INTERVAL and not has_initial_delay and interval_ms > 0:
|
||||
initial_delay_ms = int(
|
||||
data.get("initial_delay_ms", data.get("delay_ms", 0)) or 0
|
||||
)
|
||||
if (
|
||||
kind == SchedulerJobKind.INTERVAL
|
||||
and not has_initial_delay
|
||||
and interval_ms > 0
|
||||
):
|
||||
initial_delay_ms = interval_ms
|
||||
if kind == SchedulerJobKind.ONE_SHOT and not has_initial_delay and initial_delay_ms <= 0:
|
||||
if (
|
||||
kind == SchedulerJobKind.ONE_SHOT
|
||||
and not has_initial_delay
|
||||
and initial_delay_ms <= 0
|
||||
):
|
||||
initial_delay_ms = 0
|
||||
args = data.get("args", {})
|
||||
if not isinstance(args, Mapping):
|
||||
|
|
@ -156,7 +174,9 @@ class SchedulerJob:
|
|||
return False
|
||||
return self.next_run_mono_ns > 0 and now >= self.next_run_mono_ns
|
||||
|
||||
def build_request(self, *, command_id: str, now_mono_ns_value: int | None = None) -> CommandRequest:
|
||||
def build_request(
|
||||
self, *, command_id: str, now_mono_ns_value: int | None = None
|
||||
) -> CommandRequest:
|
||||
now = now_mono_ns() if now_mono_ns_value is None else now_mono_ns_value
|
||||
deadline_mono_ns = 0
|
||||
if self.deadline_offset_ms > 0:
|
||||
|
|
@ -196,7 +216,9 @@ class SchedulerJob:
|
|||
run_count=self.run_count + 1,
|
||||
next_run_mono_ns=now + _duration_to_ns(self.interval_ms),
|
||||
)
|
||||
return replace(self, last_run_mono_ns=now, run_count=self.run_count + 1, next_run_mono_ns=0)
|
||||
return replace(
|
||||
self, last_run_mono_ns=now, run_count=self.run_count + 1, next_run_mono_ns=0
|
||||
)
|
||||
|
||||
def enable(self) -> "SchedulerJob":
|
||||
return replace(self, enabled=True, completed=False)
|
||||
|
|
@ -251,4 +273,4 @@ def _target_kind_from_executor(executor: str) -> CommandTargetKind:
|
|||
return CommandTargetKind.NAVIGATION
|
||||
if key == "collector":
|
||||
return CommandTargetKind.COLLECTOR
|
||||
return CommandTargetKind.UNSPECIFIED
|
||||
return CommandTargetKind.UNSPECIFIED
|
||||
|
|
|
|||
|
|
@ -77,13 +77,17 @@ class SchedulerRegistry:
|
|||
self._jobs[name] = job.arm(now_mono_ns_value=now)
|
||||
self._last_tick_mono_ns = now
|
||||
|
||||
def due_jobs(self, *, now_mono_ns_value: int | None = None) -> tuple[SchedulerJob, ...]:
|
||||
def due_jobs(
|
||||
self, *, now_mono_ns_value: int | None = None
|
||||
) -> tuple[SchedulerJob, ...]:
|
||||
now = now_mono_ns() if now_mono_ns_value is None else now_mono_ns_value
|
||||
due = [job for job in self._jobs.values() if job.due(now)]
|
||||
due.sort(key=lambda job: (job.next_run_mono_ns, job.name))
|
||||
return tuple(due)
|
||||
|
||||
def mark_ran(self, name: str, *, now_mono_ns_value: int | None = None) -> SchedulerJob | None:
|
||||
def mark_ran(
|
||||
self, name: str, *, now_mono_ns_value: int | None = None
|
||||
) -> SchedulerJob | None:
|
||||
job = self._jobs.get(name)
|
||||
if job is None:
|
||||
return None
|
||||
|
|
@ -127,4 +131,4 @@ class SchedulerRegistry:
|
|||
|
||||
def _note_run_once(self, now_mono_ns_value: int) -> None:
|
||||
self._run_once_total += 1
|
||||
self._last_tick_mono_ns = now_mono_ns_value
|
||||
self._last_tick_mono_ns = now_mono_ns_value
|
||||
|
|
|
|||
|
|
@ -10,7 +10,6 @@ from ..core.clock import now_mono_ns
|
|||
from .models import SchedulerJob, SchedulerState, SchedulerStats
|
||||
from .registry import SchedulerRegistry
|
||||
|
||||
|
||||
CommandRequestFactory = Callable[[SchedulerJob, str, int], CommandRequest]
|
||||
|
||||
|
||||
|
|
@ -58,7 +57,9 @@ class Scheduler:
|
|||
stats=self.registry.stats(now_mono_ns_value=now),
|
||||
)
|
||||
|
||||
def run_once(self, name: str, *, now_mono_ns_value: int | None = None) -> CommandRequest:
|
||||
def run_once(
|
||||
self, name: str, *, now_mono_ns_value: int | None = None
|
||||
) -> CommandRequest:
|
||||
now = now_mono_ns() if now_mono_ns_value is None else now_mono_ns_value
|
||||
job = self.registry.get(name)
|
||||
if job is None:
|
||||
|
|
@ -85,5 +86,7 @@ class Scheduler:
|
|||
return f"sched-{job_name}-{self._sequence}"
|
||||
|
||||
|
||||
def _default_request_factory(job: SchedulerJob, command_id: str, now_mono_ns_value: int) -> CommandRequest:
|
||||
return job.build_request(command_id=command_id, now_mono_ns_value=now_mono_ns_value)
|
||||
def _default_request_factory(
|
||||
job: SchedulerJob, command_id: str, now_mono_ns_value: int
|
||||
) -> CommandRequest:
|
||||
return job.build_request(command_id=command_id, now_mono_ns_value=now_mono_ns_value)
|
||||
|
|
|
|||
|
|
@ -27,7 +27,13 @@ from .sender_types import (
|
|||
TransportType,
|
||||
WebhookTransportConfig,
|
||||
)
|
||||
from .transports import DropTransport, TransportBase, TransportIdentity, TransportResult, WebhookTransport
|
||||
from .transports import (
|
||||
DropTransport,
|
||||
TransportBase,
|
||||
TransportIdentity,
|
||||
TransportResult,
|
||||
WebhookTransport,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"BatchBuilder",
|
||||
|
|
|
|||
|
|
@ -74,7 +74,9 @@ class BatchBuilder:
|
|||
batch_id: str = "",
|
||||
created_at: datetime | None = None,
|
||||
) -> events_pb2.BatchEnvelope:
|
||||
return self.build(items, batch_id=batch_id, created_at=created_at, include_json=False).batch
|
||||
return self.build(
|
||||
items, batch_id=batch_id, created_at=created_at, include_json=False
|
||||
).batch
|
||||
|
||||
def build_json(
|
||||
self,
|
||||
|
|
@ -83,12 +85,16 @@ class BatchBuilder:
|
|||
batch_id: str = "",
|
||||
created_at: datetime | None = None,
|
||||
) -> str:
|
||||
result = self.build(items, batch_id=batch_id, created_at=created_at, include_json=True)
|
||||
result = self.build(
|
||||
items, batch_id=batch_id, created_at=created_at, include_json=True
|
||||
)
|
||||
return result.json or ""
|
||||
|
||||
def _record_to_envelope(self, record: EventRecord) -> events_pb2.EventEnvelope:
|
||||
payload = self._payload_from_record(record)
|
||||
return event_record_to_envelope(record, interner=self.cache.interner, payload=payload)
|
||||
return event_record_to_envelope(
|
||||
record, interner=self.cache.interner, payload=payload
|
||||
)
|
||||
|
||||
def _payload_from_record(self, record: EventRecord) -> events_pb2.Message | None:
|
||||
if not record.payload_ref:
|
||||
|
|
@ -112,4 +118,4 @@ class BatchBuilder:
|
|||
else:
|
||||
return None
|
||||
message.ParseFromString(payload)
|
||||
return message
|
||||
return message
|
||||
|
|
|
|||
|
|
@ -184,7 +184,14 @@ class SenderLoopBase(ABC):
|
|||
result = self.retry_policy.schedule(source, now_mono_ns=now_mono_ns)
|
||||
if result.scheduled and result.entry is not None:
|
||||
self._retry_pending.append(result.entry)
|
||||
self._retry_pending.sort(key=lambda entry: (entry.next_attempt_mono_ns, entry.expires_mono_ns, entry.priority, entry.seq_no))
|
||||
self._retry_pending.sort(
|
||||
key=lambda entry: (
|
||||
entry.next_attempt_mono_ns,
|
||||
entry.expires_mono_ns,
|
||||
entry.priority,
|
||||
entry.seq_no,
|
||||
)
|
||||
)
|
||||
self._retry_scheduled_total += 1
|
||||
continue
|
||||
self._retry_expired_total += 1
|
||||
|
|
@ -246,7 +253,9 @@ class SenderLoopBase(ABC):
|
|||
items = self.outbox.items()
|
||||
if not items:
|
||||
return self._skip_result(self._idle_reason())
|
||||
return self._dispatch(items, batch_id=batch_id, created_at=created_at, now_mono_ns=now)
|
||||
return self._dispatch(
|
||||
items, batch_id=batch_id, created_at=created_at, now_mono_ns=now
|
||||
)
|
||||
|
||||
|
||||
class ImmediateSenderLoop(SenderLoopBase):
|
||||
|
|
@ -263,7 +272,9 @@ class ImmediateSenderLoop(SenderLoopBase):
|
|||
items = self.outbox.items()
|
||||
if not items:
|
||||
return self._skip_result(self._idle_reason())
|
||||
return self._dispatch(items, batch_id=batch_id, created_at=created_at, now_mono_ns=now)
|
||||
return self._dispatch(
|
||||
items, batch_id=batch_id, created_at=created_at, now_mono_ns=now
|
||||
)
|
||||
|
||||
|
||||
class NoneSenderLoop(ImmediateSenderLoop):
|
||||
|
|
@ -372,8 +383,11 @@ def build_sender_loop(
|
|||
if config.sender_type == SenderType.NONE:
|
||||
return NoneSenderLoop(config, cache=cache, outbox=outbox, transport=transport)
|
||||
if config.sender_type == SenderType.STRICT_PRIORITY:
|
||||
return StrictPrioritySenderLoop(config, cache=cache, outbox=outbox, transport=transport)
|
||||
return StrictPrioritySenderLoop(
|
||||
config, cache=cache, outbox=outbox, transport=transport
|
||||
)
|
||||
if config.sender_type == SenderType.BUFFERED:
|
||||
return BufferedSenderLoop(config, cache=cache, outbox=outbox, transport=transport)
|
||||
return BufferedSenderLoop(
|
||||
config, cache=cache, outbox=outbox, transport=transport
|
||||
)
|
||||
raise ValueError(f"unsupported sender type: {config.sender_type.value}")
|
||||
|
||||
|
|
|
|||
|
|
@ -38,8 +38,16 @@ class OutboxItem:
|
|||
return now >= self.deadline_mono_ns
|
||||
|
||||
def sort_key(self) -> tuple[int, int, int, int, int]:
|
||||
deadline_rank = self.deadline_mono_ns if self.deadline_mono_ns > 0 else 2**63 - 1
|
||||
return (-int(self.priority), deadline_rank, int(self.enqueue_mono_ns), int(self.seq_no), int(self.attempt_no))
|
||||
deadline_rank = (
|
||||
self.deadline_mono_ns if self.deadline_mono_ns > 0 else 2**63 - 1
|
||||
)
|
||||
return (
|
||||
-int(self.priority),
|
||||
deadline_rank,
|
||||
int(self.enqueue_mono_ns),
|
||||
int(self.seq_no),
|
||||
int(self.attempt_no),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(slots=True, frozen=True)
|
||||
|
|
@ -72,7 +80,12 @@ class OutboxEnqueueResult:
|
|||
|
||||
|
||||
class OutboxQueue:
|
||||
def __init__(self, capacity: int, *, overflow_policy: OutboxOverflowPolicy = OutboxOverflowPolicy.DROP_LOWEST_PRIORITY) -> None:
|
||||
def __init__(
|
||||
self,
|
||||
capacity: int,
|
||||
*,
|
||||
overflow_policy: OutboxOverflowPolicy = OutboxOverflowPolicy.DROP_LOWEST_PRIORITY,
|
||||
) -> None:
|
||||
if capacity <= 0:
|
||||
raise ValueError("capacity must be positive")
|
||||
self.capacity = int(capacity)
|
||||
|
|
@ -114,14 +127,19 @@ class OutboxQueue:
|
|||
return OutboxEnqueueResult(True, item, None)
|
||||
|
||||
self._overflow_total += 1
|
||||
if self.overflow_policy in {OutboxOverflowPolicy.REJECT_NEW, OutboxOverflowPolicy.DROP_NEW}:
|
||||
if self.overflow_policy in {
|
||||
OutboxOverflowPolicy.REJECT_NEW,
|
||||
OutboxOverflowPolicy.DROP_NEW,
|
||||
}:
|
||||
self._rejected_total += 1
|
||||
return OutboxEnqueueResult(False, None, "outbox full", ())
|
||||
|
||||
worst = self._items[-1]
|
||||
if item.sort_key() >= worst.sort_key():
|
||||
self._rejected_total += 1
|
||||
return OutboxEnqueueResult(False, None, "lower priority than queued items", ())
|
||||
return OutboxEnqueueResult(
|
||||
False, None, "lower priority than queued items", ()
|
||||
)
|
||||
|
||||
self._items.pop()
|
||||
self._evicted_total += 1
|
||||
|
|
@ -140,10 +158,14 @@ class OutboxQueue:
|
|||
return None
|
||||
item = self._items.pop(0)
|
||||
self._dequeued_total += 1
|
||||
self._last_dequeued_mono_ns = monotonic_ns() if now_mono_ns_value is None else now_mono_ns_value
|
||||
self._last_dequeued_mono_ns = (
|
||||
monotonic_ns() if now_mono_ns_value is None else now_mono_ns_value
|
||||
)
|
||||
return item
|
||||
|
||||
def drain(self, limit: int | None = None, *, now_mono_ns_value: int | None = None) -> list[OutboxItem]:
|
||||
def drain(
|
||||
self, limit: int | None = None, *, now_mono_ns_value: int | None = None
|
||||
) -> list[OutboxItem]:
|
||||
drained: list[OutboxItem] = []
|
||||
while self._items and (limit is None or len(drained) < limit):
|
||||
item = self.pop(now_mono_ns_value=now_mono_ns_value)
|
||||
|
|
@ -213,4 +235,4 @@ class OutboxQueue:
|
|||
kept.append(item)
|
||||
if removed:
|
||||
self._items = kept
|
||||
self._expired_total += removed
|
||||
self._expired_total += removed
|
||||
|
|
|
|||
|
|
@ -65,8 +65,14 @@ class SenderRetryPolicy:
|
|||
if retry_delay_ms <= 0:
|
||||
return RetryScheduleResult(False, None, "retry disabled")
|
||||
|
||||
first_failed = int(first_failed_mono_ns if first_failed_mono_ns is not None else now_mono_ns)
|
||||
expires_mono_ns = int(item.deadline_mono_ns) if item.deadline_mono_ns > 0 else first_failed + self.max_delay_ms * 1_000_000
|
||||
first_failed = int(
|
||||
first_failed_mono_ns if first_failed_mono_ns is not None else now_mono_ns
|
||||
)
|
||||
expires_mono_ns = (
|
||||
int(item.deadline_mono_ns)
|
||||
if item.deadline_mono_ns > 0
|
||||
else first_failed + self.max_delay_ms * 1_000_000
|
||||
)
|
||||
next_attempt_mono_ns = first_failed + retry_delay_ms * 1_000_000
|
||||
if expires_mono_ns > 0 and next_attempt_mono_ns >= expires_mono_ns:
|
||||
return RetryScheduleResult(False, None, "retry expired")
|
||||
|
|
|
|||
|
|
@ -56,10 +56,36 @@ class SenderBufferedConfig:
|
|||
if not isinstance(buffered, Mapping):
|
||||
buffered = {}
|
||||
return cls(
|
||||
batch_max_events=max(1, int(buffered.get("batch_max_events", section.get("batch_max_events", 200)) or 200)),
|
||||
batch_flush_ms=max(0, int(buffered.get("batch_flush_ms", section.get("batch_flush_ms", 1000)) or 1000)),
|
||||
retry_base_ms=max(0, int(buffered.get("retry_base_ms", section.get("retry_base_ms", 500)) or 500)),
|
||||
retry_max_ms=max(0, int(buffered.get("retry_max_ms", section.get("retry_max_ms", 10_000)) or 10_000)),
|
||||
batch_max_events=max(
|
||||
1,
|
||||
int(
|
||||
buffered.get(
|
||||
"batch_max_events", section.get("batch_max_events", 200)
|
||||
)
|
||||
or 200
|
||||
),
|
||||
),
|
||||
batch_flush_ms=max(
|
||||
0,
|
||||
int(
|
||||
buffered.get("batch_flush_ms", section.get("batch_flush_ms", 1000))
|
||||
or 1000
|
||||
),
|
||||
),
|
||||
retry_base_ms=max(
|
||||
0,
|
||||
int(
|
||||
buffered.get("retry_base_ms", section.get("retry_base_ms", 500))
|
||||
or 500
|
||||
),
|
||||
),
|
||||
retry_max_ms=max(
|
||||
0,
|
||||
int(
|
||||
buffered.get("retry_max_ms", section.get("retry_max_ms", 10_000))
|
||||
or 10_000
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
|
|
@ -80,13 +106,24 @@ class WebhookTransportConfig:
|
|||
webhook = transport.get("webhook", transport)
|
||||
if not isinstance(webhook, Mapping):
|
||||
webhook = {}
|
||||
headers = _normalize_headers(webhook.get("headers", transport.get("headers", ())))
|
||||
headers = _normalize_headers(
|
||||
webhook.get("headers", transport.get("headers", ()))
|
||||
)
|
||||
return cls(
|
||||
url=str(webhook.get("url", transport.get("url", "")) or ""),
|
||||
timeout_ms=max(0, int(webhook.get("timeout_ms", transport.get("timeout_ms", 3000)) or 3000)),
|
||||
format=str(webhook.get("format", transport.get("format", "json")) or "json"),
|
||||
timeout_ms=max(
|
||||
0,
|
||||
int(
|
||||
webhook.get("timeout_ms", transport.get("timeout_ms", 3000)) or 3000
|
||||
),
|
||||
),
|
||||
format=str(
|
||||
webhook.get("format", transport.get("format", "json")) or "json"
|
||||
),
|
||||
headers=headers,
|
||||
auth_mode=str(webhook.get("auth_mode", transport.get("auth_mode", "none")) or "none"),
|
||||
auth_mode=str(
|
||||
webhook.get("auth_mode", transport.get("auth_mode", "none")) or "none"
|
||||
),
|
||||
token=str(webhook.get("token", transport.get("token", "")) or ""),
|
||||
)
|
||||
|
||||
|
|
@ -105,7 +142,9 @@ class SenderComposition:
|
|||
def validate(self) -> tuple[str, ...]:
|
||||
if self.is_supported():
|
||||
return ()
|
||||
return (f"unsupported sender/transport combination: {self.sender_type.value}+{self.transport_type.value}",)
|
||||
return (
|
||||
f"unsupported sender/transport combination: {self.sender_type.value}+{self.transport_type.value}",
|
||||
)
|
||||
|
||||
def recommended_transport(self) -> TransportType:
|
||||
if self.sender_type == SenderType.NONE:
|
||||
|
|
@ -135,8 +174,12 @@ class SenderRuntimeConfig:
|
|||
if not isinstance(transport_section, Mapping):
|
||||
transport_section = {}
|
||||
return cls(
|
||||
sender_type=SenderType.from_value(sender_section.get("type", SenderType.NONE.value)),
|
||||
transport_type=TransportType.from_value(transport_section.get("type", TransportType.DROP.value)),
|
||||
sender_type=SenderType.from_value(
|
||||
sender_section.get("type", SenderType.NONE.value)
|
||||
),
|
||||
transport_type=TransportType.from_value(
|
||||
transport_section.get("type", TransportType.DROP.value)
|
||||
),
|
||||
buffered=SenderBufferedConfig.from_toml(data),
|
||||
webhook=WebhookTransportConfig.from_toml(data),
|
||||
)
|
||||
|
|
@ -148,10 +191,22 @@ class SenderRuntimeConfig:
|
|||
return self.composition().validate()
|
||||
|
||||
def with_sender_type(self, sender_type: SenderType) -> "SenderRuntimeConfig":
|
||||
return SenderRuntimeConfig(sender_type=sender_type, transport_type=self.transport_type, buffered=self.buffered, webhook=self.webhook)
|
||||
return SenderRuntimeConfig(
|
||||
sender_type=sender_type,
|
||||
transport_type=self.transport_type,
|
||||
buffered=self.buffered,
|
||||
webhook=self.webhook,
|
||||
)
|
||||
|
||||
def with_transport_type(self, transport_type: TransportType) -> "SenderRuntimeConfig":
|
||||
return SenderRuntimeConfig(sender_type=self.sender_type, transport_type=transport_type, buffered=self.buffered, webhook=self.webhook)
|
||||
def with_transport_type(
|
||||
self, transport_type: TransportType
|
||||
) -> "SenderRuntimeConfig":
|
||||
return SenderRuntimeConfig(
|
||||
sender_type=self.sender_type,
|
||||
transport_type=transport_type,
|
||||
buffered=self.buffered,
|
||||
webhook=self.webhook,
|
||||
)
|
||||
|
||||
|
||||
_ALLOWED_COMBINATIONS: set[tuple[SenderType, TransportType]] = {
|
||||
|
|
@ -176,4 +231,4 @@ def _normalize_headers(value: Any) -> tuple[tuple[str, str], ...]:
|
|||
if isinstance(item, Sequence) and len(item) >= 2:
|
||||
headers.append((str(item[0]), str(item[1])))
|
||||
return tuple(headers)
|
||||
return ()
|
||||
return ()
|
||||
|
|
|
|||
|
|
@ -12,4 +12,4 @@ __all__ = [
|
|||
"WebhookOpener",
|
||||
"WebhookRequestParts",
|
||||
"WebhookTransport",
|
||||
]
|
||||
]
|
||||
|
|
|
|||
|
|
@ -53,4 +53,4 @@ class TransportBase(ABC):
|
|||
raise NotImplementedError
|
||||
|
||||
def supports(self, payload: Any) -> bool:
|
||||
return True
|
||||
return True
|
||||
|
|
|
|||
|
|
@ -10,7 +10,11 @@ from .base import TransportBase, TransportIdentity, TransportResult
|
|||
|
||||
class DropTransport(TransportBase):
|
||||
def __init__(self, *, name: str = "drop", enabled: bool = True) -> None:
|
||||
super().__init__(TransportIdentity(name=name, transport_type=TransportType.DROP, enabled=enabled))
|
||||
super().__init__(
|
||||
TransportIdentity(
|
||||
name=name, transport_type=TransportType.DROP, enabled=enabled
|
||||
)
|
||||
)
|
||||
|
||||
def send(
|
||||
self,
|
||||
|
|
@ -19,4 +23,11 @@ class DropTransport(TransportBase):
|
|||
content_type: str | None = None,
|
||||
headers: Mapping[str, str] | None = None,
|
||||
) -> TransportResult:
|
||||
return TransportResult(ok=True, status_code=204, reason="dropped", bytes_sent=0, url="", content_type=content_type or "")
|
||||
return TransportResult(
|
||||
ok=True,
|
||||
status_code=204,
|
||||
reason="dropped",
|
||||
bytes_sent=0,
|
||||
url="",
|
||||
content_type=content_type or "",
|
||||
)
|
||||
|
|
|
|||
|
|
@ -11,7 +11,6 @@ from urllib.request import Request, urlopen
|
|||
from ..sender_types import WebhookTransportConfig, TransportType
|
||||
from .base import TransportBase, TransportIdentity, TransportResult
|
||||
|
||||
|
||||
WebhookOpener = Callable[[Request, float | None], Any]
|
||||
|
||||
|
||||
|
|
@ -30,7 +29,11 @@ class WebhookTransport(TransportBase):
|
|||
opener: WebhookOpener | None = None,
|
||||
enabled: bool = True,
|
||||
) -> None:
|
||||
super().__init__(TransportIdentity(name=name, transport_type=TransportType.WEBHOOK, enabled=enabled))
|
||||
super().__init__(
|
||||
TransportIdentity(
|
||||
name=name, transport_type=TransportType.WEBHOOK, enabled=enabled
|
||||
)
|
||||
)
|
||||
self.config = WebhookTransportConfig() if config is None else config
|
||||
self._opener = opener or _default_opener
|
||||
|
||||
|
|
@ -42,17 +45,27 @@ class WebhookTransport(TransportBase):
|
|||
headers: Mapping[str, str] | None = None,
|
||||
) -> TransportResult:
|
||||
if not self.config.url:
|
||||
return TransportResult(ok=False, status_code=0, reason="webhook url is required", url="")
|
||||
parts = _serialize_payload(payload, content_type=content_type, preferred_format=self.config.format)
|
||||
return TransportResult(
|
||||
ok=False, status_code=0, reason="webhook url is required", url=""
|
||||
)
|
||||
parts = _serialize_payload(
|
||||
payload, content_type=content_type, preferred_format=self.config.format
|
||||
)
|
||||
request_headers = self.config.header_map()
|
||||
if headers:
|
||||
request_headers.update({str(key): str(value) for key, value in headers.items()})
|
||||
request_headers.update(
|
||||
{str(key): str(value) for key, value in headers.items()}
|
||||
)
|
||||
if self.config.auth_mode.lower() == "bearer" and self.config.token:
|
||||
request_headers.setdefault("Authorization", f"Bearer {self.config.token}")
|
||||
request_headers.setdefault("Content-Type", parts.content_type)
|
||||
request = Request(self.config.url, data=parts.body, headers=request_headers, method="POST")
|
||||
request = Request(
|
||||
self.config.url, data=parts.body, headers=request_headers, method="POST"
|
||||
)
|
||||
try:
|
||||
timeout = self.config.timeout_ms / 1000.0 if self.config.timeout_ms > 0 else None
|
||||
timeout = (
|
||||
self.config.timeout_ms / 1000.0 if self.config.timeout_ms > 0 else None
|
||||
)
|
||||
response = self._opener(request, timeout)
|
||||
status_code = getattr(response, "status", None)
|
||||
if status_code is None and hasattr(response, "getcode"):
|
||||
|
|
@ -70,7 +83,13 @@ class WebhookTransport(TransportBase):
|
|||
url=self.config.url,
|
||||
content_type=parts.content_type,
|
||||
)
|
||||
except (URLError, OSError, ValueError, TimeoutError, json.JSONDecodeError) as exc:
|
||||
except (
|
||||
URLError,
|
||||
OSError,
|
||||
ValueError,
|
||||
TimeoutError,
|
||||
json.JSONDecodeError,
|
||||
) as exc:
|
||||
return TransportResult(
|
||||
ok=False,
|
||||
status_code=0,
|
||||
|
|
@ -81,20 +100,37 @@ class WebhookTransport(TransportBase):
|
|||
)
|
||||
|
||||
|
||||
def _serialize_payload(payload: Any, *, content_type: str | None, preferred_format: str) -> WebhookRequestParts:
|
||||
def _serialize_payload(
|
||||
payload: Any, *, content_type: str | None, preferred_format: str
|
||||
) -> WebhookRequestParts:
|
||||
if isinstance(payload, (bytes, bytearray, memoryview)):
|
||||
return WebhookRequestParts(body=bytes(payload), content_type=content_type or "application/octet-stream")
|
||||
return WebhookRequestParts(
|
||||
body=bytes(payload), content_type=content_type or "application/octet-stream"
|
||||
)
|
||||
if isinstance(payload, str):
|
||||
return WebhookRequestParts(body=payload.encode("utf-8"), content_type=content_type or "text/plain; charset=utf-8")
|
||||
return WebhookRequestParts(
|
||||
body=payload.encode("utf-8"),
|
||||
content_type=content_type or "text/plain; charset=utf-8",
|
||||
)
|
||||
if isinstance(payload, Mapping):
|
||||
body = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
||||
return WebhookRequestParts(body=body, content_type=content_type or "application/json")
|
||||
body = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode(
|
||||
"utf-8"
|
||||
)
|
||||
return WebhookRequestParts(
|
||||
body=body, content_type=content_type or "application/json"
|
||||
)
|
||||
if preferred_format.lower() == "json":
|
||||
body = json.dumps(payload, sort_keys=True, default=str, separators=(",", ":")).encode("utf-8")
|
||||
return WebhookRequestParts(body=body, content_type=content_type or "application/json")
|
||||
body = json.dumps(
|
||||
payload, sort_keys=True, default=str, separators=(",", ":")
|
||||
).encode("utf-8")
|
||||
return WebhookRequestParts(
|
||||
body=body, content_type=content_type or "application/json"
|
||||
)
|
||||
body = str(payload).encode("utf-8")
|
||||
return WebhookRequestParts(body=body, content_type=content_type or "text/plain; charset=utf-8")
|
||||
return WebhookRequestParts(
|
||||
body=body, content_type=content_type or "text/plain; charset=utf-8"
|
||||
)
|
||||
|
||||
|
||||
def _default_opener(request: Request, timeout: float | None) -> Any:
|
||||
return urlopen(request, timeout=timeout)
|
||||
return urlopen(request, timeout=timeout)
|
||||
|
|
|
|||
|
|
@ -28,4 +28,6 @@ def to_jsonable(value: Any) -> Any:
|
|||
|
||||
|
||||
def dumps_json(value: Any, *, indent: int = 2) -> str:
|
||||
return json.dumps(to_jsonable(value), ensure_ascii=False, indent=indent, sort_keys=True)
|
||||
return json.dumps(
|
||||
to_jsonable(value), ensure_ascii=False, indent=indent, sort_keys=True
|
||||
)
|
||||
|
|
|
|||
|
|
@ -11,7 +11,9 @@ from agent.sender import BatchBuilder, OutboxItem
|
|||
|
||||
|
||||
def _build_cached_record():
|
||||
cache = build_default_cache(ring_capacity=8, payload_capacity_items=8, payload_capacity_bytes=4096)
|
||||
cache = build_default_cache(
|
||||
ring_capacity=8, payload_capacity_items=8, payload_capacity_bytes=4096
|
||||
)
|
||||
payload = events_pb2.RawWpaPayload(
|
||||
interface_name="wlp3s0",
|
||||
event_line="CTRL-EVENT-CONNECTED",
|
||||
|
|
@ -27,7 +29,9 @@ def _build_cached_record():
|
|||
event_kind=common_pb2.EVENT_KIND_RAW,
|
||||
source_kind=common_pb2.SOURCE_KIND_WPA_CTRL,
|
||||
severity=common_pb2.SEVERITY_INFO,
|
||||
routing=events_pb2.RoutingDirectives(cache_enabled=True, outbox_enabled=True, priority=9),
|
||||
routing=events_pb2.RoutingDirectives(
|
||||
cache_enabled=True, outbox_enabled=True, priority=9
|
||||
),
|
||||
normalized_ssid="corp",
|
||||
normalized_bssid="aa:bb:cc:dd:ee:ff",
|
||||
normalized_freq_mhz=2412,
|
||||
|
|
@ -36,7 +40,9 @@ def _build_cached_record():
|
|||
normalized_reason="connected",
|
||||
payload=payload,
|
||||
)
|
||||
record = event_envelope_to_record(envelope, interner=cache.interner, observed_mono_ns=100, ingested_mono_ns=200)
|
||||
record = event_envelope_to_record(
|
||||
envelope, interner=cache.interner, observed_mono_ns=100, ingested_mono_ns=200
|
||||
)
|
||||
stored = cache.append(record, payload=serialize_message(payload))
|
||||
outbox_item = OutboxItem(
|
||||
seq_no=int(stored.seq_no),
|
||||
|
|
@ -53,7 +59,12 @@ def test_batch_builder_materializes_batch_envelope_from_outbox_refs() -> None:
|
|||
cache, stored, outbox_item = _build_cached_record()
|
||||
builder = BatchBuilder(cache)
|
||||
|
||||
result = builder.build([outbox_item], batch_id="batch-1", created_at=datetime(2026, 4, 15, 12, 5, tzinfo=timezone.utc), include_json=True)
|
||||
result = builder.build(
|
||||
[outbox_item],
|
||||
batch_id="batch-1",
|
||||
created_at=datetime(2026, 4, 15, 12, 5, tzinfo=timezone.utc),
|
||||
include_json=True,
|
||||
)
|
||||
|
||||
assert result.count == 1
|
||||
assert result.batch.batch_id == "batch-1"
|
||||
|
|
@ -79,8 +90,10 @@ def test_batch_builder_supports_json_projection_and_missing_refs() -> None:
|
|||
assert json.loads(json_payload)["batchId"] == "batch-2"
|
||||
assert len(json.loads(json_payload)["events"]) == 1
|
||||
|
||||
result = builder.build([outbox_item, missing], batch_id="batch-3", include_json=False)
|
||||
result = builder.build(
|
||||
[outbox_item, missing], batch_id="batch-3", include_json=False
|
||||
)
|
||||
assert result.batch.batch_id == "batch-3"
|
||||
assert result.count == 1
|
||||
assert result.missing_seq_nos == (999,)
|
||||
assert result.event_ids == (int(stored.event_id),)
|
||||
assert result.event_ids == (int(stored.event_id),)
|
||||
|
|
|
|||
|
|
@ -29,7 +29,9 @@ def _record(
|
|||
source_kind=source_kind,
|
||||
event_kind=EventKind.RAW,
|
||||
severity=severity,
|
||||
event_type_id=EventTypeId(int(interner.intern(event_type)) if event_type else 0),
|
||||
event_type_id=EventTypeId(
|
||||
int(interner.intern(event_type)) if event_type else 0
|
||||
),
|
||||
source_instance_id=int(interner.intern(collector)),
|
||||
interface_id=InterfaceId(int(interner.intern(iface)) if iface else 0),
|
||||
normalized_ssid_id=int(interner.intern(ssid)) if ssid else 0,
|
||||
|
|
@ -178,7 +180,9 @@ def test_cache_api_find_filters_and_lazily_prunes_stale_entries() -> None:
|
|||
assert api.indexes.stats().by_source_kind_entries == 2
|
||||
assert api.indexes.stats().by_ssid_entries == 2
|
||||
|
||||
stale_lookup = list(api.indexes.iter_seq_nos_by_event_type(stale_event_type_id, is_live=api.get))
|
||||
stale_lookup = list(
|
||||
api.indexes.iter_seq_nos_by_event_type(stale_event_type_id, is_live=api.get)
|
||||
)
|
||||
assert stale_lookup == []
|
||||
assert api.indexes.stats().by_event_type_entries == 2
|
||||
|
||||
|
|
|
|||
|
|
@ -51,7 +51,9 @@ def _record(
|
|||
|
||||
|
||||
def _application_with_cache() -> AgentApplication:
|
||||
base = load_application(config_path=FIXTURES / "cli-basic.toml", load_env_file=False)
|
||||
base = load_application(
|
||||
config_path=FIXTURES / "cli-basic.toml", load_env_file=False
|
||||
)
|
||||
cache = build_default_cache(
|
||||
ring_capacity=4,
|
||||
payload_capacity_items=4,
|
||||
|
|
|
|||
|
|
@ -75,15 +75,28 @@ def test_collectors_list_reports_configured_collectors() -> None:
|
|||
assert code == 0
|
||||
assert stderr == ""
|
||||
assert "collectors" in stdout
|
||||
assert "journal enabled=True source_kind=journal runtime=- connection=- pipeline=-" in stdout
|
||||
assert "wpa_ctrl enabled=False source_kind=wpa_ctrl runtime=- connection=- pipeline=-" in stdout
|
||||
assert (
|
||||
"journal enabled=True source_kind=journal runtime=- connection=- pipeline=-"
|
||||
in stdout
|
||||
)
|
||||
assert (
|
||||
"wpa_ctrl enabled=False source_kind=wpa_ctrl runtime=- connection=- pipeline=-"
|
||||
in stdout
|
||||
)
|
||||
|
||||
|
||||
def test_collectors_show_reports_config_details() -> None:
|
||||
config_file = FIXTURES / "cli-collector-show.toml"
|
||||
|
||||
code, stdout, stderr = _run_cli(
|
||||
["--config", str(config_file), "--no-env-file", "collectors", "show", "wpa_ctrl"]
|
||||
[
|
||||
"--config",
|
||||
str(config_file),
|
||||
"--no-env-file",
|
||||
"collectors",
|
||||
"show",
|
||||
"wpa_ctrl",
|
||||
]
|
||||
)
|
||||
|
||||
assert code == 0
|
||||
|
|
|
|||
|
|
@ -47,7 +47,10 @@ def test_collector_base_exposes_common_state_models() -> None:
|
|||
assert collector.identity.name == "journal"
|
||||
assert collector.identity.source_kind == "journal"
|
||||
assert collector.state().health.lifecycle_state == CollectorLifecycleState.INIT
|
||||
assert collector.state().health.connection_state == CollectorConnectionState.DISCONNECTED
|
||||
assert (
|
||||
collector.state().health.connection_state
|
||||
== CollectorConnectionState.DISCONNECTED
|
||||
)
|
||||
assert collector.state().health.pipeline_state == CollectorPipelineState.IDLE
|
||||
assert collector.state().health.healthy is False
|
||||
assert collector.stats().start_total == 0
|
||||
|
|
|
|||
|
|
@ -1,13 +1,17 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from agent.collectors import CollectorPipeline, CollectorPipelineConfig, CollectorPipelineContext, CollectorRawEvent
|
||||
from agent.collectors import (
|
||||
CollectorPipeline,
|
||||
CollectorPipelineConfig,
|
||||
CollectorPipelineContext,
|
||||
CollectorRawEvent,
|
||||
)
|
||||
from agent.core import EventKind, PayloadKind, Severity, SourceKind
|
||||
from agent.utils.toml_loader import loads_toml
|
||||
|
||||
|
||||
def test_collector_pipeline_config_parses_toml_rules() -> None:
|
||||
config = loads_toml(
|
||||
"""
|
||||
config = loads_toml("""
|
||||
[collectors.journal]
|
||||
enabled = true
|
||||
|
||||
|
|
@ -28,10 +32,11 @@ def test_collector_pipeline_config_parses_toml_rules() -> None:
|
|||
add.workflow_tags = ["wifi", "roaming"]
|
||||
add.labels.site = "warehouse-a"
|
||||
add.routing.outbox_enabled = true
|
||||
"""
|
||||
)
|
||||
""")
|
||||
|
||||
pipeline_config = CollectorPipelineConfig.from_toml(config, collector_name="journal")
|
||||
pipeline_config = CollectorPipelineConfig.from_toml(
|
||||
config, collector_name="journal"
|
||||
)
|
||||
|
||||
assert pipeline_config.enabled is True
|
||||
assert len(pipeline_config.prefilter_rules) == 1
|
||||
|
|
@ -40,8 +45,7 @@ def test_collector_pipeline_config_parses_toml_rules() -> None:
|
|||
|
||||
|
||||
def test_collector_pipeline_processes_and_marks_event() -> None:
|
||||
config = loads_toml(
|
||||
"""
|
||||
config = loads_toml("""
|
||||
[collectors.wpa_ctrl]
|
||||
enabled = true
|
||||
|
||||
|
|
@ -63,8 +67,7 @@ def test_collector_pipeline_processes_and_marks_event() -> None:
|
|||
add.labels.site = "warehouse-a"
|
||||
add.routing.outbox_enabled = true
|
||||
add.routing.priority = 9
|
||||
"""
|
||||
)
|
||||
""")
|
||||
pipeline = CollectorPipeline.from_toml(config, collector_name="wpa_ctrl")
|
||||
raw = CollectorRawEvent(
|
||||
collector_name="wpa",
|
||||
|
|
@ -78,7 +81,10 @@ def test_collector_pipeline_processes_and_marks_event() -> None:
|
|||
event_kind=EventKind.RAW,
|
||||
payload_kind=PayloadKind.WPA_CTRL,
|
||||
observed_wall_ns=1_700_000_000_000_000_000,
|
||||
fields={"_SYSTEMD_UNIT": "wpa_supplicant.service", "event_name": "CTRL-EVENT-CONNECTED"},
|
||||
fields={
|
||||
"_SYSTEMD_UNIT": "wpa_supplicant.service",
|
||||
"event_name": "CTRL-EVENT-CONNECTED",
|
||||
},
|
||||
payload={"event_line": "CTRL-EVENT-CONNECTED"},
|
||||
normalized_ssid="corp",
|
||||
normalized_bssid="aa:bb:cc:dd:ee:ff",
|
||||
|
|
@ -113,15 +119,16 @@ def test_collector_pipeline_processes_and_marks_event() -> None:
|
|||
assert outcome.envelope.routing.priority == 9
|
||||
assert outcome.prefilter is not None and outcome.prefilter.accepted is True
|
||||
assert outcome.validation is not None and outcome.validation.valid is True
|
||||
assert outcome.marking is not None and outcome.marking.applied_rules == ("event_type",)
|
||||
assert outcome.marking is not None and outcome.marking.applied_rules == (
|
||||
"event_type",
|
||||
)
|
||||
assert pipeline.stats.events_received_total == 1
|
||||
assert pipeline.stats.events_normalized_total == 1
|
||||
assert pipeline.stats.events_emitted_total == 1
|
||||
|
||||
|
||||
def test_collector_pipeline_validation_failure_can_stop_processing() -> None:
|
||||
config = loads_toml(
|
||||
"""
|
||||
config = loads_toml("""
|
||||
[collectors.journal]
|
||||
enabled = true
|
||||
|
||||
|
|
@ -135,8 +142,7 @@ def test_collector_pipeline_validation_failure_can_stop_processing() -> None:
|
|||
op = "exists"
|
||||
on_fail = "drop"
|
||||
message = "message required"
|
||||
"""
|
||||
)
|
||||
""")
|
||||
pipeline = CollectorPipeline.from_toml(config, collector_name="journal")
|
||||
raw = CollectorRawEvent(
|
||||
collector_name="journal",
|
||||
|
|
@ -144,7 +150,9 @@ def test_collector_pipeline_validation_failure_can_stop_processing() -> None:
|
|||
event_type="system.raw.journal.entry",
|
||||
fields={"_SYSTEMD_UNIT": "wpa_supplicant.service"},
|
||||
)
|
||||
context = CollectorPipelineContext(collector_name="journal", source_kind=SourceKind.JOURNAL)
|
||||
context = CollectorPipelineContext(
|
||||
collector_name="journal", source_kind=SourceKind.JOURNAL
|
||||
)
|
||||
|
||||
outcome = pipeline.process(raw, context=context)
|
||||
|
||||
|
|
@ -155,8 +163,7 @@ def test_collector_pipeline_validation_failure_can_stop_processing() -> None:
|
|||
|
||||
|
||||
def test_collector_pipeline_prefilter_drop_works() -> None:
|
||||
config = loads_toml(
|
||||
"""
|
||||
config = loads_toml("""
|
||||
[collectors.journal]
|
||||
enabled = true
|
||||
|
||||
|
|
@ -166,8 +173,7 @@ def test_collector_pipeline_prefilter_drop_works() -> None:
|
|||
value = "wpa_supplicant.service"
|
||||
action = "drop"
|
||||
reason = "ignore wpa journal noise"
|
||||
"""
|
||||
)
|
||||
""")
|
||||
pipeline = CollectorPipeline.from_toml(config, collector_name="journal")
|
||||
raw = CollectorRawEvent(
|
||||
collector_name="journal",
|
||||
|
|
@ -175,7 +181,9 @@ def test_collector_pipeline_prefilter_drop_works() -> None:
|
|||
event_type="system.raw.journal.entry",
|
||||
fields={"_SYSTEMD_UNIT": "wpa_supplicant.service"},
|
||||
)
|
||||
context = CollectorPipelineContext(collector_name="journal", source_kind=SourceKind.JOURNAL)
|
||||
context = CollectorPipelineContext(
|
||||
collector_name="journal", source_kind=SourceKind.JOURNAL
|
||||
)
|
||||
|
||||
outcome = pipeline.process(raw, context=context)
|
||||
|
||||
|
|
|
|||
|
|
@ -32,8 +32,12 @@ class DummyCollector(CollectorBase):
|
|||
|
||||
|
||||
def test_supervisor_starts_enabled_collectors_and_tracks_state() -> None:
|
||||
enabled = DummyCollector(CollectorIdentity(name="journal", source_kind="journal", enabled=True))
|
||||
disabled = DummyCollector(CollectorIdentity(name="dbus", source_kind="dbus", enabled=False))
|
||||
enabled = DummyCollector(
|
||||
CollectorIdentity(name="journal", source_kind="journal", enabled=True)
|
||||
)
|
||||
disabled = DummyCollector(
|
||||
CollectorIdentity(name="dbus", source_kind="dbus", enabled=False)
|
||||
)
|
||||
supervisor = CollectorSupervisor([enabled, disabled])
|
||||
|
||||
initial_health = supervisor.health()
|
||||
|
|
@ -47,9 +51,17 @@ def test_supervisor_starts_enabled_collectors_and_tracks_state() -> None:
|
|||
state = supervisor.state()
|
||||
|
||||
assert started == ("journal",)
|
||||
assert state.collectors["journal"].health.lifecycle_state == CollectorLifecycleState.RUNNING
|
||||
assert state.collectors["journal"].health.connection_state == CollectorConnectionState.CONNECTED
|
||||
assert state.collectors["dbus"].health.lifecycle_state == CollectorLifecycleState.INIT
|
||||
assert (
|
||||
state.collectors["journal"].health.lifecycle_state
|
||||
== CollectorLifecycleState.RUNNING
|
||||
)
|
||||
assert (
|
||||
state.collectors["journal"].health.connection_state
|
||||
== CollectorConnectionState.CONNECTED
|
||||
)
|
||||
assert (
|
||||
state.collectors["dbus"].health.lifecycle_state == CollectorLifecycleState.INIT
|
||||
)
|
||||
assert supervisor.stats().start_total == 1
|
||||
assert supervisor.health().active_total == 1
|
||||
assert supervisor.health().running_total == 1
|
||||
|
|
@ -60,12 +72,20 @@ def test_supervisor_starts_enabled_collectors_and_tracks_state() -> None:
|
|||
|
||||
assert stopped == ("journal", "dbus")
|
||||
assert supervisor.stats().stop_total == 2
|
||||
assert supervisor.state().collectors["journal"].health.lifecycle_state == CollectorLifecycleState.STOPPED
|
||||
assert supervisor.state().collectors["dbus"].health.lifecycle_state == CollectorLifecycleState.STOPPED
|
||||
assert (
|
||||
supervisor.state().collectors["journal"].health.lifecycle_state
|
||||
== CollectorLifecycleState.STOPPED
|
||||
)
|
||||
assert (
|
||||
supervisor.state().collectors["dbus"].health.lifecycle_state
|
||||
== CollectorLifecycleState.STOPPED
|
||||
)
|
||||
|
||||
|
||||
def test_supervisor_watchdog_reports_active_unhealthy_collectors() -> None:
|
||||
collector = DummyCollector(CollectorIdentity(name="wpa", source_kind="wpa_ctrl", enabled=True))
|
||||
collector = DummyCollector(
|
||||
CollectorIdentity(name="wpa", source_kind="wpa_ctrl", enabled=True)
|
||||
)
|
||||
supervisor = CollectorSupervisor([collector])
|
||||
|
||||
supervisor.start_enabled()
|
||||
|
|
|
|||
|
|
@ -5,8 +5,13 @@ from contextlib import redirect_stderr, redirect_stdout
|
|||
from types import SimpleNamespace
|
||||
|
||||
from agent import cli
|
||||
from agent.commands.models import CommandOriginKind, CommandRequest, CommandResult, CommandState, CommandTargetKind
|
||||
|
||||
from agent.commands.models import (
|
||||
CommandOriginKind,
|
||||
CommandRequest,
|
||||
CommandResult,
|
||||
CommandState,
|
||||
CommandTargetKind,
|
||||
)
|
||||
|
||||
|
||||
def _run_cli(argv: list[str]) -> tuple[int, str, str]:
|
||||
|
|
@ -59,7 +64,9 @@ def test_cmd_system_set_regdomain_builds_command_request(monkeypatch) -> None:
|
|||
app = _RecordingCommandApp()
|
||||
monkeypatch.setattr(cli, "load_application", lambda **kwargs: app)
|
||||
|
||||
code, stdout, stderr = _run_cli(["cmd", "system", "set-regdomain", "--country", "US"])
|
||||
code, stdout, stderr = _run_cli(
|
||||
["cmd", "system", "set-regdomain", "--country", "US"]
|
||||
)
|
||||
|
||||
assert code == 0
|
||||
assert stderr == ""
|
||||
|
|
@ -73,4 +80,4 @@ def test_cmd_system_set_regdomain_builds_command_request(monkeypatch) -> None:
|
|||
assert request.target_kind == CommandTargetKind.SYSTEM
|
||||
assert request.target_id == "system"
|
||||
assert request.command_type == "system.set_regdomain"
|
||||
assert request.args["country"] == "US"
|
||||
assert request.args["country"] == "US"
|
||||
|
|
|
|||
|
|
@ -20,7 +20,9 @@ class RecordingRouter:
|
|||
self.calls: list[str] = []
|
||||
|
||||
def supports(self, request: CommandRequest) -> bool:
|
||||
return request.command_type.startswith("wpa.") or request.command_type.startswith("system.")
|
||||
return request.command_type.startswith(
|
||||
"wpa."
|
||||
) or request.command_type.startswith("system.")
|
||||
|
||||
def execute(self, request: CommandRequest) -> CommandResult:
|
||||
self.calls.append(request.command_id)
|
||||
|
|
@ -60,7 +62,9 @@ def _request(
|
|||
)
|
||||
|
||||
|
||||
def test_command_coordinator_accepts_cli_scheduler_and_derivator_and_dispatches_by_priority() -> None:
|
||||
def test_command_coordinator_accepts_cli_scheduler_and_derivator_and_dispatches_by_priority() -> (
|
||||
None
|
||||
):
|
||||
policy = CommandPolicy(
|
||||
CommandPolicyConfig(
|
||||
priority_operator=100,
|
||||
|
|
@ -188,4 +192,3 @@ def test_command_coordinator_emits_policy_rejections_and_suppressions() -> None:
|
|||
assert second_submit.emitted[0].accepted is False
|
||||
assert coordinator.stats().suppressed_total == 1
|
||||
assert coordinator.state().pending_command_ids == ("cmd-1",)
|
||||
|
||||
|
|
|
|||
|
|
@ -81,7 +81,9 @@ def test_command_result_tracks_state_transitions_and_duration() -> None:
|
|||
assert result.executor_name == "system"
|
||||
assert result.correlation_id == "corr-2"
|
||||
|
||||
finished = result.finished(state=CommandState.SUCCEEDED, success=True, message="done")
|
||||
finished = result.finished(
|
||||
state=CommandState.SUCCEEDED, success=True, message="done"
|
||||
)
|
||||
|
||||
assert finished.state == CommandState.SUCCEEDED
|
||||
assert finished.success is True
|
||||
|
|
|
|||
|
|
@ -73,7 +73,9 @@ def test_command_policy_resolves_default_priority_and_accepts_command() -> None:
|
|||
|
||||
|
||||
def test_command_policy_enforces_dedup_exclusive_and_cooldown_rules() -> None:
|
||||
policy = CommandPolicy(CommandPolicyConfig(dedup_window_ns=1_000, cooldown_window_ns=2_000))
|
||||
policy = CommandPolicy(
|
||||
CommandPolicyConfig(dedup_window_ns=1_000, cooldown_window_ns=2_000)
|
||||
)
|
||||
state = CommandPolicyState()
|
||||
first = _request(
|
||||
"cmd-a",
|
||||
|
|
@ -113,7 +115,9 @@ def test_command_policy_enforces_dedup_exclusive_and_cooldown_rules() -> None:
|
|||
|
||||
result = policy.evaluate(first, state, now_mono_ns_value=100)
|
||||
policy.observe_result(
|
||||
result=CommandResultStub.command_result_from_request(first, state=CommandState.SUCCEEDED),
|
||||
result=CommandResultStub.command_result_from_request(
|
||||
first, state=CommandState.SUCCEEDED
|
||||
),
|
||||
state=state,
|
||||
now_mono_ns_value=500,
|
||||
)
|
||||
|
|
@ -124,7 +128,9 @@ def test_command_policy_enforces_dedup_exclusive_and_cooldown_rules() -> None:
|
|||
exclusive_key="wpa:wlp3s0",
|
||||
cooldown_key="wpa.status",
|
||||
)
|
||||
cooldown_admission = policy.evaluate(cooldown_blocked, state, now_mono_ns_value=1000)
|
||||
cooldown_admission = policy.evaluate(
|
||||
cooldown_blocked, state, now_mono_ns_value=1000
|
||||
)
|
||||
|
||||
assert cooldown_admission.accepted is False
|
||||
assert cooldown_admission.decision == CommandDecisionKind.SUPPRESSED
|
||||
|
|
@ -157,7 +163,11 @@ def test_command_queue_orders_by_priority_and_evicts_lowest_on_overflow() -> Non
|
|||
|
||||
class CommandResultStub:
|
||||
@staticmethod
|
||||
def command_result_from_request(request: CommandRequest, *, state: CommandState) -> object:
|
||||
def command_result_from_request(
|
||||
request: CommandRequest, *, state: CommandState
|
||||
) -> object:
|
||||
from agent.commands import CommandResult
|
||||
|
||||
return CommandResult.from_request(request, state=state, accepted=True, success=True, message="done")
|
||||
return CommandResult.from_request(
|
||||
request, state=state, accepted=True, success=True, message="done"
|
||||
)
|
||||
|
|
|
|||
|
|
@ -53,7 +53,9 @@ def test_event_envelope_to_record_and_back_preserves_hot_fields() -> None:
|
|||
source_kind=common_pb2.SOURCE_KIND_WPA_CTRL,
|
||||
severity=common_pb2.SEVERITY_INFO,
|
||||
schema_version=1,
|
||||
routing=events_pb2.RoutingDirectives(cache_enabled=True, outbox_enabled=True, priority=9),
|
||||
routing=events_pb2.RoutingDirectives(
|
||||
cache_enabled=True, outbox_enabled=True, priority=9
|
||||
),
|
||||
normalized_ssid="test-ssid",
|
||||
normalized_bssid="aa:bb:cc:dd:ee:ff",
|
||||
normalized_freq_mhz=2412,
|
||||
|
|
@ -63,7 +65,9 @@ def test_event_envelope_to_record_and_back_preserves_hot_fields() -> None:
|
|||
payload=payload,
|
||||
)
|
||||
|
||||
record = event_envelope_to_record(envelope, interner=interner, observed_mono_ns=11, ingested_mono_ns=12)
|
||||
record = event_envelope_to_record(
|
||||
envelope, interner=interner, observed_mono_ns=11, ingested_mono_ns=12
|
||||
)
|
||||
|
||||
assert record.event_kind == EventKind.RAW
|
||||
assert record.source_kind == SourceKind.WPA_CTRL
|
||||
|
|
|
|||
|
|
@ -7,8 +7,7 @@ from agent.utils.toml_loader import loads_toml
|
|||
|
||||
|
||||
def _dbus_config() -> dict[str, object]:
|
||||
return loads_toml(
|
||||
"""
|
||||
return loads_toml("""
|
||||
[collectors.dbus]
|
||||
enabled = true
|
||||
bus = "system"
|
||||
|
|
@ -28,11 +27,12 @@ def _dbus_config() -> dict[str, object]:
|
|||
add.workflow_tags = ["wifi", "dbus"]
|
||||
add.labels.site = "warehouse-a"
|
||||
add.routing.outbox_enabled = true
|
||||
"""
|
||||
)
|
||||
""")
|
||||
|
||||
|
||||
def test_dbus_collector_processes_signals_through_pipeline_and_sends_envelopes() -> None:
|
||||
def test_dbus_collector_processes_signals_through_pipeline_and_sends_envelopes() -> (
|
||||
None
|
||||
):
|
||||
config = _dbus_config()
|
||||
backend = FakeDbusBackend(
|
||||
signals=[
|
||||
|
|
@ -44,7 +44,7 @@ def test_dbus_collector_processes_signals_through_pipeline_and_sends_envelopes()
|
|||
"sender": "fi.w1.wpa_supplicant1",
|
||||
"destination": "org.freedesktop.DBus",
|
||||
"message": "PropertiesChanged",
|
||||
"args_json": ["{\"State\": \"completed\"}"],
|
||||
"args_json": ['{"State": "completed"}'],
|
||||
"realtime_ns": 1_700_000_100_000_000_000,
|
||||
},
|
||||
{
|
||||
|
|
@ -60,7 +60,9 @@ def test_dbus_collector_processes_signals_through_pipeline_and_sends_envelopes()
|
|||
]
|
||||
)
|
||||
sink: list[object] = []
|
||||
collector = DbusCollector.from_toml(config, backend=backend, director_sink=sink.append)
|
||||
collector = DbusCollector.from_toml(
|
||||
config, backend=backend, director_sink=sink.append
|
||||
)
|
||||
|
||||
collector.start()
|
||||
outcomes = collector.drain_pending()
|
||||
|
|
@ -117,7 +119,9 @@ def test_dbus_collector_reconnects_after_backend_read_failure() -> None:
|
|||
fail_first_read=True,
|
||||
)
|
||||
sink: list[object] = []
|
||||
collector = DbusCollector.from_toml(config, backend=backend, director_sink=sink.append)
|
||||
collector = DbusCollector.from_toml(
|
||||
config, backend=backend, director_sink=sink.append
|
||||
)
|
||||
|
||||
collector.start()
|
||||
first = collector.poll_once()
|
||||
|
|
|
|||
|
|
@ -55,4 +55,4 @@ def test_derivator_run_once_reports_empty_window() -> None:
|
|||
assert "derived_total=0" in stdout
|
||||
assert "emitted_total=0" in stdout
|
||||
assert "workflow_count=1" in stdout
|
||||
assert "workflow_names=wifi_scan_summary" in stdout
|
||||
assert "workflow_names=wifi_scan_summary" in stdout
|
||||
|
|
|
|||
|
|
@ -29,7 +29,9 @@ def _append_record(cache, *, event_id: int, observed_ns: int) -> EventRecord:
|
|||
|
||||
|
||||
def test_derivator_worker_collects_new_seq_range_and_advances_watermark() -> None:
|
||||
cache = build_default_cache(ring_capacity=8, payload_capacity_items=8, payload_capacity_bytes=4096)
|
||||
cache = build_default_cache(
|
||||
ring_capacity=8, payload_capacity_items=8, payload_capacity_bytes=4096
|
||||
)
|
||||
base = 10_000_000_000
|
||||
for index in range(3):
|
||||
_append_record(cache, event_id=100 + index, observed_ns=base + index)
|
||||
|
|
@ -55,7 +57,9 @@ def test_derivator_worker_collects_new_seq_range_and_advances_watermark() -> Non
|
|||
|
||||
|
||||
def test_derivator_worker_reports_missing_overwritten_seq_nos() -> None:
|
||||
cache = build_default_cache(ring_capacity=2, payload_capacity_items=4, payload_capacity_bytes=4096)
|
||||
cache = build_default_cache(
|
||||
ring_capacity=2, payload_capacity_items=4, payload_capacity_bytes=4096
|
||||
)
|
||||
base = 20_000_000_000
|
||||
_append_record(cache, event_id=201, observed_ns=base)
|
||||
_append_record(cache, event_id=202, observed_ns=base + 1)
|
||||
|
|
@ -77,7 +81,9 @@ def test_derivator_worker_reports_missing_overwritten_seq_nos() -> None:
|
|||
|
||||
|
||||
def test_derivator_worker_emits_derived_envelopes_through_sink() -> None:
|
||||
cache = build_default_cache(ring_capacity=8, payload_capacity_items=8, payload_capacity_bytes=4096)
|
||||
cache = build_default_cache(
|
||||
ring_capacity=8, payload_capacity_items=8, payload_capacity_bytes=4096
|
||||
)
|
||||
base = 30_000_000_000
|
||||
_append_record(cache, event_id=301, observed_ns=base)
|
||||
|
||||
|
|
|
|||
|
|
@ -16,7 +16,9 @@ def _collector_envelope() -> events_pb2.EventEnvelope:
|
|||
event_kind=common_pb2.EVENT_KIND_RAW,
|
||||
source_kind=common_pb2.SOURCE_KIND_WPA_CTRL,
|
||||
severity=common_pb2.SEVERITY_INFO,
|
||||
routing=events_pb2.RoutingDirectives(cache_enabled=True, outbox_enabled=False, priority=7),
|
||||
routing=events_pb2.RoutingDirectives(
|
||||
cache_enabled=True, outbox_enabled=False, priority=7
|
||||
),
|
||||
trace=events_pb2.TraceContext(workflow_tags=["wifi", "roaming"]),
|
||||
attributes=common_pb2.AttributeMap(labels={"site": "warehouse-a"}),
|
||||
payload=events_pb2.RawWpaPayload(
|
||||
|
|
@ -37,7 +39,9 @@ def _derived_envelope() -> events_pb2.EventEnvelope:
|
|||
event_kind=common_pb2.EVENT_KIND_DERIVED,
|
||||
source_kind=common_pb2.SOURCE_KIND_APPLICATION,
|
||||
severity=common_pb2.SEVERITY_WARNING,
|
||||
routing=events_pb2.RoutingDirectives(cache_enabled=True, outbox_enabled=False, priority=5),
|
||||
routing=events_pb2.RoutingDirectives(
|
||||
cache_enabled=True, outbox_enabled=False, priority=5
|
||||
),
|
||||
trace=events_pb2.TraceContext(workflow_tags=["wifi"]),
|
||||
attributes=common_pb2.AttributeMap(labels={"workflow": "wifi"}),
|
||||
payload=events_pb2.DerivedEventPayload(
|
||||
|
|
@ -59,7 +63,9 @@ def _command_result_envelope() -> events_pb2.EventEnvelope:
|
|||
event_kind=common_pb2.EVENT_KIND_RAW,
|
||||
source_kind=common_pb2.SOURCE_KIND_CONTROL,
|
||||
severity=common_pb2.SEVERITY_ERROR,
|
||||
routing=events_pb2.RoutingDirectives(cache_enabled=True, outbox_enabled=False, priority=9),
|
||||
routing=events_pb2.RoutingDirectives(
|
||||
cache_enabled=True, outbox_enabled=False, priority=9
|
||||
),
|
||||
trace=events_pb2.TraceContext(workflow_tags=["control", "command"]),
|
||||
payload=events_pb2.CommandResultPayload(
|
||||
command_id="cmd-3",
|
||||
|
|
@ -88,7 +94,9 @@ def test_route_envelope_uses_normalized_fields_and_marks() -> None:
|
|||
|
||||
|
||||
def test_director_routes_collector_event_to_cache_and_derivator_interest() -> None:
|
||||
cache = build_default_cache(ring_capacity=8, payload_capacity_items=8, payload_capacity_bytes=4096)
|
||||
cache = build_default_cache(
|
||||
ring_capacity=8, payload_capacity_items=8, payload_capacity_bytes=4096
|
||||
)
|
||||
outbox_records: list[object] = []
|
||||
interest_records: list[object] = []
|
||||
director = Director(
|
||||
|
|
@ -114,7 +122,9 @@ def test_director_routes_collector_event_to_cache_and_derivator_interest() -> No
|
|||
|
||||
|
||||
def test_director_routes_derived_event_to_outbox_and_cache() -> None:
|
||||
cache = build_default_cache(ring_capacity=8, payload_capacity_items=8, payload_capacity_bytes=4096)
|
||||
cache = build_default_cache(
|
||||
ring_capacity=8, payload_capacity_items=8, payload_capacity_bytes=4096
|
||||
)
|
||||
outbox_records: list[object] = []
|
||||
interest_records: list[object] = []
|
||||
director = Director(
|
||||
|
|
@ -137,7 +147,9 @@ def test_director_routes_derived_event_to_outbox_and_cache() -> None:
|
|||
|
||||
|
||||
def test_director_routes_command_result_events_using_control_fields() -> None:
|
||||
cache = build_default_cache(ring_capacity=8, payload_capacity_items=8, payload_capacity_bytes=4096)
|
||||
cache = build_default_cache(
|
||||
ring_capacity=8, payload_capacity_items=8, payload_capacity_bytes=4096
|
||||
)
|
||||
outbox_records: list[object] = []
|
||||
interest_records: list[object] = []
|
||||
director = Director(
|
||||
|
|
@ -157,4 +169,4 @@ def test_director_routes_command_result_events_using_control_fields() -> None:
|
|||
assert len(interest_records) == 1
|
||||
assert outbox_records[0].seq_no == 1
|
||||
assert director.state().last_decision is not None
|
||||
assert director.state().last_decision.outbox is True
|
||||
assert director.state().last_decision.outbox is True
|
||||
|
|
|
|||
|
|
@ -1,13 +1,27 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from agent.commands import CommandRequest, CommandState, CommandTargetKind
|
||||
from agent.executors import ExecutorBase, ExecutorIdentity, ExecutorLifecycleState, ExecutorRouter
|
||||
from agent.executors import (
|
||||
ExecutorBase,
|
||||
ExecutorIdentity,
|
||||
ExecutorLifecycleState,
|
||||
ExecutorRouter,
|
||||
)
|
||||
from agent.commands import CommandOriginKind, CommandResult
|
||||
|
||||
|
||||
class DummyExecutor(ExecutorBase):
|
||||
def __init__(self, *, name: str, executor_kind: str, prefix: str | None = None, exact: str | None = None) -> None:
|
||||
super().__init__(ExecutorIdentity(name=name, executor_kind=executor_kind, enabled=True))
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
name: str,
|
||||
executor_kind: str,
|
||||
prefix: str | None = None,
|
||||
exact: str | None = None,
|
||||
) -> None:
|
||||
super().__init__(
|
||||
ExecutorIdentity(name=name, executor_kind=executor_kind, enabled=True)
|
||||
)
|
||||
self.prefix = prefix
|
||||
self.exact = exact
|
||||
self.executed: list[str] = []
|
||||
|
|
@ -37,7 +51,9 @@ class DummyExecutor(ExecutorBase):
|
|||
return result
|
||||
|
||||
|
||||
def _request(command_id: str, command_type: str, target_kind: CommandTargetKind) -> CommandRequest:
|
||||
def _request(
|
||||
command_id: str, command_type: str, target_kind: CommandTargetKind
|
||||
) -> CommandRequest:
|
||||
return CommandRequest(
|
||||
command_id=command_id,
|
||||
command_type=command_type,
|
||||
|
|
@ -49,11 +65,25 @@ def _request(command_id: str, command_type: str, target_kind: CommandTargetKind)
|
|||
|
||||
|
||||
def test_executor_router_prefers_exact_match_over_prefix_match() -> None:
|
||||
exact = DummyExecutor(name="system", executor_kind="system", exact="system.set_regdomain")
|
||||
prefix = DummyExecutor(name="generic-system", executor_kind="system", prefix="system.")
|
||||
exact = DummyExecutor(
|
||||
name="system", executor_kind="system", exact="system.set_regdomain"
|
||||
)
|
||||
prefix = DummyExecutor(
|
||||
name="generic-system", executor_kind="system", prefix="system."
|
||||
)
|
||||
router = ExecutorRouter()
|
||||
router.register(prefix, command_prefixes=("system.",), target_kinds=(CommandTargetKind.SYSTEM,), priority=1)
|
||||
router.register(exact, command_types=("system.set_regdomain",), target_kinds=(CommandTargetKind.SYSTEM,), priority=10)
|
||||
router.register(
|
||||
prefix,
|
||||
command_prefixes=("system.",),
|
||||
target_kinds=(CommandTargetKind.SYSTEM,),
|
||||
priority=1,
|
||||
)
|
||||
router.register(
|
||||
exact,
|
||||
command_types=("system.set_regdomain",),
|
||||
target_kinds=(CommandTargetKind.SYSTEM,),
|
||||
priority=10,
|
||||
)
|
||||
|
||||
request = _request("cmd-1", "system.set_regdomain", CommandTargetKind.SYSTEM)
|
||||
match = router.resolve(request)
|
||||
|
|
@ -74,7 +104,9 @@ def test_executor_router_prefers_exact_match_over_prefix_match() -> None:
|
|||
def test_executor_router_routes_wpa_prefix_and_reports_unsupported_commands() -> None:
|
||||
wpa = DummyExecutor(name="wpa_ctrl", executor_kind="wpa_ctrl", prefix="wpa.")
|
||||
router = ExecutorRouter([])
|
||||
router.register(wpa, command_prefixes=("wpa.",), target_kinds=(CommandTargetKind.WPA_CTRL,))
|
||||
router.register(
|
||||
wpa, command_prefixes=("wpa.",), target_kinds=(CommandTargetKind.WPA_CTRL,)
|
||||
)
|
||||
|
||||
request = _request("cmd-2", "wpa.status", CommandTargetKind.WPA_CTRL)
|
||||
assert router.supports(request) is True
|
||||
|
|
@ -93,7 +125,9 @@ def test_executor_router_routes_wpa_prefix_and_reports_unsupported_commands() ->
|
|||
|
||||
|
||||
def test_executor_base_tracks_lifecycle_and_stats_helpers() -> None:
|
||||
executor = DummyExecutor(name="base", executor_kind="system", exact="system.set_regdomain")
|
||||
executor = DummyExecutor(
|
||||
name="base", executor_kind="system", exact="system.set_regdomain"
|
||||
)
|
||||
|
||||
state = executor.state()
|
||||
assert state.health.lifecycle_state == ExecutorLifecycleState.INIT
|
||||
|
|
|
|||
|
|
@ -4,7 +4,9 @@ from agent.cache import RingBuffer, SecondaryIndexes
|
|||
from agent.core import EventRecord, EventTypeId, InterfaceId, SourceKind, StringId
|
||||
|
||||
|
||||
def _record(seq: int, *, interface_id: int, event_type_id: int, source_kind: int, ssid_id: int) -> EventRecord:
|
||||
def _record(
|
||||
seq: int, *, interface_id: int, event_type_id: int, source_kind: int, ssid_id: int
|
||||
) -> EventRecord:
|
||||
return EventRecord(
|
||||
seq_no=seq,
|
||||
interface_id=InterfaceId(interface_id),
|
||||
|
|
@ -18,9 +20,15 @@ def test_secondary_indexes_track_records_by_hot_fields() -> None:
|
|||
buffer = RingBuffer(4)
|
||||
indexes = SecondaryIndexes()
|
||||
|
||||
first = buffer.append(_record(1, interface_id=1, event_type_id=10, source_kind=1, ssid_id=100))
|
||||
second = buffer.append(_record(2, interface_id=1, event_type_id=11, source_kind=2, ssid_id=101))
|
||||
third = buffer.append(_record(3, interface_id=2, event_type_id=10, source_kind=1, ssid_id=100))
|
||||
first = buffer.append(
|
||||
_record(1, interface_id=1, event_type_id=10, source_kind=1, ssid_id=100)
|
||||
)
|
||||
second = buffer.append(
|
||||
_record(2, interface_id=1, event_type_id=11, source_kind=2, ssid_id=101)
|
||||
)
|
||||
third = buffer.append(
|
||||
_record(3, interface_id=2, event_type_id=10, source_kind=1, ssid_id=100)
|
||||
)
|
||||
|
||||
indexes.add(first)
|
||||
indexes.add(second)
|
||||