# 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. """lldpd's interface list in UCI, the step of napalm-device-types' ``LldpAgentMixin``. The template installs lldpd (``ensure_package``) and enables and restarts it (``manage_service``); this writes ``lldpd.config.interface``, which lldpd's init script turns into ``-I``. """ from __future__ import annotations import re from collections.abc import Sequence from typing import TYPE_CHECKING, Any, cast from napalm_device_types import FixStepOutcomeDict, LldpAgentMixin #: An interface name that may stand in single quotes in a shell line. _IFNAME = re.compile(r"^[A-Za-z0-9_.@-]+$") #: An 802.1Q device as OpenWrt names it: the device under it, a dot, the VLAN id. _VLAN_DEVICE = re.compile(r"^(?P.+)\.\d+$") _UCI_LIST = "lldpd.config.interface" def lldp_devices(interfaces: Sequence[str]) -> list[str]: """The devices lldpd runs on for *interfaces*, in order and once each. lldpd sends on the L2 device, so a VLAN device (``br-ap.10``) counts as the device under it (``br-ap``). :raises ValueError: for a name that is not an interface name. """ devices: list[str] = [] for name in interfaces: if not _IFNAME.match(name): raise ValueError(f"not an interface name: {name!r}") vlan = _VLAN_DEVICE.match(name) device = vlan.group("parent") if vlan else name if device not in devices: devices.append(device) return devices class OpenWrtLldpAgentMixin(LldpAgentMixin): """lldpd on the interfaces the caller names, through UCI.""" def _write_lldp_agent_config(self, interfaces: list[str]) -> FixStepOutcomeDict: devices = lldp_devices(interfaces) commands = [ "(uci -q get lldpd.config >/dev/null || uci set lldpd.config=lldpd)", f"(uci -q delete {_UCI_LIST} || true)", *(f"uci add_list {_UCI_LIST}='{device}'" for device in devices), "uci commit lldpd", ] done = f"lldpd runs on {', '.join(devices)}" return cast(FixStepOutcomeDict, self._rc_step(" && ".join(commands), done)) if TYPE_CHECKING: # pragma: no cover - the driver's def _rc_step(self, command: str, done: str) -> dict[str, Any]: ...