"""The physical NICs a bridge leaves the node through (``NetworkTargetDict.uplinks``). One group per way out of the bridge: a bond's slaves together, a single NIC alone. Read from the node's network config (``GET /nodes/{node}/network``): a Linux bridge names its ports in ``bridge_ports``, an OVS bridge in ``ovs_ports``. A Linux bond lists its NICs in ``slaves``, an OVS bond in ``ovs_bonds``. Internal ports (``OVSIntPort``) and VLAN subinterfaces are no uplinks: the first never leaves the node, the second leaves it tagged, so the switch port's untagged VLAN is not the bridge's. """ from __future__ import annotations from typing import Any #: Types of a port that is a physical NIC of its own. _NIC_TYPES = frozenset({"eth", "OVSPort"}) #: Types of a port that leaves the node through its member NICs. _BOND_TYPES = frozenset({"bond", "OVSBond"}) #: Types of a port that is no uplink. _NOT_UPLINK_TYPES = frozenset({"vlan", "OVSIntPort"}) class _Unknown(Exception): """A port whose kind the network config does not tell.""" def _words(value: Any) -> list[str]: return [w for w in str(value or "").split() if w != "none"] def _nics_of(port: str, by_name: dict[str, dict[str, Any]], in_bond: bool = False) -> list[str]: info = by_name.get(port) if info is None: raise _Unknown(port) kind = info.get("type", "") if kind in _BOND_TYPES: return _bond_nics(info, by_name) # An OVS bond's slave can come without a type of its own. if kind in _NIC_TYPES or (in_bond and not kind): # A VLAN subinterface added to an OVS bridge is an OVSPort too. return [] if "." in port else [port] if kind in _NOT_UPLINK_TYPES: return [] raise _Unknown(port) def _bond_nics(bond: dict[str, Any], by_name: dict[str, dict[str, Any]]) -> list[str]: members = _words(bond.get("slaves") or bond.get("ovs_bonds")) return [nic for member in members for nic in _nics_of(member, by_name, in_bond=True)] def bridge_uplinks(bridge: dict[str, Any], network: list[dict[str, Any]]) -> list[list[str]] | None: """The physical NICs *bridge* leaves the node through, per port, or None when unknown. An empty list is a bridge without uplink. None means a port is missing from the network config or of a kind this cannot place — a guess would send the caller to the wrong switch port. """ by_name = {iface["iface"]: iface for iface in network if iface.get("iface")} ports = _words(bridge.get("ovs_ports") or bridge.get("bridge_ports")) try: groups = [_nics_of(port, by_name) for port in ports] except _Unknown: return None return [group for group in groups if group]