rb-wf-ag/agent
Ilgiz Kamelyev afd6e85d47 поясняющий файл с описанием последовательности действий в Zabbix для настройки hosts агентов, шаблонов, триггеров, items.. 2026-05-05 12:40:30 +05:00
..
src/wfagent Для успешно распарсенных SSID и BSSID backend/agent теперь возвращает plain string вместо богатого blob-объекта 2026-05-05 09:42:04 +05:00
tests Для успешно распарсенных SSID и BSSID backend/agent теперь возвращает plain string вместо богатого blob-объекта 2026-05-05 09:42:04 +05:00
README.md Актуализирована документация 2026-05-05 10:10:36 +05:00
pyproject.toml Проект разделён по каталогам agent и backend. Поддержка legacy messages удалена 2026-05-04 10:31:02 +05:00
wfagent.example.yaml поясняющий файл с описанием последовательности действий в Zabbix для настройки hosts агентов, шаблонов, триггеров, items.. 2026-05-05 12:40:30 +05:00
wpa_cli_commands.md Проект разделён по каталогам agent и backend. Поддержка legacy messages удалена 2026-05-04 10:31:02 +05:00

README.md

wfagent

Wi-Fi event/command bridge for wpa_supplicant with a separate delivery backend.

This repository contains two installable Python applications:

  • wfagent, the agent that reads events from wpa_supplicant, processes them, writes selected events to stdout as NDJSON, and can trigger commands.
  • wfagent_backend, the HTTP backend that receives webhook deliveries from agents, normalizes them, queues them, and maps payload fields to downstream metrics.

The two applications are intentionally decoupled and can be deployed on different hosts.

Code Navigation

Main entry points

Event pipeline

Runtime behavior

  • ctrl_iface source loss is handled as a recoverable condition.
  • source_down and source_up are internal runtime events and pass through the same pipeline as start, reload, stop, and timer_tick.
  • The agent serializes selected events to stdout as NDJSON only after classification.
  • Command execution and command result data remain separate.

Payload decoding and delivery

What to look at first

  • sources.py for transport-specific source behavior and reconnect handling.
  • pipeline.py for filtering, classification, and trigger decisions.
  • payloads/decoders/ for SSID/BSSID, TLV, WPS, and WFD decoding.
  • delivery/ for backend delivery batching and retry logic.
  • enrichment.py for the optional navigation snapshot service and cache.
  • commands.py for explicit D-Bus and ctrl_iface command execution.

Tests

System Overview

The agent is the event producer and command orchestrator. It consumes:

  • D-Bus events from the wpa_supplicant tree
  • ctrl_iface unsolicited lines from the Unix socket
  • internal runtime events such as start, reload, stop, timer_tick, source_down, and source_up

The ctrl_iface source is treated as recoverable: if the Unix socket disappears, the agent emits source_down, retries, and emits source_up after recovery.

The agent then:

  1. applies source-specific filters
  2. normalizes the event into the internal model and, when configured, attaches navigation snapshot data under payload.navigation
  3. classifies it as drop, serialize_only, or serialize_and_trigger
  4. serializes selected events to stdout as NDJSON
  5. creates command requests for trigger rules
  6. dispatches commands to an explicitly configured destination
  7. optionally delivers normalized event batches to the backend over HTTP

The serialized event model keeps event_kind and data_kind separate:

  • event_kind is the event classification used by filters, classifier rules, and triggers.
  • data_kind is the payload/content classification used by downstream delivery and mapping.

Enrichment layer

src/wfagent/enrichment.py implements the optional navigation enrichment layer.

  • It is a background snapshot service, not a Wi-Fi event source.
  • It does not emit pipeline events and does not participate in classifier or trigger matching.
  • It periodically refreshes navigation status and coordinates through a configured API client.
  • It caches the last known snapshot with TTL and exposes NavigationSnapshot data to the normalizer.
  • When a fresh snapshot is available, the normalizer adds it under payload.navigation.

The current implementation includes:

  • EnrichmentService - lifecycle and refresh loop
  • NavigationCache - cached snapshot state and TTL handling
  • NavigationApiClientStub - default stub client used when no live API client is injected
  • NavigationSnapshot - serialized status/coordinate view exposed to the event payload

