feat(zabbix): a native Zabbix agent on both drivers through ZabbixAgentMixin (NetOrk/netork#2571) #69

Merged
christianmanivong merged 1 commits from feat/zabbix-agent-native into main 2026-11-17 04:32:24 +00:00
8 changed files with 241 additions and 9 deletions

No files matched your search

+10 -1
View File
@@ -8,6 +8,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
- A native Zabbix agent on both drivers (napalm-device-types `ZabbixAgentMixin`,
NetOrk/netork#2571): a node runs no container engine. `configure_zabbix_agent(settings)`
installs Debian's `zabbix-agent`, and where Debian has none and the caller names the
server's release line, Zabbix's from its repository; writes the caller's values into
`/etc/zabbix/zabbix_agentd.conf` (the old file stays as `.bak`); opens tcp/`listen_port`
in ufw where the node has it (pve-firewall's rules are the operator's); enables and
restarts the service.
- Time sync on both drivers (NetOrk/netork#2365), through napalm-device-types'
`TimeSyncMixin` (4.36.0); both write the servers and the zone. Neither API keeps time
servers -- both products run chrony on Debian -- so `get_time_sync()` reads chrony's
@@ -46,7 +53,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
in its own daemons; `get_clusters()` and `get_backup_jobs()` keep them.
### Changed
- Requires napalm-device-types 4.36.0.
- Needs napalm-device-types 4.40.0 or later (`ZabbixAgentMixin`).
- The SNMP agent's ufw step is the shared `_allow_sources(allowed, port, proto)`; the rule
it writes for udp/161 is the same.
### Fixed
- `set_hostname()` hands the name to the shell quoted (`shlex.quote`): to `hostname`, to
+2
View File
@@ -44,6 +44,7 @@ from napalm_proxmox.pbs_host import ProxmoxPbsHostMixin
from napalm_proxmox.running_backups import PbsRunningBackupsMixin
from napalm_proxmox.scheduled_jobs import PBS_PLATFORM_SOURCES, ProxmoxScheduledJobsMixin
from napalm_proxmox.time_sync import ProxmoxTimeSyncMixin
from napalm_proxmox.zabbix_agent import ProxmoxZabbixAgentMixin
logger = logging.getLogger(__name__)
@@ -69,6 +70,7 @@ class ProxmoxBackupDriver(
ProxmoxScheduledJobsMixin,
HostStatusMixin,
LicenseMixin,
ProxmoxZabbixAgentMixin,
EnsurePackageMixin,
AptProxyMixin,
OpenSshServerMixin,
+2
View File
@@ -65,6 +65,7 @@ from napalm_proxmox.vm_migrate_mixin import ProxmoxVMMigrateMixin
from napalm_proxmox.vm_mixin import ProxmoxVMMixin
from napalm_proxmox.vm_provision_mixin import ProxmoxVMProvisionMixin
from napalm_proxmox.vm_snapshot_mixin import ProxmoxVMSnapshotMixin
from napalm_proxmox.zabbix_agent import ProxmoxZabbixAgentMixin
logger = logging.getLogger(__name__)
@@ -105,6 +106,7 @@ class ProxmoxDriver(
HostStatusMixin,
LicenseMixin,
SnmpAgentMixin,
ProxmoxZabbixAgentMixin,
EnsurePackageMixin,
AptProxyMixin,
OpenSshServerMixin,
+11
View File
@@ -231,6 +231,17 @@ class ProxmoxHostMixin:
def _write_apt_file(self, path: str, content: str) -> FixStepOutcomeDict:
return self._write_root_file(path, content)
def _allow_sources(self, allowed: list[str], port: int, proto: str) -> FixStepOutcomeDict:
"""Open *proto*/*port* in ufw for *allowed*; ``ok`` with nothing to do for no
sources or no ufw -- pve-firewall's rules are the operator's."""
sources = [str(ipaddress.ip_network(s.strip(), strict=False)) for s in allowed]
if not sources:
return {"ok": True, "output": "no sources given; firewall unchanged"}
if self._rc("command -v ufw")[1] != 0:
return {"ok": True, "output": "no ufw; pve-firewall rules are the operator's"}
rules = " && ".join(f"ufw allow from {s} to any port {port} proto {proto}" for s in sources)
return self._step(rules, f"{proto}/{port} open for {', '.join(sources)}")
def _write_root_file(self, path: str, content: str) -> FixStepOutcomeDict:
"""Write *content* to *path* as root, mode 644, through a temporary file."""
encoded = base64.b64encode(content.encode()).decode()
+1 -7
View File
@@ -362,13 +362,7 @@ class ProxmoxSystemMixin:
return self._write_root_file(_SNMPD_CONF, render_snmpd_conf(settings))
def _allow_snmp_sources(self, settings: dict) -> dict:
sources = [_net(s) for s in settings.get("allowed_sources", [])]
if not sources:
return {"ok": True, "output": "no sources given; firewall unchanged"}
if self._rc("command -v ufw")[1] != 0:
return {"ok": True, "output": "no ufw; pve-firewall rules are the operator's"}
rules = " && ".join(f"ufw allow from {s} to any port 161 proto udp" for s in sources)
return self._step(rules, f"udp/161 open for {', '.join(sources)}")
return dict(self._allow_sources(settings.get("allowed_sources", []), 161, "udp"))
def _start_snmp_agent(self) -> dict:
return self._step(
+68
View File
@@ -0,0 +1,68 @@
"""A native Zabbix agent on a Proxmox node: napalm-device-types' ``ZabbixAgentMixin``.
A node runs no container engine (NetOrk/netork#2571). The template installs Debian's
``zabbix-agent`` -- or, where Debian has none, Zabbix's from its repository -- and
enables and restarts it. This writes the caller's values into
``/etc/zabbix/zabbix_agentd.conf`` and opens tcp/``listen_port`` in ufw where the node
has it; pve-firewall's rules are the operator's, as for the SNMP agent. The node's
shell runs as root.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from napalm_device_types import (
FixStepOutcomeDict,
ZabbixAgentMixin,
ZabbixAgentSettingsDict,
zabbix_agent_config,
zabbix_repository_command,
)
CONFIG = "/etc/zabbix/zabbix_agentd.conf"
class ProxmoxZabbixAgentMixin(ZabbixAgentMixin):
"""``zabbix-agent`` from Debian, or else from Zabbix's repository."""
def _add_zabbix_repository(self, release: str) -> FixStepOutcomeDict:
os_release, status = self._rc("cat /etc/os-release")
if status != 0:
return {"ok": False, "output": f"reading /etc/os-release: {os_release[-300:]}"}
try:
command = zabbix_repository_command(os_release, release)
except ValueError as exc:
return {"ok": False, "output": str(exc)}
return self._step(command, f"Zabbix {release} repository added")
def _write_zabbix_agent_config(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict:
text, status = self._rc(f"cat {CONFIG}")
if status != 0:
return {"ok": False, "output": f"reading {CONFIG}: {text[-300:]}"}
# _rc strips the output; the file ends with a newline.
new, changes = zabbix_agent_config(f"{text}\n", settings)
if not changes:
return {"ok": True, "output": f"{CONFIG} already says it"}
kept = self._step(f"cp -p {CONFIG} {CONFIG}.bak", "")
if not kept["ok"]:
return kept
written = self._write_root_file(CONFIG, new)
if not written["ok"]:
return written
return {"ok": True, "output": "; ".join(changes)}
def _allow_zabbix_agent_sources(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict:
return self._allow_sources(settings["allowed_sources"], int(settings["listen_port"]), "tcp")
if TYPE_CHECKING: # pragma: no cover - ProxmoxHostMixin's
def _rc(self, command: str) -> tuple[str, int]: ...
def _step(self, command: str, done: str) -> FixStepOutcomeDict: ...
def _write_root_file(self, path: str, content: str) -> FixStepOutcomeDict: ...
def _allow_sources(
self, allowed: list[str], port: int, proto: str
) -> FixStepOutcomeDict: ...
+1 -1
View File
@@ -21,7 +21,7 @@ classifiers = [
requires-python = ">=3.12"
dependencies = [
"napalm>=5.0.0",
"napalm_device_types>=4.36.0", # TimeSyncMixin, PosixTimeSyncMixin (DHCP's servers)
"napalm_device_types>=4.40.0", # ZabbixAgentMixin
"paramiko>=5.0.0", # CVE-2026-44405; imported directly for the node's SSH session (_base.py)
"proxmoxer>=2.0.0",
"netaddr>=0.9.0",
+146
View File
@@ -0,0 +1,146 @@
"""configure_zabbix_agent on a Proxmox node (NetOrk/netork#2571).
A node runs no container engine, so the agent cannot run as a container there. The
template installs Debian's ``zabbix-agent`` -- or Zabbix's, where Debian has none -- and
enables and restarts it; the node writes the configuration and opens ufw where there is
one. pve-firewall's rules are the operator's.
"""
from __future__ import annotations
import base64
import re
import pytest
from napalm_proxmox import ProxmoxBackupDriver, ProxmoxDriver
CONFIG = "/etc/zabbix/zabbix_agentd.conf"
STOCK = "PidFile=/run/zabbix/zabbix_agentd.pid\nServer=127.0.0.1\nServerActive=127.0.0.1\nHostname=Zabbix server\n"
DEBIAN = 'PRETTY_NAME="Debian GNU/Linux 13 (trixie)"\nID=debian\nVERSION_ID="13"\n'
SETTINGS = {
"server": "zabbix.example.com",
"server_active": "zabbix.example.com",
"listen_port": 10050,
"allowed_sources": ["10.40.100.254"],
"hostname": "pve-01",
"release": "7.4",
}
class _Node:
"""The node's root shell: files it reads, packages Debian has, what is refused."""
def __init__(self, *, config=STOCK, ufw=True, debian_has_it=True, refuse=""):
self.config = config
self.ufw = ufw
self.debian_has_it = debian_has_it
self.installed = False
self.refuse = refuse
self.ran: list[str] = []
def __call__(self, command: str) -> str:
self.ran.append(command)
out, rc = self._answer(command)
for marker in ("__PVE_RC=", "__SVC_RC="):
if marker in command:
return f"{out}\n{marker}{rc}"
return out
def _answer(self, command: str) -> tuple[str, int]:
if self.refuse and self.refuse in command:
return "E: refused", 1
if command.startswith("dpkg-query"):
return ("zabbix-agent\tinstalled\n" if self.installed else "curl\tinstalled\n"), 0
if f"cat {CONFIG}" in command:
return self.config, 0
if "cat /etc/os-release" in command:
return DEBIAN, 0
if "command -v ufw" in command:
return ("/usr/sbin/ufw", 0) if self.ufw else ("", 1)
if "repo.zabbix.com" in command:
self.debian_has_it = True
return "ok", 0
if "apt-get install" in command and "zabbix-agent" in command:
if not self.debian_has_it:
return "E: Unable to locate package zabbix-agent", 100
self.installed = True
return "ok", 0
if "base64 -d" in command and CONFIG in command:
self.config = base64.b64decode(re.search(r"echo (\S+) \|", command).group(1)).decode()
return "ok", 0
@pytest.fixture
def node():
return _Node()
@pytest.fixture(params=[ProxmoxDriver, ProxmoxBackupDriver], ids=["pve", "pbs"])
def driver(request, node):
d = request.param("pve", "root@pam", "pw")
d._exec_ssh_command = node
return d
def test_installs_writes_opens_and_starts(driver, node):
result = driver.configure_zabbix_agent(SETTINGS)
assert result["success"] is True, result["output"]
assert [s["step"] for s in result["steps"]] == ["install", "configure", "firewall", "start"]
assert any("apt-get install" in c and "zabbix-agent" in c for c in node.ran)
assert any("systemctl" in c and "restart" in c and "zabbix-agent" in c for c in node.ran)
def test_the_config_gets_the_caller_s_values_and_keeps_the_rest(driver, node):
driver.configure_zabbix_agent(SETTINGS)
assert "Server=zabbix.example.com\n" in node.config
assert "Hostname=pve-01\n" in node.config
assert node.config.startswith("PidFile=/run/zabbix/zabbix_agentd.pid\n")
assert any(f"cp -p {CONFIG} {CONFIG}.bak" in c for c in node.ran)
def test_a_config_that_already_says_it_is_not_written(driver, node):
driver.configure_zabbix_agent(SETTINGS)
node.ran.clear()
result = driver.configure_zabbix_agent(SETTINGS)
assert result["success"] is True
assert not any("base64 -d" in c for c in node.ran)
def test_without_debian_s_package_zabbix_s_repository_is_added(driver, node):
node.debian_has_it = False
result = driver.configure_zabbix_agent(SETTINGS)
assert result["success"] is True, result["output"]
repository = next(c for c in node.ran if "repo.zabbix.com" in c)
assert "zabbix-release_latest_7.4+debian13_all.deb" in repository
def test_ufw_opens_the_listen_port_for_the_sources(driver, node):
driver.configure_zabbix_agent(SETTINGS)
assert any("ufw allow from 10.40.100.254/32 to any port 10050 proto tcp" in c for c in node.ran)
def test_without_ufw_the_firewall_is_the_operator_s(driver, node):
node.ufw = False
result = driver.configure_zabbix_agent(SETTINGS)
assert result["success"] is True
assert "pve-firewall rules are the operator's" in result["output"]
assert not any("ufw allow" in c for c in node.ran)
def test_a_config_that_cannot_be_read_stops_the_fix(driver, node):
node.refuse = f"cat {CONFIG}"
result = driver.configure_zabbix_agent(SETTINGS)
assert result["success"] is False
assert result["steps"][-1]["step"] == "configure"