diff --git a/CHANGELOG.md b/CHANGELOG.md index 9ad65a9..d1d64b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,13 @@ recorded here; their history is the git log. 3.12 venv no longer has. ### Added +- `LldpAgentMixin.configure_lldp_agent(interfaces)` (`napalm_device_types.fixes`): run + an LLDP agent on the interfaces the caller names. The template installs the agent + (`ensure_package(LLDP_AGENT_PACKAGE)`), has the driver write the interface list + (`_write_lldp_agent_config`), then enables and restarts the service + (`manage_service(LLDP_AGENT_SERVICE, …)`); both names default to `lldpd`. No + interface is a ValueError before anything changes. It is the action for what LLDP + getters used to do on their own (NAPALM/napalm-openwrt#8). - `HypervisorDriver.get_clusters()` and its shapes `ClusterDict`, `ClusterNodeDict`, `ClusterStorageDict`, `ClusterNetworkDict`: every cluster the connection can see, with its nodes (offline ones included, `local` on the node the connection is), diff --git a/README.md b/README.md index 8a4c22e..54a6d9a 100644 --- a/README.md +++ b/README.md @@ -110,8 +110,9 @@ VM's clean shutdown without waiting for it — a hypervisor driver mixes it in w **Fixes are templates** (`napalm_device_types.fixes`, since 4.13). A change the application wants made on a device runs as fixed steps the driver implements, with values the caller supplies: `SnmpAgentMixin.configure_snmp_agent(settings)` (install, configure, -firewall, start), `EnsurePackageMixin.ensure_package(name)`, -`PackageProxyMixin.configure_package_proxy(url)` and +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)` 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 can take; none is on a role base. They replace `run_device_action`, which is deprecated. diff --git a/napalm_device_types/__init__.py b/napalm_device_types/__init__.py index 743e0d5..3d114dd 100644 --- a/napalm_device_types/__init__.py +++ b/napalm_device_types/__init__.py @@ -107,6 +107,7 @@ from napalm_device_types.firewall_rules import FirewallRuleMixin from napalm_device_types.firmware import FirmwareOfferMixin from napalm_device_types.fixes import ( EnsurePackageMixin, + LldpAgentMixin, PackageProxyMixin, SnmpAgentMixin, run_fix_steps, @@ -260,6 +261,7 @@ __all__ = [ "FixResultDict", "FixStepDict", "FixStepOutcomeDict", + "LldpAgentMixin", "PackageProxyMixin", "APT_PROXY_COMMAND", "AptProxyMixin", diff --git a/napalm_device_types/fixes.py b/napalm_device_types/fixes.py index a3335d6..db1dc2f 100644 --- a/napalm_device_types/fixes.py +++ b/napalm_device_types/fixes.py @@ -22,7 +22,7 @@ They replace ``run_device_action`` (docs/STRUCTURE.md): from __future__ import annotations from collections.abc import Callable, Sequence -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, ClassVar from napalm_device_types.models import ( FixResultDict, @@ -133,6 +133,66 @@ class EnsurePackageMixin: def install_package(self, name: str, version: str = "") -> None: ... +class LldpAgentMixin: + """Run an LLDP agent on the device, on the interfaces the caller names. + + The steps: install the agent, write the interfaces it runs on, enable it at boot + and restart it so it reads them. Installing and starting are generic, over + ``ensure_package`` and ``manage_service`` with ``LLDP_AGENT_PACKAGE`` and + ``LLDP_AGENT_SERVICE``; the driver writes the configuration. Which interfaces is + the caller's choice -- an agent on every interface also talks to the uplink of a + WAN port. Whether neighbours appear is the caller's to read with + ``get_lldp_neighbors``, after the agent's first advertisement interval. + """ + + #: The package that brings the agent, as ``ensure_package`` takes it. + LLDP_AGENT_PACKAGE: ClassVar[str] = "lldpd" + #: The agent's service, as ``manage_service`` takes it. + LLDP_AGENT_SERVICE: ClassVar[str] = "lldpd" + + def configure_lldp_agent(self, interfaces: Sequence[str]) -> FixResultDict: + """Install, configure for *interfaces*, enable and restart the agent. + + :raises ValueError: for no interface, before anything changes. + """ + names = [str(name) for name in interfaces] + if not names: + raise ValueError("name at least one interface for the LLDP agent") + return run_fix_steps( + [ + ("install", self._install_lldp_agent), + ("configure", lambda: self._write_lldp_agent_config(names)), + ("start", self._start_lldp_agent), + ] + ) + + def _install_lldp_agent(self) -> FixStepOutcomeDict: + result = self.ensure_package(self.LLDP_AGENT_PACKAGE) + 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"} + + 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]: ... + + # The step a driver implements: + + def _write_lldp_agent_config(self, interfaces: list[str]) -> FixStepOutcomeDict: + """Have the agent send and listen on exactly *interfaces* (names as the + device's interface getters report them), replacing the list it had.""" + ... + + class PackageProxyMixin: """Point the device's package manager at a caching proxy.""" @@ -152,6 +212,7 @@ class PackageProxyMixin: __all__ = [ "EnsurePackageMixin", "FixStep", + "LldpAgentMixin", "PackageProxyMixin", "SnmpAgentMixin", "run_fix_steps", diff --git a/tests/test_fix_templates.py b/tests/test_fix_templates.py index e6b866f..6c1adfc 100644 --- a/tests/test_fix_templates.py +++ b/tests/test_fix_templates.py @@ -14,6 +14,7 @@ from napalm_device_types import ( EnsurePackageMixin, FirewallDriver, HypervisorDriver, + LldpAgentMixin, ManagementControllerDriver, MediaDriver, OSDriver, @@ -169,11 +170,91 @@ class TestEnsurePackage: assert "no candidate" in result["output"] +class _Lldp(LldpAgentMixin): + """The generic steps over ensure_package and manage_service; the driver's configure.""" + + def __init__(self, refuse: str = ""): + self.calls: list = [] + self.refuse = refuse + + def ensure_package(self, name): + self.calls.append(("ensure_package", name)) + ok = self.refuse != "install" + return {"success": ok, "steps": [], "output": "installed" if ok else "E: no candidate"} + + def _write_lldp_agent_config(self, interfaces): + self.calls.append(("configure", interfaces)) + return {"ok": self.refuse != "configure", "output": "interfaces set"} + + def manage_service(self, name, action): + self.calls.append((action, name)) + ok = self.refuse != action + return {"success": ok, "output": "" if ok else f"cannot {action}"} + + +class TestLldpAgent: + def test_install_configure_enable_and_restart_on_the_caller_s_interfaces(self): + agent = _Lldp() + + result = agent.configure_lldp_agent(["br-lan"]) + + assert result["success"] is True + assert agent.calls == [ + ("ensure_package", "lldpd"), + ("configure", ["br-lan"]), + ("enable", "lldpd"), + ("restart", "lldpd"), + ] + assert [s["step"] for s in result["steps"]] == ["install", "configure", "start"] + + def test_a_failed_install_configures_nothing(self): + agent = _Lldp(refuse="install") + + result = agent.configure_lldp_agent(["br-lan"]) + + assert result["success"] is False + assert agent.calls == [("ensure_package", "lldpd")] + assert "no candidate" in result["output"] + + def test_an_agent_that_will_not_start_at_boot_is_not_restarted(self): + agent = _Lldp(refuse="enable") + + result = agent.configure_lldp_agent(["br-lan"]) + + assert result["success"] is False + assert ("restart", "lldpd") not in agent.calls + assert "cannot enable" in result["output"] + + def test_a_failed_restart_fails_the_fix(self): + result = _Lldp(refuse="restart").configure_lldp_agent(["br-lan"]) + + assert result["success"] is False + assert result["steps"][-1]["step"] == "start" + + def test_the_package_and_service_names_are_the_driver_s(self): + agent = _Lldp() + agent.LLDP_AGENT_PACKAGE = "lldpd-full" + agent.LLDP_AGENT_SERVICE = "lldpd.service" + + agent.configure_lldp_agent(["eth0"]) + + assert ("ensure_package", "lldpd-full") in agent.calls + assert ("restart", "lldpd.service") in agent.calls + + def test_no_interface_is_refused_before_anything_changes(self): + agent = _Lldp() + + with pytest.raises(ValueError): + agent.configure_lldp_agent([]) + assert agent.calls == [] + + @pytest.mark.parametrize("base", ROLE_BASES, ids=lambda b: b.__name__) @pytest.mark.parametrize( "method", [ "configure_snmp_agent", + "configure_lldp_agent", "ensure_package", "configure_package_proxy", "grant_container_engine_access",