NavigationSnapshot.to_payload() produces one of these compact payloads:

  • {"status":"available","age_ms":...,"coordinates":{"x":...,"y":...}}
  • {"status":"unavailable","reason":...}

Enrichment is payload-only. It does not change event_kind, data_kind, or routing decisions.

The backend is the delivery and persistence side. It:

  1. accepts webhook requests on POST /api/v1/ingest
  2. expects canonical items[] payloads only
  3. normalizes requests into internal delivery objects
  4. enqueues items for retry and batching
  5. maps selected payload fields to downstream metric definitions
  6. sends data through zabbix_sender

Architecture

Agent data flow

DBus Source -----------\
                        \
Runtime Source ---------> Source Filters -> Normalizer <--- Enrichment Snapshot Service
                        /                              |            |
CtrlIface Source ------/                               |            +-> payload.navigation
                                                        v
                                                    Classifier -> NDJSON Serializer -> stdout
                                                        |
                                                        +--> Trigger Engine -> Command Dispatcher
                                                        |
                                                        +--> Delivery Service -> Backend

Backend data flow

HTTP ingest -> Request normalization -> Queue -> Mapper -> Sender
                               |                         |
                               |                         +-> zabbix_sender
                               +-> NDJSON response/log output

Backend stdout logging is batch-oriented:

  • one log record per accepted request batch
  • top-level client metadata is added by the backend
  • accepted items live under batch.items[]

Repository Structure

Agent package

Located in src/wfagent:

  • cli.py - agent CLI entry point
  • config.py - YAML config loader and validators
  • models.py - event, command, and delivery models
  • sources.py - D-Bus, ctrl_iface, and runtime sources
  • pipeline.py - filtering, normalization, classification, serialization, triggering
  • enrichment.py - optional navigation snapshot enrichment service
  • commands.py - command dispatching
  • delivery/ - webhook delivery, queue/spool, and backend integration
  • lifecycle.py - runtime lifecycle handling
  • services.py - clock, correlation IDs, observability
  • payloads/ - payload decoding helpers

Backend package

Located in ../backend/src/wfagent_backend:

Agent Principles

The agent is designed around a single unified event pipeline:

  • sources are transport-specific and lightweight
  • source-specific filters run before normalization
  • runtime events are first-class inputs
  • optional enrichment services can add additive payload context without changing classifier or trigger logic
  • classification decides whether an event is dropped, serialized, or also used for triggering
  • stdout is the only serialization target for events in the agent
  • command execution is separated from command result data
  • every command request targets an explicit destination without fallback routing

Supported event sources

  • D-Bus:
    • fi.w1.wpa_supplicant1
    • fi.w1.wpa_supplicant1.Interface
    • signals such as InterfaceAdded, InterfaceRemoved, and PropertiesChanged
  • ctrl_iface:
    • commands such as STATUS, SCAN, SCAN_RESULTS, BSS, REASSOCIATE, RECONNECT, and TERMINATE
    • unsolicited events after ATTACH, for example CTRL-EVENT-SCAN-RESULTS
  • runtime:
    • start
    • reload
    • stop
    • timer_tick
    • source_down
    • source_up

Backend Principles

The backend is a separate HTTP service with a narrower job:

  • accept deliveries from agents over HTTP
  • validate and normalize canonical payload shapes
  • keep deliveries in memory with retry and TTL policies
  • map normalized payload fields to metric definitions
  • send metrics via zabbix_sender
  • emit structured NDJSON logging if enabled

The backend does not talk to wpa_supplicant directly.

Configuration

Both applications use versioned YAML configuration.

Agent configuration

The agent config is documented in wfagent.example.yaml. The main sections are:

  • runtime - runtime-generated events and timer interval
  • normalization - payload parsing behavior
  • enrichment - optional value-added navigation context refresh and caching
  • delivery - webhook delivery settings for the backend
  • sources - D-Bus, ctrl_iface, and runtime source settings
  • classifier - event classification rules
  • triggers - command trigger rules
  • commands - explicit destination command definitions
  • output - NDJSON serialization target
  • observability - logging and metrics behavior
  • guards - trigger loop and deduplication protection

Key deployment fields:

  • delivery.agent_id - stable logical deployment name
  • delivery.agent_instance_id - unique host/interface identity
  • delivery.webhook.url - backend ingest URL
  • sources.ctrl_iface.socket_path - wpa_supplicant control socket
  • sources.dbus.service - D-Bus service name

