diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d0cf84..9164633 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,13 @@ recorded here; their history is the git log. ## [Unreleased] +### Added +- `configure_lldp_agent(interfaces)` (napalm-device-types `LldpAgentMixin`): installs + lldpd where it is missing, writes the interfaces given as lldpd's interface list in + UCI, enables lldpd at boot and restarts it. A VLAN device (`br-ap.10`) is written as + the device under it (`br-ap`). It is the action for the setup the LLDP getters used + to do on every poll (#8). Needs napalm-device-types with `LldpAgentMixin`. + ### Changed - Python 3.12 is the floor (`requires-python = ">=3.12"`): netOrk runs every driver on 3.12, so 3.10 and 3.11 are no longer tested (NAPALM/driver-standard#6). diff --git a/README.md b/README.md index bbcaf7b..e7aa87f 100644 --- a/README.md +++ b/README.md @@ -102,6 +102,14 @@ device.commit_config() device.rollback() ``` +## LLDP agent + +`configure_lldp_agent(interfaces)` (napalm-device-types `LldpAgentMixin`) installs +`lldpd` where it is missing, sets its interface list (`lldpd.config.interface` in UCI) +to the interfaces given, enables it at boot and restarts it. A VLAN device such as +`br-ap.10` is written as the device under it (`br-ap`): lldpd sends on the L2 device. +Which interfaces is the caller's choice; at least one is required. + ## Development ```bash diff --git a/napalm_openwrt/lldp_agent.py b/napalm_openwrt/lldp_agent.py new file mode 100644 index 0000000..eb52f13 --- /dev/null +++ b/napalm_openwrt/lldp_agent.py @@ -0,0 +1,70 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""lldpd's interface list in UCI, the step of napalm-device-types' ``LldpAgentMixin``. + +The template installs lldpd (``ensure_package``) and enables and restarts it +(``manage_service``); this writes ``lldpd.config.interface``, which lldpd's init +script turns into ``-I``. +""" + +from __future__ import annotations + +import re +from collections.abc import Sequence +from typing import TYPE_CHECKING, Any, cast + +from napalm_device_types import FixStepOutcomeDict, LldpAgentMixin + +#: An interface name that may stand in single quotes in a shell line. +_IFNAME = re.compile(r"^[A-Za-z0-9_.@-]+$") +#: An 802.1Q device as OpenWrt names it: the device under it, a dot, the VLAN id. +_VLAN_DEVICE = re.compile(r"^(?P.+)\.\d+$") +_UCI_LIST = "lldpd.config.interface" + + +def lldp_devices(interfaces: Sequence[str]) -> list[str]: + """The devices lldpd runs on for *interfaces*, in order and once each. + + lldpd sends on the L2 device, so a VLAN device (``br-ap.10``) counts as the + device under it (``br-ap``). + + :raises ValueError: for a name that is not an interface name. + """ + devices: list[str] = [] + for name in interfaces: + if not _IFNAME.match(name): + raise ValueError(f"not an interface name: {name!r}") + vlan = _VLAN_DEVICE.match(name) + device = vlan.group("parent") if vlan else name + if device not in devices: + devices.append(device) + return devices + + +class OpenWrtLldpAgentMixin(LldpAgentMixin): + """lldpd on the interfaces the caller names, through UCI.""" + + def _write_lldp_agent_config(self, interfaces: list[str]) -> FixStepOutcomeDict: + devices = lldp_devices(interfaces) + commands = [ + "(uci -q get lldpd.config >/dev/null || uci set lldpd.config=lldpd)", + f"(uci -q delete {_UCI_LIST} || true)", + *(f"uci add_list {_UCI_LIST}='{device}'" for device in devices), + "uci commit lldpd", + ] + done = f"lldpd runs on {', '.join(devices)}" + return cast(FixStepOutcomeDict, self._rc_step(" && ".join(commands), done)) + + if TYPE_CHECKING: # pragma: no cover - the driver's + + def _rc_step(self, command: str, done: str) -> dict[str, Any]: ... diff --git a/napalm_openwrt/openwrt.py b/napalm_openwrt/openwrt.py index f48b3ee..e08864d 100644 --- a/napalm_openwrt/openwrt.py +++ b/napalm_openwrt/openwrt.py @@ -43,6 +43,7 @@ from netmiko.exceptions import NetmikoAuthenticationException, NetmikoTimeoutExc from napalm_openwrt.config_mixin import OpenWrtConfigMixin from napalm_openwrt.interfaces_mixin import OpenWrtInterfaceMixin +from napalm_openwrt.lldp_agent import OpenWrtLldpAgentMixin from napalm_openwrt.lldp_mixin import OpenWrtLLDPMixin from napalm_openwrt.packages_mixin import OpenWrtPackageMixin from napalm_openwrt.routing_mixin import OpenWrtRoutingMixin @@ -78,6 +79,7 @@ class OpenWrtDriver( OpenWrtRoutingMixin, ListeningSocketsMixin, SnmpAgentMixin, + OpenWrtLldpAgentMixin, EnsurePackageMixin, AccessPointDriver, ): diff --git a/tests/unit/test_lldp_agent.py b/tests/unit/test_lldp_agent.py new file mode 100644 index 0000000..c257231 --- /dev/null +++ b/tests/unit/test_lldp_agent.py @@ -0,0 +1,115 @@ +"""configure_lldp_agent: lldpd on the interfaces the caller names (#8). + +The LLDP getters used to start lldpd and rewrite its interface list on every +poll. That is an action now, napalm-device-types' ``LldpAgentMixin``: the +template installs and starts lldpd, the driver writes the list into UCI. +""" + +from __future__ import annotations + +import pytest + +from napalm_openwrt import OpenWrtDriver + + +class _Shell: + """Collects issued commands; *fail* makes a command containing it exit 1.""" + + def __init__(self, fail: str = ""): + self.fail = fail + self.issued: list[str] = [] + + def __call__(self, cmd, **kw): + self.issued.append(cmd) + if "__OWRT_RC" in cmd: + if self.fail and self.fail in cmd: + return "uci: Invalid argument\n__OWRT_RC=1" + return "__OWRT_RC=0" + return "" + + +@pytest.fixture +def shell(): + return _Shell() + + +@pytest.fixture +def owrt(shell): + d = OpenWrtDriver("ap", "root", "pw") + d._send_command = shell + d.get_packages = lambda: [{"name": "lldpd", "version": "1.0.17-1", "installed": True}] + return d + + +def _uci(shell) -> str: + return next(c for c in shell.issued if "uci commit lldpd" in c) + + +def test_install_configure_enable_and_restart(owrt, shell): + result = owrt.configure_lldp_agent(["br-lan"]) + + assert result["success"] is True, result["output"] + assert [s["step"] for s in result["steps"]] == ["install", "configure", "start"] + uci = _uci(shell) + assert "uci -q delete lldpd.config.interface" in uci + assert "uci add_list lldpd.config.interface='br-lan'" in uci + lldpd = [c.split(" 2>")[0] for c in shell.issued if c.startswith("/etc/init.d/lldpd")] + assert lldpd == ["/etc/init.d/lldpd enable", "/etc/init.d/lldpd restart"] + + +def test_the_list_is_replaced_and_a_missing_section_is_made(owrt, shell): + owrt.configure_lldp_agent(["br-lan", "eth1"]) + + uci = _uci(shell) + assert "uci set lldpd.config=lldpd" in uci + assert uci.index("delete lldpd.config.interface") < uci.index("add_list") + assert "interface='br-lan'" in uci + assert "interface='eth1'" in uci + + +def test_a_vlan_device_is_written_as_the_device_under_it(owrt, shell): + # lldpd sends on the L2 device: on br-ap, not on its VLAN br-ap.10. + owrt.configure_lldp_agent(["br-ap.10", "br-ap"]) + + uci = _uci(shell) + assert "interface='br-ap'" in uci + assert "br-ap.10" not in uci + assert uci.count("add_list") == 1 + + +def test_a_name_that_is_not_an_interface_name_writes_nothing(owrt, shell): + result = owrt.configure_lldp_agent(["br-lan'; reboot; '"]) + + assert result["success"] is False + assert result["steps"][-1]["step"] == "configure" + assert not any("uci" in c or "lldpd restart" in c for c in shell.issued) + + +def test_a_refused_uci_write_leaves_lldpd_alone(): + shell = _Shell(fail="uci commit lldpd") + d = OpenWrtDriver("ap", "root", "pw") + d._send_command = shell + d.get_packages = lambda: [{"name": "lldpd", "installed": True}] + + result = d.configure_lldp_agent(["br-lan"]) + + assert result["success"] is False + assert "Invalid argument" in result["output"] + assert not any("/etc/init.d/lldpd" in c for c in shell.issued) + + +def test_lldpd_is_installed_where_it_is_missing(owrt, shell): + owrt.get_packages = lambda: [] + asked: list[str] = [] + owrt.install_package = lambda name, version="": ( + asked.append(name) + or { + "success": True, + "output": f"installed {name}", + } + ) + + result = owrt.configure_lldp_agent(["br-lan"]) + + assert result["success"] is True + assert asked == ["lldpd"]