Сервис реализован как Python-проект с entrypoint, MQTT consumer на paho-mqtt, mapping engine, обёрткой над zabbix_sender, тестами и примером systemd unit. Основной runtime собран в service.py, правила и типы разнесены по mapping.py, parser.py, sender.py и config.py. Конфиг в r2z-backend.yaml приведён к согласованным value_path, а пример unit-файла лежит в robot2zabbix-backend.service.
Добавлены pyproject.toml, README.md, пакет в src/ и тесты в tests/, включая разбор input/telemetry_31.log, маппинг, батч-отправку и сервисную обработку сообщений. Проверка прошла: python -m pytest -q -> 13 passed. Для запуска на Linux нужен установленный paho-mqtt из зависимостей проекта и доступный в PATH бинарник zabbix_sender.
This commit is contained in:
parent
014417b805
commit
4ce451a6ca
|
|
@ -1,3 +1,7 @@
|
|||
tmp/
|
||||
output/
|
||||
input/
|
||||
.pytest_cache/
|
||||
__pycache__/
|
||||
.venv/
|
||||
*.pyc
|
||||
|
|
|
|||
|
|
@ -0,0 +1,15 @@
|
|||
# robot2zabbix-backend
|
||||
|
||||
Python service that subscribes to MQTT telemetry topics and forwards mapped metrics to Zabbix through `zabbix_sender`.
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
python -m robot2zabbix_backend --config config/r2z-backend.yaml
|
||||
```
|
||||
|
||||
## Tests
|
||||
|
||||
```bash
|
||||
pytest -q
|
||||
```
|
||||
|
|
@ -67,31 +67,31 @@ mapping:
|
|||
metrics:
|
||||
- key: wifi.state.connected
|
||||
host_path: agent_id
|
||||
value_path: payload.payload.connected
|
||||
value_path: payload.connected
|
||||
- key: wifi.state.wpa_state
|
||||
host_path: agent_id
|
||||
value_path: payload.payload.wpa_state
|
||||
value_path: payload.wpa_state
|
||||
- key: wifi.state.ssid
|
||||
host_path: agent_id
|
||||
value_path: payload.payload.ssid
|
||||
value_path: payload.ssid
|
||||
- key: wifi.state.bssid
|
||||
host_path: agent_id
|
||||
value_path: payload.payload.bssid
|
||||
value_path: payload.bssid
|
||||
- key: wifi.state.freq_mhz
|
||||
host_path: agent_id
|
||||
value_path: payload.payload.freq
|
||||
value_path: payload.freq
|
||||
- key: wifi.state.network_id
|
||||
host_path: agent_id
|
||||
value_path: payload.payload.network_id
|
||||
value_path: payload.network_id
|
||||
- key: wifi.state.mode
|
||||
host_path: agent_id
|
||||
value_path: payload.payload.mode
|
||||
value_path: payload.mode
|
||||
- key: wifi.state.ip_address
|
||||
host_path: agent_id
|
||||
value_path: payload.payload.ip_address
|
||||
value_path: payload.ip_address
|
||||
- key: wifi.state.key_mgmt
|
||||
host_path: agent_id
|
||||
value_path: payload.payload.key_mgmt
|
||||
value_path: payload.key_mgmt
|
||||
|
||||
- id: mqtt-wifi-signal
|
||||
# Map Wi-Fi signal messages to signal-quality metrics.
|
||||
|
|
@ -102,25 +102,25 @@ mapping:
|
|||
metrics:
|
||||
- key: wifi.signal.rssi_dbm
|
||||
host_path: agent_id
|
||||
value_path: payload.payload.rssi
|
||||
value_path: payload.rssi
|
||||
- key: wifi.signal.avg_rssi_dbm
|
||||
host_path: agent_id
|
||||
value_path: payload.payload.avg_rssi
|
||||
value_path: payload.avg_rssi
|
||||
- key: wifi.signal.avg_beacon_rssi_dbm
|
||||
host_path: agent_id
|
||||
value_path: payload.payload.avg_beacon_rssi
|
||||
value_path: payload.avg_beacon_rssi
|
||||
- key: wifi.signal.noise_dbm
|
||||
host_path: agent_id
|
||||
value_path: payload.payload.noise
|
||||
value_path: payload.noise
|
||||
- key: wifi.signal.snr_db
|
||||
host_path: agent_id
|
||||
value_path: payload.payload.snr
|
||||
value_path: payload.snr
|
||||
- key: wifi.signal.linkspeed_mbps
|
||||
host_path: agent_id
|
||||
value_path: payload.payload.linkspeed
|
||||
value_path: payload.linkspeed
|
||||
- key: wifi.signal.freq_mhz
|
||||
host_path: agent_id
|
||||
value_path: payload.payload.freq
|
||||
value_path: payload.freq
|
||||
|
||||
#{
|
||||
# "message_id": "cmd-7755693f6c8a4a4bb027493a94bf6c55",
|
||||
|
|
|
|||
|
|
@ -0,0 +1,15 @@
|
|||
[Unit]
|
||||
Description=robot2zabbix backend
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
WorkingDirectory=/opt/robot2zabbix-backend
|
||||
ExecStart=/opt/robot2zabbix-backend/.venv/bin/robot2zabbix-backend --config /etc/robot2zabbix/r2z-backend.yaml
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
EnvironmentFile=-/etc/default/robot2zabbix-backend
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
[build-system]
|
||||
requires = ["setuptools>=68", "wheel"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "robot2zabbix-backend"
|
||||
version = "0.1.0"
|
||||
description = "MQTT to Zabbix adapter for robot Wi-Fi telemetry"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.11"
|
||||
dependencies = [
|
||||
"paho-mqtt>=2.1.0,<3",
|
||||
"PyYAML>=6.0.1,<7",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
test = [
|
||||
"pytest>=8.2,<9",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
robot2zabbix-backend = "robot2zabbix_backend.__main__:main"
|
||||
|
||||
[tool.setuptools]
|
||||
package-dir = {"" = "src"}
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
where = ["src"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
"""robot2zabbix-backend package."""
|
||||
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
|
||||
from .service import run_service
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="MQTT to Zabbix adapter")
|
||||
parser.add_argument("--config", required=True, help="Path to YAML config")
|
||||
parser.add_argument(
|
||||
"--max-workers",
|
||||
type=int,
|
||||
default=4,
|
||||
help="Number of worker threads for MQTT message processing",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
run_service(args.config, max_workers=args.max_workers)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -0,0 +1,111 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
|
||||
from .types import (
|
||||
AppConfig,
|
||||
LoggingConfig,
|
||||
MappingRule,
|
||||
MatchConfig,
|
||||
MetricConfig,
|
||||
MqttConfig,
|
||||
MqttTlsConfig,
|
||||
ZabbixConfig,
|
||||
)
|
||||
|
||||
|
||||
def load_config(path: str | Path) -> AppConfig:
|
||||
config_path = Path(path)
|
||||
data = yaml.safe_load(config_path.read_text(encoding="utf-8"))
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("Config root must be a mapping")
|
||||
|
||||
mqtt_raw = _require_mapping(data, "mqtt")
|
||||
logging_raw = _require_mapping(data, "logging")
|
||||
zabbix_raw = _require_mapping(data, "zabbix")
|
||||
mapping_raw = _require_mapping(data, "mapping")
|
||||
|
||||
tls_raw = _require_mapping(mqtt_raw, "tls")
|
||||
rules_raw = mapping_raw.get("rules", [])
|
||||
if not isinstance(rules_raw, list):
|
||||
raise ValueError("mapping.rules must be a list")
|
||||
|
||||
rules: list[MappingRule] = []
|
||||
for rule_raw in rules_raw:
|
||||
if not isinstance(rule_raw, dict):
|
||||
raise ValueError("Each mapping rule must be a mapping")
|
||||
match_raw = _require_mapping(rule_raw, "match")
|
||||
metrics_raw = rule_raw.get("metrics", [])
|
||||
if not isinstance(metrics_raw, list):
|
||||
raise ValueError("rule.metrics must be a list")
|
||||
metrics = [
|
||||
MetricConfig(
|
||||
key=_require_str(metric_raw, "key"),
|
||||
host_path=_require_str(metric_raw, "host_path"),
|
||||
value_path=_require_str(metric_raw, "value_path"),
|
||||
value_kind=str(metric_raw.get("value_kind", "auto")),
|
||||
)
|
||||
for metric_raw in metrics_raw
|
||||
if isinstance(metric_raw, dict)
|
||||
]
|
||||
rules.append(
|
||||
MappingRule(
|
||||
id=_require_str(rule_raw, "id"),
|
||||
enabled=bool(rule_raw.get("enabled", True)),
|
||||
match=MatchConfig(
|
||||
source_type=_require_str(match_raw, "source_type"),
|
||||
event_kind=match_raw.get("event_kind"),
|
||||
event_kind_in=list(match_raw.get("event_kind_in", [])) or None,
|
||||
),
|
||||
metrics=metrics,
|
||||
)
|
||||
)
|
||||
|
||||
return AppConfig(
|
||||
mqtt=MqttConfig(
|
||||
enabled=bool(mqtt_raw.get("enabled", True)),
|
||||
host=_require_str(mqtt_raw, "host"),
|
||||
port=int(mqtt_raw.get("port", 1883)),
|
||||
topics=_require_mapping(mqtt_raw, "topics"),
|
||||
username=mqtt_raw.get("username"),
|
||||
password=mqtt_raw.get("password"),
|
||||
client_id=_require_str(mqtt_raw, "client_id"),
|
||||
site_id=mqtt_raw.get("site_id"),
|
||||
keepalive_sec=int(mqtt_raw.get("keepalive_sec", 60)),
|
||||
clean_session=bool(mqtt_raw.get("clean_session", True)),
|
||||
tls=MqttTlsConfig(
|
||||
enabled=bool(tls_raw.get("enabled", False)),
|
||||
ca_file=tls_raw.get("ca_file"),
|
||||
cert_file=tls_raw.get("cert_file"),
|
||||
key_file=tls_raw.get("key_file"),
|
||||
),
|
||||
),
|
||||
logging=LoggingConfig(
|
||||
emit_ndjson=bool(logging_raw.get("emit_ndjson", False)),
|
||||
log_level=str(logging_raw.get("log_level", "INFO")),
|
||||
),
|
||||
zabbix=ZabbixConfig(
|
||||
sender_path=_require_str(zabbix_raw, "sender_path"),
|
||||
server_host=_require_str(zabbix_raw, "server_host"),
|
||||
server_port=int(zabbix_raw.get("server_port", 10051)),
|
||||
timeout_ms=int(zabbix_raw.get("timeout_ms", 3000)),
|
||||
extra_args=[str(value) for value in zabbix_raw.get("extra_args", [])],
|
||||
),
|
||||
mapping_rules=rules,
|
||||
)
|
||||
|
||||
|
||||
def _require_mapping(data: dict, key: str) -> dict:
|
||||
value = data.get(key)
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError(f"{key} must be a mapping")
|
||||
return value
|
||||
|
||||
|
||||
def _require_str(data: dict, key: str) -> str:
|
||||
value = data.get(key)
|
||||
if not isinstance(value, str) or not value:
|
||||
raise ValueError(f"{key} must be a non-empty string")
|
||||
return value
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
from typing import Any
|
||||
|
||||
|
||||
def configure_logging(level: str, emit_ndjson: bool) -> None:
|
||||
logging.basicConfig(
|
||||
level=getattr(logging, level.upper(), logging.INFO),
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
stream=sys.stdout,
|
||||
)
|
||||
if emit_ndjson:
|
||||
logging.getLogger("robot2zabbix_backend.ndjson").setLevel(logging.INFO)
|
||||
|
||||
|
||||
def emit_ndjson(event_type: str, payload: dict[str, Any]) -> None:
|
||||
logger = logging.getLogger("robot2zabbix_backend.ndjson")
|
||||
logger.info(
|
||||
json.dumps(
|
||||
{"event_type": event_type, **payload},
|
||||
ensure_ascii=False,
|
||||
separators=(",", ":"),
|
||||
)
|
||||
)
|
||||
|
|
@ -0,0 +1,78 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from .types import MappedMetric, MappingRule, MetricConfig, NormalizedMqttEvent
|
||||
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def map_event_to_metrics(
|
||||
event: NormalizedMqttEvent,
|
||||
rules: list[MappingRule],
|
||||
) -> list[MappedMetric]:
|
||||
metrics: list[MappedMetric] = []
|
||||
for rule in rules:
|
||||
if not rule.enabled or not _matches(rule, event):
|
||||
continue
|
||||
for metric_cfg in rule.metrics:
|
||||
try:
|
||||
host = _resolve_path(event, metric_cfg.host_path)
|
||||
value = _resolve_path(event, metric_cfg.value_path)
|
||||
except KeyError as exc:
|
||||
LOGGER.warning(
|
||||
"Skipping metric because path is missing",
|
||||
extra={
|
||||
"rule_id": rule.id,
|
||||
"metric_key": metric_cfg.key,
|
||||
"topic": event.topic,
|
||||
"message_id": event.message_id,
|
||||
"missing_path": str(exc),
|
||||
},
|
||||
)
|
||||
continue
|
||||
metrics.append(
|
||||
MappedMetric(
|
||||
host=str(host),
|
||||
key=metric_cfg.key,
|
||||
value=_normalize_value(value, metric_cfg),
|
||||
value_kind=metric_cfg.value_kind,
|
||||
)
|
||||
)
|
||||
return metrics
|
||||
|
||||
|
||||
def _matches(rule: MappingRule, event: NormalizedMqttEvent) -> bool:
|
||||
if rule.match.source_type != event.source_type:
|
||||
return False
|
||||
if rule.match.event_kind is not None:
|
||||
return rule.match.event_kind == event.event_kind
|
||||
if rule.match.event_kind_in is not None:
|
||||
return event.event_kind in rule.match.event_kind_in
|
||||
return True
|
||||
|
||||
|
||||
def _resolve_path(event: NormalizedMqttEvent, path: str) -> Any:
|
||||
current: Any = event
|
||||
for part in path.split("."):
|
||||
if isinstance(current, dict):
|
||||
if part not in current:
|
||||
raise KeyError(path)
|
||||
current = current[part]
|
||||
continue
|
||||
if isinstance(current, NormalizedMqttEvent) and part in current.payload:
|
||||
current = current.payload[part]
|
||||
continue
|
||||
if not hasattr(current, part):
|
||||
raise KeyError(path)
|
||||
current = getattr(current, part)
|
||||
return current
|
||||
|
||||
|
||||
def _normalize_value(value: Any, metric_cfg: MetricConfig) -> Any:
|
||||
if metric_cfg.value_kind == "text" and not isinstance(value, str):
|
||||
return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
|
||||
return value
|
||||
|
|
@ -0,0 +1,64 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import asdict
|
||||
from typing import Any
|
||||
|
||||
from .types import NormalizedMqttEvent
|
||||
|
||||
|
||||
TOPIC_PREFIX = "wifi"
|
||||
|
||||
|
||||
def parse_topic(topic: str) -> tuple[str, str, str]:
|
||||
parts = topic.split("/")
|
||||
if len(parts) != 4 or parts[0] != TOPIC_PREFIX:
|
||||
raise ValueError(f"Unsupported topic format: {topic}")
|
||||
return parts[1], parts[2], parts[3]
|
||||
|
||||
|
||||
def parse_mqtt_message(topic: str, payload_bytes: bytes) -> NormalizedMqttEvent:
|
||||
site_id, agent_instance_id, event_kind = parse_topic(topic)
|
||||
|
||||
try:
|
||||
wrapper = json.loads(payload_bytes.decode("utf-8"))
|
||||
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
||||
raise ValueError(f"Invalid MQTT wrapper payload: {exc}") from exc
|
||||
if not isinstance(wrapper, dict):
|
||||
raise ValueError("MQTT wrapper payload must be a JSON object")
|
||||
|
||||
raw_data = wrapper.get("data")
|
||||
if not isinstance(raw_data, str):
|
||||
raise ValueError("MQTT wrapper payload must contain string field 'data'")
|
||||
|
||||
try:
|
||||
payload = json.loads(raw_data)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ValueError(f"Invalid MQTT inner payload: {exc}") from exc
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError("MQTT inner payload must be a JSON object")
|
||||
|
||||
return NormalizedMqttEvent(
|
||||
source_type="mqtt",
|
||||
topic=topic,
|
||||
site_id=site_id,
|
||||
agent_instance_id=agent_instance_id,
|
||||
event_kind=event_kind,
|
||||
payload=payload,
|
||||
message_id=_get_optional_string(payload, "message_id"),
|
||||
observed_at_unix_ms=_get_optional_int(payload, "observed_at_unix_ms"),
|
||||
)
|
||||
|
||||
|
||||
def event_to_log_dict(event: NormalizedMqttEvent) -> dict[str, Any]:
|
||||
return asdict(event)
|
||||
|
||||
|
||||
def _get_optional_string(data: dict[str, Any], key: str) -> str | None:
|
||||
value = data.get(key)
|
||||
return value if isinstance(value, str) else None
|
||||
|
||||
|
||||
def _get_optional_int(data: dict[str, Any], key: str) -> int | None:
|
||||
value = data.get(key)
|
||||
return value if isinstance(value, int) else None
|
||||
|
|
@ -0,0 +1,78 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from .types import MappedMetric, ZabbixConfig
|
||||
|
||||
|
||||
class ZabbixSenderError(RuntimeError):
|
||||
"""Raised when zabbix_sender fails."""
|
||||
|
||||
|
||||
class ZabbixSender:
|
||||
def __init__(self, config: ZabbixConfig) -> None:
|
||||
self._config = config
|
||||
|
||||
def send(self, metrics: list[MappedMetric]) -> subprocess.CompletedProcess[str] | None:
|
||||
if not metrics:
|
||||
return None
|
||||
|
||||
with tempfile.NamedTemporaryFile(
|
||||
mode="w",
|
||||
encoding="utf-8",
|
||||
suffix=".txt",
|
||||
delete=False,
|
||||
) as handle:
|
||||
payload_path = Path(handle.name)
|
||||
for metric in metrics:
|
||||
handle.write(_format_line(metric))
|
||||
handle.write("\n")
|
||||
|
||||
cmd = [
|
||||
self._config.sender_path,
|
||||
"-z",
|
||||
self._config.server_host,
|
||||
"-p",
|
||||
str(self._config.server_port),
|
||||
"-T",
|
||||
"-i",
|
||||
str(payload_path),
|
||||
*self._config.extra_args,
|
||||
]
|
||||
try:
|
||||
result = subprocess.run(
|
||||
cmd,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=self._config.timeout_ms / 1000,
|
||||
check=False,
|
||||
)
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
raise ZabbixSenderError("zabbix_sender timed out") from exc
|
||||
finally:
|
||||
payload_path.unlink(missing_ok=True)
|
||||
|
||||
if result.returncode != 0:
|
||||
raise ZabbixSenderError(
|
||||
f"zabbix_sender failed with code {result.returncode}: {result.stderr.strip()}"
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def _format_line(metric: MappedMetric) -> str:
|
||||
value = metric.value
|
||||
if isinstance(value, bool):
|
||||
value = int(value)
|
||||
if isinstance(value, (dict, list)):
|
||||
value = json.dumps(value, ensure_ascii=False, separators=(",", ":"))
|
||||
return f"{metric.host} {metric.key} {_quote_value(value)}"
|
||||
|
||||
|
||||
def _quote_value(value: object) -> str:
|
||||
if isinstance(value, str):
|
||||
escaped = value.replace("\\", "\\\\").replace('"', '\\"')
|
||||
return f'"{escaped}"'
|
||||
return str(value)
|
||||
|
|
@ -0,0 +1,212 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import signal
|
||||
import ssl
|
||||
import threading
|
||||
from concurrent.futures import Future, ThreadPoolExecutor
|
||||
from typing import Any
|
||||
|
||||
try:
|
||||
import paho.mqtt.client as mqtt
|
||||
except ModuleNotFoundError: # pragma: no cover - exercised in test environments without optional deps
|
||||
mqtt = None
|
||||
|
||||
from .config import load_config
|
||||
from .logging_utils import configure_logging, emit_ndjson
|
||||
from .mapping import map_event_to_metrics
|
||||
from .parser import event_to_log_dict, parse_mqtt_message
|
||||
from .sender import ZabbixSender, ZabbixSenderError
|
||||
from .types import AppConfig
|
||||
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Robot2ZabbixService:
|
||||
def __init__(self, config: AppConfig, max_workers: int = 4, client: Any | None = None) -> None:
|
||||
self._config = config
|
||||
self._sender = ZabbixSender(config.zabbix)
|
||||
self._executor = ThreadPoolExecutor(max_workers=max_workers, thread_name_prefix="r2z")
|
||||
self._stop_event = threading.Event()
|
||||
self._client = client or self._build_client()
|
||||
self._futures: set[Future[Any]] = set()
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def run(self) -> None:
|
||||
if not self._config.mqtt.enabled:
|
||||
raise RuntimeError("MQTT ingestion is disabled in config")
|
||||
|
||||
self._install_signal_handlers()
|
||||
self._connect()
|
||||
self._client.loop_start()
|
||||
LOGGER.info("Service started")
|
||||
|
||||
try:
|
||||
self._stop_event.wait()
|
||||
finally:
|
||||
self.stop()
|
||||
|
||||
def stop(self) -> None:
|
||||
if self._stop_event.is_set():
|
||||
pass
|
||||
else:
|
||||
self._stop_event.set()
|
||||
try:
|
||||
self._client.loop_stop()
|
||||
self._client.disconnect()
|
||||
except Exception:
|
||||
LOGGER.exception("Failed to stop MQTT client cleanly")
|
||||
self._executor.shutdown(wait=True, cancel_futures=False)
|
||||
LOGGER.info("Service stopped")
|
||||
|
||||
def _build_client(self) -> Any:
|
||||
if mqtt is None:
|
||||
raise RuntimeError("paho-mqtt is required to run the service")
|
||||
client = mqtt.Client(
|
||||
callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
|
||||
client_id=self._config.mqtt.client_id,
|
||||
clean_session=self._config.mqtt.clean_session,
|
||||
)
|
||||
if self._config.mqtt.username:
|
||||
client.username_pw_set(self._config.mqtt.username, self._config.mqtt.password)
|
||||
if self._config.mqtt.tls.enabled:
|
||||
client.tls_set(
|
||||
ca_certs=self._config.mqtt.tls.ca_file,
|
||||
certfile=self._config.mqtt.tls.cert_file,
|
||||
keyfile=self._config.mqtt.tls.key_file,
|
||||
tls_version=ssl.PROTOCOL_TLS_CLIENT,
|
||||
)
|
||||
|
||||
client.on_connect = self._on_connect
|
||||
client.on_message = self._on_message
|
||||
client.on_disconnect = self._on_disconnect
|
||||
return client
|
||||
|
||||
def _connect(self) -> None:
|
||||
self._client.connect(
|
||||
self._config.mqtt.host,
|
||||
self._config.mqtt.port,
|
||||
self._config.mqtt.keepalive_sec,
|
||||
)
|
||||
|
||||
def _install_signal_handlers(self) -> None:
|
||||
signal.signal(signal.SIGINT, self._handle_stop_signal)
|
||||
signal.signal(signal.SIGTERM, self._handle_stop_signal)
|
||||
|
||||
def _handle_stop_signal(self, signum: int, _frame: object) -> None:
|
||||
LOGGER.info("Received stop signal", extra={"signal": signum})
|
||||
self._stop_event.set()
|
||||
|
||||
def _on_connect(
|
||||
self,
|
||||
client: Any,
|
||||
_userdata: object,
|
||||
_flags: dict[str, Any],
|
||||
reason_code: Any,
|
||||
_properties: Any,
|
||||
) -> None:
|
||||
if reason_code.is_failure:
|
||||
LOGGER.error("MQTT connect failed: %s", reason_code)
|
||||
return
|
||||
|
||||
topics = _expand_topics(self._config)
|
||||
for topic in topics:
|
||||
client.subscribe(topic)
|
||||
LOGGER.info("Subscribed to topic %s", topic)
|
||||
|
||||
def _on_disconnect(
|
||||
self,
|
||||
_client: Any,
|
||||
_userdata: object,
|
||||
_disconnect_flags: Any,
|
||||
reason_code: Any,
|
||||
_properties: Any,
|
||||
) -> None:
|
||||
if self._stop_event.is_set():
|
||||
return
|
||||
LOGGER.warning("MQTT disconnected: %s", reason_code)
|
||||
|
||||
def _on_message(
|
||||
self,
|
||||
_client: Any,
|
||||
_userdata: object,
|
||||
message: Any,
|
||||
) -> None:
|
||||
future = self._executor.submit(self._process_message, message.topic, bytes(message.payload))
|
||||
with self._lock:
|
||||
self._futures.add(future)
|
||||
future.add_done_callback(self._on_future_done)
|
||||
|
||||
def _on_future_done(self, future: Future[Any]) -> None:
|
||||
with self._lock:
|
||||
self._futures.discard(future)
|
||||
try:
|
||||
future.result()
|
||||
except Exception:
|
||||
LOGGER.exception("Worker failed")
|
||||
|
||||
def _process_message(self, topic: str, payload_bytes: bytes) -> None:
|
||||
try:
|
||||
event = parse_mqtt_message(topic, payload_bytes)
|
||||
except ValueError as exc:
|
||||
LOGGER.warning("Skipping invalid MQTT message: %s", exc)
|
||||
return
|
||||
|
||||
metrics = map_event_to_metrics(event, self._config.mapping_rules)
|
||||
if self._config.logging.emit_ndjson:
|
||||
emit_ndjson(
|
||||
"mqtt_message",
|
||||
{
|
||||
"event": event_to_log_dict(event),
|
||||
"metric_count": len(metrics),
|
||||
},
|
||||
)
|
||||
|
||||
if not metrics:
|
||||
LOGGER.info("No metrics matched message topic=%s message_id=%s", topic, event.message_id)
|
||||
return
|
||||
|
||||
try:
|
||||
result = self._sender.send(metrics)
|
||||
except ZabbixSenderError as exc:
|
||||
LOGGER.error(
|
||||
"Failed to send metrics to Zabbix: %s",
|
||||
exc,
|
||||
extra={"topic": topic, "message_id": event.message_id},
|
||||
)
|
||||
return
|
||||
|
||||
LOGGER.info(
|
||||
"Sent %s metrics to Zabbix for topic=%s message_id=%s",
|
||||
len(metrics),
|
||||
topic,
|
||||
event.message_id,
|
||||
)
|
||||
if self._config.logging.emit_ndjson and result is not None:
|
||||
emit_ndjson(
|
||||
"zabbix_send",
|
||||
{
|
||||
"topic": topic,
|
||||
"message_id": event.message_id,
|
||||
"metric_count": len(metrics),
|
||||
"stdout": result.stdout.strip(),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _expand_topics(config: AppConfig) -> list[str]:
|
||||
result: list[str] = []
|
||||
for name, template in config.mqtt.topics.items():
|
||||
if name == "base":
|
||||
continue
|
||||
topic = template.format(base="wifi/+/+", site_id="+", agent_instance_id="+")
|
||||
result.append(topic)
|
||||
return sorted(set(result))
|
||||
|
||||
|
||||
def run_service(config_path: str, max_workers: int = 4) -> None:
|
||||
config = load_config(config_path)
|
||||
configure_logging(config.logging.log_level, config.logging.emit_ndjson)
|
||||
service = Robot2ZabbixService(config=config, max_workers=max_workers)
|
||||
service.run()
|
||||
|
|
@ -0,0 +1,93 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class MatchConfig:
|
||||
source_type: str
|
||||
event_kind: str | None = None
|
||||
event_kind_in: list[str] | None = None
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class MetricConfig:
|
||||
key: str
|
||||
host_path: str
|
||||
value_path: str
|
||||
value_kind: str = "auto"
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class MappingRule:
|
||||
id: str
|
||||
enabled: bool
|
||||
match: MatchConfig
|
||||
metrics: list[MetricConfig]
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class MqttTlsConfig:
|
||||
enabled: bool
|
||||
ca_file: str | None
|
||||
cert_file: str | None
|
||||
key_file: str | None
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class MqttConfig:
|
||||
enabled: bool
|
||||
host: str
|
||||
port: int
|
||||
topics: dict[str, str]
|
||||
username: str | None
|
||||
password: str | None
|
||||
client_id: str
|
||||
site_id: str | None
|
||||
keepalive_sec: int
|
||||
clean_session: bool
|
||||
tls: MqttTlsConfig
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class LoggingConfig:
|
||||
emit_ndjson: bool
|
||||
log_level: str
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class ZabbixConfig:
|
||||
sender_path: str
|
||||
server_host: str
|
||||
server_port: int
|
||||
timeout_ms: int
|
||||
extra_args: list[str]
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class AppConfig:
|
||||
mqtt: MqttConfig
|
||||
logging: LoggingConfig
|
||||
zabbix: ZabbixConfig
|
||||
mapping_rules: list[MappingRule]
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class NormalizedMqttEvent:
|
||||
source_type: str
|
||||
topic: str
|
||||
site_id: str
|
||||
agent_instance_id: str
|
||||
event_kind: str
|
||||
payload: dict[str, Any]
|
||||
message_id: str | None
|
||||
observed_at_unix_ms: int | None
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class MappedMetric:
|
||||
host: str
|
||||
key: str
|
||||
value: Any
|
||||
value_kind: str = "auto"
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SRC = ROOT / "src"
|
||||
if str(SRC) not in sys.path:
|
||||
sys.path.insert(0, str(SRC))
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from robot2zabbix_backend.config import load_config
|
||||
from robot2zabbix_backend.mapping import map_event_to_metrics
|
||||
from robot2zabbix_backend.parser import parse_mqtt_message
|
||||
|
||||
|
||||
def test_mapping_applies_to_sample_log() -> None:
|
||||
config = load_config("config/r2z-backend.yaml")
|
||||
lines = Path("input/telemetry_31.log").read_text(encoding="utf-8").splitlines()
|
||||
|
||||
total_metrics = 0
|
||||
for line in lines:
|
||||
topic, raw_payload = line.split(" ", 1)
|
||||
event = parse_mqtt_message(topic, raw_payload.encode("utf-8"))
|
||||
metrics = map_event_to_metrics(event, config.mapping_rules)
|
||||
total_metrics += len(metrics)
|
||||
|
||||
assert len(lines) == 7
|
||||
assert total_metrics == 49
|
||||
|
||||
|
||||
def test_text_metric_is_serialized() -> None:
|
||||
config = load_config("config/r2z-backend.yaml")
|
||||
wrapper = {
|
||||
"data": json.dumps(
|
||||
{
|
||||
"message_id": "scan",
|
||||
"agent_id": "agent-1",
|
||||
"payload": {"scan_results": [{"ssid": "A"}]},
|
||||
}
|
||||
)
|
||||
}
|
||||
event = parse_mqtt_message("wifi/vostok/31/scan_results", json.dumps(wrapper).encode())
|
||||
metrics = map_event_to_metrics(event, config.mapping_rules)
|
||||
scan_metric = next(metric for metric in metrics if metric.key == "wifi.scan.results")
|
||||
assert scan_metric.value == '[{"ssid":"A"}]'
|
||||
|
||||
|
||||
def test_missing_path_skips_single_metric() -> None:
|
||||
config = load_config("config/r2z-backend.yaml")
|
||||
wrapper = {
|
||||
"data": json.dumps(
|
||||
{
|
||||
"message_id": "state",
|
||||
"agent_id": "agent-1",
|
||||
"payload": {"connected": 1},
|
||||
}
|
||||
)
|
||||
}
|
||||
event = parse_mqtt_message("wifi/vostok/31/wifi_state", json.dumps(wrapper).encode())
|
||||
metrics = map_event_to_metrics(event, config.mapping_rules)
|
||||
assert any(metric.key == "wifi.state.connected" for metric in metrics)
|
||||
assert all(metric.key != "wifi.state.ssid" for metric in metrics)
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from robot2zabbix_backend.parser import parse_mqtt_message, parse_topic
|
||||
|
||||
|
||||
def test_parse_topic_success() -> None:
|
||||
assert parse_topic("wifi/vostok/31/wifi_state") == ("vostok", "31", "wifi_state")
|
||||
|
||||
|
||||
def test_parse_topic_failure() -> None:
|
||||
with pytest.raises(ValueError):
|
||||
parse_topic("broken/topic")
|
||||
|
||||
|
||||
def test_parse_mqtt_message_success() -> None:
|
||||
payload = {
|
||||
"schema_version": "1.1",
|
||||
"message_id": "abc",
|
||||
"observed_at_unix_ms": 123,
|
||||
"payload": {"connected": 1},
|
||||
}
|
||||
wrapper = {"data": json.dumps(payload)}
|
||||
event = parse_mqtt_message("wifi/vostok/31/wifi_state", json.dumps(wrapper).encode())
|
||||
assert event.site_id == "vostok"
|
||||
assert event.agent_instance_id == "31"
|
||||
assert event.payload["payload"]["connected"] == 1
|
||||
|
||||
|
||||
def test_parse_mqtt_message_invalid_outer_json() -> None:
|
||||
with pytest.raises(ValueError):
|
||||
parse_mqtt_message("wifi/vostok/31/wifi_state", b"{")
|
||||
|
||||
|
||||
def test_parse_mqtt_message_invalid_inner_json() -> None:
|
||||
wrapper = {"data": "{"}
|
||||
with pytest.raises(ValueError):
|
||||
parse_mqtt_message("wifi/vostok/31/wifi_state", json.dumps(wrapper).encode())
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from robot2zabbix_backend.sender import ZabbixSender, ZabbixSenderError
|
||||
from robot2zabbix_backend.types import MappedMetric, ZabbixConfig
|
||||
|
||||
|
||||
def make_config() -> ZabbixConfig:
|
||||
return ZabbixConfig(
|
||||
sender_path="zabbix_sender",
|
||||
server_host="127.0.0.1",
|
||||
server_port=10051,
|
||||
timeout_ms=3000,
|
||||
extra_args=[],
|
||||
)
|
||||
|
||||
|
||||
def test_sender_batches_metrics_in_single_call() -> None:
|
||||
sender = ZabbixSender(make_config())
|
||||
metrics = [
|
||||
MappedMetric(host="h1", key="a", value=1),
|
||||
MappedMetric(host="h1", key="b", value="text"),
|
||||
]
|
||||
completed = subprocess.CompletedProcess(args=["zabbix_sender"], returncode=0, stdout="ok", stderr="")
|
||||
with patch("robot2zabbix_backend.sender.subprocess.run", return_value=completed) as run_mock:
|
||||
result = sender.send(metrics)
|
||||
assert result is completed
|
||||
assert run_mock.call_count == 1
|
||||
|
||||
|
||||
def test_sender_raises_on_nonzero_exit() -> None:
|
||||
sender = ZabbixSender(make_config())
|
||||
metrics = [MappedMetric(host="h1", key="a", value=1)]
|
||||
completed = subprocess.CompletedProcess(args=["zabbix_sender"], returncode=1, stdout="", stderr="boom")
|
||||
with patch("robot2zabbix_backend.sender.subprocess.run", return_value=completed):
|
||||
with pytest.raises(ZabbixSenderError):
|
||||
sender.send(metrics)
|
||||
|
||||
|
||||
def test_sender_raises_on_timeout() -> None:
|
||||
sender = ZabbixSender(make_config())
|
||||
metrics = [MappedMetric(host="h1", key="a", value=1)]
|
||||
with patch(
|
||||
"robot2zabbix_backend.sender.subprocess.run",
|
||||
side_effect=subprocess.TimeoutExpired(cmd=["zabbix_sender"], timeout=3),
|
||||
):
|
||||
with pytest.raises(ZabbixSenderError):
|
||||
sender.send(metrics)
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from robot2zabbix_backend.config import load_config
|
||||
from robot2zabbix_backend.service import Robot2ZabbixService, _expand_topics
|
||||
|
||||
|
||||
def test_expand_topics_uses_wildcards() -> None:
|
||||
config = load_config("config/r2z-backend.yaml")
|
||||
topics = _expand_topics(config)
|
||||
assert "wifi/+/+/wifi_state" in topics
|
||||
assert "wifi/+/+/wifi_signal" in topics
|
||||
|
||||
|
||||
def test_process_message_sends_metrics() -> None:
|
||||
config = load_config("config/r2z-backend.yaml")
|
||||
client = MagicMock()
|
||||
service = Robot2ZabbixService(config, max_workers=1, client=client)
|
||||
service._sender = MagicMock()
|
||||
service._sender.send.return_value = subprocess.CompletedProcess(
|
||||
args=["zabbix_sender"], returncode=0, stdout="processed: 11", stderr=""
|
||||
)
|
||||
|
||||
wrapper = {
|
||||
"data": json.dumps(
|
||||
{
|
||||
"message_id": "state-1",
|
||||
"agent_id": "agent-1",
|
||||
"payload": {
|
||||
"connected": 1,
|
||||
"wpa_state": "COMPLETED",
|
||||
"ssid": "ssid",
|
||||
"bssid": "bssid",
|
||||
"freq": 1,
|
||||
"network_id": 0,
|
||||
"mode": "station",
|
||||
"ip_address": "1.1.1.1",
|
||||
"key_mgmt": "FT-PSK",
|
||||
"location": {"x": 1, "y": 2},
|
||||
},
|
||||
}
|
||||
)
|
||||
}
|
||||
service._process_message("wifi/vostok/31/wifi_state", json.dumps(wrapper).encode())
|
||||
|
||||
assert service._sender.send.call_count == 1
|
||||
Loading…
Reference in New Issue