Backend configuration

The backend config and ingest contract are documented in ../backend/README.md. Use ../backend/wfagent_backend.example.yaml as the concrete backend example.

Example agent config

The provided wfagent.example.yaml is a practical starting point for a single-host deployment. It enables:

  • D-Bus source
  • ctrl_iface source
  • runtime source
  • webhook delivery to the backend
  • optional navigation-context enrichment is disabled by default and can be enabled under enrichment.navigation

Install

From the repository root:

cd agent
python -m pip install -e .

Install the backend from the backend project directory:

cd backend
python -m pip install -e .

Run

Agent

cd agent
wfagent --config wfagent.example.yaml

or:

cd agent
python -m wfagent --config wfagent.example.yaml

Backend

cd backend
wfagent_backend --config wfagent_backend.example.yaml

Optional overrides:

wfagent_backend --config wfagent_backend.example.yaml --host 127.0.0.1 --port 8080

Deployment

Typical split deployment

  1. Run wfagent from agent/ on the host that has access to wpa_supplicant.
  2. Run wfagent_backend from backend/ on the destination host or on the same host.
  3. Point delivery.webhook.url in the agent config at the backend ingest endpoint.
  4. Keep delivery.agent_id stable across a logical fleet.
  5. Set delivery.agent_instance_id per host or per wireless interface.

Agent deployment notes

  • Install the agent into a virtual environment.
  • Make sure the user running the agent can access the D-Bus system bus and wpa_supplicant control socket.
  • Prefer a dedicated wpa_supplicant interface socket path per interface, for example /var/run/wpa_supplicant/wlp3s0.
  • Use timer_tick_interval_ms conservatively if triggers can cause command loops.

Backend deployment notes

  • Bind the backend to localhost if the agent runs on the same host.
  • Put the backend behind a reverse proxy or private network if it is exposed remotely.
  • Configure zabbix_sender access and credentials at the host level, not in the agent.
  • Increase queue.max_items and queue.item_ttl_ms only if you expect backpressure.

Data Format

NDJSON output from the agent

Each serialized event is written as one JSON object per line.

Example:

{"event_id":"e-1001","source_type":"runtime","source_id":"runtime","event_kind":"start","observed_at_unix_ms":1760000000000,"severity":"info","payload":{"payload":{"state":"start"}}}

Backend ingest contract

The backend accepts canonical batches with items[] and a canonical target object:

  • target.kind
  • target.value

Metric mapping rules can match nested fields with dotted paths such as target.kind and target.value.

The backend adds client itself. It is not expected from the agent payload.

Backend ingest example

Canonical payload:

{
  "batch_id": "del-1",
  "agent_id": "wfagent",
  "agent_instance_id": "wfagent@wlp3s0",
  "sent_at_unix_ms": 1760000000000,
  "items": [
    {
      "item_id": "evt-1",
      "item_kind": "event",
      "source_type": "dbus",
      "source_id": "fi.w1.wpa_supplicant1",
      "event_kind": "properties_changed",
      "observed_at_unix_ms": 1760000000000,
      "target": {
        "kind": "bss",
        "value": "/fi/w1/wpa_supplicant1/Interfaces/0/BSSs/0"
      },
      "data_kind": "properties_changed",
      "payload": {
        "changed": {
          "Signal": -41,
          "Age": 0
        }
      }
    }
  ]
}

Examples

Agent example

The agent directory includes wfagent.example.yaml, which demonstrates:

  • D-Bus source configuration
  • ctrl_iface socket configuration
  • runtime event generation
  • classifier rules
  • trigger rules
  • webhook delivery to the backend

Backend example

The backend directory includes ../backend/wfagent_backend.example.yaml, which demonstrates:

  • HTTP server binding
  • ingest path and health path
  • queue and retry configuration
  • Zabbix sender settings
  • metric mapping from BSS event payloads

Testing

Run the full test suite:

pytest

The default suite is self-contained and does not require a live wpa_supplicant.

Integration tests

The repository also includes live smoke tests for wpa_supplicant integrations.

  • D-Bus tests use the WFAGENT_DBUS_IFNAME environment variable.
  • ctrl_iface tests use the WFAGENT_CTRL_IFACE_SOCKET or WPA_CTRL_IFACE_PATH.

Run them with:

pytest -m integration