"""A native Zabbix agent, the steps of napalm-device-types' ``ZabbixAgentMixin``. For a host without a container engine (NetOrk/netork#2571). The template installs ``zabbix-agent`` -- the C agent every distribution that packages Zabbix has, and Zabbix's own repository too -- and enables and restarts its service. This writes the caller's values into ``/etc/zabbix/zabbix_agentd.conf`` (where both put it), adds Zabbix's repository where the host's own packages have none, and opens the port in whichever firewall runs. """ from __future__ import annotations from typing import TYPE_CHECKING from napalm_device_types import ( FixStepOutcomeDict, ZabbixAgentMixin, ZabbixAgentSettingsDict, zabbix_agent_config, zabbix_repository_command, ) if TYPE_CHECKING: # pragma: no cover from napalm_device_types import CommandResult CONFIG = "/etc/zabbix/zabbix_agentd.conf" def _failed(result: CommandResult, what: str) -> FixStepOutcomeDict: detail = (result.stderr or result.stdout or "").strip()[-300:] return {"ok": False, "output": f"{what}: {detail or result.exit_code}"} class LinuxZabbixAgentMixin(ZabbixAgentMixin): """``zabbix-agent`` from the distribution, or else from Zabbix's repository.""" def _add_zabbix_repository(self, release: str) -> FixStepOutcomeDict: os_release = self.run_command("cat /etc/os-release", timeout=30) try: command = zabbix_repository_command(os_release.stdout, release) except ValueError as exc: return {"ok": False, "output": str(exc)} return self._root_outcome(command, 300, f"Zabbix {release} repository added") def _write_zabbix_agent_config(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict: read = self.run_command(f"cat {CONFIG}", privileged=True, timeout=30) if read.exit_code: return _failed(read, f"reading {CONFIG}") text, changes = zabbix_agent_config(read.stdout, settings) if not changes: return {"ok": True, "output": f"{CONFIG} already says it"} kept = self._root_outcome(f"cp -p {CONFIG} {CONFIG}.bak", 30, "") if not kept["ok"]: return kept written = self._install_file_as_root(CONFIG, text) if written.exit_code: return _failed(written, f"writing {CONFIG}") 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 - the driver's def run_command( self, command: str, *, privileged: bool = False, timeout: float = 60, stdin: bytes | None = None, ) -> CommandResult: ... def _root_outcome(self, command: str, timeout: float, done: str) -> FixStepOutcomeDict: ... def _install_file_as_root(self, path: str, content: str) -> CommandResult: ... def _allow_sources( self, allowed: list[str], port: int, proto: str ) -> FixStepOutcomeDict: ...