diff --git a/python/neutron-understack/neutron_understack/lag_name.py b/python/neutron-understack/neutron_understack/lag_name.py new file mode 100644 index 000000000..c46bcc6e8 --- /dev/null +++ b/python/neutron-understack/neutron_understack/lag_name.py @@ -0,0 +1,66 @@ +"""Port-channel naming for bonded baremetal ports. + +The number is computed statelessly from the anchor interface alone: + + po = 1000 + port * 10 + D + +where D is the breakout lane (1-4, or 0 when absent) plus 0 for the first +switch of a pair or 5 for the second. Only fixed-form leaves (slot 1) are +supported. The lowest possible number is 1010, so Po1000-1009 stay reserved. +""" + +import re + +from neutron_lib import exceptions as exc + +MAX_PORT = 308 +MAX_LANE = 4 +SECOND_SWITCH_OFFSET = 5 + +_INTERFACE_RE = re.compile( + r"^(?:eth(?:ernet)?)?\s*(?P\d+)/(?P\d+)(?:/(?P\d+))?$", + re.IGNORECASE, +) + + +class InvalidLagAnchor(exc.InvalidInput): + message = "Cannot derive a port-channel name from interface %(port_id)r: %(why)s" + + +def lag_name(port_id: str, second_switch: bool = False) -> str: + """Return the port-channel name (e.g. ``Po1170``) for an anchor interface.""" + match = _INTERFACE_RE.match(port_id.strip()) + if not match: + raise InvalidLagAnchor(port_id=port_id, why="unrecognised interface name") + + slot = int(match["slot"]) + port = int(match["port"]) + lane = int(match["lane"]) if match["lane"] else 0 + + if slot != 1: + raise InvalidLagAnchor(port_id=port_id, why="slot must be 1") + if not 1 <= port <= MAX_PORT: + raise InvalidLagAnchor(port_id=port_id, why=f"port must be 1-{MAX_PORT}") + if match["lane"] and not 1 <= lane <= MAX_LANE: + raise InvalidLagAnchor(port_id=port_id, why=f"lane must be 1-{MAX_LANE}") + + digit = lane + (SECOND_SWITCH_OFFSET if second_switch else 0) + return f"Po{1000 + port * 10 + digit}" + + +def for_profile(profile: dict) -> str | None: + """Return the LAG name for a binding profile, or None if it is not bonded. + + update_port_precommit stores the name under ``lag``. Ports bound before that + have none, so derive it from the first local_link_information entry. + """ + group = profile.get("local_group_information") + if not group: + return None + if group.get("lag"): + return group["lag"] + + links = profile.get("local_link_information") or [] + if not links: + raise InvalidLagAnchor(port_id="", why="no local_link_information") + return lag_name(links[0].get("port_id", "")) diff --git a/python/neutron-understack/neutron_understack/tests/test_lag_name.py b/python/neutron-understack/neutron_understack/tests/test_lag_name.py new file mode 100644 index 000000000..7a650e188 --- /dev/null +++ b/python/neutron-understack/neutron_understack/tests/test_lag_name.py @@ -0,0 +1,29 @@ +import pytest + +from neutron_understack.lag_name import InvalidLagAnchor +from neutron_understack.lag_name import lag_name + + +@pytest.mark.parametrize( + ("port_id", "second", "expected"), + [ + ("Eth1/17", False, "Po1170"), + ("Eth1/17/2", False, "Po1172"), + ("Eth1/96", True, "Po1965"), + ("Eth1/102", False, "Po2020"), + ("Eth1/102/3", True, "Po2028"), + ("Ethernet1/1", False, "Po1010"), + ("Eth1/308/4", True, "Po4089"), + ], +) +def test_lag_name(port_id, second, expected): + assert lag_name(port_id, second_switch=second) == expected + + +@pytest.mark.parametrize( + "port_id", + ["Eth2/1", "Eth1/0", "Eth1/309", "Eth1/1/0", "Eth1/1/5", "mgmt0", ""], +) +def test_rejects_invalid_anchor(port_id): + with pytest.raises(InvalidLagAnchor): + lag_name(port_id) diff --git a/python/neutron-understack/neutron_understack/tests/test_undersync_mech.py b/python/neutron-understack/neutron_understack/tests/test_undersync_mech.py index 661eabc6f..8c56e8312 100644 --- a/python/neutron-understack/neutron_understack/tests/test_undersync_mech.py +++ b/python/neutron-understack/neutron_understack/tests/test_undersync_mech.py @@ -499,3 +499,106 @@ def test_ignores_a_trunk_with_no_subports(self, mocker, undersync_driver, trunk) ) fetch.assert_not_called() + + +class TestUndersyncDriverLagName: + def _bonded_ctx(self, vlan_segment, port_id="Eth1/17"): + ctx = _make_context(segments=[vlan_segment()]) + ctx.current[portbindings.PROFILE].update( + { + "local_link_information": [{"port_id": port_id, "switch_id": "aa"}], + "local_group_information": {"id": "g1", "name": "bond0"}, + } + ) + return ctx + + def test_precommit_stores_lag(self, undersync_driver, vlan_segment, mocker): + ctx = self._bonded_ctx(vlan_segment) + store = mocker.patch.object(undersync_mech.utils, "set_active_binding_profile") + + undersync_driver.update_port_precommit(ctx) + + profile = ctx.current[portbindings.PROFILE] + assert profile["local_group_information"]["lag"] == "Po1170" + store.assert_called_once_with(ctx.plugin_context, "port-1", profile) + + def test_precommit_keeps_existing_lag(self, undersync_driver, vlan_segment, mocker): + ctx = self._bonded_ctx(vlan_segment) + ctx.current[portbindings.PROFILE]["local_group_information"]["lag"] = "Po9" + store = mocker.patch.object(undersync_mech.utils, "set_active_binding_profile") + + undersync_driver.update_port_precommit(ctx) + + assert ( + ctx.current[portbindings.PROFILE]["local_group_information"]["lag"] == "Po9" + ) + store.assert_not_called() + + def test_precommit_ignores_unbonded_port( + self, undersync_driver, vlan_segment, mocker + ): + ctx = _make_context(segments=[vlan_segment()]) + store = mocker.patch.object(undersync_mech.utils, "set_active_binding_profile") + + undersync_driver.update_port_precommit(ctx) + + store.assert_not_called() + + def test_precommit_rejects_unnameable_anchor( + self, undersync_driver, vlan_segment, mocker + ): + ctx = self._bonded_ctx(vlan_segment, port_id="Eth2/1") + store = mocker.patch.object(undersync_mech.utils, "set_active_binding_profile") + + with pytest.raises(exc.InvalidInput): + undersync_driver.update_port_precommit(ctx) + + store.assert_not_called() + + def test_lag_derived_for_bonded_port(self, undersync_driver, vlan_segment): + ctx = self._bonded_ctx(vlan_segment) + + assert undersync_driver._lag_for(ctx.current) == "Po1170" + + def test_no_lag_for_unbonded_port(self, undersync_driver, vlan_segment): + ctx = _make_context(segments=[vlan_segment()]) + + assert undersync_driver._lag_for(ctx.current) is None + + def test_stored_lag_wins(self, undersync_driver, vlan_segment): + ctx = self._bonded_ctx(vlan_segment) + ctx.current[portbindings.PROFILE]["local_group_information"]["lag"] = "Po9" + + assert undersync_driver._lag_for(ctx.current) == "Po9" + + def test_update_postcommit_reads_lag(self, undersync_driver, vlan_segment): + ctx = self._bonded_ctx(vlan_segment) + ctx.vif_type = portbindings.VIF_TYPE_OTHER + undersync_driver._postcommit_lag = MagicMock(return_value="Po1170") + + undersync_driver.update_port_postcommit(ctx) + + undersync_driver._postcommit_lag.assert_called_once_with(ctx.current) + + def test_delete_postcommit_reads_lag(self, undersync_driver, vlan_segment): + ctx = self._bonded_ctx(vlan_segment) + undersync_driver._postcommit_lag = MagicMock(return_value="Po1170") + + undersync_driver.delete_port_postcommit(ctx) + + undersync_driver._postcommit_lag.assert_called_once_with(ctx.current) + + def test_postcommit_lag_swallows_bad_anchor(self, undersync_driver, vlan_segment): + ctx = self._bonded_ctx(vlan_segment, port_id="Eth2/1") + + assert undersync_driver._postcommit_lag(ctx.current) is None + + def test_precommit_rejects_bond_without_links( + self, undersync_driver, vlan_segment, mocker + ): + ctx = self._bonded_ctx(vlan_segment) + ctx.current[portbindings.PROFILE]["local_link_information"] = [] + mocker.patch.object(undersync_mech.utils, "set_active_binding_profile") + + with pytest.raises(exc.InvalidInput): + undersync_driver.update_port_precommit(ctx) diff --git a/python/neutron-understack/neutron_understack/undersync_mech.py b/python/neutron-understack/neutron_understack/undersync_mech.py index e9b07130b..a88fa4e40 100644 --- a/python/neutron-understack/neutron_understack/undersync_mech.py +++ b/python/neutron-understack/neutron_understack/undersync_mech.py @@ -12,6 +12,7 @@ from oslo_config import cfg from neutron_understack import config +from neutron_understack import lag_name from neutron_understack import utils from neutron_understack.undersync_client import Undersync @@ -108,6 +109,34 @@ def subscribe(self): cancellable=True, ) + def update_port_precommit(self, context: PortContext) -> None: + """Store the LAG name of a bonded port in its binding profile. + + Only generated when not already present. Runs inside the port update's + transaction, so an anchor we cannot name aborts the update. + update_port_postcommit and delete_port_postcommit then read + ``local_group_information["lag"]`` back from the profile. + """ + if not utils.is_baremetal_port(context): + return + + profile = context.current.get(portbindings.PROFILE) or {} + group = profile.get("local_group_information") + if not group: + return + + if group.get("lag"): + return + + try: + group["lag"] = lag_name.for_profile(profile) + except lag_name.InvalidLagAnchor: + LOG.exception("Cannot name the LAG for port %s", context.current["id"]) + raise + utils.set_active_binding_profile( + context.plugin_context, context.current["id"], profile + ) + def update_port_postcommit(self, context: PortContext) -> None: if not utils.is_baremetal_port(context): return @@ -122,16 +151,31 @@ def update_port_postcommit(self, context: PortContext) -> None: physnet = port[portbindings.PROFILE].get("physical_network") if physnet: + LOG.debug( + "syncing vlan group %s, lag %s", physnet, self._postcommit_lag(port) + ) self.undersync.sync(physnet) + def _postcommit_lag(self, port: dict) -> str | None: + """Best-effort LAG name; bind_port already rejected unnameable anchors.""" + try: + return self._lag_for(port) + except lag_name.InvalidLagAnchor: + LOG.error("Cannot name the LAG for port %s", port["id"]) + return None + def delete_port_postcommit(self, context: PortContext) -> None: # Releasing the segment stays with the understack driver; we only # reconcile the switch for the vlan group the port named. if not utils.is_baremetal_port(context): return - physnet = context.current[portbindings.PROFILE].get("physical_network") + port = context.current + physnet = port[portbindings.PROFILE].get("physical_network") if physnet: + LOG.debug( + "syncing vlan group %s, lag %s", physnet, self._postcommit_lag(port) + ) self.undersync.sync(physnet) def _validate_parent_physnet(self, resource, event, trunk_plugin, payload): @@ -178,6 +222,14 @@ def _sync_trunk_parent(self, trunk) -> None: LOG.debug("notifying Undersync of vlan group %s", physnet) self.undersync.sync(physnet) + @staticmethod + def _lag_for(port: dict) -> str | None: + """The port-channel name for a bonded port, or None if not bonded. + + Raises InvalidLagAnchor if the anchor cannot be named. + """ + return lag_name.for_profile(port.get(portbindings.PROFILE) or {}) + def bind_port(self, context: PortContext) -> None: port = context.current vnic_type = port.get(portbindings.VNIC_TYPE, portbindings.VNIC_NORMAL) diff --git a/python/neutron-understack/neutron_understack/utils.py b/python/neutron-understack/neutron_understack/utils.py index 83e332bad..c3978e55a 100644 --- a/python/neutron-understack/neutron_understack/utils.py +++ b/python/neutron-understack/neutron_understack/utils.py @@ -13,6 +13,7 @@ from neutron_lib import constants from neutron_lib import constants as p_const from neutron_lib import context as n_context +from neutron_lib import exceptions as exc from neutron_lib.api.definitions import segment as segment_def from neutron_lib.plugins import directory from neutron_lib.plugins import utils as plugin_utils @@ -480,6 +481,24 @@ def active_port_binding(port: port_obj.Port) -> port_obj.PortBinding | None: ) +def set_active_binding_profile(plugin_context, port_id: str, profile: dict) -> None: + """Persist ``profile`` on the port's ACTIVE binding. + + Use the caller's plugin_context from a precommit hook so the write joins + the port update's transaction. PortContext only holds a snapshot of the + binding, so changing it there is not saved. + """ + binding = port_obj.PortBinding.get_object( + plugin_context, port_id=port_id, status=constants.ACTIVE + ) + if binding is None: + raise exc.BadRequest( + resource="port", msg=f"port {port_id} has no active binding" + ) + binding.profile = profile + binding.update() + + def parent_port_is_bound(port: port_obj.Port) -> bool: port_binding = active_port_binding(port) return bool(