From 44826af37c7bc95079d99fe04d7413bb8020fdf4 Mon Sep 17 00:00:00 2001 From: Hemanth Nakkina Date: Wed, 25 Nov 2026 15:02:59 +0530 Subject: [PATCH] fix(k8s): include MetalLB interfaces in Cilium devices MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Resolve each control node’s internal and public Juju space interfaces and include the storage interface when the optional MAAS MetalLB pool exists. Keep the internal interface as the direct-routing device when multiple devices are needed. During MAAS instance recovery enablement, reconcile Cilium and storage L2 advertisements before assigning the Consul storage VIP. Closes-Bug: #2175721 Assisted-By: codex-gpt-6.2sol --- .../cilium-per-host-device-config-design.md | 40 +++- sunbeam-python/sunbeam/core/steps.py | 28 +-- .../features/instance_recovery/feature.py | 27 ++- .../sunbeam/provider/maas/commands.py | 6 +- sunbeam-python/sunbeam/steps/k8s.py | 163 +++++++++---- .../sunbeam/steps/upgrades/intra_channel.py | 19 +- .../test_instance_recovery_feature.py | 41 ++++ .../unit/sunbeam/provider/maas/test_maas.py | 90 +------- .../tests/unit/sunbeam/steps/test_k8s.py | 217 ++++++++++++++++-- .../steps/upgrades/test_intra_channel.py | 12 +- 10 files changed, 458 insertions(+), 185 deletions(-) diff --git a/docs/agents/specs/cilium-per-host-device-config-design.md b/docs/agents/specs/cilium-per-host-device-config-design.md index 85cd42e17..120188b8c 100644 --- a/docs/agents/specs/cilium-per-host-device-config-design.md +++ b/docs/agents/specs/cilium-per-host-device-config-design.md @@ -24,9 +24,13 @@ device to use on each host, rather than trying to enumerate what to avoid. ## Solution Replace the cluster-wide cilium devices annotation with per-host -`CiliumNodeConfig` resources that specify the exact interface name for each -control node. The interface is determined by querying juju for each machine's -network interfaces and matching against the internal space. +`CiliumNodeConfig` resources that specify the exact internal and public +interface names for each control node. Sunbeam queries Juju for each machine's +interfaces and matches them to the spaces used by the MetalLB advertisements. +MAAS deployments also include the storage interface when the optional storage +IPAddressPool exists. When several spaces resolve to the same interface, the +device appears once. With multiple devices, the internal interface remains the +direct-routing device. ## Reverts @@ -61,11 +65,11 @@ underscore-prefixed). This deduplicates ~60-70 lines. - **Constructor**: `deployment`, `client`, `jhelper`, `model`, `network`, `fqdn` (optional). Initializes `to_update: list[dict]`, - `to_delete: list[dict]`, `_ifnames: dict[str, str]` cache. -- **`_get_interface(node)`**: Looks up machine interfaces via - `jhelper.get_machine_interfaces()`, matches by the step's `network` space. - Caches results in `_ifnames`. Raises a step-specific error (defined by - subclass) if no matching interface found. + `to_delete: list[dict]`, and a cache of Juju machine interfaces. +- **`_get_interface(node, network=None)`** looks up machine interfaces via + `jhelper.get_machine_interfaces()` and matches the requested network's space. + It defaults to the step's configured network and raises an error if the node + has no interface in that space. - **`is_skip(context)`**: Control node lookup (single node if `fqdn` provided, all control nodes otherwise), kube client creation, calls abstract `_get_outdated_resources(nodes, kube)`, populates `to_update`/`to_delete`, @@ -97,8 +101,10 @@ Lists existing `CiliumNodeConfig` resources labeled with - `spec.nodeSelector.matchLabels` contains exactly `sunbeam/hostname: ` (guards against over-broad or empty selectors that could silently misconfigure other nodes) -- `spec.defaults.devices` matches the current internal-space interface for that - node +- `spec.defaults.devices` matches the node's internal, public, and optional + storage interfaces, in that order, with each interface listed once +- `spec.defaults.direct-routing-device` matches the internal interface when + the node has multiple devices A resource that has the right metadata label and device but a wrong or missing `nodeSelector` is considered outdated and will be re-applied. @@ -107,7 +113,7 @@ Returns `(outdated, deleted)` lists. ### `run(context)` -- For each node in `to_update`: look up interface, apply `CiliumNodeConfig` via +- For each node in `to_update`: resolve the devices, apply `CiliumNodeConfig` via lightkube, then delete the cilium pod on that node to trigger restart - For each node in `to_delete`: delete the `CiliumNodeConfig` resource and delete the cilium pod @@ -129,12 +135,18 @@ spec: matchLabels: kubernetes.io/hostname: defaults: - devices: "" + devices: "," + direct-routing-device: "" ``` Uses `cilium.io/v2` (Canonical K8s 1.32 LTS ships Cilium 1.17.1; `v2alpha1` is deprecated since Cilium 1.17). +For a shared interface, Sunbeam sets `devices` to the single interface name. +Cilium can select that device for direct routing automatically. +For a MAAS node with a distinct storage interface and an existing storage +IPAddressPool, Sunbeam appends the storage interface to `devices`. + ### Cilium Pod Restart After applying a config change for a node, restart the cilium agent on that node: @@ -174,6 +186,10 @@ configured before metallb). - Bootstrap plan — before `EnsureL2AdvertisementByHostStep`, all control nodes - Remove-node plan — all control nodes (cleans up departed node's config) +MAAS instance recovery enablement creates the optional pool first, then +reconciles Cilium and the storage L2 advertisements before assigning the +Consul storage VIP. + ### Local commands (`sunbeam-python/sunbeam/provider/local/commands.py`) - Bootstrap plan — same positioning diff --git a/sunbeam-python/sunbeam/core/steps.py b/sunbeam-python/sunbeam/core/steps.py index 94cb63985..67ff9536d 100644 --- a/sunbeam-python/sunbeam/core/steps.py +++ b/sunbeam-python/sunbeam/core/steps.py @@ -909,7 +909,7 @@ def run(self, context: StepContext) -> Result: # noqa: C901 class CreateLoadBalancerIPPoolsStep(BaseStep, abc.ABC): - """Create IPPool and L2Advertisement resources.""" + """Ensure the configured MetalLB IP pools exist.""" def __init__( self, @@ -921,9 +921,6 @@ def __init__( ) self.client = client self.lbpool_resource = K8SHelper.get_lightkube_loadbalancer_resource() - self.l2_advertisement_resource = ( - K8SHelper.get_lightkube_l2_advertisement_resource() - ) self.model = K8SHelper.get_loadbalancer_namespace() @abc.abstractmethod @@ -962,21 +959,6 @@ def handle_lb_pools(self, name: str, addresses: list[str]): ) self.kube.create(new_ippool) - def handle_l2_advertisement(self, name: str): - """Manage L2Advertisement resource. - - Kept for backward compatibility, deleting the resource on - upgraded versions of Sunbeam. - """ - try: - self.kube.get( - self.l2_advertisement_resource, name=name, namespace=self.model - ) - self.kube.delete(self.l2_advertisement_resource, name, namespace=self.model) - except l_exceptions.ApiError as e: - if e.status.code != 404: - raise - def run(self, context: StepContext) -> Result: """Create Loadbalancer IPPool.""" try: @@ -1001,12 +983,4 @@ def run(self, context: StepContext) -> Result: f"Error in processing LoadBalancer pool {name}: {str(e)}", ) - try: - self.handle_l2_advertisement(name) - except l_exceptions.ApiError as e: - return Result( - ResultType.FAILED, - f"Error in processing L2Advertisement {name}: {str(e)}", - ) - return Result(ResultType.COMPLETED) diff --git a/sunbeam-python/sunbeam/features/instance_recovery/feature.py b/sunbeam-python/sunbeam/features/instance_recovery/feature.py index 4a2df4ea0..cf51d1221 100644 --- a/sunbeam-python/sunbeam/features/instance_recovery/feature.py +++ b/sunbeam-python/sunbeam/features/instance_recovery/feature.py @@ -9,7 +9,7 @@ from rich.console import Console from sunbeam.core.common import BaseStep, run_plan -from sunbeam.core.deployment import Deployment +from sunbeam.core.deployment import Deployment, Networks from sunbeam.core.juju import JujuHelper from sunbeam.core.manifest import ( AddManifestStep, @@ -31,6 +31,10 @@ from sunbeam.provider.maas.steps import MaasCreateLoadBalancerIPPoolsStep from sunbeam.steps.hypervisor import ReapplyHypervisorTerraformPlanStep from sunbeam.steps.juju import RemoveSaasApplicationsStep +from sunbeam.steps.k8s import ( + EnsureCiliumDeviceByHostStep, + EnsureL2AdvertisementByHostStep, +) from sunbeam.steps.openstack import ValidateInfraAppsStep from sunbeam.utils import click_option_show_hints, pass_method_obj from sunbeam.versions import CONSUL_CHANNEL, OPENSTACK_CHANNEL @@ -154,14 +158,31 @@ def run_enable_plans( plan2.extend( [ MaasCreateLoadBalancerIPPoolsStep(deployment, client, maas_client), + EnsureCiliumDeviceByHostStep( + deployment, + client, + jhelper, + deployment.openstack_machines_model, + storage_pool=deployment.storage_ip_pool, + ), + EnsureL2AdvertisementByHostStep( + deployment, + client, + jhelper, + deployment.openstack_machines_model, + Networks.STORAGE, + deployment.storage_ip_pool, + optional_if_pool_missing=True, + remove_legacy=True, + ), consul.PatchConsulStorageLoadBalancerIPPoolStep( client, - deployment.storage_ippool_label, + deployment.storage_ip_pool, ignore_errors=True, ), consul.PatchConsulStorageLoadBalancerIPStep( client, - pool_name=deployment.storage_ippool_label, + pool_name=deployment.storage_ip_pool, ignore_errors=True, ), ] diff --git a/sunbeam-python/sunbeam/provider/maas/commands.py b/sunbeam-python/sunbeam/provider/maas/commands.py index 684191f78..b32c5234f 100644 --- a/sunbeam-python/sunbeam/provider/maas/commands.py +++ b/sunbeam-python/sunbeam/provider/maas/commands.py @@ -787,7 +787,6 @@ def deploy( deployment, client, jhelper, deployment.openstack_machines_model ) ) - plan2.append(EnsureDefaultL2AdvertisementMutedStep(deployment, client, jhelper)) plan2.append(MaasCreateLoadBalancerIPPoolsStep(deployment, client, maas_client)) plan2.append( EnsureCiliumDeviceByHostStep( @@ -795,6 +794,7 @@ def deploy( client, jhelper, deployment.openstack_machines_model, + storage_pool=deployment.storage_ip_pool, ), ) plan2.append( @@ -815,6 +815,7 @@ def deploy( deployment.openstack_machines_model, Networks.PUBLIC, deployment.public_ip_pool, + remove_legacy=True, ) ) plan2.append( @@ -826,8 +827,10 @@ def deploy( Networks.STORAGE, deployment.storage_ip_pool, optional_if_pool_missing=True, + remove_legacy=True, ) ) + plan2.append(EnsureDefaultL2AdvertisementMutedStep(deployment, client, jhelper)) plan2.append(AddK8SCloudStep(deployment, jhelper)) plan2.append(TerraformInitStep(tfhelper_microceph)) @@ -1799,6 +1802,7 @@ def remove_node(ctx: click.Context, name: str, force: bool, show_hints: bool) -> client, jhelper, deployment.openstack_machines_model, + storage_pool=deployment.storage_ip_pool, ), EnsureL2AdvertisementByHostStep( deployment, diff --git a/sunbeam-python/sunbeam/steps/k8s.py b/sunbeam-python/sunbeam/steps/k8s.py index 1e243d41d..9ea0916c3 100644 --- a/sunbeam-python/sunbeam/steps/k8s.py +++ b/sunbeam-python/sunbeam/steps/k8s.py @@ -1307,23 +1307,24 @@ def __init__( self.fqdn = fqdn self.to_update: list[dict] = [] self.to_delete: list[dict] = [] - self._ifnames: dict[str, str] = {} + self._machine_interfaces: dict[ + str, dict[str, "jubilant.statustypes.NetworkInterface"] + ] = {} - def _get_interface(self, node: dict) -> str: - """Get the network interface for the node in the configured space.""" - name = node["name"] - if name in self._ifnames: - return self._ifnames[name] + def _get_interface(self, node: dict, network: Networks | None = None) -> str: + """Get the node's interface in the requested space.""" + network = network or self.network machine_id = str(node["machineid"]) - machine_interfaces = self.jhelper.get_machine_interfaces(self.model, machine_id) - LOG.debug("Machine %r interfaces: %r", machine_id, machine_interfaces) - network_space = self.deployment.get_space(self.network) - for ifname, iface in machine_interfaces.items(): + if machine_id not in self._machine_interfaces: + interfaces = self.jhelper.get_machine_interfaces(self.model, machine_id) + LOG.debug("Machine %r interfaces: %r", machine_id, interfaces) + self._machine_interfaces[machine_id] = interfaces + network_space = self.deployment.get_space(network) + for ifname, iface in self._machine_interfaces[machine_id].items(): if (spaces := iface.space) and network_space in spaces.split(): - self._ifnames[name] = ifname return ifname raise self._InterfaceError( - f"Node {node['name']} has no interface in {self.network.name} space" + f"Node {node['name']} has no interface in {network.name} space" ) def _get_outdated_resources( @@ -1343,6 +1344,7 @@ def is_skip(self, context: StepContext) -> Result: """Determines if the step should be skipped or not.""" self.to_update = [] self.to_delete = [] + self._machine_interfaces.clear() control = Role.CONTROL.name.lower() region_controller = Role.REGION_CONTROLLER.name.lower() if self.fqdn: @@ -1384,7 +1386,11 @@ def is_skip(self, context: StepContext) -> Result: outdated, deleted = self._get_outdated_resources( self.control_nodes, self.kube ) - except (l_exceptions.ApiError, self._InterfaceError) as e: + except ( + l_exceptions.ApiError, + self._InterfaceError, + MachineNotFoundException, + ) as e: LOG.debug("Failed to get outdated resources", exc_info=True) return Result(ResultType.FAILED, str(e)) @@ -1410,7 +1416,7 @@ def is_skip(self, context: StepContext) -> Result: class EnsureCiliumDeviceByHostStep(_PerHostK8SResourceStep): - """Ensure each control node has a CiliumNodeConfig for its internal-space device.""" + """Configure Cilium on each control node's LoadBalancer interfaces.""" _CILIUM_NAMESPACE = "kube-system" _RESTART_TIMEOUT = 300 @@ -1419,6 +1425,7 @@ class EnsureCiliumDeviceByHostStep(_PerHostK8SResourceStep): _LOCK_RETRY_INTERVAL = 5 _RESTART_PENDING_ANNOTATION = "sunbeam/restart-pending" _TERRAFORM_PLAN = "k8s-plan" + _DIRECT_ROUTING_DEVICE = "direct-routing-device" def __init__( self, @@ -1428,6 +1435,7 @@ def __init__( model: str, fqdn: str | None = None, reconcile_existing: bool = False, + storage_pool: str | None = None, ): super().__init__( "Ensure Cilium device config", @@ -1441,6 +1449,9 @@ def __init__( fqdn=fqdn, ) self._reconcile_existing = reconcile_existing + self.storage_pool = storage_pool + self._include_storage = False + self._desired_defaults: dict[str, dict[str, str]] = {} self.cilium_node_config_resource = ( K8SHelper.get_lightkube_cilium_node_config_resource() ) @@ -1551,11 +1562,44 @@ def _labels(self, hostname: str) -> dict[str, str]: HOSTNAME_LABEL: hostname, } + def _get_cilium_defaults(self, node: dict) -> dict[str, str]: + """Return the Cilium device settings for the node.""" + internal = self._get_interface(node) + devices = [internal, self._get_interface(node, Networks.PUBLIC)] + if self._include_storage: + devices.append(self._get_interface(node, Networks.STORAGE)) + devices = list(dict.fromkeys(devices)) + defaults = {"devices": ",".join(devices)} + # Preserve the direct-routing device used with the internal-only list. + # With multiple devices Cilium otherwise looks for the Kubernetes node IP, + # which may be on a separate management interface. + if len(devices) > 1: + defaults[self._DIRECT_ROUTING_DEVICE] = internal + return defaults + def _get_outdated_resources( self, nodes: list[dict], kube: "l_client.Client" ) -> tuple[list[str], list[str]]: - node_names = {node["name"] for node in nodes} - outdated: list[str] = [node["name"] for node in nodes] + self._desired_defaults.clear() + self._include_storage = False + if self.storage_pool is not None: + try: + kube.get( + K8SHelper.get_lightkube_loadbalancer_resource(), + name=self.storage_pool, + namespace=K8SHelper.get_loadbalancer_namespace(), + ) + except l_exceptions.ApiError as e: + if e.status.code != 404: + raise + LOG.debug( + "Optional MetalLB storage pool %s is absent", self.storage_pool + ) + else: + self._include_storage = True + + nodes_by_name = {node["name"]: node for node in nodes} + outdated = list(nodes_by_name) deleted: list[str] = [] configs = kube.list( @@ -1578,7 +1622,7 @@ def _get_outdated_resources( if config.spec is None: LOG.debug("CiliumNodeConfig %r has no spec", hostname) continue - if hostname not in node_names: + if hostname not in nodes_by_name: LOG.debug( "CiliumNodeConfig %s has no matching node", config.metadata.name, @@ -1586,6 +1630,20 @@ def _get_outdated_resources( deleted.append(hostname) continue + defaults = config.spec.get("defaults", {}) + desired = self._get_cilium_defaults(nodes_by_name[hostname]) + override = defaults.get(self._DIRECT_ROUTING_DEVICE) + if override and self._DIRECT_ROUTING_DEVICE not in desired: + # An explicit override prevents Cilium's automatic single-device + # selection. Correct an incompatible override even if another + # field manager set it, before restarting the agent. + device = desired["devices"] + if override != device and not ( + override.endswith("+") and device.startswith(override.rstrip("+")) + ): + desired[self._DIRECT_ROUTING_DEVICE] = device + self._desired_defaults[hostname] = desired + # Validate nodeSelector node_selector = config.spec.get("nodeSelector", {}) match_labels = node_selector.get("matchLabels", {}) @@ -1596,24 +1654,12 @@ def _get_outdated_resources( ) continue - # Validate device - defaults = config.spec.get("defaults", {}) - interface = None - for node in nodes: - if node["name"] == hostname: - interface = self._get_interface(node) - if not interface: + if any(defaults.get(key) != value for key, value in desired.items()): LOG.debug( - "CiliumNodeConfig %s: no interface for node", + "CiliumNodeConfig %s has wrong device settings (got %s, want %s)", config.metadata.name, - ) - continue - if defaults.get("devices") != interface: - LOG.debug( - "CiliumNodeConfig %s has wrong device (got %s, want %s)", - config.metadata.name, - defaults.get("devices"), - interface, + defaults, + desired, ) continue @@ -1738,7 +1784,11 @@ def _apply_changes(self, context: StepContext) -> Result: for node in self.to_update: name = node["name"] try: - interface = self._get_interface(node) + defaults = self._desired_defaults.get(name) + if defaults is None: + defaults = self._get_cilium_defaults(node) + except self._InterfaceError as e: + return Result(ResultType.FAILED, str(e)) except MachineNotFoundException: LOG.debug( "Failed to get machine for CiliumNodeConfig on %s", @@ -1766,9 +1816,7 @@ def _apply_changes(self, context: StepContext) -> Result: HOSTNAME_LABEL: name, }, }, - "defaults": { - "devices": interface, - }, + "defaults": defaults, }, ), field_manager=self.deployment.name, @@ -1852,6 +1900,7 @@ def __init__( pool: str, fqdn: str | None = None, optional_if_pool_missing: bool = False, + remove_legacy: bool = False, ): super().__init__( "Ensure L2 advertisement", @@ -1866,6 +1915,8 @@ def __init__( ) self.pool = pool self.optional_if_pool_missing = optional_if_pool_missing + self.remove_legacy = remove_legacy + self._legacy_to_remove = False self.lbpool_resource = K8SHelper.get_lightkube_loadbalancer_resource() self.l2_advertisement_resource = ( K8SHelper.get_lightkube_l2_advertisement_resource() @@ -1873,9 +1924,10 @@ def __init__( self.l2_advertisement_namespace = K8SHelper.get_loadbalancer_namespace() def is_skip(self, context: StepContext) -> Result: - """Skip optional advertisements when the IPAddressPool is absent.""" + """Check for per-host changes and a legacy advertisement to retire.""" self.to_update = [] self.to_delete = [] + self._legacy_to_remove = False if self.optional_if_pool_missing: try: kube = get_kube_client(self.client, self.kube_namespace) @@ -1897,7 +1949,26 @@ def is_skip(self, context: StepContext) -> Result: LOG.debug("Failed to get ipaddresspool %s", self.pool, exc_info=True) return Result(ResultType.FAILED, str(e)) - return super().is_skip(context) + result = super().is_skip(context) + if ( + result.result_type == ResultType.FAILED + or not self.remove_legacy + or self.fqdn + or not self.control_nodes + ): + return result + try: + self.kube.get( + self.l2_advertisement_resource, + name=self.pool, + namespace=self.l2_advertisement_namespace, + ) + except l_exceptions.ApiError as e: + if e.status.code == 404: + return result + return Result(ResultType.FAILED, str(e)) + self._legacy_to_remove = True + return Result(ResultType.COMPLETED) def _labels(self, name: str, space: str) -> dict[str, str]: """Return labels for the L2 advertisement.""" @@ -2069,6 +2140,20 @@ def run(self, context: StepContext) -> Result: LOG.debug("Failed to delete L2 advertisement", exc_info=True) continue + if self._legacy_to_remove: + try: + self.kube.delete( + self.l2_advertisement_resource, + self.pool, + namespace=self.l2_advertisement_namespace, + ) + except l_exceptions.ApiError as e: + if e.status.code != 404: + return Result( + ResultType.FAILED, + f"Failed to delete legacy L2 advertisement {self.pool}: {e}", + ) + return Result(ResultType.COMPLETED) diff --git a/sunbeam-python/sunbeam/steps/upgrades/intra_channel.py b/sunbeam-python/sunbeam/steps/upgrades/intra_channel.py index 1d3e1b733..5135d87f2 100644 --- a/sunbeam-python/sunbeam/steps/upgrades/intra_channel.py +++ b/sunbeam-python/sunbeam/steps/upgrades/intra_channel.py @@ -566,19 +566,17 @@ def get_plan(self) -> list[BaseStep]: maas_client = MaasClient.from_deployment(self.deployment) plan.extend( [ + MaasCreateLoadBalancerIPPoolsStep( + self.deployment, # type: ignore [arg-type] + self.client, + maas_client, + ), EnsureCiliumDeviceByHostStep( self.deployment, self.client, self.jhelper, self.deployment.openstack_machines_model, - ), - EnsureDefaultL2AdvertisementMutedStep( - self.deployment, self.client, self.jhelper - ), - MaasCreateLoadBalancerIPPoolsStep( - self.deployment, # type: ignore [arg-type] - self.client, - maas_client, + storage_pool=self.deployment.storage_ip_pool, # type: ignore [attr-defined] ), EnsureL2AdvertisementByHostStep( self.deployment, @@ -595,6 +593,7 @@ def get_plan(self) -> list[BaseStep]: self.deployment.openstack_machines_model, Networks.PUBLIC, self.deployment.public_ip_pool, # type: ignore [attr-defined] + remove_legacy=True, ), EnsureL2AdvertisementByHostStep( self.deployment, @@ -604,6 +603,10 @@ def get_plan(self) -> list[BaseStep]: Networks.STORAGE, self.deployment.storage_ip_pool, # type: ignore [attr-defined] optional_if_pool_missing=True, + remove_legacy=True, + ), + EnsureDefaultL2AdvertisementMutedStep( + self.deployment, self.client, self.jhelper ), OpenStackPatchLoadBalancerServicesIPPoolStep( self.client, diff --git a/sunbeam-python/tests/unit/sunbeam/features/test_instance_recovery_feature.py b/sunbeam-python/tests/unit/sunbeam/features/test_instance_recovery_feature.py index b256cd842..c68c4c0da 100644 --- a/sunbeam-python/tests/unit/sunbeam/features/test_instance_recovery_feature.py +++ b/sunbeam-python/tests/unit/sunbeam/features/test_instance_recovery_feature.py @@ -5,8 +5,15 @@ import pytest +from sunbeam.core.deployment import Networks from sunbeam.core.openstack import OPENSTACK_MODEL +from sunbeam.features.instance_recovery import consul from sunbeam.features.instance_recovery.feature import InstanceRecoveryFeature +from sunbeam.provider.maas.steps import MaasCreateLoadBalancerIPPoolsStep +from sunbeam.steps.k8s import ( + EnsureCiliumDeviceByHostStep, + EnsureL2AdvertisementByHostStep, +) from sunbeam.steps.openstack import ValidateInfraAppsStep @@ -32,6 +39,40 @@ def _get_tfhelper(plan: str): return deploy +@patch("sunbeam.features.instance_recovery.feature.MaasClient") +@patch("sunbeam.features.instance_recovery.feature.JujuHelper") +@patch("sunbeam.features.instance_recovery.feature.run_plan") +@patch( + "sunbeam.features.instance_recovery.feature.is_maas_deployment", return_value=True +) +def test_enable_reconciles_storage_network_before_assigning_consul_vip( + _mock_is_maas, mock_run_plan, _mock_jhelper, _mock_maas_client, deployment +): + deployment.get_tfhelper.side_effect = None + deployment.storage_ip_pool = "test-storage-ippool" + feature = InstanceRecoveryFeature() + feature._manifest = Mock() + + feature.run_enable_plans(deployment, Mock(), show_hints=False) + + pool_plan = next( + call.args[0] + for call in mock_run_plan.call_args_list + if isinstance(call.args[0][0], MaasCreateLoadBalancerIPPoolsStep) + ) + create_pool, cilium, storage_l2, assign_pool, assign_ip, *_ = pool_plan + assert isinstance(create_pool, MaasCreateLoadBalancerIPPoolsStep) + assert isinstance(cilium, EnsureCiliumDeviceByHostStep) + assert cilium.storage_pool == deployment.storage_ip_pool + assert isinstance(storage_l2, EnsureL2AdvertisementByHostStep) + assert storage_l2.network == Networks.STORAGE + assert storage_l2.pool == deployment.storage_ip_pool + assert storage_l2.optional_if_pool_missing + assert storage_l2.remove_legacy + assert isinstance(assign_pool, consul.PatchConsulStorageLoadBalancerIPPoolStep) + assert isinstance(assign_ip, consul.PatchConsulStorageLoadBalancerIPStep) + + @pytest.mark.parametrize( "db_topology, expected_extra_masakari_apps", [ diff --git a/sunbeam-python/tests/unit/sunbeam/provider/maas/test_maas.py b/sunbeam-python/tests/unit/sunbeam/provider/maas/test_maas.py index 06d5e251b..832ac50a8 100644 --- a/sunbeam-python/tests/unit/sunbeam/provider/maas/test_maas.py +++ b/sunbeam-python/tests/unit/sunbeam/provider/maas/test_maas.py @@ -1990,13 +1990,6 @@ def __init__(self, addresses): self.spec = {"addresses": addresses} -class FakeL2Advertisement: - """k8s ipaddresspool.""" - - def __init__(self, name): - self.spec = {"ipAddressPools": [name]} - - class TestMaasCreateLoadBalancerIPPoolsStep: @pytest.fixture def read_config(self, mocker): @@ -2029,6 +2022,7 @@ def read_config(self, mocker): def test_run(self, deployment_k8s, mocker, read_config, step_context): pool_name = deployment_k8s.public_api_label + deployment_k8s.public_ip_pool = pool_name ippool_from_maas = { "10.149.100.128/25": [ {"label": pool_name, "start": "10.149.100.200", "end": "10.149.100.210"} @@ -2043,14 +2037,7 @@ def test_run(self, deployment_k8s, mocker, read_config, step_context): "sunbeam.core.steps.l_client.Client", new=Mock( return_value=Mock( - get=Mock( - side_effect=[ - FakeIPPool(["10.149.100.200-10.149.100.210"]), - FakeL2Advertisement(pool_name), - FakeIPPool(["10.149.100.200-10.149.100.210"]), - FakeL2Advertisement(pool_name), - ] - ) + get=Mock(return_value=FakeIPPool(["10.149.100.200-10.149.100.210"])) ) ), ) @@ -2066,6 +2053,10 @@ def test_run(self, deployment_k8s, mocker, read_config, step_context): assert result.result_type == ResultType.COMPLETED get_ip_ranges_from_space_mock.assert_any_call(maas_client, "public_space") step.kube.create.assert_not_called() + step.kube.get.assert_called_once_with( + step.lbpool_resource, name=pool_name, namespace="metallb-system" + ) + step.kube.delete.assert_not_called() def test_run_with_missing_ipaddresspool( self, deployment_k8s, mocker, read_config, step_context @@ -2081,9 +2072,11 @@ def test_run_with_missing_ipaddresspool( maas_client = Mock() k8s_snap = Mock() mocker.patch("sunbeam.core.k8s.Snap", k8s_snap) + api_error = ApiError.__new__(ApiError) + api_error.status = Mock(code=404) mocker.patch( "sunbeam.core.steps.l_client.Client", - new=Mock(return_value=Mock(get=Mock(side_effect=[None, None, None, None]))), + new=Mock(return_value=Mock(get=Mock(side_effect=api_error))), ) k8s_snap().config.get.return_value = "k8s" @@ -2108,62 +2101,6 @@ def get_ip_ranges_side_effect(client, space): "addresses" ) == ["10.149.100.200-10.149.100.210"] - def test_run_with_missing_l2advertisement( - self, - deployment_k8s, - mocker, - read_config, - step_context, - ): - pool_name = deployment_k8s.public_api_label - ippool_from_maas = { - "10.149.100.128/25": [ - {"label": pool_name, "start": "10.149.100.200", "end": "10.149.100.210"} - ] - } - - cclient = Mock() - maas_client = Mock() - k8s_snap = Mock() - mocker.patch("sunbeam.core.k8s.Snap", k8s_snap) - api_error = ApiError.__new__(ApiError) - api_error.status = Mock(code=404) - mocker.patch( - "sunbeam.core.steps.l_client.Client", - new=Mock( - return_value=Mock( - get=Mock( - side_effect=[ - FakeIPPool(["10.149.100.200-10.149.100.210"]), - api_error, - FakeIPPool(["10.149.100.200-10.149.100.210"]), - api_error, - ] - ) - ) - ), - ) - k8s_snap().config.get.return_value = "k8s" - - def get_ip_ranges_side_effect(client, space): - if space == "public_space": - return ippool_from_maas - return {} # No storage ranges - - get_ip_ranges_from_space_mock = mocker.patch( - "sunbeam.provider.maas.client.get_ip_ranges_from_space", - side_effect=get_ip_ranges_side_effect, - ) - - step = MaasCreateLoadBalancerIPPoolsStep(deployment_k8s, cclient, maas_client) - - result = step.run(step_context) - assert result.result_type == ResultType.COMPLETED - get_ip_ranges_from_space_mock.assert_any_call(maas_client, "public_space") - # Only 2 get calls for public pool (ipaddresspool + l2advertisement) - assert step.kube.get.call_count == 2 - assert step.kube.delete.call_count == 0 - def test_run_with_different_ippool( self, deployment_k8s, mocker, read_config, step_context ): @@ -2182,14 +2119,7 @@ def test_run_with_different_ippool( "sunbeam.core.steps.l_client.Client", new=Mock( return_value=Mock( - get=Mock( - side_effect=[ - FakeIPPool(["10.149.100.120-10.149.100.130"]), - FakeL2Advertisement(pool_name), - FakeIPPool(["10.149.100.120-10.149.100.130"]), - FakeL2Advertisement(pool_name), - ] - ) + get=Mock(return_value=FakeIPPool(["10.149.100.120-10.149.100.130"])) ) ), ) diff --git a/sunbeam-python/tests/unit/sunbeam/steps/test_k8s.py b/sunbeam-python/tests/unit/sunbeam/steps/test_k8s.py index ffeeb83f7..e024749a0 100644 --- a/sunbeam-python/tests/unit/sunbeam/steps/test_k8s.py +++ b/sunbeam-python/tests/unit/sunbeam/steps/test_k8s.py @@ -11,6 +11,7 @@ import pytest import tenacity from lightkube import ApiError +from lightkube.models.meta_v1 import ManagedFieldsEntry, ObjectMeta from lightkube.types import PatchType from sunbeam.clusterd.service import ( @@ -492,12 +493,35 @@ def test_run_update_failure(self, step): api_error = ApiError.__new__(ApiError) api_error.status = Mock(code=500) step.kube.apply = Mock(side_effect=api_error) + step._legacy_to_remove = True result = step.run(None) step.kube.apply.assert_called_once() + step.kube.delete.assert_not_called() assert result.result_type == ResultType.FAILED + @pytest.mark.parametrize("outdated", [[], ["node1"]]) + def test_retires_legacy_advertisement_after_reconciling_replacements( + self, step, step_context, outdated + ): + step.remove_legacy = True + step.network = Networks.PUBLIC + step._get_outdated_resources = Mock(return_value=(outdated, [])) + step._get_interface = Mock(return_value="eth0") + + with patch("sunbeam.steps.k8s.get_kube_client", return_value=step.kube): + assert step.is_skip(step_context).result_type == ResultType.COMPLETED + assert step.run(step_context).result_type == ResultType.COMPLETED + + operations = [call[0] for call in step.kube.mock_calls] + assert operations == ( + ["get", "apply", "delete"] if outdated else ["get", "delete"] + ) + step.kube.delete.assert_called_once_with( + step.l2_advertisement_resource, "test-pool", namespace="metallb-system" + ) + def test_run_missing_machine_skips(self, step): step.to_update = [{"name": "node1", "machineid": "1"}] step.to_delete = [] @@ -525,10 +549,13 @@ def test_run_delete_failure(self, step): step.kube.delete.assert_called_once() assert result.result_type == ResultType.COMPLETED - def test_get_interface_cached(self, step): - step._ifnames = {"node1": "eth0"} - result = step._get_interface({"name": "node1"}) - assert result == "eth0" + def test_get_interface_cached(self, step, jhelper): + step.deployment.get_space.return_value = "management" + jhelper.get_machine_interfaces.return_value = {"eth0": Mock(space="management")} + node = {"name": "node1", "machineid": "1"} + assert step._get_interface(node) == "eth0" + assert step._get_interface(node) == "eth0" + jhelper.get_machine_interfaces.assert_called_once() def test_get_interface_found(self, step, jhelper, deployment): jhelper.get_machine_interfaces.return_value = { @@ -538,7 +565,6 @@ def test_get_interface_found(self, step, jhelper, deployment): deployment.get_space.return_value = "management" result = step._get_interface({"name": "node1", "machineid": "1"}) assert result == "eth0" - assert step._ifnames["node1"] == "eth0" def test_get_interface_not_found(self, step, jhelper, deployment): """Test that _get_interface raises exception when interface is not found.""" @@ -1473,6 +1499,152 @@ def test_run_no_changes(self, step, step_context): step.client.cluster.lock_terraform_plan.assert_called_once() step.client.cluster.unlock_terraform_plan.assert_called_once() + @pytest.mark.parametrize("devices", ["eth1.2743", "eth1.2743,eth1.101"]) + def test_run_reconciles_devices(self, step, step_context, devices): + step.deployment.get_space.side_effect = lambda network: network.value + machine_interfaces = { + "1": { + "eth1": Mock(space=None), + "eth1.2743": Mock(space="internal"), + "eth1.101": Mock(space="public"), + }, + "2": {"bond0.2743": Mock(space="internal public")}, + } + step.jhelper.get_machine_interfaces.side_effect = lambda model, machine_id: ( + machine_interfaces[machine_id] + ) + configs = [ + step.cilium_node_config_resource( + metadata=ObjectMeta(labels={"sunbeam/hostname": hostname}), + spec={ + "nodeSelector": {"matchLabels": {"sunbeam/hostname": hostname}}, + "defaults": {"devices": interface}, + }, + ) + for hostname, interface in (("node1", devices), ("node2", "bond0.2743")) + ] + step.kube.list.return_value = configs + step._restart_cilium_on_node = Mock() + + with patch("sunbeam.steps.k8s.get_kube_client", return_value=step.kube): + assert step.run(step_context).result_type == ResultType.COMPLETED + step.kube.apply.assert_called_once() + applied = step.kube.apply.call_args.args[0] + assert applied.spec["defaults"] == { + "devices": "eth1.2743,eth1.101", + "direct-routing-device": "eth1.2743", + } + assert step.jhelper.get_machine_interfaces.call_count == 2 + + applied.metadata.annotations["sunbeam/restart-pending"] = "false" + configs[0] = applied + assert step.run(step_context).result_type == ResultType.SKIPPED + step.kube.apply.assert_called_once() + step._restart_cilium_on_node.assert_called_once_with("node1") + + @pytest.mark.parametrize( + ("manager", "override", "expected"), + [ + ("test-deployment", "eth1", ResultType.COMPLETED), + ("another-manager", "eth1", ResultType.COMPLETED), + ("another-manager", "eth0", ResultType.SKIPPED), + ("another-manager", "eth+", ResultType.SKIPPED), + ], + ) + def test_run_reconciles_stale_direct_routing_device( + self, step, step_context, manager, override, expected + ): + step.client.cluster.list_nodes_by_role.return_value = [ + {"name": "node1", "machineid": "1"} + ] + step.jhelper.get_machine_interfaces.return_value = { + "eth0": Mock(space="internal"), + } + config = step.cilium_node_config_resource( + metadata=ObjectMeta( + labels={"sunbeam/hostname": "node1"}, + managedFields=[ + ManagedFieldsEntry( + manager=manager, + operation="Apply", + fieldsV1={ + "f:spec": {"f:defaults": {"f:direct-routing-device": {}}} + }, + ) + ], + ), + spec={ + "nodeSelector": {"matchLabels": {"sunbeam/hostname": "node1"}}, + "defaults": {"devices": "eth0", "direct-routing-device": override}, + }, + ) + step.kube.list.return_value = [config] + step._restart_cilium_on_node = Mock() + + with patch("sunbeam.steps.k8s.get_kube_client", return_value=step.kube): + assert step.run(step_context).result_type == expected + if expected == ResultType.SKIPPED: + step.kube.apply.assert_not_called() + step._restart_cilium_on_node.assert_not_called() + return + + applied = step.kube.apply.call_args.args[0] + assert applied.spec["defaults"] == { + "devices": "eth0", + "direct-routing-device": "eth0", + } + applied.metadata.annotations["sunbeam/restart-pending"] = "false" + step.kube.list.return_value = [applied] + assert step.run(step_context).result_type == ResultType.SKIPPED + + step.kube.apply.assert_called_once() + step._restart_cilium_on_node.assert_called_once_with("node1") + + @pytest.mark.parametrize( + ("pool_exists", "public_spaces", "expected_devices"), + [ + (False, "public", "eth0,eth1"), + (True, "public", "eth0,eth1,eth2"), + (True, "public storage", "eth0,eth1"), + ], + ) + def test_run_storage_devices( + self, step, step_context, pool_exists, public_spaces, expected_devices + ): + step.storage_pool = "test-storage-ippool" + step.deployment.get_space.side_effect = lambda network: network.value + step.client.cluster.list_nodes_by_role.return_value = [ + {"name": "node1", "machineid": "1"} + ] + step.jhelper.get_machine_interfaces.return_value = { + "eth0": Mock(space="internal"), + "eth1": Mock(space=public_spaces), + } + if pool_exists: + step.jhelper.get_machine_interfaces.return_value["eth2"] = Mock( + space="storage" + ) + else: + api_error = ApiError.__new__(ApiError) + api_error.status = Mock(code=404) + step.kube.get.side_effect = api_error + step.kube.list.return_value = [] + step._restart_cilium_on_node = Mock() + + with patch("sunbeam.steps.k8s.get_kube_client", return_value=step.kube): + assert step.run(step_context).result_type == ResultType.COMPLETED + + step.kube.get.assert_called_once() + assert step.kube.get.call_args.kwargs == { + "name": "test-storage-ippool", + "namespace": "metallb-system", + } + applied = step.kube.apply.call_args.args[0] + assert applied.spec["defaults"] == { + "devices": expected_devices, + "direct-routing-device": "eth0", + } + def test_run_outdated_device(self, step, step_context): step._get_outdated_resources = Mock(return_value=(["node1"], [])) step._apply_changes = Mock(return_value=Result(ResultType.COMPLETED)) @@ -1660,7 +1832,7 @@ def test_is_skip_wrong_node_selector(self, step, control_nodes, jhelper): def test_apply_changes_creates_config(self, step): step.to_update = [{"name": "node1", "machineid": "1"}] step.to_delete = [] - step._get_interface = Mock(return_value="eth0") + step._get_cilium_defaults = Mock(return_value={"devices": "eth0"}) step._resolve_k8s_node_name = Mock(return_value="node1") step.kube.apply = Mock() step.kube.patch = Mock() @@ -1710,7 +1882,9 @@ def test_apply_changes_updates_config(self, step): {"name": "node2", "machineid": "2"}, ] step.to_delete = [] - step._get_interface = Mock(side_effect=["eth0", "eth1"]) + step._get_cilium_defaults = Mock( + side_effect=[{"devices": "eth0"}, {"devices": "eth1"}] + ) step._resolve_k8s_node_name = Mock(side_effect=lambda n: n) step.kube.apply = Mock() step.kube.patch = Mock() @@ -1783,7 +1957,7 @@ def list_side_effect(*args, **kwargs): def test_apply_changes_api_error(self, step): step.to_update = [{"name": "node1", "machineid": "1"}] step.to_delete = [] - step._get_interface = Mock(return_value="eth0") + step._get_cilium_defaults = Mock(return_value={"devices": "eth0"}) api_error = ApiError.__new__(ApiError) api_error.status = Mock(code=500) step.kube.apply = Mock(side_effect=api_error) @@ -1793,19 +1967,34 @@ def test_apply_changes_api_error(self, step): assert result.result_type == ResultType.FAILED assert "Failed to apply CiliumNodeConfig for node1" in result.message - def test_apply_changes_no_interface_found(self, step): + def test_apply_changes_machine_not_found(self, step): step.to_update = [{"name": "node1", "machineid": "1"}] step.to_delete = [] - step._get_interface = Mock(side_effect=MachineNotFoundException("not found")) + step._get_cilium_defaults = Mock( + side_effect=MachineNotFoundException("not found") + ) result = step._apply_changes(None) assert result.result_type == ResultType.FAILED + def test_apply_changes_public_interface_missing(self, step): + step.to_update = [{"name": "node1", "machineid": "1"}] + step.deployment.get_space.side_effect = lambda network: network.value + step.jhelper.get_machine_interfaces.return_value = { + "eth0": Mock(space="internal"), + } + + result = step._apply_changes(None) + + assert result.result_type == ResultType.FAILED + assert result.message == "Node node1 has no interface in PUBLIC space" + step.kube.apply.assert_not_called() + def test_apply_changes_cilium_pod_not_found(self, step): step.to_update = [{"name": "node1", "machineid": "1"}] step.to_delete = [] - step._get_interface = Mock(return_value="eth0") + step._get_cilium_defaults = Mock(return_value={"devices": "eth0"}) step._resolve_k8s_node_name = Mock(return_value="node1") step.kube.apply = Mock() step.kube.list = Mock(return_value=[]) @@ -1818,7 +2007,7 @@ def test_apply_changes_cilium_pod_not_found(self, step): def test_apply_changes_restart_timeout(self, step): step.to_update = [{"name": "node1", "machineid": "1"}] step.to_delete = [] - step._get_interface = Mock(return_value="eth0") + step._get_cilium_defaults = Mock(return_value={"devices": "eth0"}) step._resolve_k8s_node_name = Mock(return_value="node1") step.kube.apply = Mock() @@ -1855,7 +2044,7 @@ def test_apply_changes_old_pod_ignored_during_readiness_wait(self, step): """The terminating pod (same name as deleted) must not satisfy readiness.""" step.to_update = [{"name": "node1", "machineid": "1"}] step.to_delete = [] - step._get_interface = Mock(return_value="eth0") + step._get_cilium_defaults = Mock(return_value={"devices": "eth0"}) step._resolve_k8s_node_name = Mock(return_value="node1") step.kube.apply = Mock() step.kube.patch = Mock() @@ -1934,7 +2123,7 @@ def test_apply_changes_fqdn_vs_short_hostname(self, step): """Full flow: sunbeam FQDN resolved to K8s short hostname for pod lookup.""" step.to_update = [{"name": "node1.maas", "machineid": "1"}] step.to_delete = [] - step._get_interface = Mock(return_value="eth0") + step._get_cilium_defaults = Mock(return_value={"devices": "eth0"}) step.kube.apply = Mock() step.kube.patch = Mock() diff --git a/sunbeam-python/tests/unit/sunbeam/steps/upgrades/test_intra_channel.py b/sunbeam-python/tests/unit/sunbeam/steps/upgrades/test_intra_channel.py index 90e48c0db..26d0096a1 100644 --- a/sunbeam-python/tests/unit/sunbeam/steps/upgrades/test_intra_channel.py +++ b/sunbeam-python/tests/unit/sunbeam/steps/upgrades/test_intra_channel.py @@ -994,13 +994,23 @@ def test_get_plan_maas_includes_lb_ip_pool_step(self, mock_is_maas): plan = coordinator.get_plan() step_types = [type(step) for step in plan] - assert EnsureCiliumDeviceByHostStep in step_types + cilium_index = step_types.index(EnsureCiliumDeviceByHostStep) + assert ( + plan.index( + mock_maas_steps_module.MaasCreateLoadBalancerIPPoolsStep.return_value + ) + < cilium_index + ) assert OpenStackPatchLoadBalancerServicesIPPoolStep in step_types assert EnsureDefaultL2AdvertisementMutedStep in step_types l2_steps = [ step for step in plan if isinstance(step, EnsureL2AdvertisementByHostStep) ] assert len(l2_steps) == 3 + mute_index = step_types.index(EnsureDefaultL2AdvertisementMutedStep) + assert all(cilium_index < plan.index(step) < mute_index for step in l2_steps) + assert not l2_steps[0].remove_legacy + assert all(step.remove_legacy for step in l2_steps[1:]) storage_l2_steps = [step for step in l2_steps if step.network.name == "STORAGE"] assert len(storage_l2_steps) == 1 assert storage_l2_steps[0].pool == "test-storage-ippool"