fix(vlans): read bridge-vlan membership from UCI, repair stale tests

get_vlans() relied on `bridge vlan show` for port membership. On devices
whose BusyBox ships without the bridge/ip-full packages the command does
not exist, _send_command returns the shell error, and the parser silently
finds nothing in it. All that survived was the sub-interface fallback,
which restates the bridge topology (br-ap tagged, br-ap.10 untagged) and
never names the uplink port — the only port whose tagging matters.

Measured on two Sophos AP100 (BusyBox 1.37.0): eth0 was absent from the
output entirely, while UCI held ports='eth0:u*' for the management VLAN
and 'eth0:t' for the rest.

UCI bridge-vlan sections are now parsed as a second source. They are
readable without the bridge binary and describe the configured state.
Section collection goes through the type declaration, so named sections
(network.apbr_vlan10) are recognised alongside anonymous ones — the old
regex matched only @bridge-vlan[N], so a hand-built bridge was invisible
even for name lookup. Runtime data keeps precedence where it exists,
since that is what the kernel actually enforces.

Option values are kept raw through collection; stripping quotes there
would collapse ports='lan1:t' 'lan2:t' into a single mangled item.

Also repairs TestGetVlans, red on master since get_vlans() moved to
separate tagged/untagged lists while the tests still asserted the old
'interfaces' key, and TestGetFacts, which never learned about the
number_of_interfaces key get_facts() sets deliberately. Both had left
the interesting behaviour uncovered.
This commit is contained in:
Christian Manivong
2026-08-17 22:50:08 +07:00
parent a8637461bb
commit c686fac55e
2 changed files with 228 additions and 21 deletions
+79 -13
View File
@@ -17,6 +17,63 @@ import re
from typing import Any
def _split_uci_list(value: str) -> list[str]:
"""Split a ``uci show`` option value into its items.
List options are rendered space-separated with each item quoted
(``ports='lan1:t' 'lan2:t'``); scalar options carry a single quoted value.
"""
items = re.findall(r"'([^']*)'", value)
if items:
return [i for i in items if i]
stripped = value.strip().strip("'")
return [stripped] if stripped else []
def _uci_scalar(value: str) -> str:
"""Return the single unquoted value of a scalar ``uci show`` option."""
items = _split_uci_list(value)
return items[0] if items else ""
def _parse_port_spec(spec: str) -> tuple[str, bool]:
"""Return ``(port, is_tagged)`` for an OpenWrt bridge-vlan port spec.
``eth0:t`` is a tagged member; ``eth0:u*`` (untagged + PVID), ``eth0:*``
and a bare ``eth0`` are untagged members.
"""
port, _, flags = spec.partition(":")
return port, "t" in flags
def _uci_sections_of_type(uci_out: str, sec_type: str) -> list[dict[str, str]]:
"""Collect all ``network`` sections of *sec_type* from ``uci show network``.
Handles both anonymous (``network.@bridge-vlan[0]``) and named
(``network.apbr_vlan10``) sections — only the former was recognised before,
so tool- or hand-provisioned bridges were invisible.
Option values are kept raw (quotes included) so that list options stay
distinguishable from scalars; use :func:`_uci_scalar` or
:func:`_split_uci_list` to read them.
"""
decl = re.compile(rf"^network\.(\S+)={re.escape(sec_type)}$")
option = re.compile(r"^network\.(\S+?)\.(\w+)=(.*)$")
section_ids: set[str] = set()
for line in uci_out.splitlines():
m = decl.match(line.strip())
if m:
section_ids.add(m.group(1))
sections: dict[str, dict[str, str]] = {sid: {} for sid in section_ids}
for line in uci_out.splitlines():
m = option.match(line.strip())
if m and m.group(1) in section_ids:
sections[m.group(1)][m.group(2)] = m.group(3).strip()
return list(sections.values())
class OpenWrtVLANMixin:
"""Mixin providing VLAN and network-instance NAPALM getters."""
@@ -68,19 +125,28 @@ class OpenWrtVLANMixin:
if current_port not in vlans[vlan_id]["tagged"]:
vlans[vlan_id]["tagged"].append(current_port)
# Enrich with UCI VLAN names from explicit bridge-vlan sections
uci_entries: dict[str, dict[str, str]] = {}
for line in uci_out.splitlines():
m = re.match(r"network\.@bridge-vlan\[(\d+)\]\.(\w+)='([^']*)'", line.strip())
if m:
idx, key, value = m.group(1), m.group(2), m.group(3)
uci_entries.setdefault(idx, {})[key] = value
for entry in uci_entries.values():
if "vlan" in entry and "name" in entry:
vlan_id = str(int(entry["vlan"]))
if vlan_id in vlans:
vlans[vlan_id]["name"] = entry["name"]
# Enrich with the configured membership from UCI bridge-vlan sections.
# On devices whose BusyBox ships without the `bridge` utility this is
# the only source that names the physical ports at all — the
# sub-interface fallback below can only ever report br-ap/br-ap.N.
# Runtime data from `bridge vlan show` describes what the kernel
# actually enforces, so it keeps precedence where both are present.
for entry in _uci_sections_of_type(uci_out, "bridge-vlan"):
if "vlan" not in entry:
continue
try:
vlan_id = str(int(_uci_scalar(entry["vlan"])))
except ValueError:
continue
vlan = vlans.setdefault(vlan_id, {"name": "", "tagged": [], "untagged": []})
uci_name = _uci_scalar(entry.get("name", ""))
if uci_name and not vlan["name"]:
vlan["name"] = uci_name
for spec in _split_uci_list(entry.get("ports", "")):
port, tagged = _parse_port_spec(spec)
if port in vlan["tagged"] or port in vlan["untagged"]:
continue
vlan["tagged" if tagged else "untagged"].append(port)
# Also derive VLAN names from UCI network interface sections that
# reference subinterfaces like eth0.N or br-ap.N: