feat(fixes): ZabbixAgentMixin, a native Zabbix agent for a host without a container engine (NetOrk/netork#2571)
driver / lint (pull_request) Successful in 16s
driver / standard (pull_request) Successful in 18s
driver / types (pull_request) Successful in 49s
driver / test (3.13) (pull_request) Successful in 1m6s
driver / lowest (pull_request) Successful in 34s
driver / test (3.12) (pull_request) Successful in 1m11s
driver / build (pull_request) Successful in 24s
driver / security (pull_request) Successful in 55s
CI / driver (pull_request) Successful in 2m20s
driver / publish (pull_request) Skipped

configure_zabbix_agent(settings) loads the package index where the driver can,
installs ZABBIX_AGENT_PACKAGE from the host's own packages and, where those have
none and settings["release"] names the server's release line, from Zabbix's
repository (the driver's _add_zabbix_repository); then the driver writes the
configuration and opens the firewall, and the service is enabled and restarted.
Settings that do not hold raise ValueError before anything changes.

zabbix_agent.py holds what is the same on every host, without I/O: the settings
check, the agent's configuration with Server, ServerActive, ListenPort and
Hostname set and the rest kept, and the root command that adds Zabbix's
repository for Debian, Ubuntu, Raspberry Pi OS and the RHEL family, in the
layout before and since 7.2. LldpAgentMixin and ZabbixAgentMixin share the
start step (enable_and_restart).
This commit is contained in:
christianmanivong committed 2026-11-17 04:50:42 +01:00
1 parent 7c0e4fffc5
commit 5217c6e333
8 files changed
+730 -8

No files matched your search

+1
View File
@@ -259,6 +259,7 @@ class TestLldpAgent:
"ensure_package",
"configure_package_proxy",
"grant_container_engine_access",
"configure_zabbix_agent",
],
)
def test_no_role_base_offers_a_fix(base, method):
+360
View File
@@ -0,0 +1,360 @@
"""A native Zabbix agent: its configuration, its repository and the fix template
(``ZabbixAgentMixin``, NetOrk/netork#2571).
Where a host has no container engine the application installs the agent from the
host's own packages, and from Zabbix's repository only where those have none.
"""
from __future__ import annotations
import pytest
from napalm_device_types import (
ZabbixAgentMixin,
check_zabbix_agent_settings,
zabbix_agent_config,
zabbix_repository_command,
)
SETTINGS = {
"server": "zabbix.example.com",
"server_active": "zabbix.example.com",
"listen_port": 10050,
"allowed_sources": ["10.40.100.254"],
"hostname": "ap-1og",
"release": "7.4",
}
SAMPLE = """# This is a configuration file for Zabbix agent daemon (Unix)
LogFile=/tmp/zabbix_agentd.log
### Option: Server
# Server=
Server=127.0.0.1
ServerActive=127.0.0.1
Hostname=Zabbix server
# Include=/etc/zabbix_agentd.conf.d/*.conf
"""
class TestConfig:
def test_the_lines_that_say_who_may_ask_get_the_caller_s_values(self):
text, changes = zabbix_agent_config(SAMPLE, SETTINGS)
assert "\nServer=zabbix.example.com\n" in text
assert "\nServerActive=zabbix.example.com\n" in text
assert "\nHostname=ap-1og\n" in text
assert "Server: 127.0.0.1 → zabbix.example.com" in changes
assert "Hostname: Zabbix server → ap-1og" in changes
def test_comments_and_other_lines_stay_as_they_were(self):
text, _ = zabbix_agent_config(SAMPLE, SETTINGS)
assert text.startswith("# This is a configuration file")
assert "LogFile=/tmp/zabbix_agentd.log\n" in text
assert "# Server=\n" in text
assert text.endswith("# Include=/etc/zabbix_agentd.conf.d/*.conf\n" + "ListenPort=10050\n")
def test_a_key_the_file_does_not_set_is_added_at_the_end(self):
text, changes = zabbix_agent_config(SAMPLE, SETTINGS)
assert text.endswith("ListenPort=10050\n")
assert "ListenPort: (not set) → 10050" in changes
def test_a_file_that_already_says_it_changes_nothing(self):
text, _ = zabbix_agent_config(SAMPLE, SETTINGS)
again, changes = zabbix_agent_config(text, SETTINGS)
assert again == text
assert changes == []
def test_without_a_hostname_the_agent_keeps_its_own(self):
settings = {k: v for k, v in SETTINGS.items() if k != "hostname"}
text, changes = zabbix_agent_config(SAMPLE, settings)
assert "\nHostname=Zabbix server\n" in text
assert not any(c.startswith("Hostname") for c in changes)
def test_no_active_server_comments_the_line_out(self):
text, changes = zabbix_agent_config(SAMPLE, {**SETTINGS, "server_active": ""})
assert "\n# ServerActive=127.0.0.1\n" in text
assert "\nServerActive=" not in text
assert "ServerActive: 127.0.0.1 → (not set)" in changes
def test_a_file_without_a_final_newline_gets_one_before_what_is_added(self):
text, _ = zabbix_agent_config("Server=127.0.0.1", SETTINGS)
assert text.startswith("Server=zabbix.example.com\n")
assert text.endswith("\n")
def test_every_line_of_a_key_set_twice_says_the_same(self):
text, _ = zabbix_agent_config("Server=a\nServer=b\n", SETTINGS)
assert text.count("Server=zabbix.example.com\n") == 2
class TestSettings:
@pytest.mark.parametrize(
"server",
["", "zabbix.example.com\nUserParameter=x,id", "a b", "a;rm -rf /", "'a'"],
)
def test_a_server_that_is_not_addresses_is_refused(self, server):
with pytest.raises(ValueError):
check_zabbix_agent_settings({**SETTINGS, "server": server})
def test_several_servers_and_ports_pass(self):
check_zabbix_agent_settings(
{**SETTINGS, "server": "10.0.0.1,zabbix.example.com", "server_active": "[::1]:10051"}
)
def test_a_hostname_with_a_newline_is_refused(self):
with pytest.raises(ValueError):
check_zabbix_agent_settings({**SETTINGS, "hostname": "ap\nServer=evil"})
@pytest.mark.parametrize("port", [0, 65536, "10050"])
def test_a_listen_port_out_of_range_is_refused(self, port):
with pytest.raises(ValueError):
check_zabbix_agent_settings({**SETTINGS, "listen_port": port})
@pytest.mark.parametrize("release", ["7", "7.4.1", "latest", "7.4; id"])
def test_a_release_that_is_not_major_dot_minor_is_refused(self, release):
with pytest.raises(ValueError):
check_zabbix_agent_settings({**SETTINGS, "release": release})
def _os_release(**fields: str) -> str:
return "".join(f'{key}="{value}"\n' for key, value in fields.items())
class TestRepository:
BASE = "https://repo.zabbix.com/zabbix"
@pytest.mark.parametrize(
("os_release", "url"),
[
(
_os_release(ID="ubuntu", VERSION_ID="24.04", ID_LIKE="debian"),
"7.4/release/ubuntu/pool/main/z/zabbix-release/"
"zabbix-release_latest_7.4+ubuntu24.04_all.deb",
),
(
_os_release(ID="debian", VERSION_ID="12"),
"7.4/release/debian/pool/main/z/zabbix-release/"
"zabbix-release_latest_7.4+debian12_all.deb",
),
(
_os_release(ID="ol", VERSION_ID="9.4", ID_LIKE="fedora"),
"7.4/release/oracle/9/noarch/zabbix-release-latest-7.4.el9.noarch.rpm",
),
(
_os_release(ID="rhel", VERSION_ID="10.0", ID_LIKE="fedora"),
"7.4/release/rhel/10/noarch/zabbix-release-latest-7.4.el10.noarch.rpm",
),
(
_os_release(ID="almalinux", VERSION_ID="9.5", ID_LIKE="rhel centos fedora"),
"7.4/release/alma/9/noarch/zabbix-release-latest-7.4.el9.noarch.rpm",
),
(
_os_release(ID="rocky", VERSION_ID="9.5", ID_LIKE="rhel centos fedora"),
"7.4/release/rocky/9/noarch/zabbix-release-latest-7.4.el9.noarch.rpm",
),
],
)
def test_the_release_package_of_the_host_s_distribution(self, os_release, url):
command = zabbix_repository_command(os_release, "7.4")
assert f"{self.BASE}/{url}" in command
def test_a_release_before_7_2_lives_in_the_old_layout(self):
deb = zabbix_repository_command(_os_release(ID="ubuntu", VERSION_ID="24.04"), "7.0")
rpm = zabbix_repository_command(_os_release(ID="ol", VERSION_ID="9.4"), "7.0")
assert f"{self.BASE}/7.0/ubuntu/pool/main/z/zabbix-release/" in deb
assert f"{self.BASE}/7.0/oracle/9/x86_64/zabbix-release-latest-7.0.el9.noarch.rpm" in rpm
def test_a_deb_is_installed_with_dpkg_and_the_index_refreshed(self):
command = zabbix_repository_command(_os_release(ID="debian", VERSION_ID="12"), "7.4")
assert "dpkg -i" in command
assert "apt-get update" in command
def test_an_rpm_is_installed_with_the_package_manager(self):
command = zabbix_repository_command(_os_release(ID="rocky", VERSION_ID="9.5"), "7.4")
assert "dnf -y install" in command
def test_a_derivative_falls_back_to_what_it_is_like(self):
command = zabbix_repository_command(
_os_release(ID="centos", VERSION_ID="9", ID_LIKE="rhel fedora"), "7.4"
)
assert "/7.4/release/rhel/9/noarch/" in command
def test_a_distribution_zabbix_has_no_repository_for_is_refused(self):
with pytest.raises(ValueError, match="openwrt"):
zabbix_repository_command(_os_release(ID="openwrt", VERSION_ID="25.12.2"), "7.4")
def test_a_release_that_is_not_major_dot_minor_is_refused(self):
with pytest.raises(ValueError):
zabbix_repository_command(_os_release(ID="debian", VERSION_ID="12"), "7.4;id")
class _Agent(ZabbixAgentMixin):
"""The generic steps over ensure_package and manage_service; the driver's others."""
def __init__(self, refuse: frozenset[str] = frozenset(), repository: bool = True):
self.calls: list = []
self.refuse = refuse
self.installs = 0
if not repository:
self._add_zabbix_repository = None # type: ignore[assignment]
def refresh_available_updates(self):
self.calls.append(("refresh",))
ok = "refresh" not in self.refuse
return {"success": ok, "output": "" if ok else "Temporary failure resolving"}
def ensure_package(self, name):
self.calls.append(("ensure_package", name))
self.installs += 1
# The distribution has no package; after the repository is added it has.
ok = "distribution" not in self.refuse or self.installs > 1
return {"success": ok, "steps": [], "output": "installed" if ok else "E: no candidate"}
def _add_zabbix_repository(self, release):
self.calls.append(("repository", release))
ok = "repository" not in self.refuse
return {"ok": ok, "output": f"Zabbix {release} repository added" if ok else "404"}
def _write_zabbix_agent_config(self, settings):
self.calls.append(("configure", settings["server"]))
return {"ok": "configure" not in self.refuse, "output": "written"}
def _allow_zabbix_agent_sources(self, settings):
self.calls.append(("firewall", settings["allowed_sources"]))
return {"ok": "firewall" not in self.refuse, "output": "open"}
def manage_service(self, name, action):
self.calls.append((action, name))
ok = action not in self.refuse
return {"success": ok, "output": "" if ok else f"cannot {action}"}
class TestZabbixAgentMixin:
def test_install_configure_open_enable_and_restart(self):
agent = _Agent()
result = agent.configure_zabbix_agent(SETTINGS)
assert result["success"] is True
assert agent.calls == [
("refresh",),
("ensure_package", "zabbix-agent"),
("configure", "zabbix.example.com"),
("firewall", ["10.40.100.254"]),
("enable", "zabbix-agent"),
("restart", "zabbix-agent"),
]
assert [s["step"] for s in result["steps"]] == ["install", "configure", "firewall", "start"]
def test_without_a_package_in_the_distribution_zabbix_s_repository_is_added(self):
agent = _Agent(refuse=frozenset({"distribution"}))
result = agent.configure_zabbix_agent(SETTINGS)
assert result["success"] is True
assert agent.calls[:4] == [
("refresh",),
("ensure_package", "zabbix-agent"),
("repository", "7.4"),
("ensure_package", "zabbix-agent"),
]
assert "Zabbix 7.4 repository added" in result["output"]
def test_without_a_release_there_is_no_fallback(self):
settings = {k: v for k, v in SETTINGS.items() if k != "release"}
agent = _Agent(refuse=frozenset({"distribution"}))
result = agent.configure_zabbix_agent(settings)
assert result["success"] is False
assert ("repository", "7.4") not in agent.calls
assert "no candidate" in result["output"]
def test_a_driver_that_cannot_add_the_repository_fails_with_the_distribution_s_answer(self):
agent = _Agent(refuse=frozenset({"distribution"}), repository=False)
result = agent.configure_zabbix_agent(SETTINGS)
assert result["success"] is False
assert "no candidate" in result["output"]
def test_a_repository_that_cannot_be_added_configures_nothing(self):
agent = _Agent(refuse=frozenset({"distribution", "repository"}))
result = agent.configure_zabbix_agent(SETTINGS)
assert result["success"] is False
assert [c[0] for c in agent.calls] == ["refresh", "ensure_package", "repository"]
assert "404" in result["output"]
def test_the_package_index_is_loaded_first(self):
agent = _Agent()
agent.configure_zabbix_agent(SETTINGS)
assert agent.calls[0] == ("refresh",)
def test_an_index_that_will_not_load_still_lets_the_install_try(self):
agent = _Agent(refuse=frozenset({"refresh"}))
result = agent.configure_zabbix_agent(SETTINGS)
assert result["success"] is True
assert ("ensure_package", "zabbix-agent") in agent.calls
assert "Temporary failure resolving" in result["steps"][0]["output"]
def test_a_driver_without_an_index_to_load_installs_straight_away(self):
agent = _Agent()
agent.refresh_available_updates = None # type: ignore[assignment]
result = agent.configure_zabbix_agent(SETTINGS)
assert result["success"] is True
assert agent.calls[0] == ("ensure_package", "zabbix-agent")
def test_a_closed_firewall_starts_nothing(self):
agent = _Agent(refuse=frozenset({"firewall"}))
assert agent.configure_zabbix_agent(SETTINGS)["success"] is False
assert ("restart", "zabbix-agent") not in agent.calls
def test_an_agent_that_will_not_start_at_boot_is_not_restarted(self):
agent = _Agent(refuse=frozenset({"enable"}))
result = agent.configure_zabbix_agent(SETTINGS)
assert result["success"] is False
assert ("restart", "zabbix-agent") not in agent.calls
assert "cannot enable" in result["output"]
def test_the_package_and_service_names_are_the_driver_s(self):
agent = _Agent()
agent.ZABBIX_AGENT_PACKAGE = "zabbix-agentd"
agent.ZABBIX_AGENT_SERVICE = "zabbix_agentd"
agent.configure_zabbix_agent(SETTINGS)
assert ("ensure_package", "zabbix-agentd") in agent.calls
assert ("restart", "zabbix_agentd") in agent.calls
def test_settings_that_do_not_hold_are_refused_before_anything_changes(self):
agent = _Agent()
with pytest.raises(ValueError):
agent.configure_zabbix_agent({**SETTINGS, "server": "a\nb"})
assert agent.calls == []