fix(lldp): keep every neighbour on a port

The keyvalue output was grouped by local interface only, so with several
neighbours on one port their keys overwrote each other and one mixed
entry came back. A neighbour now ends where the next one opens (alias,
then via, as lldpd prints it); a key repeated inside one neighbour, such
as one mgmt-ip per address, does not start a new one.

Closes #9
This commit is contained in:
Christian Manivong committed 2026-11-01 21:47:34 +01:00
1 parent 097d9b9581
commit 5e71f0b471
3 files changed
+88 -16

No files matched your search

+3
View File
@@ -27,6 +27,9 @@ recorded here; their history is the git log.
- `get_environment()` reports the CPU usage of the last second, from two reads of
`/proc/stat` one second apart; it used to report the average since boot, so a box
busy for the last minute could show a low figure (#10).
- `get_lldp_neighbors()` and `get_lldp_neighbors_detail()` report every neighbour
on a port (a phone with a PC behind it, a switch without LLDP of its own); only
the last one came back, mixed with fields of the others (#9).
## [0.7.0] - 2026-10-23
+28 -16
View File
@@ -14,6 +14,33 @@ from __future__ import annotations
from typing import Any
#: The keys a neighbour opens with in ``lldpctl -f keyvalue``: an optional
#: ``alias``, then ``via`` (lldpd's ``display_interface``).
_NEIGHBOUR_START = ("alias", "via")
def _keyvalue_neighbours(output: str) -> list[tuple[str, dict[str, str]]]:
"""``lldpctl -f keyvalue`` as ``(local interface, {subkey: value})``, one per neighbour.
Every neighbour on a port prints the same keys, so a port is no key: a
neighbour ends where the next one opens. A key may repeat inside one
neighbour (``chassis.mgmt-ip``, one per address); the last value stays.
"""
neighbours: list[tuple[str, dict[str, str]]] = []
for line in output.splitlines():
key, sep, value = line.strip().partition("=")
parts = key.split(".")
# parts: ['lldp', '<iface>', <category>, <field>, ...]
if not sep or len(parts) < 3 or parts[0] != "lldp":
continue
iface, subkey = parts[1], ".".join(parts[2:])
current = neighbours[-1][1] if neighbours and neighbours[-1][0] == iface else None
if current is None or (subkey in _NEIGHBOUR_START and set(current) - {"alias"}):
current = {}
neighbours.append((iface, current))
current[subkey] = value
return neighbours
class OpenWrtLLDPMixin:
"""Mixin providing LLDP NAPALM getters."""
@@ -78,22 +105,7 @@ class OpenWrtLLDPMixin:
output = self._send_command("lldpctl -f keyvalue")
rows: list[dict[str, Any]] = []
# Group by local interface prefix: lldp.<iface>.*
entries: dict[str, dict[str, str]] = {}
for line in output.splitlines():
line_s = line.strip()
if "=" not in line_s:
continue
key, _, value = line_s.partition("=")
parts = key.split(".")
# parts: ['lldp', '<iface>', <category>, <field>, ...]
if len(parts) < 3 or parts[0] != "lldp":
continue
iface = parts[1]
subkey = ".".join(parts[2:])
entries.setdefault(iface, {})[subkey] = value
for iface, data in entries.items():
for iface, data in _keyvalue_neighbours(output):
rows.append(
{
"local_port": iface,
+57
View File
@@ -336,6 +336,63 @@ class TestGetLldpNeighbors:
assert result["eth0"][0]["port"] == "ether1"
# Two neighbours on one port, laid out the way lldpd's keyvalue writer prints them
# (src/client/display.c, kv_writer.c): every neighbour opens with an optional
# ``alias`` and then ``via``, and the same key may repeat inside one neighbour
# (one ``chassis.mgmt-ip`` per address). Not recorded from a device.
LLDPCTL_KV_TWO_ON_ONE_PORT = """\
lldp.lan1.via=LLDP
lldp.lan1.rid=1
lldp.lan1.age=0 day, 00:10:00
lldp.lan1.chassis.mac=00:11:22:33:44:01
lldp.lan1.chassis.name=desk-phone
lldp.lan1.chassis.mgmt-ip=10.0.0.21
lldp.lan1.chassis.mgmt-ip=fe80::211:22ff:fe33:4401
lldp.lan1.port.ifname=lan
lldp.lan1.port.descr=phone uplink
lldp.lan1.alias=desk
lldp.lan1.via=LLDP
lldp.lan1.rid=2
lldp.lan1.age=0 day, 00:09:00
lldp.lan1.chassis.mac=00:11:22:33:44:02
lldp.lan1.chassis.name=desk-pc
lldp.lan1.port.ifname=eno1
lldp.eth0.via=LLDP
lldp.eth0.rid=3
lldp.eth0.chassis.mac=00:aa:bb:cc:dd:ee
lldp.eth0.chassis.name=core-router
lldp.eth0.port.ifname=ether1
"""
class TestLldpSeveralNeighboursOnOnePort:
"""Each neighbour on a port is its own entry; none is lost (#9)."""
def test_both_neighbours_on_the_port_are_reported(self, driver):
driver._send_command = lambda cmd, **kw: LLDPCTL_KV_TWO_ON_ONE_PORT
result = driver.get_lldp_neighbors()
assert result["lan1"] == [
{"hostname": "desk-phone", "port": "lan"},
{"hostname": "desk-pc", "port": "eno1"},
]
assert result["eth0"] == [{"hostname": "core-router", "port": "ether1"}]
def test_a_neighbour_keeps_only_its_own_fields(self, driver):
driver._send_command = lambda cmd, **kw: LLDPCTL_KV_TWO_ON_ONE_PORT
pc = driver.get_lldp_neighbors_detail("lan1")["lan1"][1]
assert pc["remote_chassis_id"] == "00:11:22:33:44:02"
assert pc["remote_port_description"] == ""
def test_a_repeated_key_inside_one_neighbour_is_no_new_neighbour(self, driver):
driver._send_command = lambda cmd, **kw: LLDPCTL_KV_TWO_ON_ONE_PORT
assert len(driver.get_lldp_neighbors_detail("lan1")["lan1"]) == 2
BRIDGE_VLAN_SHOW = """\
port vlan-id
eth0 1 PVID Egress Untagged