fix(getters): raise on a failed LLDP or environment read
driver / standard (pull_request) Successful in 18s
driver / lint (pull_request) Successful in 21s
driver / types (pull_request) Failing after 6s
driver / test (3.12) (pull_request) Failing after 17s
driver / test (3.13) (pull_request) Failing after 15s
driver / lowest (pull_request) Failing after 6s
driver / build (pull_request) Successful in 33s
driver / security (pull_request) Failing after 38s
CI / driver (pull_request) Failing after 1m36s
driver / publish (pull_request) Skipped
driver / standard (pull_request) Successful in 18s
driver / lint (pull_request) Successful in 21s
driver / types (pull_request) Failing after 6s
driver / test (3.12) (pull_request) Failing after 17s
driver / test (3.13) (pull_request) Failing after 15s
driver / lowest (pull_request) Failing after 6s
driver / build (pull_request) Successful in 33s
driver / security (pull_request) Failing after 38s
CI / driver (pull_request) Failing after 1m36s
driver / publish (pull_request) Skipped
lldpctl's error text has no "=", so a missing lldpctl or a stopped lldpd read as a device without neighbours. lldpctl now runs as napalm-device-types' LLDPCTL_KEYVALUE_COMMAND, which brings its exit status and message back, and the shared parser raises on a failure. get_environment swallowed an unreadable /proc/stat or /proc/meminfo and reported 0 % CPU and 0 bytes of memory, a plausible value instead of a failure. Both now raise ValueError; 0 % stays for counters that did not move between the two reads. Closes #27
This commit is contained in:
1 parent
231def768e
commit
aafb5636a9
5 files changed
+111
-32
No files matched your search
@@ -35,6 +35,12 @@ recorded here; their history is the git log.
|
||||
chassis named by a local id or an address with that id. The detail now also
|
||||
carries the neighbour's system description and capabilities, which were always
|
||||
empty. lldpd's output is parsed by napalm-device-types' shared parser.
|
||||
- `get_lldp_neighbors()` and `get_lldp_neighbors_detail()` raise when lldpctl fails
|
||||
(not installed, lldpd not running or unreachable), with lldpctl's message; they used
|
||||
to return no neighbours, the same answer as a device without any (#27). An empty
|
||||
result now means lldpctl ran and listed none. `get_environment()` raises when
|
||||
`/proc/stat` or `/proc/meminfo` cannot be read or parsed, instead of reporting 0 %
|
||||
CPU and 0 bytes of memory.
|
||||
- `get_arp_table()` reports an unknown age as `-1.0` (napalm-device-types'
|
||||
`ARP_AGE_UNKNOWN`) instead of `0.0`, which means "confirmed just now": neither
|
||||
`ip neigh` nor `/proc/net/arp` has an age (NetOrk/netork#1327).
|
||||
|
||||
@@ -61,9 +61,9 @@ device.close()
|
||||
| `get_arp_table` | ✅ | Uses `ip neigh show` |
|
||||
| `get_mac_address_table` | ✅ | Uses `bridge fdb show` |
|
||||
| `get_config` | ✅ | Uses `uci export` |
|
||||
| `get_environment` | ✅ | CPU from `/proc/stat`, memory from `/proc/meminfo` |
|
||||
| `get_lldp_neighbors` | ✅ | Requires `lldpd` installed and running; reads only, never starts or configures it |
|
||||
| `get_lldp_neighbors_detail` | ✅ | Requires `lldpd` installed and running; reads only, never starts or configures it |
|
||||
| `get_environment` | ✅ | CPU from `/proc/stat`, memory from `/proc/meminfo`; raises when either cannot be read |
|
||||
| `get_lldp_neighbors` | ✅ | Requires `lldpd` installed and running (raises otherwise); reads only, never starts or configures it |
|
||||
| `get_lldp_neighbors_detail` | ✅ | Requires `lldpd` installed and running (raises otherwise); reads only, never starts or configures it |
|
||||
| `get_listening_sockets` | ✅ | busybox `netstat -lntup`, procd service from the process's cgroup (napalm-device-types `ListeningSocketsMixin`); over an SSH exec channel |
|
||||
|
||||
## Configuration management
|
||||
|
||||
@@ -16,15 +16,13 @@ from typing import TYPE_CHECKING
|
||||
|
||||
from napalm.base.models import LLDPNeighborDetailDict, LLDPNeighborDict
|
||||
from napalm_device_types import (
|
||||
LLDPCTL_KEYVALUE_COMMAND,
|
||||
LldpNeighborRow,
|
||||
lldp_neighbors,
|
||||
lldp_neighbors_detail,
|
||||
parse_lldpctl_keyvalue,
|
||||
)
|
||||
|
||||
#: lldpd's neighbours, parsed by napalm-device-types' ``parse_lldpctl_keyvalue``.
|
||||
_LLDPCTL_COMMAND = "lldpctl -f keyvalue"
|
||||
|
||||
|
||||
class OpenWrtLLDPMixin:
|
||||
"""Mixin providing LLDP NAPALM getters."""
|
||||
@@ -45,8 +43,11 @@ class OpenWrtLLDPMixin:
|
||||
Reads only: lldpd is neither started nor reconfigured here. Installing,
|
||||
starting and configuring it are the caller's (``ensure_package``,
|
||||
``manage_service``).
|
||||
|
||||
:raises ValueError: when lldpctl failed (not installed, lldpd not
|
||||
running): that is no answer, not a port without neighbours.
|
||||
"""
|
||||
return parse_lldpctl_keyvalue(self._send_command(_LLDPCTL_COMMAND))
|
||||
return parse_lldpctl_keyvalue(self._send_command(LLDPCTL_KEYVALUE_COMMAND))
|
||||
|
||||
def get_lldp_neighbors_detail(
|
||||
self, interface: str = ""
|
||||
|
||||
@@ -25,6 +25,8 @@ _RC_RE = re.compile(rf"^{_RC_MARKER}(\d+)\s*$", re.MULTILINE)
|
||||
_APK_INDEX_MISSING = re.compile(r"opening from cache .*No such file or directory")
|
||||
#: The aggregate CPU line of ``/proc/stat``, read twice one second apart.
|
||||
_CPU_SAMPLES = "grep '^cpu ' /proc/stat; sleep 1; grep '^cpu ' /proc/stat"
|
||||
#: ``MemTotal: 124608 kB`` and ``MemAvailable:`` of ``/proc/meminfo``.
|
||||
_MEMINFO_RE = re.compile(r"^(MemTotal|MemAvailable):\s+(\d+)\s+kB\s*$", re.MULTILINE)
|
||||
|
||||
|
||||
def _split_status(raw: str) -> tuple[str, int | None]:
|
||||
@@ -61,22 +63,33 @@ def _cpu_counters(line: str) -> tuple[int, int]:
|
||||
def _cpu_usage_percent(output: str) -> float:
|
||||
"""Busy share of the time between the two ``cpu`` lines of :data:`_CPU_SAMPLES`.
|
||||
|
||||
0.0 when there are not two readable lines or the counters did not move.
|
||||
0.0 when the counters did not move.
|
||||
|
||||
:raises ValueError: when the output does not hold two readable ``cpu`` lines.
|
||||
"""
|
||||
lines = [line for line in output.splitlines() if line.startswith("cpu ")]
|
||||
if len(lines) < 2:
|
||||
return 0.0
|
||||
try:
|
||||
idle1, total1 = _cpu_counters(lines[0])
|
||||
idle2, total2 = _cpu_counters(lines[1])
|
||||
except ValueError:
|
||||
return 0.0
|
||||
raise ValueError(f"/proc/stat gave no two cpu readings: {output[:200]!r}")
|
||||
idle1, total1 = _cpu_counters(lines[0])
|
||||
idle2, total2 = _cpu_counters(lines[1])
|
||||
elapsed = total2 - total1
|
||||
if elapsed <= 0:
|
||||
return 0.0
|
||||
return (1 - (idle2 - idle1) / elapsed) * 100
|
||||
|
||||
|
||||
def _meminfo_kib(output: str) -> tuple[int, int]:
|
||||
"""``(MemTotal, MemAvailable)`` in KiB from ``/proc/meminfo``.
|
||||
|
||||
:raises ValueError: when either is missing or not a number.
|
||||
"""
|
||||
values = dict(_MEMINFO_RE.findall(output))
|
||||
missing = [key for key in ("MemTotal", "MemAvailable") if key not in values]
|
||||
if missing:
|
||||
raise ValueError(f"/proc/meminfo has no {', '.join(missing)}: {output[:200]!r}")
|
||||
return int(values["MemTotal"]), int(values["MemAvailable"])
|
||||
|
||||
|
||||
class OpenWrtSystemMixin:
|
||||
"""Mixin providing system-level NAPALM getters.
|
||||
|
||||
@@ -89,23 +102,12 @@ class OpenWrtSystemMixin:
|
||||
CPU usage from ``/proc/stat``: the difference of two reads one second
|
||||
apart, so it is the last second, not the average since boot.
|
||||
Memory from ``/proc/meminfo``.
|
||||
|
||||
:raises ValueError: when either file could not be read or parsed; a
|
||||
failed read is no 0 % CPU and no 0 bytes of memory.
|
||||
"""
|
||||
cpu_pct = _cpu_usage_percent(self._send_command(_CPU_SAMPLES))
|
||||
mem_out = self._send_command("cat /proc/meminfo")
|
||||
|
||||
mem_total = 0
|
||||
mem_available = 0
|
||||
for line in mem_out.splitlines():
|
||||
if line.startswith("MemTotal:"):
|
||||
try:
|
||||
mem_total = int(line.split()[1])
|
||||
except (IndexError, ValueError):
|
||||
pass
|
||||
elif line.startswith("MemAvailable:"):
|
||||
try:
|
||||
mem_available = int(line.split()[1])
|
||||
except (IndexError, ValueError):
|
||||
pass
|
||||
mem_total, mem_available = _meminfo_kib(self._send_command("cat /proc/meminfo"))
|
||||
|
||||
return {
|
||||
"fans": {},
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import LLDPCTL_KEYVALUE_COMMAND
|
||||
|
||||
from napalm_openwrt.openwrt import OpenWrtDriver
|
||||
|
||||
@@ -390,7 +391,7 @@ class TestLldpGettersOnlyRead:
|
||||
|
||||
getattr(driver, getter)()
|
||||
|
||||
assert sent == ["lldpctl -f keyvalue"]
|
||||
assert sent == [LLDPCTL_KEYVALUE_COMMAND]
|
||||
|
||||
|
||||
class TestLldpSeveralNeighboursOnOnePort:
|
||||
@@ -421,6 +422,44 @@ class TestLldpSeveralNeighboursOnOnePort:
|
||||
assert len(driver.get_lldp_neighbors_detail("lan1")["lan1"]) == 2
|
||||
|
||||
|
||||
class TestLldpFailedRead:
|
||||
"""A failed lldpctl raises; no neighbours only when it ran and listed none (#27)."""
|
||||
|
||||
@pytest.mark.parametrize("getter", ["get_lldp_neighbors", "get_lldp_neighbors_detail"])
|
||||
def test_a_missing_lldpctl_raises(self, driver, getter):
|
||||
driver._send_command = lambda cmd, **kw: "ash: lldpctl: not found\n__LLDPCTL_RC=127"
|
||||
|
||||
with pytest.raises(ValueError, match="lldpctl: not found"):
|
||||
getattr(driver, getter)()
|
||||
|
||||
def test_an_unreachable_lldpd_raises(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: (
|
||||
"[WARN/control] unable to connect to socket /var/run/lldpd.socket: "
|
||||
"No such file or directory\n__LLDPCTL_RC=1"
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="unable to connect"):
|
||||
driver.get_lldp_neighbors()
|
||||
|
||||
def test_lldpctl_without_neighbours_lists_none(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: "__LLDPCTL_RC=0"
|
||||
|
||||
assert driver.get_lldp_neighbors() == {}
|
||||
assert driver.get_lldp_neighbors_detail() == {}
|
||||
|
||||
def test_the_exit_status_comes_back_with_the_output(self, driver):
|
||||
sent: list = []
|
||||
|
||||
def send(cmd, **kw):
|
||||
sent.append(cmd)
|
||||
return LLDPCTL_KV + "__LLDPCTL_RC=0"
|
||||
|
||||
driver._send_command = send
|
||||
|
||||
assert driver.get_lldp_neighbors()["eth0"][0]["hostname"] == "core-router"
|
||||
assert sent == [LLDPCTL_KEYVALUE_COMMAND]
|
||||
|
||||
|
||||
# A swconfig VLAN interface (``eth0.1``) with a neighbour that names its port by
|
||||
# MAC, and a switch on ``eth1`` that names itself and its port by local ids.
|
||||
# Laid out the way lldpd's keyvalue writer prints them (src/client/display.c):
|
||||
@@ -2198,10 +2237,41 @@ class TestGetEnvironmentCpu:
|
||||
|
||||
assert driver.get_environment()["cpu"][0]["%usage"] == 0.0
|
||||
|
||||
def test_a_single_read_is_not_taken_for_usage(self, driver):
|
||||
def test_a_single_read_raises(self, driver):
|
||||
# Not taken for the usage (#10), and not reported as 0 % either (#27).
|
||||
self._answer(driver, "cpu 1000 0 500 8500 0 0 0\n")
|
||||
|
||||
assert driver.get_environment()["cpu"][0]["%usage"] == 0.0
|
||||
with pytest.raises(ValueError, match="/proc/stat"):
|
||||
driver.get_environment()
|
||||
|
||||
def test_an_unreadable_proc_stat_raises(self, driver):
|
||||
self._answer(driver, "grep: /proc/stat: No such file or directory\n")
|
||||
|
||||
with pytest.raises(ValueError, match="/proc/stat"):
|
||||
driver.get_environment()
|
||||
|
||||
def test_a_garbled_cpu_line_raises(self, driver):
|
||||
self._answer(driver, "cpu 1000 0 500 x 0 0 0\ncpu 1090 0 500 8510 0 0 0\n")
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
driver.get_environment()
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"meminfo",
|
||||
[
|
||||
"cat: can't open '/proc/meminfo': No such file or directory",
|
||||
"MemTotal: 124608 kB\nMemFree: 43204 kB\n",
|
||||
"MemTotal: 124608 kB\nMemAvailable:\n",
|
||||
],
|
||||
)
|
||||
def test_an_unreadable_meminfo_raises(self, driver, meminfo):
|
||||
def send(cmd, **kw):
|
||||
return meminfo if "meminfo" in cmd else PROC_STAT_CPU_TWICE
|
||||
|
||||
driver._send_command = send
|
||||
|
||||
with pytest.raises(ValueError, match="/proc/meminfo"):
|
||||
driver.get_environment()
|
||||
|
||||
def test_memory_is_still_read(self, driver):
|
||||
self._answer(driver, PROC_STAT_CPU_TWICE)
|
||||
|
||||
Reference in new issue
Block a user