feat(lldp): configure_lldp_agent sets up lldpd on the given interfaces
driver / standard (pull_request) Successful in 16s
driver / lint (pull_request) Successful in 12s
driver / types (pull_request) Failing after 1m1s
driver / test (3.12) (pull_request) Failing after 59s
driver / test (3.13) (pull_request) Failing after 49s
driver / lowest (pull_request) Failing after 25s
driver / build (pull_request) Successful in 27s
driver / security (pull_request) Successful in 1m1s
CI / driver (pull_request) Failing after 2m28s
driver / publish (pull_request) Skipped

The LLDP getters started lldpd and rewrote its interface list on every
poll; with read-only getters that setup needs an action. The driver
mixes in napalm-device-types' LldpAgentMixin and writes the step the
template leaves to it: lldpd.config.interface in UCI. A VLAN device is
written as the device under it, as the old helper did, since lldpd
sends on the L2 device. Which interfaces is the caller's choice.

Refs #8
This commit is contained in:
Christian Manivong committed 2026-11-01 22:13:56 +01:00
1 parent d78a55dd1a
commit 5cce38b2bb
5 files changed
+202

No files matched your search

+7
View File
@@ -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).
+8
View File
@@ -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
+70
View File
@@ -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<parent>.+)\.\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]: ...
+2
View File
@@ -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,
):
+115
View File
@@ -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"]