daemon теперь автоматически поднимает только journal и dbus источники, если для них в ACL есть хотя бы одно правило с cache. navigation без такого правила не стартует. На старте и остановке health синхронизируется в БД

This commit is contained in:
Ilgiz Kalmetyev 2026-04-11 23:57:30 +05:00
parent 4fe9be4333
commit 73ef00752c
8 changed files with 871 additions and 30 deletions

View File

@ -1,4 +1,4 @@
from __future__ import annotations
from __future__ import annotations
import inspect
from dataclasses import dataclass, field
@ -408,6 +408,230 @@ class FakeDbusClient(DbusClientProtocol):
self._health_reporter(status, details)
@dataclass(slots=True)
class SystemDbusClient(DbusClientProtocol):
connected: bool = field(default=False, init=False)
health: SourceStatus = field(default=SourceStatus.DISCONNECTED, init=False)
_bus: Any = field(default=None, init=False, repr=False, compare=False)
_health_reporter: SourceHealthReporter | None = field(
default=None, init=False, repr=False, compare=False
)
_subscriptions: dict[
str, tuple[DbusSignalSubscription, DbusSignalCallback, Callable[[Any], None]]
] = field(default_factory=dict, init=False, repr=False, compare=False)
_subscription_sequence: int = field(default=0, init=False, repr=False, compare=False)
async def connect(self) -> None:
if self.connected and self._bus is not None:
return
try:
from dbus_next.aio import MessageBus
from dbus_next import BusType
except ImportError as exc: # pragma: no cover - deployment only
raise RuntimeError(
'dbus-next is required for the system D-Bus client'
) from exc
self._bus = MessageBus(bus_type=BusType.SYSTEM)
self._bus = await self._bus.connect()
self.connected = True
self._apply_health(SourceStatus.HEALTHY)
async def disconnect(self) -> None:
if self._bus is not None:
for _, _, handler in list(self._subscriptions.values()):
remover = getattr(self._bus, 'remove_message_handler', None)
if callable(remover):
remover(handler)
disconnect = getattr(self._bus, 'disconnect', None)
if callable(disconnect):
result = disconnect()
if inspect.isawaitable(result):
await result
self._subscriptions.clear()
self._bus = None
self.connected = False
self._apply_health(SourceStatus.DISCONNECTED)
async def subscribe(
self, subscription: DbusSignalSubscription, callback: DbusSignalCallback
) -> DbusSubscriptionHandle:
if not self.connected or self._bus is None:
raise RuntimeError('dbus client is not connected')
if not callable(callback):
raise TypeError('callback must be callable')
subscription_id = f'sub-{self._subscription_sequence}'
self._subscription_sequence += 1
handler = self._build_message_handler(subscription, callback)
self._bus.add_message_handler(handler)
self._subscriptions[subscription_id] = (subscription, callback, handler)
self._apply_health(self.health)
return DbusSubscriptionHandle(
subscription_id=subscription_id, subscription=subscription
)
async def unsubscribe(self, handle: DbusSubscriptionHandle | str) -> None:
subscription_id = handle if isinstance(handle, str) else handle.subscription_id
entry = self._subscriptions.pop(subscription_id, None)
if entry is None or self._bus is None:
return
remover = getattr(self._bus, 'remove_message_handler', None)
if callable(remover):
remover(entry[2])
async def call_method(
self,
bus_name: str,
object_path: str,
interface_name: str,
method_name: str,
*,
arguments: Mapping[str, Any] | None = None,
) -> Any:
if not self.connected or self._bus is None:
raise RuntimeError('dbus client is disconnected')
try:
from dbus_next import Message
from dbus_next.constants import MessageType
except ImportError as exc: # pragma: no cover - deployment only
raise RuntimeError('dbus-next is required for dbus method calls') from exc
body = [] if arguments is None else [arguments[key] for key in sorted(arguments)]
message = Message(
destination=bus_name,
path=object_path,
interface=interface_name,
member=method_name,
message_type=MessageType.METHOD_CALL,
body=body,
)
response = await self._bus.call(message)
return getattr(response, 'body', None)
def set_health_reporter(self, reporter: SourceHealthReporter | None) -> None:
self._health_reporter = reporter
def _build_message_handler(
self,
subscription: DbusSignalSubscription,
callback: DbusSignalCallback,
) -> Callable[[Any], None]:
def _handler(message: Any) -> None:
if not self._matches_subscription(message, subscription):
return
event = DbusSignalEvent(
bus_name=subscription.bus_name,
object_path=subscription.object_path,
interface_name=subscription.interface_name,
signal_name=subscription.signal_name,
body=self._message_body_to_mapping(message),
metadata=self._message_metadata(message),
)
try:
outcome = callback(event)
if inspect.isawaitable(outcome):
asyncio.create_task(outcome)
except Exception:
logger.exception('dbus signal callback failed')
return _handler
def _matches_subscription(self, message: Any, subscription: DbusSignalSubscription) -> bool:
if getattr(message, 'path', None) != subscription.object_path:
return False
if getattr(message, 'interface', None) != subscription.interface_name:
return False
if getattr(message, 'member', None) != subscription.signal_name:
return False
return True
def _message_body_to_mapping(self, message: Any) -> dict[str, Any]:
body = list(getattr(message, 'body', []) or [])
signal_name = str(getattr(message, 'member', '') or 'signal')
payload: dict[str, Any] = {
'signal_name': signal_name,
'signal': signal_name,
'event_type': signal_name,
'MESSAGE': signal_name,
}
if signal_name == 'StateChanged':
if body:
payload['state'] = body[0]
if len(body) > 1:
payload['old_state'] = body[1]
if len(body) > 2:
payload['reason'] = body[2]
return payload
if signal_name == 'PropertiesChanged':
if body:
payload['interface_name'] = body[0]
if len(body) > 1 and isinstance(body[1], Mapping):
changed_properties = dict(body[1])
payload['changed_properties'] = changed_properties
payload['properties'] = dict(changed_properties)
if 'State' in changed_properties:
payload['state'] = changed_properties['State']
if len(body) > 2:
payload['invalidated_properties'] = list(body[2])
return payload
if signal_name in {'BlobAdded', 'BlobRemoved'} and body:
payload['blobName'] = body[0]
elif signal_name in {'NetworkAdded', 'NetworkRemoved', 'NetworkSelected'} and body:
payload['network'] = body[0]
elif signal_name in {'StaAuthorized', 'StaDeauthorized'} and body:
payload['mac'] = body[0]
elif signal_name == 'Certification' and body:
payload['depth'] = body[0]
if len(body) > 1:
payload['subject'] = body[1]
elif signal_name == 'EAP' and body:
payload['status'] = body[0]
if len(body) > 1:
payload['parameter'] = body[1]
elif signal_name == 'NetworkRequest' and body:
payload['network'] = body[0]
if len(body) > 1:
payload['field'] = body[1]
if len(body) > 2:
payload['txt'] = body[2]
elif signal_name == 'ProbeRequest' and body:
keys = ('addr', 'dst', 'bssid', 'ies', 'signal')
for key, value in zip(keys, body):
payload[key] = value
elif len(body) == 1 and isinstance(body[0], Mapping):
payload.update(dict(body[0]))
elif body:
payload['args'] = body
return payload
def _message_metadata(self, message: Any) -> dict[str, Any]:
metadata = {
'sender': getattr(message, 'sender', None),
'destination': getattr(message, 'destination', None),
'path': getattr(message, 'path', None),
'interface': getattr(message, 'interface', None),
'member': getattr(message, 'member', None),
'signature': getattr(message, 'signature', None),
}
return {key: value for key, value in metadata.items() if value is not None}
def _apply_health(self, status: SourceStatus) -> None:
self.health = status
if self._health_reporter is not None:
self._health_reporter(
status,
build_health_details(
connected=self.connected,
subscription_count=len(self._subscriptions),
extra={
'phase': 'connected'
if status is SourceStatus.HEALTHY
else 'disconnected'
},
),
)
__all__ = [
"DbusClientProtocol",
"DbusMethodCall",
@ -417,4 +641,8 @@ __all__ = [
"DbusSignalSubscription",
"DbusSubscriptionHandle",
"FakeDbusClient",
"SystemDbusClient",
]

View File

@ -1,5 +1,7 @@
from __future__ import annotations
from __future__ import annotations
import asyncio
import json
from typing import Any, Mapping, Protocol, runtime_checkable
from .filters import JournalFilter
@ -14,4 +16,90 @@ class JournalReaderProtocol(Protocol):
) -> list[RawJournalEntry]: ...
__all__ = ["JournalReaderProtocol", "RawJournalEntry"]
class SystemJournalReader(JournalReaderProtocol):
def __init__(self, *, command: str = 'journalctl', encoding: str = 'utf-8') -> None:
self.command = command
self.encoding = encoding
async def read(
self, journal_filter: JournalFilter, *, limit: int | None = None
) -> list[RawJournalEntry]:
command = self._build_command(journal_filter)
try:
process = await asyncio.create_subprocess_exec(
*command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
except FileNotFoundError as exc:
raise RuntimeError('journalctl command not found') from exc
stdout, stderr = await process.communicate()
if process.returncode != 0:
message = stderr.decode(self.encoding, errors='replace').strip()
raise RuntimeError(message or 'journalctl invocation failed')
entries: list[RawJournalEntry] = []
for line in stdout.decode(self.encoding, errors='replace').splitlines():
text = line.strip()
if not text.startswith('{'):
continue
try:
entry = json.loads(text)
except json.JSONDecodeError:
continue
if not isinstance(entry, dict):
continue
if not self._matches_filter(entry, journal_filter):
continue
entries.append(entry)
if limit is not None and len(entries) >= limit:
break
return entries
def _build_command(self, journal_filter: JournalFilter) -> list[str]:
command = [self.command, '--no-pager', '--output=json', '--show-cursor']
if journal_filter.cursor is not None:
command.extend(['--after-cursor', journal_filter.cursor.value])
elif journal_filter.since is not None:
command.extend(['--since', str(journal_filter.since)])
else:
command.extend(['--since', 'now'])
if journal_filter.until is not None:
command.extend(['--until', str(journal_filter.until)])
return command
def _matches_filter(
self, entry: Mapping[str, Any], journal_filter: JournalFilter
) -> bool:
if journal_filter.source_names and not self._matches_any_name(
entry, journal_filter.source_names
):
return False
if journal_filter.process_names and not self._matches_any_name(
entry, journal_filter.process_names
):
return False
for key, expected in journal_filter.field_matches.items():
value = entry.get(key)
if value is None:
return False
if str(value).strip() != expected:
return False
return True
def _matches_any_name(
self, entry: Mapping[str, Any], names: tuple[str, ...]
) -> bool:
candidate_fields = ('_COMM', 'SYSLOG_IDENTIFIER', 'process_name', 'process')
for field_name in candidate_fields:
value = entry.get(field_name)
if not isinstance(value, str):
continue
normalized = value.strip()
if normalized and normalized in names:
return True
return False
__all__ = ['JournalReaderProtocol', 'RawJournalEntry', 'SystemJournalReader']

View File

@ -1,10 +1,11 @@
from __future__ import annotations
from __future__ import annotations
from contextlib import asynccontextmanager
from typing import AsyncIterator
from fastapi import FastAPI
from app.bootstrap import create_daemon_runtime
from app.core.acl import load_acl_config_from_file
from app.core.config import Settings, load_settings
from app.core.constants import APP_NAME
@ -19,25 +20,33 @@ from .metrics import metrics_router
@asynccontextmanager
async def _lifespan(app: FastAPI) -> AsyncIterator[None]:
owns_bootstrap = False
if getattr(app.state, "bootstrap", None) is None:
settings = getattr(app.state, "settings", None)
if settings is None:
settings = load_settings()
app.state.settings = settings
if (
getattr(app.state, "acl_policy", None) is None
and settings.config_path is not None
):
app.state.acl_policy = load_acl_config_from_file(settings.config_path)
bootstrap = create_database_bootstrap(settings.database_dsn)
app.state.bootstrap = bootstrap
owns_bootstrap = True
app.state.owns_bootstrap = owns_bootstrap
runtime = getattr(app.state, 'runtime', None)
settings = getattr(app.state, 'settings', None)
bootstrap = getattr(app.state, 'bootstrap', None)
try:
if bootstrap is None:
if settings is None:
settings = load_settings()
app.state.settings = settings
bootstrap = create_database_bootstrap(settings.database_dsn)
app.state.bootstrap = bootstrap
owns_bootstrap = True
if (
runtime is None
and settings is not None
and getattr(app.state, 'acl_policy', None) is not None
):
runtime = create_daemon_runtime(
settings=settings,
bootstrap=bootstrap,
acl_policy=app.state.acl_policy,
)
app.state.runtime = runtime
await runtime.start()
yield
finally:
bootstrap = getattr(app.state, "bootstrap", None)
if runtime is not None:
await runtime.stop()
if owns_bootstrap and bootstrap is not None:
await bootstrap.dispose()
@ -50,19 +59,15 @@ def create_app(
app = FastAPI(title=APP_NAME, lifespan=_lifespan)
app.state.settings = settings
app.state.bootstrap = bootstrap
app.state.runtime = None
app.state.owns_bootstrap = False
app.state.acl_policy = None
if settings is not None and settings.config_path is not None:
app.state.acl_policy = load_acl_config_from_file(settings.config_path)
app.include_router(health_router)
app.include_router(metrics_router)
app.include_router(admin_router)
app.include_router(command_router)
return app
app = create_app()
__all__ = ["app", "create_app"]
__all__ = ['app', 'create_app']

View File

@ -1 +1,346 @@
"""Application bootstrap and wiring."""
from __future__ import annotations
import asyncio
import json
import logging
from collections.abc import Callable, Mapping
from contextlib import suppress
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from app.adapters import JournalAdapter, JournalFilter, SourceAdapterProtocol
from app.adapters.dbus_wpa import DbusWpaAdapter
from app.adapters.dbus_wpa.client import SystemDbusClient
from app.adapters.journal.reader import SystemJournalReader
from app.core.acl import SourceAclConfig
from app.core.clock import Clock, SystemClock
from app.core.config import Settings
from app.core.logging import build_log_context
from app.ingestion import IngestionDispatcher, SourceManager
from app.storage.db import DatabaseBootstrap
from app.storage.repositories import (
CachedEventRecord,
CachedEventRepository,
JournalCursorRecord,
JournalCursorRepository,
SourceRegistryRecord,
schema,
)
from app.workers import SourceHealthWorker
logger = logging.getLogger(__name__)
SourceAdapterFactory = Callable[
[
SourceRegistryRecord,
DatabaseBootstrap,
Settings,
SourceAclConfig,
IngestionDispatcher,
Clock,
],
SourceAdapterProtocol | None,
]
@dataclass(slots=True)
class _SessionBackedCachedEventRepository:
session_factory: async_sessionmaker[AsyncSession]
async def save(self, record: CachedEventRecord) -> None:
async with self.session_factory() as session:
await CachedEventRepository(session).save(record)
await session.commit()
@dataclass(slots=True)
class _SessionBackedJournalCursorRepository:
session_factory: async_sessionmaker[AsyncSession]
async def get(self, cursor_key: str) -> JournalCursorRecord | None:
async with self.session_factory() as session:
return await JournalCursorRepository(session).get(cursor_key)
async def save(self, record: JournalCursorRecord) -> None:
async with self.session_factory() as session:
await JournalCursorRepository(session).save(record)
await session.commit()
def _parse_timestamp(value: str) -> datetime:
return datetime.fromisoformat(value.replace('Z', '+00:00')).astimezone(
timezone.utc
)
def _source_record_from_row(row: Mapping[str, Any]) -> SourceRegistryRecord | None:
try:
metadata = json.loads(row['metadata_json'] or '{}')
if not isinstance(metadata, dict):
metadata = {'value': metadata}
return SourceRegistryRecord(
id=row['id'],
source_key=row['source_key'],
source_kind=row['source_kind'],
display_name=row['display_name'],
is_enabled=bool(row['is_enabled']),
metadata=metadata,
created_at=_parse_timestamp(str(row['created_at'])),
updated_at=_parse_timestamp(str(row['updated_at'])),
)
except Exception as exc:
logger.warning(
'source registry record skipped',
extra=build_log_context(
source_key=str(row.get('source_key', '')),
source_kind=str(row.get('source_kind', '')),
error=str(exc),
),
)
return None
def _metadata_text(
record: SourceRegistryRecord, key: str, default: str | None
) -> str | None:
value = record.metadata.get(key)
if isinstance(value, str):
normalized = value.strip()
if normalized:
return normalized
return default
def _metadata_int(record: SourceRegistryRecord, key: str, default: int) -> int:
value = record.metadata.get(key)
if value is None:
return default
try:
normalized = int(value)
except (TypeError, ValueError) as exc:
raise ValueError(f"source metadata field '{key}' must be an integer") from exc
if normalized <= 0:
raise ValueError(f"source metadata field '{key}' must be positive")
return normalized
def _metadata_mapping(
record: SourceRegistryRecord, key: str
) -> Mapping[str, Any] | None:
value = record.metadata.get(key)
return value if isinstance(value, Mapping) else None
def _source_kind_has_cache_rules(
acl_policy: SourceAclConfig | None, source_kind: str
) -> bool:
if acl_policy is None:
return False
rules = getattr(acl_policy, source_kind, ())
return any(rule.cache_policy == 'cache' for rule in rules)
def _build_journal_adapter(
record: SourceRegistryRecord,
bootstrap: DatabaseBootstrap,
settings: Settings,
acl_policy: SourceAclConfig,
dispatcher: IngestionDispatcher,
clock: Clock,
) -> SourceAdapterProtocol:
return JournalAdapter(
source_key=record.source_key,
source_id=record.id,
reader=SystemJournalReader(),
cursor_repository=_SessionBackedJournalCursorRepository(
bootstrap.session_factory
),
dispatcher=dispatcher,
filter_template=JournalFilter(
source_names=_metadata_mapping(record, 'source_names'),
process_names=_metadata_mapping(record, 'process_names'),
field_matches=_metadata_mapping(record, 'field_matches'),
),
clock=clock,
acl_policy=acl_policy,
cache_repository=_SessionBackedCachedEventRepository(
bootstrap.session_factory
),
cache_ttl_seconds=_metadata_int(
record, 'cache_ttl_seconds', settings.cache_ttl_seconds
),
)
def _build_dbus_adapter(
record: SourceRegistryRecord,
bootstrap: DatabaseBootstrap,
settings: Settings,
acl_policy: SourceAclConfig,
dispatcher: IngestionDispatcher,
clock: Clock,
) -> SourceAdapterProtocol:
wifi_interface_name = _metadata_text(
record, 'wifi_interface_name', settings.wifi_interface_name
)
if wifi_interface_name is None:
raise ValueError('wifi_interface_name must be configured for dbus sources')
return DbusWpaAdapter(
source_key=record.source_key,
source_id=record.id,
client=SystemDbusClient(),
dispatcher=dispatcher,
wifi_interface_name=wifi_interface_name,
object_path=_metadata_text(record, 'object_path', None),
clock=clock,
acl_policy=acl_policy,
cache_repository=_SessionBackedCachedEventRepository(
bootstrap.session_factory
),
cache_ttl_seconds=_metadata_int(
record, 'cache_ttl_seconds', settings.cache_ttl_seconds
),
)
DEFAULT_SOURCE_ADAPTER_FACTORIES: dict[str, SourceAdapterFactory] = {
'journal': _build_journal_adapter,
'dbus': _build_dbus_adapter,
}
@dataclass(slots=True)
class DaemonRuntime:
settings: Settings
bootstrap: DatabaseBootstrap
acl_policy: SourceAclConfig
clock: Clock = field(default_factory=SystemClock)
source_adapter_factories: Mapping[str, SourceAdapterFactory] = field(
default_factory=dict
)
dispatcher: IngestionDispatcher = field(init=False)
source_manager: SourceManager = field(init=False)
health_worker: SourceHealthWorker = field(init=False)
_health_task: asyncio.Task[None] | None = field(
default=None, init=False, repr=False, compare=False
)
_started: bool = field(default=False, init=False, repr=False, compare=False)
def __post_init__(self) -> None:
self.dispatcher = IngestionDispatcher()
self.dispatcher.register_supported_channels()
self.source_manager = SourceManager(self.dispatcher, clock=self.clock)
self.health_worker = SourceHealthWorker(
manager=self.source_manager,
session_factory=self.bootstrap.session_factory,
clock=self.clock,
)
factories = dict(DEFAULT_SOURCE_ADAPTER_FACTORIES)
factories.update(dict(self.source_adapter_factories))
self.source_adapter_factories = factories
async def start(self) -> tuple[str, ...]:
if self._started:
return tuple()
async with self.bootstrap.session_factory() as session:
result = await session.execute(
select(schema.source_registry)
.where(schema.source_registry.c.is_enabled.is_(True))
.order_by(schema.source_registry.c.source_key.asc())
)
for row in result.mappings().all():
record = _source_record_from_row(dict(row))
if record is None:
continue
if not _source_kind_has_cache_rules(
self.acl_policy, record.source_kind
):
logger.info(
'source skipped because acl has no cache rules',
extra=build_log_context(
source_key=record.source_key,
source_kind=record.source_kind,
),
)
continue
factory = self.source_adapter_factories.get(record.source_kind)
if factory is None:
logger.warning(
'source skipped because no runtime adapter factory exists',
extra=build_log_context(
source_key=record.source_key,
source_kind=record.source_kind,
),
)
continue
adapter = factory(
record,
self.bootstrap,
self.settings,
self.acl_policy,
self.dispatcher,
self.clock,
)
if adapter is not None:
self.source_manager.register(adapter)
result = await self.source_manager.start_all()
if self.source_manager.statuses:
await self.health_worker.run_once()
self._started = True
logger.info(
'daemon runtime started',
extra=build_log_context(
source_count=len(self.source_manager.statuses),
started_count=len(result.started),
skipped_count=len(result.skipped),
failed_count=len(result.failed),
),
)
return result.started
async def stop(self) -> None:
if not self._started and self._health_task is None:
return
await self.source_manager.stop_all()
if self.source_manager.statuses:
await self.health_worker.run_once()
self._started = False
logger.info('daemon runtime stopped')
def create_daemon_runtime(
*,
settings: Settings,
bootstrap: DatabaseBootstrap,
acl_policy: SourceAclConfig,
clock: Clock | None = None,
source_adapter_factories: Mapping[str, SourceAdapterFactory] | None = None,
) -> DaemonRuntime:
return DaemonRuntime(
settings=settings,
bootstrap=bootstrap,
acl_policy=acl_policy,
clock=SystemClock() if clock is None else clock,
source_adapter_factories={}
if source_adapter_factories is None
else dict(source_adapter_factories),
)
__all__ = [
'DaemonRuntime',
'DEFAULT_SOURCE_ADAPTER_FACTORIES',
'SourceAdapterFactory',
'_source_kind_has_cache_rules',
'create_daemon_runtime',
]

View File

@ -1,4 +1,4 @@
# Operational Procedures
# Operational Procedures
This document describes the day-to-day procedures used by operators and maintainers.
@ -42,6 +42,7 @@ wf-agent --config-file /etc/wf-agent/wf-agent.toml cache clear
- `inspect cache` shows active cached events with TTL and ACL marks.
- `cache clear` removes local cached events from the canonical cache table.
- If `inspect sources` is empty after deploy, run `wf-agent --config-file /etc/wf-agent/wf-agent.toml bootstrap sources` to seed registry and health rows.
- At daemon start, enabled sources that have at least one `cache` ACL rule are started automatically and begin collecting incoming data.
- If `--config-file` is omitted, the CLI uses `/etc/wf-agent/wf-agent.toml`.
## Restart
@ -76,3 +77,4 @@ wf-agent --config-file /etc/wf-agent/wf-agent.toml cache clear
- Batch rows should appear in scheduler-selected groups.
- Retried rows should have a future `available_at`.
- Dead-letter rows should stop re-entering the delivery loop.

View File

@ -1,4 +1,4 @@
# wf-agent Runbook
# wf-agent Runbook
This runbook describes the normal operating posture for `wf-agent` on a Linux host.
@ -26,7 +26,7 @@ This runbook describes the normal operating posture for `wf-agent` on a Linux ho
1. Install the application under `/opt/wf-agent`, or update `WorkingDirectory` and `ExecStart` in `deployment/systemd/wf-agent.service` to match the actual path.
2. Copy `deployment/config/wf-agent.toml.example` to `/etc/wf-agent/wf-agent.toml`.
3. Ensure `wf-agent.toml` contains `app_env`, `database_dsn`, `log_level`, `wifi_interface_name`, `cache_ttl_seconds`, and the `[acl]` section.
4. Apply migrations and seed `source_registry` and `source_health` with `wf-agent --config-file /etc/wf-agent/wf-agent.toml bootstrap sources` before the first start.
4. Apply migrations and seed `source_registry` and `source_health` with `wf-agent --config-file /etc/wf-agent/wf-agent.toml bootstrap sources` before the first start. The daemon then auto-starts any enabled `journal` or `dbus` source that has at least one `cache` ACL rule.
5. Enable and start `wf-agent.service`.
6. For local inspection, use `wf-agent --config-file /etc/wf-agent/wf-agent.toml inspect sources|outbox|health|cache`.
7. For D-Bus sources, confirm `wifi_interface_name` matches the target Wi-Fi interface on the host.
@ -55,3 +55,4 @@ This runbook describes the normal operating posture for `wf-agent` on a Linux ho
5. Use `wf-agent cache clear` only when the local cache must be purged manually.
6. Check structured logs for `correlation_id`, `source_id`, `command_id`, and `outbox_id`.
7. Use the recovery scenarios in `docs/operations/procedures.md` if the issue persists.

View File

@ -15,6 +15,7 @@ dependencies = [
"alembic>=1.13",
"fastapi>=0.128.0",
"uvicorn>=0.30",
"dbus-next>=0.2.3",
]
[project.optional-dependencies]

View File

@ -0,0 +1,171 @@
from __future__ import annotations
import asyncio
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from uuid import UUID
from alembic import command
from app.adapters.base import SourceHealthReporter
from app.bootstrap import _source_kind_has_cache_rules, create_daemon_runtime
from app.core.acl import AclRule, SourceAclConfig, load_acl_config_from_file
from app.core.clock import FrozenClock
from app.core.config import load_settings
from app.domain.enums import SourceStatus
from app.storage.db import create_database_bootstrap
from app.storage.repositories import SourceHealthRepository
from app.storage.source_bootstrap import STANDARD_SOURCE_SEEDS, seed_standard_sources
from tests.integration.test_repositories import _alembic_config
BASE_TIME = datetime(2026, 4, 11, 12, 0, tzinfo=timezone.utc)
@dataclass
class FakeAdapter:
source_key: str
ingestion_channel: str
enabled: bool = True
start_calls: int = 0
stop_calls: int = 0
health_reporter: SourceHealthReporter | None = field(default=None, init=False)
async def start(self) -> None:
self.start_calls += 1
if self.health_reporter is not None:
self.health_reporter(
SourceStatus.HEALTHY,
{'phase': 'started', 'source_key': self.source_key},
)
async def stop(self) -> None:
self.stop_calls += 1
if self.health_reporter is not None:
self.health_reporter(
SourceStatus.DISCONNECTED,
{'phase': 'stopped', 'source_key': self.source_key},
)
def set_enabled(self, enabled: bool) -> None:
self.enabled = enabled
def set_health_reporter(self, reporter: SourceHealthReporter | None) -> None:
self.health_reporter = reporter
async def _migrated_bootstrap(db_path: Path):
database_dsn = f'sqlite+aiosqlite:///{db_path.as_posix()}'
await asyncio.to_thread(command.upgrade, _alembic_config(database_dsn), 'head')
return create_database_bootstrap(database_dsn)
async def _seed_sources(bootstrap) -> None:
async with bootstrap.session_factory() as session:
await seed_standard_sources(session, clock=FrozenClock(BASE_TIME))
async def _scenario(db_path: Path, config_path: Path) -> None:
bootstrap = await _migrated_bootstrap(db_path)
try:
await _seed_sources(bootstrap)
settings = load_settings(config_path=config_path)
acl_policy = load_acl_config_from_file(config_path)
adapters: dict[str, FakeAdapter] = {}
def _factory(kind: str):
def _build(*args, **kwargs): # type: ignore[no-untyped-def]
record = args[0]
adapter = FakeAdapter(
source_key=record.source_key,
ingestion_channel=kind,
)
adapters[record.source_key] = adapter
return adapter
return _build
runtime = create_daemon_runtime(
settings=settings,
bootstrap=bootstrap,
acl_policy=acl_policy,
clock=FrozenClock(BASE_TIME),
source_adapter_factories={
'journal': _factory('journal'),
'dbus': _factory('dbus'),
},
)
started = await runtime.start()
assert started == ('dbus-main', 'journal-main')
assert set(adapters) == {'dbus-main', 'journal-main'}
assert adapters['dbus-main'].start_calls == 1
assert adapters['journal-main'].start_calls == 1
async with bootstrap.session_factory() as session:
health_repo = SourceHealthRepository(session)
journal_health = await health_repo.get(
next(seed.id for seed in STANDARD_SOURCE_SEEDS if seed.source_key == 'journal-main')
)
dbus_health = await health_repo.get(
next(seed.id for seed in STANDARD_SOURCE_SEEDS if seed.source_key == 'dbus-main')
)
nav_health = await health_repo.get(
next(seed.id for seed in STANDARD_SOURCE_SEEDS if seed.source_key == 'navigation-main')
)
assert journal_health is not None and journal_health.status is SourceStatus.HEALTHY
assert dbus_health is not None and dbus_health.status is SourceStatus.HEALTHY
assert nav_health is not None and nav_health.status is SourceStatus.DISCONNECTED
await runtime.stop()
assert adapters['dbus-main'].stop_calls == 1
assert adapters['journal-main'].stop_calls == 1
async with bootstrap.session_factory() as session:
health_repo = SourceHealthRepository(session)
journal_health = await health_repo.get(
next(seed.id for seed in STANDARD_SOURCE_SEEDS if seed.source_key == 'journal-main')
)
dbus_health = await health_repo.get(
next(seed.id for seed in STANDARD_SOURCE_SEEDS if seed.source_key == 'dbus-main')
)
assert journal_health is not None and journal_health.status is SourceStatus.DISCONNECTED
assert dbus_health is not None and dbus_health.status is SourceStatus.DISCONNECTED
finally:
await bootstrap.dispose()
def test_source_kind_cache_policy_detects_cache_rules() -> None:
policy = SourceAclConfig(
journal=(AclRule('wpa_supplicant', '.*', 'cache'),),
dbus=(AclRule('wpa_supplicant', '.*', 'drop'),),
)
assert _source_kind_has_cache_rules(policy, 'journal') is True
assert _source_kind_has_cache_rules(policy, 'dbus') is False
assert _source_kind_has_cache_rules(None, 'journal') is False
def test_daemon_runtime_starts_cache_eligible_sources_and_persists_health(tmp_path: Path) -> None:
config_path = tmp_path / 'wf-agent.toml'
config_path.write_text(
f'''
app_env = "test"
database_dsn = "sqlite+aiosqlite:///{(tmp_path / 'wf_agent_runtime_test.sqlite3').as_posix()}"
wifi_interface_name = "wlan0"
[acl]
journal = [
'cache process wpa_supplicant regexp ".*"',
]
dbus = [
'cache process wpa_supplicant regexp ".*"',
]
'''.strip(),
encoding='utf-8',
)
asyncio.run(_scenario(tmp_path / 'wf_agent_runtime_test.sqlite3', config_path))