"""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() == {}