diff --git a/CHANGELOG.md b/CHANGELOG.md index 99b32fc..d4b4ffa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,22 @@ recorded here; their history is the git log. ## [Unreleased] ### Added +- `ZabbixAgentMixin.configure_zabbix_agent(settings)`: a native Zabbix agent, for a host + without a container engine (NetOrk/netork#2571). Install (`ensure_package` with + `ZABBIX_AGENT_PACKAGE`, and where the host's own packages have none and + `settings["release"]` names the server's release line, the driver's + `_add_zabbix_repository(release)` and a second try), configure (the driver's + `_write_zabbix_agent_config`), firewall (the driver's `_allow_zabbix_agent_sources`), + start (`manage_service` enable and restart of `ZABBIX_AGENT_SERVICE`). Settings that do + not hold raise `ValueError` before anything changes. +- `ZabbixAgentSettingsDict`; `zabbix_agent_config(text, settings)`, the agent's + configuration with `Server`, `ServerActive`, `ListenPort` and `Hostname` set and the rest + kept; `zabbix_repository_command(os_release, release)`, the root command that adds + Zabbix's repository for Debian, Ubuntu, Raspberry Pi OS, RHEL, CentOS, Oracle Linux, + AlmaLinux and Rocky Linux, in the layout before and since 7.2; + `check_zabbix_agent_settings(settings)`. +- `fixes.enable_and_restart(manage_service, service)`, the start step `LldpAgentMixin` and + `ZabbixAgentMixin` share. - Podman as a container engine (NetOrk/netork#818): `container_engines()` lists it with the API `podman-libpod`, and `open_container_engine("podman")` reaches it with `podman system dial-stdio` (Podman 4.0 and later). It is the host's rootful Podman, so the connection diff --git a/README.md b/README.md index fb507e9..c65b7db 100644 --- a/README.md +++ b/README.md @@ -124,7 +124,10 @@ application wants made on a device runs as fixed steps the driver implements, wi the caller supplies: `SnmpAgentMixin.configure_snmp_agent(settings)` (install, configure, firewall, start), `LldpAgentMixin.configure_lldp_agent(interfaces)` (install, write the interfaces, enable and restart; the driver writes only the interfaces), -`EnsurePackageMixin.ensure_package(name)`, `PackageProxyMixin.configure_package_proxy(url)`, +`ZabbixAgentMixin.configure_zabbix_agent(settings)` (install from the host's packages or +else Zabbix's repository, configure, firewall, enable and restart; the driver writes the +configuration and opens the firewall), `EnsurePackageMixin.ensure_package(name)`, +`PackageProxyMixin.configure_package_proxy(url)`, `TimeSyncMixin.configure_time_sync(ntp_servers, timezone)` and `ContainerEngineMixin.grant_container_engine_access(user)`. A driver whose device takes the change in one call overrides the template method. A driver mixes in the fixes its device diff --git a/docs/STRUCTURE.md b/docs/STRUCTURE.md index ccad117..6634702 100644 --- a/docs/STRUCTURE.md +++ b/docs/STRUCTURE.md @@ -80,6 +80,7 @@ The same shape replaces every action in today's `run_device_action`: | `fix_apt_proxy` | `configure_package_proxy(url)` | | `fix_docker_permissions` | `grant_container_engine_access(user)` | | `install_lldpd`, `install_auc` | `ensure_package(name)` | +| the Zabbix agent where no container engine runs (NetOrk/netork#2571) | `configure_zabbix_agent(settings)` | The mixin is mixed in by the driver, or by the platform package, not by a role base. A driver that inherits a template it cannot run on its device, as a NAS driver built on the diff --git a/napalm_device_types/__init__.py b/napalm_device_types/__init__.py index 69af84b..5ade277 100644 --- a/napalm_device_types/__init__.py +++ b/napalm_device_types/__init__.py @@ -144,6 +144,7 @@ from napalm_device_types.fixes import ( LldpAgentMixin, PackageProxyMixin, SnmpAgentMixin, + ZabbixAgentMixin, run_fix_steps, ) from napalm_device_types.health_metrics import HealthMetricsMixin @@ -343,6 +344,12 @@ from napalm_device_types.virtual_ips import ( ) from napalm_device_types.vm_migration import MigrationPreflightDict from napalm_device_types.vm_stop_request import VmStopRequestMixin +from napalm_device_types.zabbix_agent import ( + ZabbixAgentSettingsDict, + check_zabbix_agent_settings, + zabbix_agent_config, + zabbix_repository_command, +) __all__ = [ "BACKUP_JOB_KINDS", @@ -392,6 +399,11 @@ __all__ = [ "SnmpAgentMixin", "SnmpAgentSettingsDict", "run_fix_steps", + "ZabbixAgentMixin", + "ZabbixAgentSettingsDict", + "check_zabbix_agent_settings", + "zabbix_agent_config", + "zabbix_repository_command", "SnmpHealthProfile", "SnmpInterfacesSpec", "SnmpMemorySpec", diff --git a/napalm_device_types/fixes.py b/napalm_device_types/fixes.py index db1dc2f..c55075c 100644 --- a/napalm_device_types/fixes.py +++ b/napalm_device_types/fixes.py @@ -16,6 +16,7 @@ They replace ``run_device_action`` (docs/STRUCTURE.md): ``fix_apt_proxy`` :meth:`PackageProxyMixin.configure_package_proxy` ``fix_docker_permissions`` ``ContainerEngineMixin.grant_container_engine_access`` ``install_lldpd`` and co. :meth:`EnsurePackageMixin.ensure_package` +(new) :meth:`ZabbixAgentMixin.configure_zabbix_agent` ========================== =================================================== """ @@ -31,6 +32,7 @@ from napalm_device_types.models import ( PackageDict, SnmpAgentSettingsDict, ) +from napalm_device_types.zabbix_agent import ZabbixAgentSettingsDict, check_zabbix_agent_settings #: One step of a fix: its name and the call that does it. FixStep = tuple[str, Callable[[], FixStepOutcomeDict]] @@ -58,6 +60,23 @@ def run_fix_steps(steps: Sequence[FixStep]) -> FixResultDict: } +def enable_and_restart( + manage_service: Callable[[str, str], dict[str, Any]], service: str +) -> FixStepOutcomeDict: + """Enable *service* at boot, then restart it so it reads its configuration; not + restarted when it cannot be enabled.""" + for action in ("enable", "restart"): + result = manage_service(service, action) + if not result.get("success"): + output = str(result.get("output", "")).strip() + return {"ok": False, "output": f"{action} {service}: {output}".rstrip(": ")} + return {"ok": True, "output": f"{service} enabled and restarted"} + + +def _joined(*parts: object) -> str: + return "\n".join(str(p).strip() for p in parts if p and str(p).strip()) + + class SnmpAgentMixin: """Run an SNMP agent on the device that answers the caller. @@ -171,13 +190,7 @@ class LldpAgentMixin: return {"ok": bool(result["success"]), "output": str(result.get("output", ""))} def _start_lldp_agent(self) -> FixStepOutcomeDict: - service = self.LLDP_AGENT_SERVICE - for action in ("enable", "restart"): - result = self.manage_service(service, action) - if not result.get("success"): - output = str(result.get("output", "")).strip() - return {"ok": False, "output": f"{action} {service}: {output}".rstrip(": ")} - return {"ok": True, "output": f"{service} enabled and restarted"} + return enable_and_restart(self.manage_service, self.LLDP_AGENT_SERVICE) if TYPE_CHECKING: # pragma: no cover - declared for type checkers only @@ -193,6 +206,110 @@ class LldpAgentMixin: ... +class ZabbixAgentMixin: + """Run a native Zabbix agent that answers the caller's server. + + For a host without a container engine, where the agent cannot run as a + container. The steps: load the package index where the driver can + (``refresh_available_updates``), install the agent from the host's own packages -- and + where those have none, from Zabbix's repository for ``settings["release"]`` + (:func:`~napalm_device_types.zabbix_agent.zabbix_repository_command`) --, write + its configuration (:func:`~napalm_device_types.zabbix_agent.zabbix_agent_config`), + let the allowed sources through the host's firewall, enable and restart it. + Installing and starting are generic, over ``ensure_package`` and + ``manage_service`` with ``ZABBIX_AGENT_PACKAGE`` and ``ZABBIX_AGENT_SERVICE``. + Whether Zabbix reaches it is the caller's to ask Zabbix. + + The settings are checked before anything changes; ``ValueError`` names the one + that does not hold. A driver that cannot add a repository sets + ``_add_zabbix_repository`` to ``None``: its hosts then take the distribution's + package or none. + """ + + #: The package that brings the agent, as ``ensure_package`` takes it. + ZABBIX_AGENT_PACKAGE: ClassVar[str] = "zabbix-agent" + #: The agent's service, as ``manage_service`` takes it. + ZABBIX_AGENT_SERVICE: ClassVar[str] = "zabbix-agent" + + def configure_zabbix_agent(self, settings: ZabbixAgentSettingsDict) -> FixResultDict: + """Install, configure, open, enable and restart the agent with *settings*. + + :raises ValueError: for settings the agent's configuration cannot take, + before anything changes. + """ + check_zabbix_agent_settings(settings) + return run_fix_steps( + [ + ("install", lambda: self._install_zabbix_agent(settings)), + ("configure", lambda: self._write_zabbix_agent_config(settings)), + ("firewall", lambda: self._allow_zabbix_agent_sources(settings)), + ("start", self._start_zabbix_agent), + ] + ) + + def _install_zabbix_agent(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict: + index = self._load_package_index() + first = self.ensure_package(self.ZABBIX_AGENT_PACKAGE) + if first["success"]: + return {"ok": True, "output": _joined(index, first.get("output"))} + release = settings.get("release") + add = getattr(self, "_add_zabbix_repository", None) + if not release or not callable(add): + return {"ok": False, "output": _joined(index, first.get("output"))} + added = add(release) + if not added["ok"]: + return {"ok": False, "output": _joined(index, added.get("output"))} + second = self.ensure_package(self.ZABBIX_AGENT_PACKAGE) + return { + "ok": bool(second["success"]), + "output": _joined(index, added.get("output"), second.get("output")), + } + + def _load_package_index(self) -> str: + """Load the package index where the driver can (OpenWrt keeps it in RAM, gone + after a restart); what went wrong, or "". The install tries either way.""" + refresh = getattr(self, "refresh_available_updates", None) + if not callable(refresh): + return "" + loaded = refresh() + if loaded.get("success"): + return "" + return f"package index not loaded: {str(loaded.get('output', '')).strip()}" + + def _start_zabbix_agent(self) -> FixStepOutcomeDict: + return enable_and_restart(self.manage_service, self.ZABBIX_AGENT_SERVICE) + + if TYPE_CHECKING: # pragma: no cover - declared for type checkers only + + def ensure_package(self, name: str) -> FixResultDict: ... + + def manage_service(self, name: str, action: str) -> dict[str, Any]: ... + + def refresh_available_updates(self) -> dict[str, Any]: ... + + # The steps a driver implements: + + def _add_zabbix_repository(self, release: str) -> FixStepOutcomeDict: + """Add Zabbix's repository for *release* and refresh the package index + (``zabbix_repository_command`` builds the command for most hosts).""" + ... + + def _write_zabbix_agent_config( + self, settings: ZabbixAgentSettingsDict + ) -> FixStepOutcomeDict: + """Write *settings* into the agent's configuration file, keeping the rest of + it (``zabbix_agent_config``), and whatever else the device needs before the + agent may start.""" + ... + + def _allow_zabbix_agent_sources( + self, settings: ZabbixAgentSettingsDict + ) -> FixStepOutcomeDict: + """Let ``settings["allowed_sources"]`` reach tcp/``listen_port``; ``ok`` with + nothing to do where the host has no firewall of its own, or for [].""" + ... + + class PackageProxyMixin: """Point the device's package manager at a caching proxy.""" @@ -215,5 +332,7 @@ __all__ = [ "LldpAgentMixin", "PackageProxyMixin", "SnmpAgentMixin", + "ZabbixAgentMixin", + "enable_and_restart", "run_fix_steps", ] diff --git a/napalm_device_types/zabbix_agent.py b/napalm_device_types/zabbix_agent.py new file mode 100644 index 0000000..53854d3 --- /dev/null +++ b/napalm_device_types/zabbix_agent.py @@ -0,0 +1,210 @@ +"""A native Zabbix agent: its configuration and Zabbix's package repository. + +What :class:`~napalm_device_types.fixes.ZabbixAgentMixin` needs that is the same on +every host, without I/O: which settings an agent may be given +(:func:`check_zabbix_agent_settings`), the agent's configuration file with them +(:func:`zabbix_agent_config`), and the command that adds Zabbix's repository where +the host's own packages have no agent (:func:`zabbix_repository_command`). A driver +reads and writes the file and runs the command. + +**Which lines.** ``Server`` (who may ask, for passive checks), ``ServerActive`` +(where active checks go), ``ListenPort`` and, when the caller names one, +``Hostname`` -- the host's technical name in Zabbix, which an active agent sends. +Every other line stays as it was; a key the file does not set is added at its end. + +**The repository.** Zabbix publishes a ``zabbix-release`` package per release line +and distribution that adds its repository and key. Since 7.2 it lives under +``/release//``; up to 7.0 under ``//``, +with the rpm in an ``x86_64`` directory. The release line is the server's: an agent +may be older than its server, not newer. +""" + +from __future__ import annotations + +import re +import shlex +from typing import NotRequired, TypedDict + + +class ZabbixAgentSettingsDict(TypedDict): + """What the caller wants a native Zabbix agent to be (``ZabbixAgentMixin``).""" + + server: str # Server: the addresses that may ask (passive checks), comma-separated + server_active: str # ServerActive: where active checks go, comma-separated; "" for none + listen_port: int # ListenPort + # addresses or CIDRs let through to the port; [] changes no firewall + allowed_sources: list[str] + # Hostname: the host's technical name in Zabbix; absent keeps the agent's + hostname: NotRequired[str] + # the server's release line ("7.4"): Zabbix's repository to fall back to where the + # host's own packages have no agent; absent: no fallback + release: NotRequired[str] + + +#: Addresses, comma-separated, as ``Server`` and ``ServerActive`` take them: names, +#: IPv4, ``[IPv6]`` and ports. Nothing a config line or a shell word breaks out of. +_ADDRESSES = re.compile(r"^[A-Za-z0-9.:\[\]-]+(,[A-Za-z0-9.:\[\]-]+)*$") +#: What Zabbix allows in a technical host name. +_HOSTNAME = re.compile(r"^[A-Za-z0-9._ -]+$") +#: A release line, as Zabbix's repository names it. +_RELEASE = re.compile(r"^(\d+)\.(\d+)$") + +_KEYS = ("Server", "ServerActive", "ListenPort", "Hostname") +_LINE = re.compile(r"^(\s*)(" + "|".join(_KEYS) + r")\s*=\s*(.*?)\s*$") + +REPOSITORY = "https://repo.zabbix.com/zabbix" +#: The distributions Zabbix publishes packages for, by ``/etc/os-release``'s ``ID``: +#: the name in the repository's path, and whether they take a deb. +_DISTRIBUTIONS: dict[str, tuple[str, bool]] = { + "ubuntu": ("ubuntu", True), + "debian": ("debian", True), + "raspbian": ("raspbian", True), + "rhel": ("rhel", False), + "centos": ("rhel", False), + "ol": ("oracle", False), + "almalinux": ("alma", False), + "rocky": ("rocky", False), +} + + +def check_zabbix_agent_settings(settings: ZabbixAgentSettingsDict) -> None: + """Refuse what an agent's configuration or a shell line cannot take. + + :raises ValueError: naming the setting. + """ + _check_addresses("Server", str(settings.get("server", "")), required=True) + _check_addresses("ServerActive", str(settings.get("server_active", "")), required=False) + hostname = settings.get("hostname") + if hostname is not None and not _HOSTNAME.match(hostname): + raise ValueError(f"not a Zabbix host name: {hostname!r}") + port = settings.get("listen_port") + if not isinstance(port, int) or isinstance(port, bool) or not 1 <= port <= 65535: + raise ValueError(f"not a port: {port!r}") + release = settings.get("release") + if release is not None and not _RELEASE.match(release): + raise ValueError(f"not a Zabbix release line (major.minor): {release!r}") + + +def _check_addresses(key: str, value: str, *, required: bool) -> None: + if (value or required) and not _ADDRESSES.match(value): + raise ValueError(f"not addresses an agent's {key} takes: {value!r}") + + +def _wanted(settings: ZabbixAgentSettingsDict) -> dict[str, str]: + wanted = { + "Server": settings["server"], + "ServerActive": settings.get("server_active", ""), + "ListenPort": str(settings["listen_port"]), + } + if settings.get("hostname"): + wanted["Hostname"] = str(settings["hostname"]) + return wanted + + +def zabbix_agent_config(text: str, settings: ZabbixAgentSettingsDict) -> tuple[str, list[str]]: + """*text*, an agent's configuration file, with *settings*; and what changed, one + ``"Key: old → new"`` each. + + An empty ``server_active`` comments ``ServerActive`` out: the agent then runs + passive checks only. + """ + wanted = _wanted(settings) + lines: list[str] = [] + changes: list[str] = [] + seen: set[str] = set() + for line in text.splitlines(keepends=True): + match = _LINE.match(line.rstrip("\r\n")) + if not match or match.group(2) not in wanted: + lines.append(line) + continue + seen.add(match.group(2)) + lines.append(_set_line(line, match, wanted, changes)) + _add_missing( + lines, [key for key in _KEYS if wanted.get(key) and key not in seen], wanted, changes + ) + return "".join(lines), changes + + +def _add_missing( + lines: list[str], keys: list[str], wanted: dict[str, str], changes: list[str] +) -> None: + """*keys*, which the file does not set, at its end.""" + if keys and lines and not lines[-1].endswith("\n"): + lines[-1] += "\n" + for key in keys: + lines.append(f"{key}={wanted[key]}\n") + changes.append(f"{key}: (not set) → {wanted[key]}") + + +def _set_line(line: str, match: re.Match[str], wanted: dict[str, str], changes: list[str]) -> str: + """*line*, which sets a key the caller wants, as the caller wants it.""" + indent, key, old = match.groups() + end = "\n" if line.endswith("\n") else "" + new = wanted[key] + if not new: + changes.append(f"{key}: {old} → (not set)") + return f"{indent}# {key}={old}{end}" + if old == new: + return line + changes.append(f"{key}: {old} → {new}") + return f"{indent}{key}={new}{end}" + + +def _os_release(text: str) -> dict[str, str]: + fields = {} + for line in text.splitlines(): + key, sep, value = line.partition("=") + if sep: + fields[key.strip()] = value.strip().strip("'\"") + return fields + + +def _distribution(fields: dict[str, str]) -> tuple[str, bool]: + for candidate in [fields.get("ID", ""), *fields.get("ID_LIKE", "").split()]: + if candidate in _DISTRIBUTIONS: + return _DISTRIBUTIONS[candidate] + raise ValueError(f"Zabbix publishes no repository for {fields.get('ID') or 'this system'}") + + +def zabbix_repository_command(os_release: str, release: str) -> str: + """The root command that adds Zabbix's *release* repository to the host whose + ``/etc/os-release`` is *os_release*, and refreshes the package index. + + :raises ValueError: for a release line that is not ``major.minor``, or a + distribution Zabbix publishes nothing for. + """ + match = _RELEASE.match(release) + if not match: + raise ValueError(f"not a Zabbix release line (major.minor): {release!r}") + fields = _os_release(os_release) + name, deb = _distribution(fields) + version = fields.get("VERSION_ID", "") + new_layout = (int(match.group(1)), int(match.group(2))) >= (7, 2) + base = f"{REPOSITORY}/{release}/" + ("release/" if new_layout else "") + name + if deb: + # Raspberry Pi OS's packages are named after the Debian release they follow. + label = "debian" if name == "raspbian" else name + filename = f"zabbix-release_latest_{release}+{label}{version}_all.deb" + url = f"{base}/pool/main/z/zabbix-release/{filename}" + package = shlex.quote(url) + return ( + "t=$(mktemp -d) && " + f'{{ curl -fsSL -o "$t/zabbix-release.deb" {package} ' + f'|| wget -qO "$t/zabbix-release.deb" {package}; }} && ' + 'dpkg -i "$t/zabbix-release.deb" && apt-get update; ' + # The download's directory goes either way; the status is the install's. + 's=$?; rm -rf "$t"; [ "$s" -eq 0 ]' + ) + major = version.split(".")[0] + arch = "noarch" if new_layout else "x86_64" + url = f"{base}/{major}/{arch}/zabbix-release-latest-{release}.el{major}.noarch.rpm" + return f"dnf -y install {shlex.quote(url)}" + + +__all__ = [ + "REPOSITORY", + "ZabbixAgentSettingsDict", + "check_zabbix_agent_settings", + "zabbix_agent_config", + "zabbix_repository_command", +] diff --git a/tests/test_fix_templates.py b/tests/test_fix_templates.py index 1eb9c3d..0850740 100644 --- a/tests/test_fix_templates.py +++ b/tests/test_fix_templates.py @@ -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): diff --git a/tests/test_zabbix_agent.py b/tests/test_zabbix_agent.py new file mode 100644 index 0000000..483c28e --- /dev/null +++ b/tests/test_zabbix_agent.py @@ -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 == []