fix(lldp): read lldpd through the shared parser and raise on failure #46

Merged
christianmanivong merged 3 commits from fix/lldp-keyvalue into main 2026-11-02 11:06:19 +00:00
7 changed files with 184 additions and 136 deletions

No files matched your search

+10 -1
View File
@@ -8,7 +8,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Changed
- The floor on napalm-device-types is 4.23.0, the first release with what this driver uses.
- The floor on napalm-device-types is 4.24.0, the first release with what this driver
uses (its shared `lldpctl` parser).
- 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).
@@ -63,6 +64,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
napalm-device-types (NetOrk/netork#1636).
### Fixed
- `get_lldp_neighbors()` and `get_lldp_neighbors_detail()` raise when lldpctl fails
(lldpd not running, lldpctl missing) or the node gives no answer, with lldpctl's
message; they used to return no neighbours, the same answer as a node without any
(#44). Capabilities carry NAPALM's names (`telephone`, `wlan-access-point`,
`docsis-cable-device`) instead of lldpd's symbols (`tel`, `wlan`, `docsis`).
lldpd is read with `lldpctl -f keyvalue` through napalm-device-types' shared
parser, so a neighbour named by its chassis MAC also carries it as `mac`, and an
interface name with a dot stays whole.
- `get_ipv6_neighbors_table()` reports an unknown age as `-1.0`, as `get_arp_table()`
already did (napalm-device-types' `ARP_AGE_UNKNOWN`), instead of `0.0`, which
means "confirmed just now" (NetOrk/netork#1327).
+2 -2
View File
@@ -116,8 +116,8 @@ device = driver(
| `compare_config` | Unified diff |
| `commit_config` | Writes `/etc/network/interfaces` + `ifreload -a` |
| `discard_config` / `rollback` | Revert candidate |
| `get_lldp_neighbors` | `lldpcli show neighbors` over SSH |
| `get_lldp_neighbors_detail` | Full LLDP detail |
| `get_lldp_neighbors` | `lldpctl -f keyvalue` over SSH (napalm-device-types' parser); raises when lldpctl fails |
| `get_lldp_neighbors_detail` | Full LLDP detail, capabilities in NAPALM's names |
| `get_ipv6_neighbors_table` | `ip -6 neigh show` |
| `ping` | Linux `ping` over SSH |
| `traceroute` | `traceroute -n` over SSH |
+41 -71
View File
@@ -12,91 +12,61 @@
# See the License for the specific language governing permissions and
# limitations under the License.
"""LLDP-related NAPALM getters for Proxmox VE nodes."""
"""LLDP-related NAPALM getters for Proxmox VE nodes.
lldpd's neighbours come from ``lldpctl -f keyvalue``, parsed and projected by
napalm-device-types (``parse_lldpctl_keyvalue``, ``lldp_neighbors``,
``lldp_neighbors_detail``), as on every host that runs lldpd.
"""
from __future__ import annotations
import re
from typing import Any
from typing import TYPE_CHECKING
_JsonDict = dict[str, Any]
from napalm.base.models import LLDPNeighborDetailDict
from napalm_device_types import (
LLDPCTL_KEYVALUE_COMMAND,
LldpNeighborDict,
LldpNeighborRow,
lldp_neighbors,
lldp_neighbors_detail,
parse_lldpctl_keyvalue,
)
class ProxmoxLLDPMixin:
"""Mixin providing LLDP NAPALM methods."""
def get_lldp_neighbors(self) -> dict[str, list[_JsonDict]]:
def get_lldp_neighbors(self) -> dict[str, list[LldpNeighborDict]]:
"""Return LLDP neighbours (requires lldpd on the Proxmox node).
lldpcli prints one ``Interface:`` block per neighbour, so a port with
several neighbours appears once for each of them.
Every neighbour of a port is its own entry; one that names its chassis
by a MAC address carries it as ``mac``.
:raises ValueError: when lldpctl failed or gave no answer.
"""
result: dict[str, list[_JsonDict]] = {}
raw = self._exec_ssh_command("lldpcli show neighbors summary 2>/dev/null || true")
current: _JsonDict | None = None
for line in raw.splitlines():
m_iface = re.match(r"^\s*Interface:\s+(\S+?),?\s", line)
if m_iface:
current = {"hostname": "", "port": ""}
result.setdefault(m_iface.group(1), []).append(current)
continue
m_sys = re.match(r"^\s*SysName:\s+(.+)", line)
m_port = re.match(r"^\s*PortID:\s+\S+\s+(.+)", line)
if m_sys and current is not None:
current["hostname"] = m_sys.group(1).strip()
if m_port and current is not None:
current["port"] = m_port.group(1).strip()
return result
return lldp_neighbors(self._get_lldp_table())
def get_lldp_neighbors_detail(self, interface: str = "") -> dict[str, list[_JsonDict]]:
"""Return detailed LLDP neighbour information."""
result: dict[str, list[_JsonDict]] = {}
raw = self._exec_ssh_command("lldpcli show neighbors details 2>/dev/null || true")
current_iface = ""
current_entry: _JsonDict = {}
def get_lldp_neighbors_detail(
self, interface: str = ""
) -> dict[str, list[LLDPNeighborDetailDict]]:
"""Return detailed LLDP neighbour information, of *interface* only when given.
def _flush():
if current_iface and current_entry:
result.setdefault(current_iface, []).append(current_entry.copy())
:raises ValueError: when lldpctl failed or gave no answer.
"""
return lldp_neighbors_detail(self._get_lldp_table(), interface)
for line in raw.splitlines():
m_iface = re.match(r"^\s*Interface:\s+(\S+?),?\s", line)
if m_iface:
_flush()
current_iface = m_iface.group(1)
if interface and current_iface != interface:
current_iface = ""
current_entry = {
"parent_interface": "",
"remote_chassis_id": "",
"remote_system_name": "",
"remote_port": "",
"remote_port_description": "",
"remote_system_description": "",
"remote_system_capab": [],
"remote_system_enable_capab": [],
}
continue
if not current_iface:
continue
for key, pattern in (
("remote_chassis_id", r"ChassisID:\s+\S+\s+(.+)"),
("remote_system_name", r"SysName:\s+(.+)"),
("remote_port", r"PortID:\s+\S+\s+(.+)"),
("remote_port_description", r"PortDescr:\s+(.+)"),
("remote_system_description", r"SysDescr:\s+(.+)"),
):
m = re.match(rf"^\s*{pattern}", line)
if m:
current_entry[key] = m.group(1).strip()
def _get_lldp_table(self) -> list[LldpNeighborRow]:
"""``lldpctl -f keyvalue`` on the node, one row per neighbour.
m_cap = re.match(r"^\s*Capability:\s+(\S+),\s+(\w+)", line)
if m_cap:
cap = m_cap.group(1).lower()
enabled = m_cap.group(2).lower() == "on"
current_entry["remote_system_capab"].append(cap)
if enabled:
current_entry["remote_system_enable_capab"].append(cap)
The command always prints lldpctl's exit status, so an empty answer
means it never ran: that is no answer, not a node without neighbours.
"""
raw = self._exec_ssh_command(LLDPCTL_KEYVALUE_COMMAND)
if not raw.strip():
raise ValueError("lldpctl gave no answer on the node")
return parse_lldpctl_keyvalue(raw)
_flush()
return result
if TYPE_CHECKING: # pragma: no cover - the driver's
def _exec_ssh_command(self, command: str) -> str: ...
+1 -2
View File
@@ -21,7 +21,7 @@ classifiers = [
requires-python = ">=3.12"
dependencies = [
"napalm>=5.0.0",
"napalm_device_types>=4.23.0",
"napalm_device_types>=4.24.0",
"paramiko>=5.0.0", # CVE-2026-44405; imported directly for SSH fallback (driver.py)
"proxmoxer>=2.0.0",
"netaddr>=0.9.0",
@@ -73,7 +73,6 @@ module = [
"napalm_proxmox.config_mixin",
"napalm_proxmox.driver",
"napalm_proxmox.interfaces_mixin",
"napalm_proxmox.lldp_mixin",
"napalm_proxmox.routing_mixin",
"napalm_proxmox.sdn_mixin",
"napalm_proxmox.system_mixin",
-2
View File
@@ -27,7 +27,6 @@
"function_lines": {
"napalm_proxmox/driver.py::ProxmoxDriver.get_facts": 82,
"napalm_proxmox/interfaces_mixin.py::ProxmoxInterfaceMixin.get_mac_address_table": 71,
"napalm_proxmox/lldp_mixin.py::ProxmoxLLDPMixin.get_lldp_neighbors_detail": 52,
"napalm_proxmox/routing_mixin.py::ProxmoxRoutingMixin.ping": 78,
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin._get_vm_vlan_tags": 54,
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin.get_vlans": 66,
@@ -45,7 +44,6 @@
"napalm_proxmox.config_mixin",
"napalm_proxmox.driver",
"napalm_proxmox.interfaces_mixin",
"napalm_proxmox.lldp_mixin",
"napalm_proxmox.routing_mixin",
"napalm_proxmox.sdn_mixin",
"napalm_proxmox.system_mixin",
+116 -36
View File
@@ -1,43 +1,63 @@
"""LLDP neighbours read from lldpd's ``lldpcli show neighbors``."""
"""LLDP neighbours read from lldpd's ``lldpctl -f keyvalue`` (#44).
The output is parsed by napalm-device-types' ``parse_lldpctl_keyvalue`` and
projected by its ``lldp_neighbors`` / ``lldp_neighbors_detail``. Before, the
driver parsed ``lldpcli show neighbors`` text with ``2>/dev/null || true``, so
a failed read came back as no neighbours, and capabilities were lldpd's own
symbols lower-cased (``tel``, ``wlan``) instead of NAPALM's names.
"""
from __future__ import annotations
import pytest
from napalm_device_types import LLDPCTL_KEYVALUE_COMMAND
from napalm_proxmox import ProxmoxDriver
# lldpd 1.0 output: one "Interface:" block per neighbour, so a port with two
# neighbours (a switch and a phone behind it) appears twice. The phone sends
# no SysName.
# Laid out the way lldpd's keyvalue writer prints ``show neighbors details``
# (src/client/display.c, kv_writer.c): every neighbour opens with ``via``, an id
# is printed under its type, a capability as ``chassis.<Symbol>.enabled``. Not
# recorded from a device. On eno1 a switch and a phone behind it (the phone
# sends no SysName), on eno2 a second switch; lldpctl's exit status follows, as
# LLDPCTL_KEYVALUE_COMMAND prints it.
TWO_NEIGHBOURS_ON_ONE_PORT = """\
-------------------------------------------------------------------------------
LLDP neighbors:
-------------------------------------------------------------------------------
Interface: eno1, via: LLDP, RID: 1, Time: 0 day, 00:10:12
Chassis:
ChassisID: mac 00:11:22:33:44:55
SysName: sw1
Port:
PortID: ifname gi1/0/1
PortDescr: GigabitEthernet1/0/1
-------------------------------------------------------------------------------
Interface: eno1, via: LLDP, RID: 2, Time: 0 day, 00:01:02
Chassis:
ChassisID: mac aa:bb:cc:dd:ee:ff
Port:
PortID: mac aa:bb:cc:dd:ee:ff
-------------------------------------------------------------------------------
Interface: eno2, via: LLDP, RID: 3, Time: 0 day, 00:10:12
Chassis:
ChassisID: mac 00:11:22:33:44:66
SysName: sw2
Port:
PortID: ifname gi1/0/2
-------------------------------------------------------------------------------
lldp.eno1.via=LLDP
lldp.eno1.rid=1
lldp.eno1.age=0 day, 00:10:12
lldp.eno1.chassis.mac=00:11:22:33:44:55
lldp.eno1.chassis.name=sw1
lldp.eno1.chassis.descr=Switch OS 2.4
lldp.eno1.chassis.Bridge.enabled=on
lldp.eno1.chassis.Router.enabled=off
lldp.eno1.port.ifname=gi1/0/1
lldp.eno1.port.descr=GigabitEthernet1/0/1
lldp.eno1.via=LLDP
lldp.eno1.rid=2
lldp.eno1.age=0 day, 00:01:02
lldp.eno1.chassis.mac=AA:BB:CC:DD:EE:FF
lldp.eno1.chassis.Bridge.enabled=off
lldp.eno1.chassis.Tel.enabled=on
lldp.eno1.port.mac=aa:bb:cc:dd:ee:ff
lldp.eno2.via=LLDP
lldp.eno2.rid=3
lldp.eno2.age=0 day, 00:10:12
lldp.eno2.chassis.mac=00:11:22:33:44:66
lldp.eno2.chassis.name=sw2
lldp.eno2.chassis.Wlan.enabled=on
lldp.eno2.port.ifname=gi1/0/2
__LLDPCTL_RC=0
"""
def _driver(output: str) -> ProxmoxDriver:
def _driver(output: str, sent: list[str] | None = None) -> ProxmoxDriver:
d = ProxmoxDriver("pve", "root@pam", "pw")
d._exec_ssh_command = lambda command: output
def run(command: str) -> str:
if sent is not None:
sent.append(command)
return output
d._exec_ssh_command = run # type: ignore[method-assign]
return d
@@ -47,14 +67,22 @@ class TestGetLldpNeighbors:
assert result == {
"eno1": [
{"hostname": "sw1", "port": "gi1/0/1"},
{"hostname": "", "port": "aa:bb:cc:dd:ee:ff"},
{"hostname": "sw1", "port": "gi1/0/1", "mac": "00:11:22:33:44:55"},
{"hostname": "", "port": "aa:bb:cc:dd:ee:ff", "mac": "aa:bb:cc:dd:ee:ff"},
],
"eno2": [{"hostname": "sw2", "port": "gi1/0/2"}],
"eno2": [{"hostname": "sw2", "port": "gi1/0/2", "mac": "00:11:22:33:44:66"}],
}
def test_no_lldpd_output_is_no_neighbour(self):
assert _driver("").get_lldp_neighbors() == {}
def test_lldpctl_without_neighbours_lists_none(self):
assert _driver("__LLDPCTL_RC=0").get_lldp_neighbors() == {}
@pytest.mark.parametrize("getter", ["get_lldp_neighbors", "get_lldp_neighbors_detail"])
def test_lldpctl_is_asked_with_its_exit_status(self, getter):
sent: list[str] = []
getattr(_driver(TWO_NEIGHBOURS_ON_ONE_PORT, sent), getter)()
assert sent == [LLDPCTL_KEYVALUE_COMMAND]
class TestGetLldpNeighborsDetail:
@@ -62,4 +90,56 @@ class TestGetLldpNeighborsDetail:
result = _driver(TWO_NEIGHBOURS_ON_ONE_PORT).get_lldp_neighbors_detail()
assert [e["remote_system_name"] for e in result["eno1"]] == ["sw1", ""]
assert result["eno1"][1]["remote_chassis_id"] == "aa:bb:cc:dd:ee:ff"
assert result["eno1"][1]["remote_chassis_id"] == "AA:BB:CC:DD:EE:FF"
def test_capabilities_carry_napalm_names(self):
result = _driver(TWO_NEIGHBOURS_ON_ONE_PORT).get_lldp_neighbors_detail()
phone = result["eno1"][1]
assert phone["remote_system_capab"] == ["bridge", "telephone"]
assert phone["remote_system_enable_capab"] == ["telephone"]
assert result["eno2"][0]["remote_system_capab"] == ["wlan-access-point"]
def test_the_fields_of_a_neighbour(self):
switch = _driver(TWO_NEIGHBOURS_ON_ONE_PORT).get_lldp_neighbors_detail()["eno1"][0]
assert switch == {
"parent_interface": "",
"remote_port": "gi1/0/1",
"remote_port_description": "GigabitEthernet1/0/1",
"remote_chassis_id": "00:11:22:33:44:55",
"remote_system_name": "sw1",
"remote_system_description": "Switch OS 2.4",
"remote_system_capab": ["bridge", "router"],
"remote_system_enable_capab": ["bridge"],
}
def test_one_interface_only(self):
result = _driver(TWO_NEIGHBOURS_ON_ONE_PORT).get_lldp_neighbors_detail("eno2")
assert list(result) == ["eno2"]
class TestFailedRead:
"""A failed read raises; ``{}`` only when lldpctl ran and listed nobody."""
@pytest.mark.parametrize("getter", ["get_lldp_neighbors", "get_lldp_neighbors_detail"])
def test_lldpctl_failing_raises(self, getter):
output = (
"[WARN/control] unable to connect to socket /run/lldpd.socket: "
"No such file or directory\n__LLDPCTL_RC=1"
)
with pytest.raises(ValueError, match="unable to connect"):
getattr(_driver(output), getter)()
def test_a_missing_lldpctl_raises(self):
with pytest.raises(ValueError, match="not found"):
_driver("sh: 1: lldpctl: not found\n__LLDPCTL_RC=127").get_lldp_neighbors()
@pytest.mark.parametrize("getter", ["get_lldp_neighbors", "get_lldp_neighbors_detail"])
def test_no_answer_at_all_raises(self, getter):
# lldpctl's exit status is always printed; nothing at all means the
# command never ran on the node.
with pytest.raises(ValueError, match="no answer"):
getattr(_driver(""), getter)()
+14 -22
View File
@@ -279,35 +279,27 @@ class TestGetRouteTo:
class TestLLDPNeighbors:
# Real `lldpcli show neighbors summary` output. The interface line carries
# ", via: LLDP, ..." after the name, which is what the parser matches on —
# the previous fixture stopped at the name and matched nothing.
LLDP_SUMMARY = (
"LLDP neighbors:\n"
"-------------------------------------------------------------------------------\n"
"Interface: eth0, via: LLDP, RID: 1, Time: 0 day, 00:11:22\n"
" Chassis:\n"
" SysName: sw01.example.com\n"
" Port:\n"
" PortID: ifname GigabitEthernet1/0/1\n"
"-------------------------------------------------------------------------------\n"
"Interface: eth1, via: LLDP, RID: 2, Time: 0 day, 00:11:22\n"
" Chassis:\n"
" SysName: sw02.example.com\n"
" Port:\n"
" PortID: ifname GigabitEthernet1/0/2\n"
"-------------------------------------------------------------------------------\n"
# ``lldpctl -f keyvalue`` with its exit status, as LLDPCTL_KEYVALUE_COMMAND prints
# it (the parse itself is covered in test_lldp.py).
LLDP_KEYVALUE = (
"lldp.eth0.via=LLDP\n"
"lldp.eth0.chassis.name=sw01.example.com\n"
"lldp.eth0.port.ifname=GigabitEthernet1/0/1\n"
"lldp.eth1.via=LLDP\n"
"lldp.eth1.chassis.name=sw02.example.com\n"
"lldp.eth1.port.ifname=GigabitEthernet1/0/2\n"
"__LLDPCTL_RC=0\n"
)
def test_neighbors_found(self, driver):
with patch.object(driver, "_exec_ssh_command", return_value=self.LLDP_SUMMARY):
with patch.object(driver, "_exec_ssh_command", return_value=self.LLDP_KEYVALUE):
result = driver.get_lldp_neighbors()
assert "eth0" in result
assert result["eth0"][0]["hostname"] == "sw01.example.com"
def test_empty_when_no_lldp(self, driver):
driver._node_ssh().output = ""
result = driver.get_lldp_neighbors()
def test_empty_when_no_lldp_neighbour(self, driver):
with patch.object(driver, "_exec_ssh_command", return_value="__LLDPCTL_RC=0"):
result = driver.get_lldp_neighbors()
assert result == {}