Files
napalm-openwrt/napalm_openwrt/vlan_mixin.py
T
Christian ManivongandClaude Sonnet 4.6 2c0a5e94bf chore: track extracted mixin modules
Split from monolithic openwrt.py into separate mixin files for
interfaces, VLANs, packages, routing, wireless, LLDP, and config.
Already in use by the main driver; just missing from git tracking.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 22:13:04 +02:00

222 lines
9.0 KiB
Python

# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
import re
from typing import Any
class OpenWrtVLANMixin:
"""Mixin providing VLAN and network-instance NAPALM getters."""
def get_vlans(self) -> dict[str, Any]:
"""Return VLAN information with proper tagged/untagged separation.
Uses ``bridge vlan show`` (DSA-based OpenWrt ≥21.02) for VLAN/port
membership and ``uci show network`` for VLAN names.
A port marked *PVID Egress Untagged* is an untagged member.
All other VLAN memberships for the same port are tagged.
Also detects legacy 802.1q sub-interfaces (``eth0.10`` etc.) from
``ip link show``. The parent interface (``eth0``) is added as a
tagged member for every such VLAN.
"""
bridge_out = self._send_command("bridge vlan show")
uci_out = self._send_command("uci show network")
# vlan_id -> {name, tagged: [], untagged: []}
vlans: dict[str, Any] = {}
current_port: str | None = None
for line in bridge_out.splitlines():
line_s = line.strip()
if not line_s or line_s.lower().startswith("port"):
continue
# Port line: "eth0 1 PVID Egress Untagged"
m = re.match(r"^(\S+)\s+(\d+)(.*)", line)
if m:
current_port = m.group(1)
vlan_id = str(int(m.group(2)))
flags = m.group(3).upper()
vlans.setdefault(vlan_id, {"name": "", "tagged": [], "untagged": []})
if "PVID" in flags or "UNTAGGED" in flags:
if current_port not in vlans[vlan_id]["untagged"]:
vlans[vlan_id]["untagged"].append(current_port)
else:
if current_port not in vlans[vlan_id]["tagged"]:
vlans[vlan_id]["tagged"].append(current_port)
continue
# Continuation line with only a VLAN ID (tagged for current_port)
m = re.match(r"^(\d+)", line_s)
if m and current_port:
vlan_id = str(int(m.group(1)))
vlans.setdefault(vlan_id, {"name": "", "tagged": [], "untagged": []})
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"]
# Also derive VLAN names from UCI network interface sections that
# reference subinterfaces like eth0.N or br-ap.N:
# network.guest.device='eth0.8' -> VLAN 8 name = "guest"
# network.ap_v8.device='br-ap.8' -> VLAN 8 name = "ap_v8"
# Only fills in names that are still empty after bridge-vlan lookup.
for line in uci_out.splitlines():
m = re.match(r"network\.(\w+)\.device='[\w-]+\.(\d+)'", line.strip())
if m:
section_name, vid_str = m.group(1), m.group(2)
vlan_id = str(int(vid_str))
if vlan_id in vlans and not vlans[vlan_id]["name"]:
vlans[vlan_id]["name"] = section_name
# Also detect VLAN sub-interfaces (eth0.10, br-ap.8, ...) from ip link show.
# The sub-interface is the untagged egress point; its parent is tagged.
link_out = self._send_command("ip link show")
for line in link_out.splitlines():
lm = re.match(r"^\d+:\s+(\S+?)[@:]", line)
if not lm:
continue
iface = lm.group(1)
vm = re.match(r"^([\w-]+)\.(\d+)$", iface) # allow hyphens (br-ap)
if not vm:
continue
parent = vm.group(1) # e.g. "eth0" or "br-ap"
vlan_id = str(int(vm.group(2))) # e.g. "10"
vlans.setdefault(vlan_id, {"name": "", "tagged": [], "untagged": []})
# sub-interface itself -> untagged egress
if iface not in vlans[vlan_id]["untagged"] and iface not in vlans[vlan_id]["tagged"]:
vlans[vlan_id]["untagged"].append(iface)
# parent -> tagged trunk
if parent not in vlans[vlan_id]["tagged"] and parent not in vlans[vlan_id]["untagged"]:
vlans[vlan_id]["tagged"].append(parent)
return vlans
def delete_vlan(self, vlan_id: int) -> None:
"""Remove a VLAN from the device by deleting its UCI bridge-vlan section.
Finds the ``network.@bridge-vlan[N]`` section whose ``.vlan`` matches
*vlan_id*, deletes it and commits. If no matching section is found the
method is a no-op (the VLAN may only exist as an eth0.N sub-interface,
which cannot be deleted via UCI alone).
:param vlan_id: VLAN ID to remove.
:raises ValueError: If *vlan_id* is out of the valid range.
"""
if not 1 <= vlan_id <= 4094:
raise ValueError(f"VLAN ID {vlan_id} is out of range (1-4094)")
uci_out = self.cli(["uci show network"]).get("uci show network", "")
idx = None
for line in uci_out.splitlines():
m = re.match(r"network\.@bridge-vlan\[(\d+)\]\.vlan='(\d+)'", line.strip())
if m and int(m.group(2)) == vlan_id:
idx = m.group(1)
break
if idx is None:
# No explicit bridge-vlan section -- nothing to delete via UCI
return
self.cli([
f"uci delete network.@bridge-vlan[{idx}]",
"uci commit network",
"/etc/init.d/network reload",
])
def get_network_instances(self, name: str = "") -> dict[str, Any]:
"""Return network instances (Linux network namespaces + default).
The ``default`` instance contains all interfaces not assigned to a
named namespace. Named namespaces are discovered via ``ip netns list``.
Example::
{
'default': {
'name': 'default',
'type': 'DEFAULT_INSTANCE',
'state': {'route_distinguisher': None},
'interfaces': {'interface': {'br-lan': {}, 'eth0': {}}}
}
}
"""
netns_out = self._send_command("ip netns list")
iface_list = self._get_interface_list()
instances: dict[str, Any] = {}
# Named namespaces
netns_names: list[str] = []
for line in netns_out.splitlines():
line_s = line.strip()
if not line_s:
continue
# "myns (id: 3)" or just "myns"
ns_name = line_s.split()[0]
netns_names.append(ns_name)
# Interfaces inside the namespace
ns_ifaces_out = self._send_command(f"ip netns exec {ns_name} ip link show")
ns_ifaces: dict[str, Any] = {}
for iline in ns_ifaces_out.splitlines():
im = re.match(r"^\d+:\s+(\S+?)[@:]", iline)
if im and im.group(1) != "lo":
ns_ifaces[im.group(1)] = {}
instances[ns_name] = {
"name": ns_name,
"type": "L3VRF",
"state": {"route_distinguisher": None},
"interfaces": {"interface": ns_ifaces},
}
# Default instance: interfaces NOT in any named namespace
# (on most OpenWrt devices there are no named namespaces)
default_ifaces = {iface: {} for iface in iface_list}
instances["default"] = {
"name": "default",
"type": "DEFAULT_INSTANCE",
"state": {"route_distinguisher": None},
"interfaces": {"interface": default_ifaces},
}
if name:
return {k: v for k, v in instances.items() if k == name}
return instances
def set_hostname(self, new_hostname: str) -> None:
"""Set the system hostname via UCI and reload the system service."""
self._send_command(
f"uci set system.@system[0].hostname='{new_hostname}' && "
f"uci commit system && "
f"/etc/init.d/system reload"
)