Files
napalm-proxmox/tests/test_zabbix_agent.py
T
Christian Manivong 370aeed482 feat(zabbix): an active-only agent closes the port netOrk opened for it (NetOrk/netork#2693)
Every rule the firewall step adds in ufw is recorded in napalm-device-types'
opened_ports record, only when ufw did not have it before. For an active-only
agent, _revoke_zabbix_agent_sources removes exactly the agent's recorded rules
and reports what ufw has left for the port.
2026-11-26 08:21:53 +01:00

244 lines
8.6 KiB
Python

"""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_device_types import OPENED_PORTS_RECORD
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] = []
#: What reading the record of opened rules prints (NetOrk/netork#2693).
self.record = ""
#: What counting the rules left for the port prints.
self.left = "0"
self.record_written: str | None = None
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 "stat -c" in command and OPENED_PORTS_RECORD in command:
return self.record, 0
if "grep -c" in command:
return self.left, 0
if "base64 -d" in command and OPENED_PORTS_RECORD in command:
written = re.search(r"echo (\S*) \|", command).group(1)
self.record_written = base64.b64decode(written).decode()
return "", 0
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"
# --- The record of the rules netOrk opened (NetOrk/netork#2693) ---------------------
ACTIVE_ONLY = {**SETTINGS, "active_only": True, "allowed_sources": []}
ROOT = "0 755 directory\n0 644 regular file\n"
ZABBIX_UFW = "v1 zabbix-agent ufw tcp 10050 10.40.100.254/32"
SNMP_UFW = "v1 snmp ufw udp 161 10.40.100.254/32"
def test_ufw_records_the_rule_it_added_under_the_agent(driver, node):
driver.configure_zabbix_agent(SETTINGS)
opened = next(c for c in node.ran if "ufw allow" in c)
assert "*Skipping*) ;;" in opened
assert f'"{ZABBIX_UFW}" >> {OPENED_PORTS_RECORD}' in opened
def test_the_snmp_rule_is_recorded_under_snmp(node):
driver = ProxmoxDriver("pve", "root@pam", "pw")
driver._exec_ssh_command = node
driver.configure_snmp_agent({"community": "c0mm", "allowed_sources": ["10.40.100.254"]})
assert any(f'"{SNMP_UFW}" >>' in c for c in node.ran)
def test_active_only_removes_the_agent_s_recorded_rules_and_keeps_the_rest(driver, node):
node.record = ROOT + f"{ZABBIX_UFW}\n{SNMP_UFW}\n"
result = driver.configure_zabbix_agent(ACTIVE_ONLY)
assert result["success"] is True, result["output"]
deletes = [c for c in node.ran if "ufw delete" in c]
assert len(deletes) == 1
assert "ufw delete allow from 10.40.100.254/32 to any port 10050 proto tcp" in deletes[0]
assert node.record_written == f"{SNMP_UFW}\n"
assert "removed" in result["steps"][2]["output"]
assert not any("ufw allow" in c for c in node.ran)
def test_without_a_record_nothing_is_removed_and_what_is_left_is_reported(driver, node):
node.left = "1"
result = driver.configure_zabbix_agent(ACTIVE_ONLY)
assert result["success"] is True
assert not any("ufw delete" in c for c in node.ran)
assert node.record_written is None
firewall = result["steps"][2]["output"]
assert "netOrk recorded no rule" in firewall
assert "1 rule(s) for tcp/10050" in firewall
def test_a_record_someone_else_could_write_is_not_acted_on(driver, node):
node.record = f"0 755 directory\n0 666 regular file\n{ZABBIX_UFW}\n"
result = driver.configure_zabbix_agent(ACTIVE_ONLY)
assert result["success"] is False
assert "writable" in result["output"]
assert not any("ufw delete" in c for c in node.ran)
def test_a_rule_that_will_not_go_stays_in_the_record(driver, node):
node.record = ROOT + f"{ZABBIX_UFW}\n"
node.refuse = "ufw delete"
result = driver.configure_zabbix_agent(ACTIVE_ONLY)
assert result["success"] is False
assert node.record_written is None
def test_a_recorded_rule_of_another_firewall_is_not_touched(driver, node):
"""A node's rules are ufw's; a firewalld line is not one this driver removes."""
node.record = ROOT + "v1 zabbix-agent iptables tcp 10050 10.40.100.254/32\n"
result = driver.configure_zabbix_agent(ACTIVE_ONLY)
assert result["success"] is False
assert "iptables" in result["output"]
assert node.record_written is None