Merge remote-tracking branch 'origin/main' into feat/lldp-agent-setup
This commit is contained in:
commit
1e988c87f4
7 files changed
+383
-78
No files matched your search
@@ -14,12 +14,39 @@ 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."""
|
||||
|
||||
def get_lldp_neighbors(self) -> dict[str, list[dict[str, Any]]]:
|
||||
"""Return LLDP neighbors (requires ``lldpd`` to be installed on the device).
|
||||
"""Return LLDP neighbors (requires ``lldpd`` installed and running on the device).
|
||||
|
||||
Uses ``lldpctl -f keyvalue`` output::
|
||||
|
||||
@@ -33,67 +60,17 @@ class OpenWrtLLDPMixin:
|
||||
)
|
||||
return neighbors
|
||||
|
||||
def _lldpd_fix_interface(self) -> None:
|
||||
"""Ensure lldpd UCI config uses the actual management interface.
|
||||
|
||||
Detects the interface carrying the default route (e.g. br-lan.10 on a
|
||||
VLAN trunk) and replaces any stale/wrong interface entry in the lldpd
|
||||
UCI config. Idempotent — only writes if the config needs updating.
|
||||
"""
|
||||
mgmt_iface = self._send_command(
|
||||
"ip route show default 2>/dev/null | head -1 | grep -oE 'dev [^ ]+' | awk '{print $2}'"
|
||||
).strip()
|
||||
if not mgmt_iface:
|
||||
mgmt_iface = "br-lan"
|
||||
# LLDP is a L2 protocol — it must run on the bridge, not a VLAN subinterface.
|
||||
# Strip .VID suffix so br-ap.10 → br-ap.
|
||||
if "." in mgmt_iface:
|
||||
mgmt_iface = mgmt_iface.rsplit(".", 1)[0]
|
||||
|
||||
current = self._send_command("uci get lldpd.config.interface 2>/dev/null").strip()
|
||||
if mgmt_iface in current:
|
||||
return # already correct
|
||||
|
||||
# Reset the interface list to just the management interface
|
||||
self._send_command(
|
||||
"uci delete lldpd.config.interface 2>/dev/null; "
|
||||
f"uci add_list lldpd.config.interface='{mgmt_iface}' 2>/dev/null; "
|
||||
"uci commit lldpd 2>/dev/null; "
|
||||
"/etc/init.d/lldpd restart 2>/dev/null"
|
||||
)
|
||||
|
||||
def _get_lldp_table(self) -> list[dict[str, Any]]:
|
||||
"""Parse ``lldpctl -f keyvalue`` into a list of row dicts.
|
||||
|
||||
Ensures ``lldpd`` is enabled and running before querying; if it was
|
||||
not already running the daemon needs time to discover neighbors so
|
||||
the first call after a fresh install will return an empty list.
|
||||
Reads only: lldpd is neither started nor reconfigured here. Installing,
|
||||
starting and configuring it are the caller's (``ensure_package``,
|
||||
``manage_service``).
|
||||
"""
|
||||
# Ensure lldpd is running on the correct management interface
|
||||
self._send_command(
|
||||
"pgrep lldpd >/dev/null 2>&1 || "
|
||||
"(/etc/init.d/lldpd enable 2>/dev/null; /etc/init.d/lldpd start 2>/dev/null)"
|
||||
)
|
||||
self._lldpd_fix_interface()
|
||||
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,
|
||||
|
||||
@@ -111,8 +111,8 @@ class OpenWrtDriver(
|
||||
self.timeout = timeout
|
||||
self.device: ConnectHandler | None = None
|
||||
|
||||
if optional_args is None:
|
||||
optional_args = {}
|
||||
# A copy: the caller's dict stays as it was.
|
||||
optional_args = dict(optional_args or {})
|
||||
|
||||
self.port = optional_args.pop("port", 22)
|
||||
self.netmiko_optional_args = netmiko_args(optional_args)
|
||||
|
||||
@@ -23,6 +23,8 @@ _RC_MARKER = "__OWRT_RC="
|
||||
_RC_RE = re.compile(rf"^{_RC_MARKER}(\d+)\s*$", re.MULTILINE)
|
||||
#: What apk prints when its index is not in RAM (after a reboot).
|
||||
_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"
|
||||
|
||||
|
||||
def _split_status(raw: str) -> tuple[str, int | None]:
|
||||
@@ -32,6 +34,49 @@ def _split_status(raw: str) -> tuple[str, int | None]:
|
||||
return output, int(statuses[-1]) if statuses else None
|
||||
|
||||
|
||||
def _status_result(raw: str, command: str) -> dict[str, Any]:
|
||||
"""``{"success", "output"}`` from what a command marked with ``_RC_MARKER`` printed.
|
||||
|
||||
Only the exit status decides; output without a status is no success.
|
||||
"""
|
||||
output, status = _split_status(raw)
|
||||
if status is None:
|
||||
return {"success": False, "output": output or "No exit status came back from the device."}
|
||||
if status:
|
||||
return {"success": False, "output": output or f"{command} exited with status {status}."}
|
||||
return {"success": True, "output": output}
|
||||
|
||||
|
||||
def _cpu_counters(line: str) -> tuple[int, int]:
|
||||
"""``(idle, total)`` jiffies of a ``cpu`` line.
|
||||
|
||||
The total counts user, nice, system, idle, iowait, irq and softirq.
|
||||
"""
|
||||
fields = [int(x) for x in line.split()[1:8]]
|
||||
if len(fields) < 7:
|
||||
raise ValueError(f"not a cpu line: {line!r}")
|
||||
return fields[3], sum(fields)
|
||||
|
||||
|
||||
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.
|
||||
"""
|
||||
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
|
||||
elapsed = total2 - total1
|
||||
if elapsed <= 0:
|
||||
return 0.0
|
||||
return (1 - (idle2 - idle1) / elapsed) * 100
|
||||
|
||||
|
||||
class OpenWrtSystemMixin:
|
||||
"""Mixin providing system-level NAPALM getters.
|
||||
|
||||
@@ -41,21 +86,13 @@ class OpenWrtSystemMixin:
|
||||
def get_environment(self) -> dict[str, Any]:
|
||||
"""Return device environment data (CPU, memory).
|
||||
|
||||
CPU usage from ``/proc/stat`` (two samples 1 second apart via ``awk``).
|
||||
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``.
|
||||
"""
|
||||
cpu_out = self._send_command(
|
||||
"awk '/^cpu /{idle1=$5; total1=$2+$3+$4+$5+$6+$7+$8} "
|
||||
"END{print (1-(idle1/total1))*100}' /proc/stat"
|
||||
)
|
||||
cpu_pct = _cpu_usage_percent(self._send_command(_CPU_SAMPLES))
|
||||
mem_out = self._send_command("cat /proc/meminfo")
|
||||
|
||||
cpu_pct = 0.0
|
||||
try:
|
||||
cpu_pct = float(cpu_out.strip())
|
||||
except (ValueError, AttributeError):
|
||||
pass
|
||||
|
||||
mem_total = 0
|
||||
mem_available = 0
|
||||
for line in mem_out.splitlines():
|
||||
@@ -389,15 +426,19 @@ class OpenWrtSystemMixin:
|
||||
return result
|
||||
|
||||
def manage_service(self, name: str, action: str) -> dict[str, Any]:
|
||||
"""Execute a lifecycle action (start/stop/restart/enable/disable) on a service."""
|
||||
"""Execute a lifecycle action (start/stop/restart/enable/disable) on a service.
|
||||
|
||||
Only the init script's exit status decides ``success``; a missing script
|
||||
or a failed action comes back with what the device printed.
|
||||
"""
|
||||
import re as _re
|
||||
|
||||
if not _re.match(r"^[a-zA-Z0-9_\-]+$", name):
|
||||
raise ValueError(f"Invalid service name: {name!r}")
|
||||
if action not in ("start", "stop", "restart", "enable", "disable"):
|
||||
raise ValueError(f"Invalid action: {action!r}")
|
||||
output = self._send_command(f"/etc/init.d/{name} {action} 2>&1")
|
||||
return {"success": True, "output": output}
|
||||
command = f"/etc/init.d/{name} {action}"
|
||||
return _status_result(self._send_command(f"{command} 2>&1; echo {_RC_MARKER}$?"), command)
|
||||
|
||||
def get_available_updates(self) -> list[dict[str, Any]]:
|
||||
"""Return list of upgradable packages from the local package manager cache.
|
||||
@@ -463,7 +504,10 @@ class OpenWrtSystemMixin:
|
||||
return {"success": status == 0, "output": output}
|
||||
|
||||
def apply_updates(self, packages: list[str]) -> dict[str, Any]:
|
||||
"""Upgrade the given packages using the device's package manager."""
|
||||
"""Upgrade the given packages using the device's package manager.
|
||||
|
||||
Only the package manager's exit status decides ``success``.
|
||||
"""
|
||||
import re as _re
|
||||
|
||||
for pkg in packages:
|
||||
@@ -472,11 +516,18 @@ class OpenWrtSystemMixin:
|
||||
pm = self._pm_type()
|
||||
pkg_args = " ".join(packages)
|
||||
if pm == "apk":
|
||||
cmd = f"apk upgrade {pkg_args} 2>&1"
|
||||
cmd = f"apk upgrade {pkg_args}"
|
||||
else:
|
||||
cmd = f"opkg upgrade {pkg_args} 2>&1"
|
||||
output = self._send_command(cmd)
|
||||
return {"success": True, "output": output}
|
||||
cmd = f"opkg upgrade {pkg_args}"
|
||||
output, status = _split_status(self._send_command(f"{cmd} 2>&1; echo {_RC_MARKER}$?"))
|
||||
if status == 0:
|
||||
return {"success": True, "output": output}
|
||||
error = (
|
||||
f"{cmd.strip()} exited with status {status}"
|
||||
if status is not None
|
||||
else "No exit status came back from the device."
|
||||
)
|
||||
return {"success": False, "output": output, "error": error}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# NTP
|
||||
|
||||
Reference in new issue
Block a user