diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e30484..48fa87a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,17 @@ recorded here; their history is the git log. `noble-security`), once each new suite's `InRelease` or `Release` is fetched with apt's downloader; nothing is written where the vendor has none. - `parse_apt_releases`, `rewrite_release`, `suite_release`, `APT_RELEASES_COMMAND`. +- `ZabbixAgentSettingsDict.active_only`: an agent that only connects out + (NetOrk/netork#2683). `zabbix_agent_config` writes `StartAgents=0` -- no passive + checks, no listening port -- and comments `Server` out, which Zabbix requires only + while `StartAgents` is not 0; `check_zabbix_agent_settings` then requires + `server_active` instead of `server`. `configure_zabbix_agent`'s firewall step opens + nothing for it and does not call the driver's `_allow_zabbix_agent_sources`, so no + driver changes. + +### Changed +- `zabbix_agent_config` comments a `StartAgents=0` line out for an agent that is not + active only, since it would keep the agent from listening; another count stays. ## [4.41.0] - 2026-11-17 diff --git a/README.md b/README.md index feda9de..3887427 100644 --- a/README.md +++ b/README.md @@ -126,7 +126,8 @@ firewall, start), `LldpAgentMixin.configure_lldp_agent(interfaces)` (install, wr interfaces, enable and restart; the driver writes only the interfaces), `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)`, +configuration and opens the firewall; an `active_only` agent gets `StartAgents=0` and no +firewall opening), `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 diff --git a/napalm_device_types/fixes.py b/napalm_device_types/fixes.py index c55075c..94c022c 100644 --- a/napalm_device_types/fixes.py +++ b/napalm_device_types/fixes.py @@ -215,7 +215,8 @@ class ZabbixAgentMixin: 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. + let the allowed sources through the host's firewall -- not for an agent that is + ``active_only``, which listens on no port --, 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. @@ -242,7 +243,7 @@ class ZabbixAgentMixin: [ ("install", lambda: self._install_zabbix_agent(settings)), ("configure", lambda: self._write_zabbix_agent_config(settings)), - ("firewall", lambda: self._allow_zabbix_agent_sources(settings)), + ("firewall", lambda: self._open_zabbix_agent_port(settings)), ("start", self._start_zabbix_agent), ] ) @@ -276,6 +277,13 @@ class ZabbixAgentMixin: return "" return f"package index not loaded: {str(loaded.get('output', '')).strip()}" + def _open_zabbix_agent_port(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict: + """The driver's firewall step; nothing for an agent that only connects out, + which listens on no port (NetOrk/netork#2683).""" + if settings.get("active_only"): + return {"ok": True, "output": "active only: the agent listens on no port"} + return self._allow_zabbix_agent_sources(settings) + def _start_zabbix_agent(self) -> FixStepOutcomeDict: return enable_and_restart(self.manage_service, self.ZABBIX_AGENT_SERVICE) @@ -306,7 +314,8 @@ class ZabbixAgentMixin: 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 [].""" + nothing to do where the host has no firewall of its own, or for []. Not + called for an ``active_only`` agent.""" ... diff --git a/napalm_device_types/zabbix_agent.py b/napalm_device_types/zabbix_agent.py index 53854d3..8db6bfe 100644 --- a/napalm_device_types/zabbix_agent.py +++ b/napalm_device_types/zabbix_agent.py @@ -12,6 +12,13 @@ reads and writes the file and runs the command. ``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. +**Active only** (NetOrk/netork#2683). An agent whose site only lets it connect out +gets ``StartAgents=0``: Zabbix's agent then runs no passive checks and listens on no +port. ``Server`` is mandatory only while ``StartAgents`` is not 0, so it is commented +out -- nobody may ask -- and ``ServerActive`` is required instead. An agent that is not +active only gets a ``StartAgents=0`` line commented out, since it would keep the agent +from listening; another count of listeners stays. + **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 ``//``, @@ -39,6 +46,9 @@ class ZabbixAgentSettingsDict(TypedDict): # 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] + # the agent only connects out: StartAgents=0, Server commented out (``server`` may be + # ""), ServerActive required, and the firewall step opens nothing; absent: False + active_only: NotRequired[bool] #: Addresses, comma-separated, as ``Server`` and ``ServerActive`` take them: names, @@ -49,7 +59,7 @@ _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") +_KEYS = ("Server", "ServerActive", "ListenPort", "Hostname", "StartAgents") _LINE = re.compile(r"^(\s*)(" + "|".join(_KEYS) + r")\s*=\s*(.*?)\s*$") REPOSITORY = "https://repo.zabbix.com/zabbix" @@ -72,8 +82,11 @@ def check_zabbix_agent_settings(settings: ZabbixAgentSettingsDict) -> None: :raises ValueError: naming the setting. """ - _check_addresses("Server", str(settings.get("server", "")), required=True) - _check_addresses("ServerActive", str(settings.get("server_active", "")), required=False) + active_only = settings.get("active_only", False) + if not isinstance(active_only, bool): + raise ValueError(f"active_only is True or False, not {active_only!r}") + _check_addresses("Server", str(settings.get("server", "")), required=not active_only) + _check_addresses("ServerActive", str(settings.get("server_active", "")), required=active_only) hostname = settings.get("hostname") if hostname is not None and not _HOSTNAME.match(hostname): raise ValueError(f"not a Zabbix host name: {hostname!r}") @@ -91,34 +104,49 @@ def _check_addresses(key: str, value: str, *, required: bool) -> None: def _wanted(settings: ZabbixAgentSettingsDict) -> dict[str, str]: + """The value of each key the caller sets; "" comments the key out.""" + active_only = bool(settings.get("active_only")) wanted = { - "Server": settings["server"], + "Server": "" if active_only else settings["server"], "ServerActive": settings.get("server_active", ""), "ListenPort": str(settings["listen_port"]), } if settings.get("hostname"): wanted["Hostname"] = str(settings["hostname"]) + if active_only: + wanted["StartAgents"] = "0" return wanted +def _unwanted(settings: ZabbixAgentSettingsDict) -> dict[str, str]: + """Lines commented out where they hold this value, though the caller sets no value + for their key: ``StartAgents=0`` would keep an agent that is not active only from + listening.""" + return {} if settings.get("active_only") else {"StartAgents": "0"} + + 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. + passive checks only. ``active_only`` is the other way round: ``StartAgents=0`` + and ``Server`` commented out. """ - wanted = _wanted(settings) + wanted, unwanted = _wanted(settings), _unwanted(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: + key = match.group(2) if match else "" + if match and key in wanted: + seen.add(key) + lines.append(_set_line(line, match, wanted, changes)) + elif match and unwanted.get(key) == match.group(3): + lines.append(_set_line(line, match, {key: ""}, changes)) + else: 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 ) diff --git a/tests/test_zabbix_agent.py b/tests/test_zabbix_agent.py index 483c28e..3a40fce 100644 --- a/tests/test_zabbix_agent.py +++ b/tests/test_zabbix_agent.py @@ -97,6 +97,75 @@ class TestConfig: assert text.count("Server=zabbix.example.com\n") == 2 +ACTIVE_ONLY = {**SETTINGS, "active_only": True, "allowed_sources": []} + + +class TestActiveOnly: + """A site whose agents only connect out (NetOrk/netork#2683): no passive listener. + + Zabbix's ``StartAgents=0`` disables passive checks and the agent listens on no + port; ``Server`` is mandatory only while ``StartAgents`` is not 0, so nothing is + left that may ask. + """ + + def test_it_starts_no_listener_and_lets_nobody_ask(self): + text, changes = zabbix_agent_config(SAMPLE, ACTIVE_ONLY) + + assert text.endswith("StartAgents=0\n") + assert "\n# Server=127.0.0.1\n" in text + assert "\nServer=" not in text + assert "\nServerActive=zabbix.example.com\n" in text + assert "\nHostname=ap-1og\n" in text + assert "StartAgents: (not set) → 0" in changes + assert "Server: 127.0.0.1 → (not set)" in changes + + def test_a_listener_count_of_its_own_becomes_none(self): + text, changes = zabbix_agent_config("StartAgents=5\n", ACTIVE_ONLY) + + assert text.startswith("StartAgents=0\n") + assert "StartAgents: 5 → 0" in changes + + def test_a_file_that_already_says_it_changes_nothing(self): + text, _ = zabbix_agent_config(SAMPLE, ACTIVE_ONLY) + + again, changes = zabbix_agent_config(text, ACTIVE_ONLY) + + assert again == text + assert changes == [] + + def test_a_passive_agent_listens_again(self): + """An agent that was active only before: ``StartAgents=0`` would keep it deaf.""" + text, _ = zabbix_agent_config(SAMPLE, ACTIVE_ONLY) + + again, changes = zabbix_agent_config(text, SETTINGS) + + assert "\n# StartAgents=0\n" in again + assert "\nServer=zabbix.example.com\n" in again + assert "StartAgents: 0 → (not set)" in changes + + def test_a_passive_agent_keeps_its_own_listener_count(self): + text, changes = zabbix_agent_config("StartAgents=5\n", SETTINGS) + + assert text.startswith("StartAgents=5\n") + assert not any(c.startswith("StartAgents") for c in changes) + + def test_it_needs_somewhere_to_send_its_checks(self): + with pytest.raises(ValueError): + check_zabbix_agent_settings({**ACTIVE_ONLY, "server_active": ""}) + + def test_it_needs_no_server_that_may_ask(self): + check_zabbix_agent_settings({**ACTIVE_ONLY, "server": ""}) + + def test_a_server_that_is_not_addresses_is_still_refused(self): + with pytest.raises(ValueError): + check_zabbix_agent_settings({**ACTIVE_ONLY, "server": "a\nb"}) + + @pytest.mark.parametrize("value", ["yes", 1, None]) + def test_active_only_is_a_bool(self, value): + with pytest.raises(ValueError): + check_zabbix_agent_settings({**SETTINGS, "active_only": value}) + + class TestSettings: @pytest.mark.parametrize( "server", @@ -327,6 +396,17 @@ class TestZabbixAgentMixin: assert result["success"] is True assert agent.calls[0] == ("ensure_package", "zabbix-agent") + def test_an_active_only_agent_opens_no_port(self): + """NetOrk/netork#2683: nothing listens, so nothing is let through.""" + agent = _Agent() + + result = agent.configure_zabbix_agent({**ACTIVE_ONLY, "allowed_sources": ["10.0.0.1"]}) + + assert result["success"] is True + assert not [c for c in agent.calls if c[0] == "firewall"] + assert [s["step"] for s in result["steps"]] == ["install", "configure", "firewall", "start"] + assert "active only" in result["steps"][2]["output"] + def test_a_closed_firewall_starts_nothing(self): agent = _Agent(refuse=frozenset({"firewall"}))