Merge pull request 'fix(lldp): list every neighbour of a port, with its chassis MAC' (#62) from fix/lldp-keyvalue into main
driver / standard (push) Successful in 19s
driver / lint (push) Successful in 15s
driver / types (push) Successful in 1m12s
driver / test (3.12) (push) Successful in 1m14s
driver / test (3.13) (push) Successful in 1m1s
driver / lowest (push) Successful in 33s
driver / build (push) Successful in 31s
driver / security (push) Successful in 1m18s
CI / driver (push) Successful in 3m4s
driver / publish (push) Skipped
driver / standard (push) Successful in 19s
driver / lint (push) Successful in 15s
driver / types (push) Successful in 1m12s
driver / test (3.12) (push) Successful in 1m14s
driver / test (3.13) (push) Successful in 1m1s
driver / lowest (push) Successful in 33s
driver / build (push) Successful in 31s
driver / security (push) Successful in 1m18s
CI / driver (push) Successful in 3m4s
driver / publish (push) Skipped
This commit was merged in pull request #62.
This commit is contained in:
commit
cb0e308a78
5 files changed
+264
-40
No files matched your search
@@ -43,8 +43,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
### 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).
|
||||
- The floor on napalm-device-types is 4.24.0, for its shared `lldpctl` parser.
|
||||
|
||||
### Fixed
|
||||
- `get_lldp_neighbors()` raises when lldpd runs but lldpctl fails (its socket out of
|
||||
the login's reach, a daemon restarting), with lldpctl's message, instead of reporting
|
||||
no neighbours (#66). A stopped lldpd is recognised as stopped: systemd's `inactive`
|
||||
used to pass the running check, as it contains the word "active". A host without
|
||||
lldpd, or with lldpd stopped, still reports no neighbours.
|
||||
- `get_lldp_neighbors()` lists every neighbour of a port (#58): a phone and the PC
|
||||
behind it, or the devices behind an unmanaged switch, used to merge into one entry
|
||||
and only the last one was left. A neighbour whose chassis id is a MAC address now
|
||||
carries it as `mac` (it never did), a port given as a MAC address or local id is
|
||||
reported instead of coming back empty, and an interface with a dot in its name
|
||||
(`eth0.100`) keeps its whole name.
|
||||
- `get_route_to()` reads unreachable, blackhole, prohibit and throw routes and
|
||||
multipath routes (#57). Their destinations came back as `unreachable/32`,
|
||||
`blackhole/32` or `nexthop/32`, and a multipath route as one entry without a next
|
||||
|
||||
+18
-38
@@ -28,6 +28,7 @@ from napalm.base.netmiko_helpers import netmiko_args
|
||||
from napalm_device_types import (
|
||||
APT_UPGRADABLE_COMMAND,
|
||||
DNF_SECURITY_COMMAND,
|
||||
LLDPCTL_KEYVALUE_COMMAND,
|
||||
AptProxyMixin,
|
||||
ByteStream,
|
||||
CommandResult,
|
||||
@@ -38,6 +39,7 @@ from napalm_device_types import (
|
||||
HostStatusMixin,
|
||||
KernelFactsMixin,
|
||||
ListeningSocketsMixin,
|
||||
LldpNeighborDict,
|
||||
OpenSshServerMixin,
|
||||
OSDriver,
|
||||
ServiceClustersMixin,
|
||||
@@ -47,9 +49,11 @@ from napalm_device_types import (
|
||||
SystemdUnavailable,
|
||||
SystemIdentityMixin,
|
||||
VirtualIpsMixin,
|
||||
lldp_neighbors,
|
||||
open_stream_on_transport,
|
||||
parse_apt_upgradable,
|
||||
parse_dnf_security,
|
||||
parse_lldpctl_keyvalue,
|
||||
run_fix_steps,
|
||||
run_on_transport,
|
||||
strip_terminal_codes,
|
||||
@@ -127,6 +131,11 @@ _DNF_RC_RE = re.compile(r"^__DNF_RC=(\d+)\s*$", re.MULTILINE)
|
||||
#: Restart the host two seconds later, detached from this session: the launcher's
|
||||
#: exit status comes back before the host goes down, and closing the session
|
||||
#: cannot take the restart with it.
|
||||
#: ``running`` when systemd has lldpd active or a process of that name runs, else ``stopped``.
|
||||
_LLDPD_STATE_COMMAND = (
|
||||
"if systemctl is-active --quiet lldpd 2>/dev/null || pgrep -x lldpd >/dev/null 2>&1; "
|
||||
"then echo running; else echo stopped; fi"
|
||||
)
|
||||
_REBOOT_DETACHED = "sh -c '(trap \"\" HUP; sleep 2; /sbin/reboot) </dev/null >/dev/null 2>&1 &'"
|
||||
|
||||
#: Why ``run_command`` refuses stdin to a privileged command while a sudo
|
||||
@@ -760,53 +769,24 @@ class LinuxDriver(
|
||||
except (IndexError, ValueError):
|
||||
return 0
|
||||
|
||||
def get_lldp_neighbors(self) -> dict[str, list[dict[str, Any]]]:
|
||||
def get_lldp_neighbors(self) -> dict[str, list[LldpNeighborDict]]:
|
||||
"""Return LLDP neighbors if lldpd is installed and currently running.
|
||||
|
||||
Uses ``lldpctl -f keyvalue``. Returns an empty dict when lldpd is
|
||||
Uses ``lldpctl -f keyvalue``, parsed by napalm-device-types: every
|
||||
neighbour of a port is its own entry, and one whose chassis id is a MAC
|
||||
address carries it as ``mac``. Returns an empty dict when lldpd is
|
||||
absent or stopped — does NOT attempt to start the daemon.
|
||||
|
||||
:raises ValueError: when lldpd runs but lldpctl fails (socket out of reach).
|
||||
"""
|
||||
# Check lldpctl is available
|
||||
if not self._send("command -v lldpctl 2>/dev/null").strip():
|
||||
return {}
|
||||
|
||||
# Check lldpd is active (systemd or fallback to pgrep)
|
||||
running = self._send(
|
||||
"systemctl is-active lldpd 2>/dev/null || "
|
||||
"service lldpd status 2>/dev/null | grep -q running && echo active || "
|
||||
"pgrep -x lldpd >/dev/null 2>&1 && echo active || true"
|
||||
).strip()
|
||||
if "active" not in running:
|
||||
# The whole state: systemctl's "inactive" holds the word "active" (#66).
|
||||
if self._send(_LLDPD_STATE_COMMAND).strip() != "running":
|
||||
return {}
|
||||
|
||||
output = self._send("lldpctl -f keyvalue 2>/dev/null || true")
|
||||
neighbors: dict[str, list[dict[str, Any]]] = {}
|
||||
entries: dict[str, dict[str, str]] = {}
|
||||
|
||||
for line in output.splitlines():
|
||||
line = line.strip()
|
||||
if "=" not in line:
|
||||
continue
|
||||
key, _, value = line.partition("=")
|
||||
parts = key.split(".")
|
||||
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():
|
||||
entry = {
|
||||
"hostname": data.get("chassis.name", ""),
|
||||
"port": data.get("port.ifname", data.get("port.id.value", "")),
|
||||
}
|
||||
if data.get("chassis.id.subtype") == "mac":
|
||||
mac = data.get("chassis.id.value", "")
|
||||
if re.match(r"^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$", mac):
|
||||
entry["mac"] = mac.lower()
|
||||
neighbors.setdefault(iface, []).append(entry)
|
||||
|
||||
return neighbors
|
||||
return lldp_neighbors(parse_lldpctl_keyvalue(self._send(LLDPCTL_KEYVALUE_COMMAND)))
|
||||
|
||||
def get_interfaces(self) -> dict[str, Any]:
|
||||
"""Return interface operational data."""
|
||||
|
||||
+1
-1
@@ -34,7 +34,7 @@ classifiers = [
|
||||
]
|
||||
dependencies = [
|
||||
"napalm>=4.0",
|
||||
"napalm-device-types>=4.22.0",
|
||||
"napalm-device-types>=4.24.0",
|
||||
"netmiko>=4.0.0",
|
||||
"paramiko>=5.0.0", # CVE-2026-44405
|
||||
]
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
"napalm_linux.linux"
|
||||
],
|
||||
"python_file_lines": {
|
||||
"napalm_linux/linux.py": 2138
|
||||
"napalm_linux/linux.py": 2118
|
||||
},
|
||||
"untyped_public": []
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
"""get_lldp_neighbors: every neighbour of a port, its chassis MAC and its port (#58).
|
||||
|
||||
lldpd's ``lldpctl -f keyvalue`` is parsed by napalm-device-types'
|
||||
``parse_lldpctl_keyvalue``. Before, the driver grouped the lines by interface,
|
||||
so a second neighbour on a port overwrote the first; it looked for
|
||||
``chassis.id.subtype``/``chassis.id.value`` and ``port.id.value``, keys lldpd
|
||||
never prints, so the chassis MAC was never reported and a port given by MAC or
|
||||
local id came back empty; and it cut ``eth0.100`` at its dot.
|
||||
|
||||
#66: the running check took systemctl's ``inactive`` for running, and a failed
|
||||
lldpctl read as no neighbours.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import LLDPCTL_KEYVALUE_COMMAND
|
||||
|
||||
from napalm_linux.linux import LinuxDriver
|
||||
|
||||
_RC = "__LLDPCTL_RC"
|
||||
|
||||
# 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. Not recorded from a device. On eth0 a phone and the
|
||||
# PC behind it (an unmanaged switch between them and the host), on the VLAN
|
||||
# interface eth0.100 a switch that names its port by a local id.
|
||||
LLDPCTL_KEYVALUE = """\
|
||||
lldp.eth0.via=LLDP
|
||||
lldp.eth0.rid=1
|
||||
lldp.eth0.age=0 day, 00:10:00
|
||||
lldp.eth0.chassis.mac=00:11:22:33:44:AA
|
||||
lldp.eth0.chassis.name=desk-phone
|
||||
lldp.eth0.chassis.descr=SIP phone
|
||||
lldp.eth0.chassis.Tel.enabled=on
|
||||
lldp.eth0.port.mac=00:11:22:33:44:aa
|
||||
lldp.eth0.port.descr=WAN
|
||||
lldp.eth0.port.ttl=120
|
||||
lldp.eth0.via=LLDP
|
||||
lldp.eth0.rid=2
|
||||
lldp.eth0.age=0 day, 00:09:00
|
||||
lldp.eth0.chassis.mac=00:11:22:33:44:bb
|
||||
lldp.eth0.chassis.name=desk-pc
|
||||
lldp.eth0.chassis.Station.enabled=on
|
||||
lldp.eth0.port.ifname=eno1
|
||||
lldp.eth0.port.ttl=120
|
||||
lldp.eth0.100.via=LLDP
|
||||
lldp.eth0.100.rid=3
|
||||
lldp.eth0.100.age=1 day, 02:00:00
|
||||
lldp.eth0.100.chassis.local=access-sw-01
|
||||
lldp.eth0.100.chassis.name=access-sw
|
||||
lldp.eth0.100.chassis.Bridge.enabled=on
|
||||
lldp.eth0.100.port.local=gi1/0/7
|
||||
lldp.eth0.100.port.descr=GigabitEthernet1/0/7
|
||||
"""
|
||||
|
||||
|
||||
#: Shell stubs for the host's lldpd state: ``systemctl`` and ``service`` as a
|
||||
#: systemd host answers them, ``pgrep`` as procps does.
|
||||
_RUNNING = (
|
||||
"systemctl() { case $* in *--quiet*) ;; *) echo active ;; esac; return 0; }; "
|
||||
"service() { echo ' Active: active (running)'; return 0; }; "
|
||||
"pgrep() { return 0; }; "
|
||||
)
|
||||
_STOPPED = (
|
||||
"systemctl() { case $* in *--quiet*) ;; *) echo inactive ;; esac; return 3; }; "
|
||||
"service() { echo ' Active: inactive (dead)'; return 3; }; "
|
||||
"pgrep() { return 1; }; "
|
||||
)
|
||||
_FAILED = (
|
||||
"systemctl() { case $* in *--quiet*) ;; *) echo failed ;; esac; return 3; }; "
|
||||
"service() { echo ' Active: failed (Result: exit-code)'; return 3; }; "
|
||||
"pgrep() { return 1; }; "
|
||||
)
|
||||
#: No systemd, lldpd started by its init script: only pgrep finds it.
|
||||
_RUNNING_WITHOUT_SYSTEMD = (
|
||||
"systemctl() { return 127; }; service() { return 1; }; pgrep() { return 0; }; "
|
||||
)
|
||||
|
||||
|
||||
def _shell(stubs: str, command: str) -> str:
|
||||
"""What *command* prints in ``sh`` with the state commands stubbed out."""
|
||||
done = subprocess.run( # a local sh, no network
|
||||
["sh", "-c", stubs + command], capture_output=True, text=True, check=False, timeout=10
|
||||
)
|
||||
return done.stdout.strip()
|
||||
|
||||
|
||||
def _answer(
|
||||
driver: LinuxDriver,
|
||||
lldpctl: str,
|
||||
*,
|
||||
installed: bool = True,
|
||||
state: str = _RUNNING,
|
||||
lldpctl_error: str = "",
|
||||
lldpctl_status: int = 0,
|
||||
):
|
||||
"""Answer ``_send`` the way the host's shell would.
|
||||
|
||||
lldpctl prints *lldpctl* on stdout, *lldpctl_error* on stderr and exits with
|
||||
*lldpctl_status*; the redirections and the status echo of the command sent
|
||||
decide what of that comes back.
|
||||
"""
|
||||
sent: list[str] = []
|
||||
|
||||
def send(command: str, read_timeout: float = 100) -> str:
|
||||
sent.append(command)
|
||||
if command.startswith("command -v lldpctl"):
|
||||
return "/usr/sbin/lldpctl" if installed else ""
|
||||
if "lldpd" in command and "lldpctl" not in command:
|
||||
return _shell(state, command)
|
||||
if command.startswith("lldpctl"):
|
||||
out = lldpctl
|
||||
if "2>&1" in command:
|
||||
out += lldpctl_error
|
||||
if f"echo {_RC}" in command:
|
||||
out += f"\n{_RC}={lldpctl_status}"
|
||||
return out.strip()
|
||||
raise AssertionError(f"unexpected command {command!r}")
|
||||
|
||||
driver._send = send # type: ignore[method-assign]
|
||||
return sent
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def driver() -> LinuxDriver:
|
||||
return LinuxDriver.__new__(LinuxDriver)
|
||||
|
||||
|
||||
class TestNeighbours:
|
||||
def test_every_neighbour_of_a_port_is_reported(self, driver):
|
||||
_answer(driver, LLDPCTL_KEYVALUE)
|
||||
|
||||
result = driver.get_lldp_neighbors()
|
||||
|
||||
assert [n["hostname"] for n in result["eth0"]] == ["desk-phone", "desk-pc"]
|
||||
|
||||
def test_the_chassis_mac_is_reported_in_lower_case(self, driver):
|
||||
_answer(driver, LLDPCTL_KEYVALUE)
|
||||
|
||||
phone, pc = driver.get_lldp_neighbors()["eth0"]
|
||||
|
||||
assert phone["mac"] == "00:11:22:33:44:aa"
|
||||
assert pc["mac"] == "00:11:22:33:44:bb"
|
||||
|
||||
def test_a_port_given_by_mac_or_local_id_is_reported(self, driver):
|
||||
_answer(driver, LLDPCTL_KEYVALUE)
|
||||
|
||||
result = driver.get_lldp_neighbors()
|
||||
|
||||
assert result["eth0"][0]["port"] == "00:11:22:33:44:aa"
|
||||
assert result["eth0"][1]["port"] == "eno1"
|
||||
assert result["eth0.100"][0]["port"] == "gi1/0/7"
|
||||
|
||||
def test_a_dotted_interface_name_stays_whole(self, driver):
|
||||
_answer(driver, LLDPCTL_KEYVALUE)
|
||||
|
||||
assert sorted(driver.get_lldp_neighbors()) == ["eth0", "eth0.100"]
|
||||
|
||||
def test_a_chassis_not_named_by_a_mac_has_no_mac(self, driver):
|
||||
_answer(driver, LLDPCTL_KEYVALUE)
|
||||
|
||||
assert driver.get_lldp_neighbors()["eth0.100"] == [
|
||||
{"hostname": "access-sw", "port": "gi1/0/7"}
|
||||
]
|
||||
|
||||
def test_a_chassis_mac_that_is_no_mac_address_is_left_out(self, driver):
|
||||
_answer(driver, "lldp.eth0.via=LLDP\nlldp.eth0.chassis.mac=00:11\n")
|
||||
|
||||
assert driver.get_lldp_neighbors() == {"eth0": [{"hostname": "", "port": ""}]}
|
||||
|
||||
|
||||
class TestWithoutLldpd:
|
||||
def test_without_lldpctl_there_are_no_neighbours(self, driver):
|
||||
sent = _answer(driver, LLDPCTL_KEYVALUE, installed=False)
|
||||
|
||||
assert driver.get_lldp_neighbors() == {}
|
||||
assert not any(c.startswith("lldpctl") for c in sent)
|
||||
|
||||
def test_lldpd_without_neighbours_lists_none(self, driver):
|
||||
_answer(driver, "")
|
||||
|
||||
assert driver.get_lldp_neighbors() == {}
|
||||
|
||||
|
||||
class TestLldpdState:
|
||||
"""Only a running lldpd is asked; a stopped one is no neighbours (#66)."""
|
||||
|
||||
@pytest.mark.parametrize("state", [_STOPPED, _FAILED], ids=["inactive", "failed"])
|
||||
def test_a_stopped_lldpd_is_not_asked(self, driver, state):
|
||||
sent = _answer(driver, LLDPCTL_KEYVALUE, state=state)
|
||||
|
||||
assert driver.get_lldp_neighbors() == {}
|
||||
assert not any(c.startswith("lldpctl") for c in sent)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"state", [_RUNNING, _RUNNING_WITHOUT_SYSTEMD], ids=["systemd", "without-systemd"]
|
||||
)
|
||||
def test_a_running_lldpd_is_asked(self, driver, state):
|
||||
_answer(driver, LLDPCTL_KEYVALUE, state=state)
|
||||
|
||||
assert sorted(driver.get_lldp_neighbors()) == ["eth0", "eth0.100"]
|
||||
|
||||
|
||||
class TestFailedRead:
|
||||
"""With lldpd running, a failed lldpctl raises instead of reading as none (#66)."""
|
||||
|
||||
def test_lldpctl_is_asked_with_its_exit_status(self, driver):
|
||||
sent = _answer(driver, LLDPCTL_KEYVALUE)
|
||||
|
||||
driver.get_lldp_neighbors()
|
||||
|
||||
assert sent[-1] == LLDPCTL_KEYVALUE_COMMAND
|
||||
|
||||
def test_an_unreachable_lldpd_raises(self, driver):
|
||||
_answer(
|
||||
driver,
|
||||
"",
|
||||
lldpctl_error="[WARN/control] unable to connect to socket /run/lldpd.socket: "
|
||||
"Permission denied",
|
||||
lldpctl_status=1,
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="Permission denied"):
|
||||
driver.get_lldp_neighbors()
|
||||
|
||||
def test_lldpctl_without_neighbours_lists_none(self, driver):
|
||||
_answer(driver, "")
|
||||
|
||||
assert driver.get_lldp_neighbors() == {}
|
||||
Reference in new issue
Block a user