From b1ea36467458848153770f450d23eeb7cf3f2607 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Wed, 25 Nov 2026 21:24:39 +0100 Subject: [PATCH 1/3] feat(zabbix): an agent that only connects out listens on no port (NetOrk/netork#2683) ZabbixAgentSettingsDict.active_only: zabbix_agent_config writes StartAgents=0 and comments Server out (mandatory only while StartAgents is not 0); ServerActive is required instead. configure_zabbix_agent's firewall step opens nothing for it. An agent that is not active only gets a StartAgents=0 line commented out. --- CHANGELOG.md | 11 ++++ README.md | 3 +- napalm_device_types/fixes.py | 15 ++++-- napalm_device_types/zabbix_agent.py | 48 +++++++++++++---- tests/test_zabbix_agent.py | 80 +++++++++++++++++++++++++++++ 5 files changed, 143 insertions(+), 14 deletions(-) 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"})) From cd47587e80a093dd372c50617a030940a14fb3c0 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Wed, 25 Nov 2026 21:26:37 +0100 Subject: [PATCH 2/3] feat(hypervisor): resume_vm, and a paused guest is never running (NetOrk/netork#2658) The contract could suspend a VM but not bring it back: suspend_vm pointed at start_vm, which Proxmox refuses for a paused guest because it is still running. resume_vm is declared beside suspend_vm, optional like every power action, and get_vms() says a guest that is not executing is paused or suspended, never running. --- CHANGELOG.md | 10 ++++++++++ napalm_device_types/hypervisor.py | 32 +++++++++++++++++++++++++++++-- tests/test_role_contracts.py | 23 ++++++++++++++++++++++ 3 files changed, 63 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e30484..3845310 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,16 @@ 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`. +- `HypervisorDriver.resume_vm(name)`: bring a paused or suspended VM back where it stopped, + the counterpart of `suspend_vm` (NetOrk/netork#2658). Optional like every power action; + a driver that can resume some guests but not others refuses the others with + `RuntimeError`. + +### Changed +- `HypervisorDriver.get_vms()`: a guest that is not executing is never `"running"`. It is + `"paused"` while its process still holds its memory and `"suspended"` once its state was + saved away (NetOrk/netork#2658). `suspend_vm` names `resume_vm`, not `start_vm`, as the + way back. ## [4.41.0] - 2026-11-17 diff --git a/napalm_device_types/hypervisor.py b/napalm_device_types/hypervisor.py index 8784884..bc66e94 100644 --- a/napalm_device_types/hypervisor.py +++ b/napalm_device_types/hypervisor.py @@ -71,7 +71,11 @@ class HypervisorDriver(PackageManagementMixin, HealthMetricsMixin, DeviceTypeDri * name (string) - VM display name * vmid (string) - hypervisor-internal ID (Proxmox: ``"100"``, VMware: the instance UUID) - * status (string) - ``"running"``, ``"stopped"``, ``"paused"``, ``"suspended"`` + * status (string) - ``"running"``, ``"stopped"``, ``"paused"``, ``"suspended"``. + A guest that is not executing is never ``"running"``: ``"paused"`` + while its process still holds its memory (Proxmox's ``qmpstatus`` + ``paused``), ``"suspended"`` once its state was saved away (VMware's + ``suspended``). :meth:`resume_vm` brings either back. * vcpus (int) - number of virtual CPUs assigned * memory (int) - configured RAM in megabytes * cpu_usage (float) - current CPU utilisation 0.0–1.0 @@ -248,7 +252,9 @@ class HypervisorDriver(PackageManagementMixin, HealthMetricsMixin, DeviceTypeDri def suspend_vm(self, name: str) -> None: """ Suspends (pauses) a running virtual machine, preserving its in-memory - state. The VM can be resumed with :meth:`start_vm`. + state. :meth:`get_vms` then reports it ``"paused"`` (its process + still holds the memory) or ``"suspended"`` (its state was saved + away), and :meth:`resume_vm` brings it back. :param name: VM name or its ``vmid``. :raises ValueError: If no VM with the given name/ID exists. @@ -260,6 +266,28 @@ class HypervisorDriver(PackageManagementMixin, HealthMetricsMixin, DeviceTypeDri """ ... + def resume_vm(self, name: str) -> None: + """ + Resumes a paused or suspended virtual machine where it stopped, the + counterpart of :meth:`suspend_vm`. The method blocks until the + hypervisor took the request. + + Optional, like every power action: a driver whose platform cannot + resume a guest does not implement it, and a caller then offers no + resume. A driver that can resume some guests but not others (a + Proxmox container) refuses the others with ``RuntimeError``. + + :param name: VM name or its ``vmid``. + :raises ValueError: If no VM with the given name/ID exists. + :raises RuntimeError: If the VM is neither paused nor suspended, or + the platform cannot resume this kind of guest. + + Example:: + + driver.resume_vm("web01") + """ + ... + # ------------------------------------------------------------------ # Snapshots # ------------------------------------------------------------------ diff --git a/tests/test_role_contracts.py b/tests/test_role_contracts.py index d2baec4..00f1c4c 100644 --- a/tests/test_role_contracts.py +++ b/tests/test_role_contracts.py @@ -12,6 +12,7 @@ These tests pin the property that prevents a fourth. from __future__ import annotations +import ast import inspect import pytest @@ -82,6 +83,7 @@ class TestDeclaredMethodsDoNotExistAtRuntime: (StorageDriver, "get_disks"), (StorageDriver, "get_volumes"), (HypervisorDriver, "get_vms"), + (HypervisorDriver, "resume_vm"), (FirewallDriver, "send_wake_on_lan"), (SwitchDriver, "set_vlan"), (AccessPointDriver, "get_wireless_config"), @@ -101,6 +103,27 @@ class TestDeclaredMethodsDoNotExistAtRuntime: assert not hasattr(base, method) +class TestHypervisorPowerContract: + """The power actions a hypervisor driver may implement, as declared.""" + + @staticmethod + def _declared(module) -> dict[str, list[str]]: + tree = ast.parse(inspect.getsource(module)) + methods: dict[str, list[str]] = {} + for node in ast.walk(tree): + if isinstance(node, ast.FunctionDef): + methods[node.name] = [a.arg for a in node.args.args] + return methods + + def test_resume_vm_is_declared_beside_suspend_vm(self): + """A VM netOrk paused must be one it can bring back (NetOrk/netork#2658).""" + from napalm_device_types import hypervisor + + declared = self._declared(hypervisor) + assert declared.get("suspend_vm") == ["self", "name"] + assert declared.get("resume_vm") == ["self", "name"] + + class TestNoShadowingAcrossRoles: """The regression test for the bug class.""" From ae21c7fba799e5bf5637343654cc5c0420278e2a Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Wed, 25 Nov 2026 22:09:09 +0100 Subject: [PATCH 3/3] chore(release): 4.42.0 --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 220cce4..f2e655a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "napalm-device-types" -version = "4.41.0" +version = "4.42.0" description = "Abstract device-type base classes for NAPALM drivers" readme = "README.md" requires-python = ">=3.12"