From 27366fd937ccee47635f4d7f99484f4c2810b885 Mon Sep 17 00:00:00 2001 From: Guillaume Boutry Date: Sat, 21 Nov 2026 09:42:34 +0100 Subject: [PATCH 1/2] feat: collect network-agent logs through machine observability Manage network agents' cos-agent relations in the machine collector Terraform plan. Keep the collector on the same MicroOVN principal for both architectures and check the deployed charm's actual endpoint before integrating it. Assisted-By: Codex (gpt-6.2-sol) Signed-off-by: Guillaume Boutry --- sunbeam-python/sunbeam/core/juju.py | 19 +++++ .../sunbeam/features/observability/feature.py | 78 +++++++++++++++++-- .../tests/unit/sunbeam/core/test_juju.py | 15 ++++ .../sunbeam/features/test_observability.py | 78 +++++++++++++++---- 4 files changed, 168 insertions(+), 22 deletions(-) diff --git a/sunbeam-python/sunbeam/core/juju.py b/sunbeam-python/sunbeam/core/juju.py index c0163c1ea..94f656475 100644 --- a/sunbeam-python/sunbeam/core/juju.py +++ b/sunbeam-python/sunbeam/core/juju.py @@ -864,6 +864,25 @@ def run_action( raise ActionFailedException(str(task)) return task.results + def get_application_endpoints( + self, applications: list[str], model: str + ) -> dict[str, set[str]]: + """Return declared endpoint names, including those with no relation.""" + with self._model(model) as juju: + try: + details = self.cli( + "show-application", + *applications, + include_controller=False, + juju=juju, + ) + except jubilant.CLIError as error: + raise JujuException(str(error)) from error + return { + name: set(info.get("endpoint-bindings", {})) + for name, info in details.items() + } + def get_application_actions(self, application: str, model: str) -> list[str]: """Return action names available for an application in a model.""" with self._model(model) as juju: diff --git a/sunbeam-python/sunbeam/features/observability/feature.py b/sunbeam-python/sunbeam/features/observability/feature.py index 4ce599c42..b00cee9e0 100644 --- a/sunbeam-python/sunbeam/features/observability/feature.py +++ b/sunbeam-python/sunbeam/features/observability/feature.py @@ -16,6 +16,7 @@ from pathlib import Path import click +from jubilant.statustypes import AppStatus from packaging.version import Version from rich.console import Console from rich.table import Table @@ -46,6 +47,7 @@ from sunbeam.core.deployment import Deployment from sunbeam.core.juju import ( ActionFailedException, + JujuException, JujuHelper, JujuStepHelper, JujuWaitException, @@ -129,10 +131,11 @@ "prometheus_remote_write", "loki_push_api", ] -OBSERVABILITY_AGNET_INTEGRATION_APPS = ["openstack-hypervisor", "microceph", "k8s"] +OBSERVABILITY_AGENT_INTEGRATION_APPS = ["openstack-hypervisor", "microceph", "k8s"] OBSERVABILITY_AGENT_APP = "opentelemetry-collector" OBSERVABILITY_AGENT_INFRA_APP = "opentelemetry-collector-infra" -MICROOVN_APP = "microovn" +MICROOVN_APPS = {"microovn", "microovn-arm64"} +NETWORK_AGENTS_CHARM = "openstack-network-agents" SUNBEAM_MACHINE_APP = "sunbeam-machine" SUNBEAM_CLUSTERD_APP = "sunbeam-clusterd" @@ -140,6 +143,67 @@ HARDWARE_OBSERVER_CHANNEL = "latest/stable" +def machine_collector_applications( + jhelper: JujuHelper, model: str, apps: dict[str, AppStatus] +) -> list[str]: + """Select applications with a machine collector cos-agent relation.""" + network_apps = sorted( + name for name, app in apps.items() if app.charm_name == NETWORK_AGENTS_CHARM + ) + log_providers = [] + if network_apps: + endpoints = jhelper.get_application_endpoints(network_apps, model) + log_providers = [ + name for name in network_apps if "cos-agent" in endpoints.get(name, set()) + ] + + # Each collector unit must share the MicroOVN principal of its network + # agents to exchange data over the container-scoped cos-agent relation. + return [ + *OBSERVABILITY_AGENT_INTEGRATION_APPS, + *sorted(MICROOVN_APPS & apps.keys()), + *log_providers, + ] + + +def refresh_machine_collector_integrations( + deployment: Deployment, jhelper: JujuHelper +) -> None: + """Pick up principals and log providers installed after observability.""" + try: + client = deployment.get_client() + config = read_config(client, OBSERVABILITY_AGENT_CONFIG_KEY) + configured = set(config.get("observability-agent-integration-apps", [])) + if not configured: + return + model = deployment.openstack_machines_model + apps = jhelper.get_model_status(model).apps + if (collector := apps.get(OBSERVABILITY_AGENT_APP)) is None: + return + integrations = machine_collector_applications(jhelper, model, apps) + related = { + relation.related_app + for relation in collector.relations.get("cos-agent", []) + } + if set(integrations) == configured and configured <= related: + return + tfhelper = deployment.get_tfhelper(OBSERVABILITY_AGENT_TFPLAN) + tfhelper.init() + tfhelper.update_tfvars_and_apply_tf( + client, + deployment.get_manifest(), + tfvar_config=OBSERVABILITY_AGENT_CONFIG_KEY, + override_tfvars={"observability-agent-integration-apps": integrations}, + tf_apply_extra_args=[ + "-target=juju_integration.observability-agent-integrations" + ], + ) + except ConfigItemNotFoundException: + return + except (JujuException, TerraformException, TerraformStateLockedException) as error: + LOG.warning("Could not refresh machine collector integrations: %s", error) + + class ProviderType(enum.Enum): EXTERNAL = 1 EMBEDDED = 2 @@ -401,14 +465,12 @@ def __init__( def run(self, context: StepContext) -> Result: """Execute configuration using terraform.""" - model_status = self.jhelper.get_model_status(self.model) - integration_apps = list(OBSERVABILITY_AGNET_INTEGRATION_APPS) - # network role is optional, only add microovn if it's deployed in the model - if MICROOVN_APP in model_status.apps: - integration_apps.append(MICROOVN_APP) + apps = self.jhelper.get_model_status(self.model).apps extra_tfvars = { "principal-application-model-uuid": self.jhelper.get_model_uuid(self.model), - "observability-agent-integration-apps": integration_apps, + "observability-agent-integration-apps": machine_collector_applications( + self.jhelper, self.model, apps + ), "observability-agent-integration-apps-juju-info": [SUNBEAM_MACHINE_APP], # Workaround for https://github.com/canonical/opentelemetry-collector-k8s-operator/issues/265 "opentelemetry-collector-config": {"tls_insecure_skip_verify": True}, diff --git a/sunbeam-python/tests/unit/sunbeam/core/test_juju.py b/sunbeam-python/tests/unit/sunbeam/core/test_juju.py index 0822e4410..c18f3ea91 100644 --- a/sunbeam-python/tests/unit/sunbeam/core/test_juju.py +++ b/sunbeam-python/tests/unit/sunbeam/core/test_juju.py @@ -642,6 +642,21 @@ def test_get_secret_not_found(jhelper, juju): jhelper.get_secret("test-model", "secret-id") +def test_get_application_endpoints_includes_unrelated_endpoints(jhelper, juju): + juju.cli.return_value = ( + '{"agent": {"endpoint-bindings": {"juju-info": "alpha", "cos-agent": "alpha"}},' + '"legacy": {"endpoint-bindings": {"juju-info": "alpha"}}}' + ) + + assert jhelper.get_application_endpoints(["agent", "legacy"], "test-model") == { + "agent": {"juju-info", "cos-agent"}, + "legacy": {"juju-info"}, + } + juju.cli.assert_called_once_with( + "show-application", "--format", "json", "agent", "legacy" + ) + + def test_get_app_config_success(jhelper, juju): test_config = {"key": "value"} juju.config.return_value = test_config diff --git a/sunbeam-python/tests/unit/sunbeam/features/test_observability.py b/sunbeam-python/tests/unit/sunbeam/features/test_observability.py index 718be9fd8..2f171b95d 100644 --- a/sunbeam-python/tests/unit/sunbeam/features/test_observability.py +++ b/sunbeam-python/tests/unit/sunbeam/features/test_observability.py @@ -402,27 +402,40 @@ def test_run( jhelper.wait_application_ready.assert_called_once() assert result.result_type == ResultType.COMPLETED - def test_run_includes_microovn_when_present( + def test_run_connects_both_microovn_architectures_and_supported_agents( self, deployment, tfhelper, jhelper, observabilityfeature, step_context ): - """Microovn is added to integration-apps when it exists in the model.""" - jhelper.get_model_status.return_value = Mock( - apps={ - "openstack-hypervisor": Mock(), - "microovn": Mock(), - } - ) - + jhelper.get_model_status.return_value.apps = { + "microovn": Mock(), + "microovn-arm64": Mock(), + "openstack-network-agents": Mock(charm_name="openstack-network-agents"), + "openstack-network-agents-arm64": Mock( + charm_name="openstack-network-agents" + ), + "legacy-agents": Mock(charm_name="openstack-network-agents"), + } + jhelper.get_application_endpoints.return_value = { + "openstack-network-agents": {"cos-agent", "juju-info"}, + "openstack-network-agents-arm64": {"cos-agent", "juju-info"}, + "legacy-agents": {"juju-info"}, + } step = observability_feature.DeployObservabilityAgentStep( deployment, Mock(), observabilityfeature, tfhelper, jhelper ) - step.run(step_context) - call_kwargs = tfhelper.update_tfvars_and_apply_tf.call_args.kwargs - integration_apps = call_kwargs["override_tfvars"][ - "observability-agent-integration-apps" + assert step.run(step_context).result_type == ResultType.COMPLETED + override = tfhelper.update_tfvars_and_apply_tf.call_args.kwargs[ + "override_tfvars" + ] + assert override["observability-agent-integration-apps"] == [ + "openstack-hypervisor", + "microceph", + "k8s", + "microovn", + "microovn-arm64", + "openstack-network-agents", + "openstack-network-agents-arm64", ] - assert "microovn" in integration_apps def test_run_excludes_microovn_when_absent( self, deployment, tfhelper, jhelper, observabilityfeature, step_context @@ -488,6 +501,43 @@ def test_run_waiting_timed_out( assert result.message == "timed out" +def test_refresh_collector_integrates_network_agents_deployed_later( + deployment, jhelper, read_config_obs +): + related = ["openstack-hypervisor", "microceph", "k8s", "microovn"] + read_config_obs.return_value = {"observability-agent-integration-apps": related} + collector = Mock( + relations={"cos-agent": [AppStatusRelation(related_app=app) for app in related]} + ) + jhelper.get_model_status.return_value.apps = { + "opentelemetry-collector": collector, + "microovn": Mock(), + "openstack-network-agents": Mock(charm_name="openstack-network-agents"), + } + jhelper.get_application_endpoints.return_value = { + "openstack-network-agents": {"cos-agent"} + } + + observability_feature.refresh_machine_collector_integrations(deployment, jhelper) + + tfhelper = deployment.get_tfhelper.return_value + tfhelper.init.assert_called_once() + tfhelper.update_tfvars_and_apply_tf.assert_called_once_with( + deployment.get_client(), + deployment.get_manifest(), + tfvar_config=observability_feature.OBSERVABILITY_AGENT_CONFIG_KEY, + override_tfvars={ + "observability-agent-integration-apps": [ + *related, + "openstack-network-agents", + ] + }, + tf_apply_extra_args=[ + "-target=juju_integration.observability-agent-integrations" + ], + ) + + class TestRemoveObservabilityAgentStep: def test_run( self, From 3aa4c8a9f236a0704ae9feab7297263ff7a390e2 Mon Sep 17 00:00:00 2001 From: Guillaume Boutry Date: Thu, 19 Nov 2026 23:48:09 +0100 Subject: [PATCH 2/2] feat: enable Neutron dynamic routing in Sunbeam Resolve and validate placement with the published NDR contract. Manage protected agents on MicroOVN network nodes, preserve router ID reservations, and require a drain before changing an attachment. Use the deployment region with shared Keystone and verify the Neutron BGP API before applying placements. Initialize Terraform before reading the offer and applying AMQP relations. Wait for broker credentials before configuring units. Recover confirmed placement after a failed action and honor updates from the cluster manifest. Refresh the machine collector integrations when network agents were deployed after observability. Assisted-By: Codex (gpt-6.2-sol) Signed-off-by: Guillaume Boutry --- cloud/etc/deploy-microovn/main.tf | 17 + cloud/etc/deploy-microovn/variables.tf | 12 + sunbeam-python/pyproject.toml | 3 +- sunbeam-python/sunbeam/core/openstack_api.py | 7 +- .../features/dynamic_routing/README.md | 102 ++ .../features/dynamic_routing/__init__.py | 4 + .../features/dynamic_routing/feature.py | 1011 +++++++++++++++++ .../sunbeam/provider/local/commands.py | 4 +- .../sunbeam/provider/maas/commands.py | 4 +- .../sunbeam/features/test_dynamic_routing.py | 984 ++++++++++++++++ .../sunbeam/provider/local/test_commands.py | 32 + .../unit/sunbeam/provider/maas/test_maas.py | 29 + sunbeam-python/uv.lock | 11 + 13 files changed, 2216 insertions(+), 4 deletions(-) create mode 100644 sunbeam-python/sunbeam/features/dynamic_routing/README.md create mode 100644 sunbeam-python/sunbeam/features/dynamic_routing/__init__.py create mode 100644 sunbeam-python/sunbeam/features/dynamic_routing/feature.py create mode 100644 sunbeam-python/tests/unit/sunbeam/features/test_dynamic_routing.py diff --git a/cloud/etc/deploy-microovn/main.tf b/cloud/etc/deploy-microovn/main.tf index ea10e7350..abbf7be58 100644 --- a/cloud/etc/deploy-microovn/main.tf +++ b/cloud/etc/deploy-microovn/main.tf @@ -67,6 +67,23 @@ resource "juju_application" "openstack-network-agents-arm64" { endpoint_bindings = var.openstack_network_agents_endpoint_bindings } +resource "juju_integration" "amqp" { + # Sunbeam resolves the installed applications before configuring NDR. + # Keep this relation independent so a targeted apply preserves local charms. + for_each = var.ndr_rabbitmq_offer_url == null ? toset([]) : toset(var.ndr_applications) + + model_uuid = data.juju_model.machine_model.uuid + + application { + name = each.key + endpoint = "amqp" + } + + application { + offer_url = var.ndr_rabbitmq_offer_url + } +} + resource "juju_application" "microcluster-token-distributor" { name = "microcluster-token-distributor" model_uuid = data.juju_model.machine_model.uuid diff --git a/cloud/etc/deploy-microovn/variables.tf b/cloud/etc/deploy-microovn/variables.tf index ad35200a6..16ebb8551 100644 --- a/cloud/etc/deploy-microovn/variables.tf +++ b/cloud/etc/deploy-microovn/variables.tf @@ -136,3 +136,15 @@ variable "ca-offer-url" { type = string default = null } + +variable "ndr_rabbitmq_offer_url" { + description = "Control-plane RabbitMQ offer for Neutron dynamic routing agents" + type = string + default = null +} + +variable "ndr_applications" { + description = "Network-agents applications with Neutron dynamic routing enabled" + type = list(string) + default = [] +} diff --git a/sunbeam-python/pyproject.toml b/sunbeam-python/pyproject.toml index 6f19325a3..9ae39c820 100644 --- a/sunbeam-python/pyproject.toml +++ b/sunbeam-python/pyproject.toml @@ -48,6 +48,7 @@ dependencies = [ "tenacity", "jubilant>=1.3.0", "packaging>=23.2", + "sunbeam-ndr-contract==2027.1.0.dev0", ] [project.optional-dependencies] @@ -127,7 +128,7 @@ install = "sunbeam.hooks:install" post-refresh = "sunbeam.hooks:upgrade" [tool.setuptools] -packages = ["sunbeam"] +packages = ["sunbeam", "sunbeam.features.dynamic_routing"] [tool.setuptools.package-data] sunbeam = ["features/*/etc/*/*.tf", "features/*/etc/*/modules/*/*.tf"] diff --git a/sunbeam-python/sunbeam/core/openstack_api.py b/sunbeam-python/sunbeam/core/openstack_api.py index 6bc5a78cc..16a8bcd22 100644 --- a/sunbeam-python/sunbeam/core/openstack_api.py +++ b/sunbeam-python/sunbeam/core/openstack_api.py @@ -19,14 +19,18 @@ def get_admin_connection( - jhelper: JujuHelper, deployment: Deployment + jhelper: JujuHelper, deployment: Deployment, *, region_name: str | None = None ) -> "openstack.connection.Connection": """Return a connection to keystone using admin credentials. :param jhelper: Juju helpers for retrieving admin credentials + :param region_name: Region to select from the service catalog :raises: openstack.exceptions.SDKException """ admin_auth_info = retrieve_admin_credentials(jhelper, deployment, OPENSTACK_MODEL) + options: dict[str, typing.Any] = {} + if region_name is not None: + options["region_name"] = region_name conn = openstack.connect( auth_url=admin_auth_info.get("OS_AUTH_URL"), username=admin_auth_info.get("OS_USERNAME"), @@ -35,6 +39,7 @@ def get_admin_connection( user_domain_name=admin_auth_info.get("OS_USER_DOMAIN_NAME"), project_domain_name=admin_auth_info.get("OS_PROJECT_DOMAIN_NAME"), cacert=admin_auth_info.get("OS_CACERT"), + **options, ) return conn diff --git a/sunbeam-python/sunbeam/features/dynamic_routing/README.md b/sunbeam-python/sunbeam/features/dynamic_routing/README.md new file mode 100644 index 000000000..c6ddcd734 --- /dev/null +++ b/sunbeam-python/sunbeam/features/dynamic_routing/README.md @@ -0,0 +1,102 @@ +# Neutron dynamic routing + +The feature runs one idle DR agent per routing domain on each selected +MicroOVN network node. It requires NDR-enabled revisions +of the `neutron-k8s` and `openstack-network-agents` charms, the agent snap, +and a Neutron rock built from published NDR packages containing the +required route-event fixes. The nodes must already be joined to the +Sunbeam deployment and have the +`network` role. Neutron must use MicroOVN through the `sunbeam-ovn-proxy` +`ovsdb-cms` relation. + +```yaml +features: + dynamic-routing: + config: + routing-domains: + red: + peering: + provider-trunk: + physnet: physnet1 + vlan: 120 + nodes: + net-01: {address: 192.0.2.3/28} + net-02: {address: 192.0.2.4/28} + blue: + address-families: [ipv6] + peering: + dedicated-uplink: + nodes: + net-01: {interface: enp5s0.122} + net-02: {interface: enp5s0.122} +``` + +Each domain accepts exactly one address family. Omitting `address-families` +selects IPv4. IPv4 and IPv6 domains can share the same network nodes. +Each attachment requires an explicit non-empty node map. For a provider +trunk, allow the specified VLAN on the fabric trunk and provide a static +CIDR for each node. For a dedicated uplink, provision the interface and +addressing before enablement. In Manual mode, give the interface name. In +MAAS, tag exactly one interface on each selected machine with +`ndr:` and omit the interface name. Specify a bare `address` when +the interface has more than one usable source in the chosen family. +Sunbeam validates the hosts and the Neutron schema before enabling NDR. + +NDR is off by default. To opt in, run enable with your full deployment +manifest. + +```bash +sunbeam enable --manifest deployment.yaml dynamic-routing +openstack bgp dragent list +``` + +Use each agent's unique host value, such as `net-01.red.v4`, to identify +its UUID. Set the fabric VRF and create and bind the peers and speaker +with `openstack bgp`. The NDR agent initiates the BGP connection. Configure +the fabric peer to accept connections to TCP port 179 from the agent's +peering address. For subnet-only export, use +`--no-advertise-floating-ip-host-routes`. An IPv4 speaker can export both +subnets and centralized floating IPs. + +Reapply the manifest after changing placement or joining a candidate node. +Sunbeam reports bound agents before removal. Unbind them first, or use the +feature's `--force` option to stop the agents while retaining their Neutron +bindings. Re-adding an identity can reactivate an existing binding. Coordinate +placement updates with OpenStack operators so bindings do not change during the +removal check and apply. Manual and MAAS node removal require the node +to be drained from NDR placement first, even when removing with `--force`. +Drain the node while its charm unit is still available. + +Run `sunbeam disable dynamic-routing` to stop all managed +instances and disable the plugin. The host watcher remains available to +process committed snap settings when NDR is enabled again. + +To change a domain's family or an agent's peering attachment or address, +unbind and remove the affected placement first. Reapply the manifest to +drain it, then add the new placement and bind the agents. An empty +`routing-domains: {}` map drains the last domain. Omitting the entire map +reuses saved placement. + +Drain legacy prototype domains explicitly after refreshing the charm and +snap. The old flat `nodes` schema cannot select host attachments. Bind any +replacement agent that registers under a new UUID. + +If a saved provider-trunk attachment can no longer be resolved, for example +because its physnet mapping disappeared, the snap stops the NDR agents on +that unit and retains the existing firewall protection. Restore the mapping +so the watcher can validate the placement and resume the agents. + +Sunbeam assigns router IDs from `router-id-pool`, which defaults to +`198.18.0.0/15`, and retains its reservations across drain and re-enable +with the same pool. Omit the option to keep the saved pool. Disable NDR +before switching pools. + +Sunbeam retrieves admin credentials from the deployment's Keystone and +uses the deployment's region to select the Neutron endpoint. IPv4 and +IPv6 each need their own Neutron BGP speaker and agent binding. IPv6 uses +a numbered IPv6 peer and next hop in the qualified topology. The BGP +router ID remains a 32-bit identifier. +The first rollout uses plain RabbitMQ transport. Release qualification includes +route freshness during RPC loss and forwarding through the selected fabric VRFs. +On IPv6 fabrics with multicast snooping, verify neighbor resolution after +cache expiry as part of release qualification. diff --git a/sunbeam-python/sunbeam/features/dynamic_routing/__init__.py b/sunbeam-python/sunbeam/features/dynamic_routing/__init__.py new file mode 100644 index 000000000..366ab203f --- /dev/null +++ b/sunbeam-python/sunbeam/features/dynamic_routing/__init__.py @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: 2026 - Canonical Ltd +# SPDX-License-Identifier: Apache-2.0 + +"""Neutron dynamic routing feature.""" diff --git a/sunbeam-python/sunbeam/features/dynamic_routing/feature.py b/sunbeam-python/sunbeam/features/dynamic_routing/feature.py new file mode 100644 index 000000000..af3af1914 --- /dev/null +++ b/sunbeam-python/sunbeam/features/dynamic_routing/feature.py @@ -0,0 +1,1011 @@ +# SPDX-FileCopyrightText: 2026 - Canonical Ltd +# SPDX-License-Identifier: Apache-2.0 + +"""Manage Neutron dynamic routing agents on MicroOVN network nodes.""" + +import hashlib +import ipaddress +import json +import re +import socket +import uuid +from collections.abc import Iterator +from contextlib import contextmanager +from datetime import UTC, datetime +from typing import Annotated, Literal, NotRequired, TypedDict + +import click +from openstack.exceptions import HttpException, SDKException +from packaging.version import Version +from pydantic import ( + Field, + IPvAnyAddress, + IPvAnyInterface, + StringConstraints, + ValidationError, + field_validator, + model_validator, +) +from rich.console import Console +from sunbeam_ndr_contract import CONTRACT_VERSION, parse_instances +from tenacity import Retrying, retry_if_exception, stop_after_delay, wait_fixed + +from sunbeam.clusterd.client import Client +from sunbeam.clusterd.service import TerraformPlanLockConflictException +from sunbeam.core.checks import JujuLoginCheck, run_preflight_checks +from sunbeam.core.deployment import Deployment +from sunbeam.core.juju import ActionFailedException, JujuHelper +from sunbeam.core.manifest import FeatureConfig, ManifestModel +from sunbeam.core.openstack import OPENSTACK_MODEL +from sunbeam.core.openstack_api import get_admin_connection +from sunbeam.core.ovn import microovn_application_name_for_node +from sunbeam.features.interface.v1.base import EnableDisableFeature, FeatureError +from sunbeam.features.interface.v1.openstack import OPENSTACK_TERRAFORM_VARS +from sunbeam.features.observability.feature import ( + refresh_machine_collector_integrations, +) +from sunbeam.provider.maas.client import MaasClient, is_maas_deployment, list_machines +from sunbeam.steps.microovn import AGENT_APP, CONFIG_KEY +from sunbeam.utils import pass_method_obj + +ACTION = "set-dynamic-routing-instances" +VALIDATE_ACTION = "validate-dynamic-routing-instances" +AGENT_TYPE = "BGP dynamic routing agent" +NEUTRON_OPTION = "enable-dynamic-routing" +PLACEMENT_LOCK = "dynamic-routing-placement" +FORCE_HELP = "Stop agents even if BGP speakers are still bound. Retain their bindings." +ROUTER_ID_POOL = ipaddress.IPv4Network("198.18.0.0/15") +console = Console() + +DomainName = Annotated[ + str, StringConstraints(pattern=r"^[a-z0-9]+(?:-[a-z0-9]+)*$", max_length=50) +] +NodeName = Annotated[str, StringConstraints(min_length=1)] +InterfaceName = Annotated[ + str, StringConstraints(pattern=r"^[A-Za-z0-9_.-]+$", min_length=1, max_length=15) +] +AddressFamily = Literal["ipv4", "ipv6"] +Instance = TypedDict( + "Instance", + { + "domain": str, + "family": AddressFamily, + "service-name": str, + "host": str, + "router-id": NotRequired[str], + "peering": NotRequired[dict[str, dict[str, str | int]]], + }, +) +Instances = dict[str, list[Instance]] +MULTICAST_V4 = ipaddress.IPv4Network("224.0.0.0/4") + + +class ProviderTrunkNode(ManifestModel): + """Static peering address on a managed OVS port.""" + + address: IPvAnyInterface + + @field_validator("address", mode="before") + @classmethod + def require_prefix_length(cls, value: object) -> object: + """Require the operator to set a prefix length explicitly.""" + if not isinstance(value, str) or "/" not in value: + raise ValueError("provider-trunk address must include a prefix length") + return value + + +class DedicatedUplinkNode(ManifestModel): + """An existing peering interface and optional source address.""" + + interface: InterfaceName | None = None + address: IPvAnyAddress | None = None + + +class ProviderTrunk(ManifestModel): + """A provider VLAN with a static peering address per node.""" + + physnet: Annotated[ + str, StringConstraints(pattern=r"^[A-Za-z0-9_.-]+$", min_length=1) + ] + vlan: int = Field(ge=1, le=4094, strict=True) + nodes: dict[NodeName, ProviderTrunkNode] = Field(min_length=1) + + +class DedicatedUplink(ManifestModel): + """An existing peering attachment on each selected node.""" + + nodes: dict[NodeName, DedicatedUplinkNode] = Field(min_length=1) + + +class Peering(ManifestModel): + """One attachment type for the routing domain.""" + + provider_trunk: ProviderTrunk | None = Field(None, alias="provider-trunk") + dedicated_uplink: DedicatedUplink | None = Field(None, alias="dedicated-uplink") + + @model_validator(mode="after") + def validate_attachment(self) -> "Peering": + """Require one, and only one, attachment.""" + if (self.provider_trunk is None) == (self.dedicated_uplink is None): + raise ValueError("peering requires exactly one attachment") + return self + + +class RoutingDomain(ManifestModel): + """Placement settings for an operator-managed routing domain.""" + + address_families: list[AddressFamily] = Field( + default=["ipv4"], alias="address-families", min_length=1, max_length=1 + ) + peering: Peering + + @model_validator(mode="after") + def validate_address_family(self) -> "RoutingDomain": + """Validate declared addresses against the domain family.""" + attachment = self.peering.provider_trunk or self.peering.dedicated_uplink + if attachment: + for node, settings in attachment.nodes.items(): + address = settings.address + if address is None: + continue + ip = ( + address.ip + if isinstance( + address, (ipaddress.IPv4Interface, ipaddress.IPv6Interface) + ) + else address + ) + if f"ipv{ip.version}" != self.address_families[0]: + raise ValueError( + f"{node}: peering address must match the domain family" + ) + if ( + ip.is_unspecified + or ip.is_multicast + or ip.is_loopback + or "%" in str(address) + ): + raise ValueError( + f"{node}: peering address must be an unscoped unicast IP" + ) + return self + + +class DynamicRoutingConfig(FeatureConfig): + """Desired routing domains. An omitted map reuses the applied configuration.""" + + routing_domains: dict[DomainName, RoutingDomain] | None = Field( + None, alias="routing-domains" + ) + router_id_pool: ipaddress.IPv4Network | None = Field(None, alias="router-id-pool") + + +def resolve_domains( + config: DynamicRoutingConfig, state: dict +) -> dict[str, RoutingDomain]: + """Use an explicit manifest or load the previously saved placement.""" + domains = config.routing_domains + if domains is None: + try: + domains = DynamicRoutingConfig.model_validate( + {"routing-domains": state.get("routing-domains", {})} + ).routing_domains + except ValidationError as error: + raise FeatureError( + "The saved dynamic routing placement is invalid. " + "Drain legacy domains with an explicit routing-domains map " + "before adding them back with peering attachments." + ) from error + if not domains and not state: + raise FeatureError("Declare at least one routing domain in the manifest.") + return domains or {} + + +def agent_instance(domain: str, family: AddressFamily, node: str) -> Instance: + """Generate stable per-family agent settings on a network node.""" + version = f"v{family[-1]}" + service = f"agent-{domain}-{version}" + host = f"{node.lower()}.{domain}.{version}" + if len(host) > 255 or not re.fullmatch(r"[a-z0-9.-]+", host): + raise FeatureError(f"Invalid NDR agent host {host!r}.") + + return { + "domain": domain, + "family": family, + "service-name": service, + "host": host, + } + + +def resolve_instances( + domains: dict[str, RoutingDomain], + nodes: list[dict], + maas_interfaces: dict[str, list[dict]] | None = None, +) -> Instances: + """Expand domains using registered Sunbeam network node names.""" + inventory = {node["name"]: node for node in nodes} + network_nodes = { + node["name"] + for node in nodes + if "network" in node.get("role", []) + and node.get("machineid") not in (None, -1, "-1", "") + } + instances: Instances = {} + identities: set[str] = set() + trunk_sources: set[tuple[str, int, str]] = set() + + for domain, config in sorted(domains.items()): + trunk = config.peering.provider_trunk + uplink = config.peering.dedicated_uplink + placement = trunk.nodes if trunk else uplink.nodes if uplink else {} + eligible = ", ".join(sorted(network_nodes)) or "none" + family = config.address_families[0] + for node in sorted(placement): + if node not in network_nodes: + if node not in inventory: + reason = "is not registered in this deployment" + elif "network" not in inventory[node].get("role", []): + reason = "does not have the network role" + else: + reason = "does not have a deployed Juju machine" + raise FeatureError( + f"Routing domain {domain!r}: {node!r} {reason}. " + f"Eligible node names: {eligible}." + ) + instance = agent_instance(domain, family, node) + host = instance["host"] + if host in identities: + raise FeatureError(f"Duplicate NDR agent host {host!r}.") + identities.add(host) + if trunk: + address = trunk.nodes[node].address + source = (trunk.physnet, trunk.vlan, str(address.ip)) + if source in trunk_sources: + raise FeatureError( + f"Routing domain {domain!r} on {node!r}: duplicate peering " + f"address {address.ip} on {trunk.physnet} VLAN {trunk.vlan}." + ) + trunk_sources.add(source) + instance["peering"] = { + "provider-trunk": { + "physnet": trunk.physnet, + "vlan": trunk.vlan, + "address": str(address), + } + } + elif uplink: + settings = uplink.nodes[node] + interface = settings.interface + if maas_interfaces is not None: + tag = f"ndr:{domain}" + matches = [ + nic["name"] + for nic in maas_interfaces.get(node, []) + if tag in nic["tags"] + ] + if len(matches) != 1 or (interface and interface != matches[0]): + raise FeatureError( + f"Routing domain {domain!r} on {node!r} requires exactly " + f"one MAAS interface matching {tag!r} and the declared " + "name if present." + ) + interface = matches[0] + if not interface: + raise FeatureError( + f"Routing domain {domain!r} on {node!r} requires an explicit " + "dedicated-uplink interface in Manual mode." + ) + peering: dict[str, str | int] = {"interface": interface} + if settings.address is not None: + peering["address"] = str(settings.address) + instance["peering"] = {"dedicated-uplink": peering} + instances.setdefault(node, []).append(instance) + + return instances + + +def reserve_router_ids( + requested_pool: ipaddress.IPv4Network | None, + state: dict, + current: Instances, + desired: Instances, +) -> dict: + """Reuse persisted IDs and reserve free IDs before starting agents.""" + try: + saved_pool = ipaddress.IPv4Network(state.get("router-id-pool", ROUTER_ID_POOL)) + except (TypeError, ValueError) as error: + raise FeatureError("The saved NDR router ID pool is invalid.") from error + pool = requested_pool if requested_pool is not None else saved_pool + if pool != saved_pool and state.get("enabled") == "true": + raise FeatureError( + "Disable dynamic routing before changing the router ID pool." + ) + if pool.num_addresses < 4 or pool.overlaps(MULTICAST_V4): + raise FeatureError("The NDR router ID pool must contain usable IPv4 addresses.") + + # Seed older placements with their existing IDs and keep all reservations + # in the current pool, including for drained agents that can return. + saved = state.get("router-ids", {}) if pool == saved_pool else {} + if not isinstance(saved, dict): + raise FeatureError("The saved NDR router ID allocations are invalid.") + reservations = dict(saved) + for placements in current.values(): + for instance in placements: + host, saved_address = instance["host"], instance.get("router-id") + if saved_address is None: + raise FeatureError(f"Missing saved NDR router ID for {host!r}.") + if reservations.setdefault(host, saved_address) != saved_address: + raise FeatureError( + f"Conflicting saved router IDs for NDR agent {host!r}." + ) + used: set[ipaddress.IPv4Address] = set() + first, last = pool.network_address, pool.broadcast_address + for host, value in reservations.items(): + try: + address = ipaddress.IPv4Address(value) + except (TypeError, ValueError) as error: + raise FeatureError(f"Invalid saved NDR router ID for {host!r}.") from error + if not isinstance(value, str) or not first < address < last or address in used: + raise FeatureError( + f"Invalid or conflicting saved NDR router ID for {host!r}." + ) + used.add(address) + + for placements in desired.values(): + for instance in placements: + host = instance["host"] + if host not in reservations: + address = next_router_id(host, pool, used) + reservations[host] = str(address) + used.add(address) + instance["router-id"] = reservations[host] + return {"router-id-pool": str(pool), "router-ids": reservations} + + +def next_router_id( + host: str, pool: ipaddress.IPv4Network, used: set[ipaddress.IPv4Address] +) -> ipaddress.IPv4Address: + """Find the first free router ID from the host's stable hash position.""" + count = pool.num_addresses - 2 + digest = hashlib.sha256(host.encode()).digest() + candidate = int.from_bytes(digest[:4], "big") % count + for step in range(min(count, len(used) + 1)): + address = pool.network_address + 1 + (candidate + step) % count + if address not in used: + return address + raise FeatureError(f"The NDR router ID pool {pool} is exhausted.") + + +def check_family_changes(domains: dict[str, RoutingDomain], current: Instances) -> None: + """Require old agent placements to be removed before changing their family.""" + for instances in current.values(): + for instance in instances: + name = instance["domain"] + domain = domains.get(name) + if domain and instance["family"] != domain.address_families[0]: + raise FeatureError( + f"Routing domain {name!r} still has {instance['family']} agents. " + "To drain it, remove the domain from the manifest and apply it " + "before adding the domain with the new address family." + ) + + +def check_peering_changes( + current: Instances, desired: Instances, *, resolved: bool = False +) -> None: + """Require a drain before changing a running unit's peering attachment.""" + desired_attachments = { + instance["domain"]: domain_attachment(instance) + for instances in desired.values() + for instance in instances + } + for node, instances in current.items(): + for instance in instances: + domain = instance["domain"] + if ( + domain in desired_attachments + and domain_attachment(instance) != desired_attachments[domain] + ): + raise FeatureError( + f"NDR agent {instance['host']!r} has a different or legacy " + "peering attachment. Drain its domain before replacing it." + ) + previous = {instance["host"]: instance.get("peering") for instance in instances} + for instance in desired.get(node, []): + host = instance["host"] + if host not in previous: + continue + current_peering = previous[host] + desired_peering = instance["peering"] + uplink = desired_peering.get("dedicated-uplink") + if not resolved and uplink is not None and "address" not in uplink: + current_uplink = (current_peering or {}).get("dedicated-uplink", {}) + current_peering = { + "dedicated-uplink": { + key: value + for key, value in current_uplink.items() + if key != "address" + } + } + if current_peering != desired_peering: + raise FeatureError( + f"NDR agent {host!r} has a different or legacy peering attachment. " + "Drain it before applying the new attachment." + ) + + +def domain_attachment(instance: Instance) -> tuple[str | int, ...]: + """Compare settings shared across all nodes of one routing domain.""" + peering = instance.get("peering", {}) + if trunk := peering.get("provider-trunk"): + return ("provider-trunk", trunk["physnet"], trunk["vlan"]) + if "dedicated-uplink" in peering: + return ("dedicated-uplink",) + return () + + +def instance_action_params(instances: list[Instance]) -> dict[str, int | str]: + """Validate and render a complete per-unit Juju placement.""" + try: + parse_instances(instances) + except (TypeError, ValueError) as error: + raise FeatureError(f"Invalid NDR placement: {error}") from error + return {"contract-version": CONTRACT_VERSION, "instances": json.dumps(instances)} + + +def validate_unit_placements( + jhelper: JujuHelper, model: str, units: dict[str, str], desired: Instances +) -> None: + """Run read-only host validation and accept only expected normalization.""" + for node, unit in units.items(): + instances = desired.get(node, []) + try: + result = jhelper.run_action( + unit, model, VALIDATE_ACTION, instance_action_params(instances) + ) + except (ActionFailedException, FeatureError) as error: + raise FeatureError( + f"NDR peering preflight failed on {unit}: {error}" + ) from error + try: + normalized = json.loads(result["instances"]) + if ( + str(result["contract-version"]) != str(CONTRACT_VERSION) + or not isinstance(normalized, list) + or len(normalized) != len(instances) + ): + raise ValueError + parse_instances(normalized) + by_host = {instance["host"]: instance for instance in normalized} + for instance in instances: + candidate = by_host[instance["host"]] + expected = instance + uplink = instance["peering"].get("dedicated-uplink") + if uplink is not None and "address" not in uplink: + selected = candidate["peering"]["dedicated-uplink"].get("address") + if not isinstance(selected, str) or "%" in selected: + raise ValueError + ip = ipaddress.ip_address(selected) + expected = { + **instance, + "peering": {"dedicated-uplink": {**uplink, "address": str(ip)}}, + } + if candidate != expected: + raise ValueError + except (AttributeError, KeyError, TypeError, ValueError) as error: + raise FeatureError( + f"{unit} returned an invalid NDR preflight result." + ) from error + if instances: + desired[node] = normalized + + +def check_microovn(jhelper: JujuHelper) -> None: + """Require Neutron's deployed OVN control plane to use the MicroOVN proxy.""" + neutron = jhelper.get_model_status(OPENSTACK_MODEL).apps.get("neutron") + ovsdb_relations = neutron.relations.get("ovsdb-cms", []) if neutron else [] + if not any(rel.related_app == "sunbeam-ovn-proxy" for rel in ovsdb_relations): + raise FeatureError( + "Dynamic routing requires MicroOVN. " + "Neutron must be related to sunbeam-ovn-proxy through ovsdb-cms." + ) + + +def resolve_units( + jhelper: JujuHelper, + model: str, + nodes: list[dict], + desired: Instances, + current: Instances, +) -> dict[str, str]: + """Resolve every affected node before applying any changes.""" + inventory = {node["name"]: node for node in nodes} + status = jhelper.get_model_status(model) + units: dict[str, str] = {} + checked_apps: set[str] = set() + for name in sorted(desired.keys() | current.keys()): + node = inventory.get(name) + if node is None: + raise FeatureError(f"Previously configured NDR node {name!r} is missing.") + principal = microovn_application_name_for_node(node) + agent_app = AGENT_APP + principal.removeprefix("microovn") + app_status = status.apps.get(principal) + machine_id = str(node.get("machineid")) + matches = [ + subordinate + for unit in (app_status.units.values() if app_status else []) + if unit.machine == machine_id + for subordinate in (unit.subordinates or {}) + if subordinate.startswith(f"{agent_app}/") + ] + if len(matches) != 1 or matches[0] in units.values(): + raise FeatureError( + f"Node {name!r} must have exactly one distinct {agent_app} " + "subordinate on its MicroOVN unit." + ) + if agent_app not in checked_apps: + actions = jhelper.get_application_actions(agent_app, model) + for required in (ACTION, VALIDATE_ACTION): + if required not in actions: + raise FeatureError( + f"{agent_app} does not provide the {required} action." + ) + checked_apps.add(agent_app) + units[name] = matches[0] + return units + + +class DynamicRoutingFeature(EnableDisableFeature[DynamicRoutingConfig]): + """Configure the Neutron dynamic routing workload.""" + + name = "dynamic-routing" + version = Version("0.0.1") + + def config_type(self) -> type[DynamicRoutingConfig]: + """Return the manifest configuration model.""" + return DynamicRoutingConfig + + @click.command() + @click.option("--force", is_flag=True, help=FORCE_HELP) + @pass_method_obj + def enable_cmd(self, deployment: Deployment, force: bool) -> None: + """Enable dynamic routing or reconcile an updated placement.""" + context = click.get_current_context() + manifest_path = ( + context.parent.params.get("manifest") if context.parent else None + ) + manifest = deployment.get_manifest(manifest_path) + feature = manifest.get_feature(self.name) + config = feature.config if feature else None + if not isinstance(config, DynamicRoutingConfig): + config = DynamicRoutingConfig.model_validate({}) + self.apply_placement(deployment, config, force=force) + + @click.command() + @click.option("--force", is_flag=True, help=FORCE_HELP) + @pass_method_obj + def disable_cmd(self, deployment: Deployment, force: bool) -> None: + """Stop the agents and disable the Neutron plugin.""" + self.apply_placement( + deployment, + DynamicRoutingConfig.model_validate({}), + force=force, + enabled=False, + ) + + def run_enable_plans( + self, deployment: Deployment, config: DynamicRoutingConfig, show_hints: bool + ) -> None: + """Apply the requested placement.""" + self.apply_placement(deployment, config) + + def run_disable_plans(self, deployment: Deployment, show_hints: bool) -> None: + """Stop the agents and disable the server plugin.""" + self.apply_placement( + deployment, DynamicRoutingConfig.model_validate({}), enabled=False + ) + + def agent_bindings( + self, deployment: Deployment, keystone_helper: JujuHelper, hosts: set[str] + ) -> list[str]: + """Get current speaker bindings without modifying any Neutron object.""" + if not hosts: + return [] + # A charm config change can briefly make the API unavailable while + # Juju still reports Neutron active. + retry = Retrying( + retry=retry_if_exception( + lambda error: ( + isinstance(error, HttpException) and error.status_code == 503 + ) + ), + stop=stop_after_delay(120), + wait=wait_fixed(5), + reraise=True, + ) + try: + with get_admin_connection( + keystone_helper, deployment, region_name=deployment.get_region_name() + ) as connection: + network = connection.network + return retry( + lambda: [ + f"Agent {agent.host} ({agent.id}) hosts speaker " + f"{speaker.name} ({speaker.id})." + for agent in network.agents(agent_type=AGENT_TYPE) + if agent.host in hosts + for speaker in network.get_bgp_speakers_hosted_by_dragent(agent) + ] + ) + except SDKException as error: + raise FeatureError("Unable to check Neutron speaker bindings.") from error + + def apply_placement( + self, + deployment: Deployment, + config: DynamicRoutingConfig, + *, + force: bool = False, + enabled: bool = True, + ) -> None: + """Serialize placement changes across the deployment's admin nodes.""" + client = deployment.get_client() + with self._placement_lock(client): + self._apply_placement(deployment, client, config, force, enabled) + + @contextmanager + def node_removal_guard(self, client: Client, node: str) -> Iterator[None]: + """Require an empty NDR placement and prevent re-placement during removal.""" + with self._placement_lock(client): + if self.get_feature_info(client).get("instances", {}).get(node): + raise click.ClickException( + f"Drain dynamic routing placement for {node!r} before removing it. " + "Remove the node from the routing domains in the deployment " + "manifest and reapply dynamic routing while its unit is reachable." + ) + yield + + @contextmanager + def _placement_lock(self, client: Client) -> Iterator[None]: + """Serialize changes to NDR placement and the nodes it can use.""" + lock = { + "ID": str(uuid.uuid4()), + "Operation": "Dynamic routing placement", + "Who": socket.gethostname(), + "Created": datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%S.%f001Z"), + } + try: + client.cluster.lock_terraform_plan(PLACEMENT_LOCK, lock) + except TerraformPlanLockConflictException as error: + raise FeatureError( + "Another dynamic routing placement change is in progress." + ) from error + try: + yield + finally: + client.cluster.unlock_terraform_plan(PLACEMENT_LOCK, lock) + + def _apply_placement( + self, + deployment: Deployment, + client: Client, + config: DynamicRoutingConfig, + force: bool, + enabled: bool, + ) -> None: + """Validate and apply a full placement under the deployment lock.""" + state = self.get_feature_info(client) + if not enabled and state.get("enabled") != "true": + return + domains = resolve_domains(config, state) if enabled else {} + current: Instances = state.get("instances", {}) + check_family_changes(domains, current) + run_preflight_checks([JujuLoginCheck(deployment.juju_account)], console) + jhelper = JujuHelper(deployment.juju_controller) + keystone_helper = deployment.get_juju_helper(keystone=True) + if enabled: + check_microovn(jhelper) + nodes = client.cluster.list_nodes() + maas_interfaces = None + uplink_nodes = { + node + for domain in domains.values() + if (uplink := domain.peering.dedicated_uplink) is not None + for node in uplink.nodes + } + if uplink_nodes and is_maas_deployment(deployment): + maas = MaasClient.from_deployment(deployment) + maas_interfaces = { + machine["hostname"]: machine["nics"] + for machine in list_machines(maas, hostname=sorted(uplink_nodes)) + } + desired = resolve_instances(domains, nodes, maas_interfaces) + allocations = reserve_router_ids(config.router_id_pool, state, current, desired) + check_peering_changes(current, desired) + model = deployment.openstack_machines_model + units = resolve_units(jhelper, model, nodes, desired, current) + validate_unit_placements(jhelper, model, units, desired) + check_peering_changes(current, desired, resolved=True) + desired_apps = {units[node].split("/")[0] for node in desired} + current_apps = {units[node].split("/")[0] for node in current} + + current_hosts = { + instance["host"] for items in current.values() for instance in items + } + desired_hosts = { + instance["host"] for items in desired.values() for instance in items + } + bindings = self.agent_bindings( + deployment, keystone_helper, current_hosts - desired_hosts + ) + for binding in bindings: + click.echo(f"{binding} Removing it may withdraw routes.", err=True) + if bindings and not force: + raise FeatureError("Unbind the affected agents or use --force.") + self.check_neutron_config(deployment, jhelper) + + offer = None + if enabled and (current_apps or desired_apps): + openstack_plan = deployment.get_tfhelper("openstack-plan") + openstack_plan.init() + offer = openstack_plan.output().get("rabbitmq-offer-url") + if not offer: + raise FeatureError("The control plane has no RabbitMQ offer for NDR.") + + routing_domains = state.get("routing-domains", {}) + if enabled: + routing_domains = { + domain: settings.model_dump( + mode="json", by_alias=True, exclude_none=True + ) + for domain, settings in domains.items() + } + self.update_feature_info( + client, + {"enabled": "true", "routing-domains": routing_domains, **allocations}, + ) + self.configure_neutron(deployment, jhelper, enabled=True) + jhelper.wait_until_desired_status( + OPENSTACK_MODEL, ["neutron"], status=["active"] + ) + self.check_neutron_api(deployment, keystone_helper) + for binding in self.agent_bindings( + deployment, keystone_helper, desired_hosts - current_hosts + ): + click.echo( + f"{binding} The retained binding may resume advertising.", err=True + ) + self.configure_amqp(deployment, current_apps | desired_apps, offer) + self.wait_for_amqp(jhelper, model, units, desired) + + self.apply_units(client, jhelper, model, units, current, desired) + + if enabled and desired_hosts: + self.wait_for_agents(deployment, keystone_helper, desired_hosts) + elif not enabled: + self.configure_neutron(deployment, jhelper, enabled=False) + if not enabled or current_apps - desired_apps: + self.configure_amqp(deployment, desired_apps, offer) + self.update_feature_info( + client, + { + "enabled": str(enabled).lower(), + "instances": desired, + "routing-domains": routing_domains, + **allocations, + }, + ) + if enabled and desired_apps: + refresh_machine_collector_integrations(deployment, jhelper) + click.echo(f"Dynamic routing {'configured' if enabled else 'disabled'}.") + + def check_neutron_config(self, deployment: Deployment, jhelper: JujuHelper) -> None: + """Ensure the installed charm supports the feature-owned option.""" + neutron = deployment.get_manifest().core.software.charms.get("neutron-k8s") + if neutron and neutron.config and NEUTRON_OPTION in neutron.config: + raise FeatureError( + f"Manage {NEUTRON_OPTION} through the dynamic-routing feature, " + "and remove the charm override from the manifest." + ) + if NEUTRON_OPTION not in jhelper.get_app_config("neutron", OPENSTACK_MODEL): + raise FeatureError(f"The neutron charm does not provide {NEUTRON_OPTION}.") + + def check_neutron_api( + self, deployment: Deployment, keystone_helper: JujuHelper + ) -> None: + """Check the active Neutron API before configuring DR agents.""" + try: + with get_admin_connection( + keystone_helper, deployment, region_name=deployment.get_region_name() + ) as connection: + # Juju can still report active while Neutron reloads its workers. + def check_bgp_api() -> None: + aliases = { + extension.alias for extension in connection.network.extensions() + } + missing = {"bgp", "bgp_dragent_scheduler"} - aliases + if missing: + raise FeatureError( + f"Neutron API is missing NDR extensions: " + f"{', '.join(sorted(missing))}." + ) + # The extensions list does not exercise the BGP speaker tables. + next(connection.network.bgp_speakers(limit=1), None) + + retry = Retrying( + retry=retry_if_exception( + lambda error: ( + isinstance(error, FeatureError) + or ( + isinstance(error, HttpException) + and error.status_code == 503 + ) + ) + ), + stop=stop_after_delay(120), + wait=wait_fixed(5), + reraise=True, + ) + retry(check_bgp_api) + except HttpException as error: + raise FeatureError( + f"Neutron BGP API check failed (HTTP {error.status_code})." + ) from error + except SDKException as error: + raise FeatureError("Unable to check the Neutron BGP API.") from error + + def wait_for_amqp( + self, jhelper: JujuHelper, model: str, units: dict[str, str], desired: Instances + ) -> None: + """Wait for RabbitMQ relation credentials on units that will run agents.""" + pending = {node: units[node] for node in desired} + retry = Retrying( + retry=retry_if_exception(lambda error: isinstance(error, FeatureError)), + stop=stop_after_delay(120), + wait=wait_fixed(5), + reraise=True, + ) + for attempt in retry: + with attempt: + for node, unit in list(pending.items()): + try: + result = jhelper.run_action( + unit, + model, + VALIDATE_ACTION, + instance_action_params(desired[node]), + timeout=30, + ) + except ActionFailedException as error: + raise FeatureError( + "Unable to check NDR RabbitMQ credentials on " + f"{unit}: {error}" + ) from error + if str(result.get("amqp-ready", False)).lower() == "true": + del pending[node] + if pending: + raise FeatureError( + "Waiting for NDR RabbitMQ credentials on " + f"{', '.join(sorted(pending.values()))}." + ) + + def apply_units( + self, + client: Client, + jhelper: JujuHelper, + model: str, + units: dict[str, str], + current: Instances, + desired: Instances, + ) -> None: + """Apply each validated unit plan and persist recoverable progress.""" + for node, unit in units.items(): + instances = desired.get(node, []) + params = instance_action_params(instances) + # Persist both sets so retry or disable can recover a lost action response. + previous = current.get(node, []) + before = {item["host"]: item for item in previous} + before.update({item["host"]: item for item in instances}) + current[node] = list(before.values()) + self.update_feature_info(client, {"enabled": "true", "instances": current}) + try: + result = jhelper.run_action(unit, model, ACTION, params) + except ActionFailedException as error: + try: + status = jhelper.run_action(unit, model, VALIDATE_ACTION, params) + saved = json.loads(status["saved-instances"]) + except (ActionFailedException, KeyError, TypeError, ValueError): + saved = None + if saved == previous: + if previous: + current[node] = previous + else: + del current[node] + self.update_feature_info(client, {"instances": current}) + raise + if saved == instances: + raise FeatureError( + f"{unit} saved its placement but did not confirm readiness. " + "Retry the placement operation." + ) from error + raise + if instances and str(result.get("configured", False)).lower() != "true": + raise FeatureError( + f"{unit} saved its placement but did not confirm readiness. " + "Check the peering interfaces and addresses and the AMQP " + "relation, then retry." + ) + if instances: + current[node] = instances + else: + del current[node] + self.update_feature_info(client, {"instances": current}) + + def configure_neutron( + self, deployment: Deployment, jhelper: JujuHelper, *, enabled: bool + ) -> None: + """Set NDR on the installed charm and persist it for future Terraform runs.""" + config = {NEUTRON_OPTION: enabled} + jhelper.set_app_config("neutron", OPENSTACK_MODEL, config) + helper = deployment.get_tfhelper("openstack-plan") + helper.update_tfvars( + deployment.get_client(), + deployment.get_manifest(), + tfvar_config=OPENSTACK_TERRAFORM_VARS, + override_tfvars={"neutron-config": config}, + ) + + def configure_amqp( + self, deployment: Deployment, applications: set[str], offer: str | None + ) -> None: + """Apply the feature-owned RabbitMQ integrations.""" + helper = deployment.get_tfhelper("microovn-plan") + helper.init() + helper.update_tfvars_and_apply_tf( + deployment.get_client(), + deployment.get_manifest(), + tfvar_config=CONFIG_KEY, + override_tfvars={ + "ndr_rabbitmq_offer_url": offer if applications else None, + "ndr_applications": sorted(applications), + }, + tf_apply_extra_args=["-target=juju_integration.amqp"], + ) + + def wait_for_agents( + self, deployment: Deployment, keystone_helper: JujuHelper, expected: set[str] + ) -> None: + """Wait for a new heartbeat from each desired agent after placement.""" + try: + with get_admin_connection( + keystone_helper, deployment, region_name=deployment.get_region_name() + ) as connection: + retry = Retrying( + stop=stop_after_delay(180), + wait=wait_fixed(5), + reraise=True, + ) + baseline: dict[str, str] | None = None + for attempt in retry: + with attempt: + present = { + agent.host: agent.last_heartbeat_at + for agent in connection.network.agents( + agent_type=AGENT_TYPE + ) + if agent.host in expected and agent.is_alive + } + if baseline is None: + baseline = present + fresh = { + host + for host, heartbeat in present.items() + if heartbeat and heartbeat != baseline.get(host) + } + if missing := expected - fresh: + raise FeatureError( + "Waiting for new NDR agent heartbeats: " + f"{', '.join(sorted(missing))}." + ) + except SDKException as error: + raise FeatureError("Unable to check NDR agent heartbeats.") from error diff --git a/sunbeam-python/sunbeam/provider/local/commands.py b/sunbeam-python/sunbeam/provider/local/commands.py index d042e92b3..1ca9d25ac 100644 --- a/sunbeam-python/sunbeam/provider/local/commands.py +++ b/sunbeam-python/sunbeam/provider/local/commands.py @@ -84,6 +84,7 @@ feature_gate_command, feature_gate_option, ) +from sunbeam.features.dynamic_routing.feature import DynamicRoutingFeature from sunbeam.provider.base import ProviderBase from sunbeam.provider.common.multiregion import connect_to_region_controller from sunbeam.provider.local.deployment import LOCAL_TYPE, LocalDeployment @@ -2023,7 +2024,8 @@ def remove(ctx: click.Context, name: str, force: bool, show_hints: bool) -> None ] ) - run_plan(plan, console, show_hints) + with DynamicRoutingFeature().node_removal_guard(client, name): + run_plan(plan, console, show_hints) click.echo(f"Removed node {name} from the cluster") # Removing machine does not clean up all deployed juju components. This is # deliberate, see https://bugs.launchpad.net/juju/+bug/1851489. diff --git a/sunbeam-python/sunbeam/provider/maas/commands.py b/sunbeam-python/sunbeam/provider/maas/commands.py index 684191f78..cd3b9d1cd 100644 --- a/sunbeam-python/sunbeam/provider/maas/commands.py +++ b/sunbeam-python/sunbeam/provider/maas/commands.py @@ -71,6 +71,7 @@ from sunbeam.core.openstack import OPENSTACK_MODEL from sunbeam.core.terraform import TerraformInitStep from sunbeam.feature_gates import feature_gate_option +from sunbeam.features.dynamic_routing.feature import DynamicRoutingFeature from sunbeam.provider.base import ProviderBase from sunbeam.provider.common.multiregion import connect_to_region_controller from sunbeam.provider.maas.client import ( @@ -1871,7 +1872,8 @@ def remove_node(ctx: click.Context, name: str, force: bool, show_hints: bool) -> ), ] - run_plan(plan, console, show_hints) + with DynamicRoutingFeature().node_removal_guard(client, name): + run_plan(plan, console, show_hints) click.echo(f"Removed node {name} from the cluster.") diff --git a/sunbeam-python/tests/unit/sunbeam/features/test_dynamic_routing.py b/sunbeam-python/tests/unit/sunbeam/features/test_dynamic_routing.py new file mode 100644 index 000000000..500978b34 --- /dev/null +++ b/sunbeam-python/tests/unit/sunbeam/features/test_dynamic_routing.py @@ -0,0 +1,984 @@ +# SPDX-FileCopyrightText: 2026 - Canonical Ltd +# SPDX-License-Identifier: Apache-2.0 + +"""Test the dynamic routing feature's placement and operator workflow.""" + +import ipaddress +import json +from types import SimpleNamespace +from unittest.mock import MagicMock, Mock, call + +import click +import pytest +import yaml +from click.testing import CliRunner +from openstack.exceptions import HttpException, SDKException +from pydantic import ValidationError + +from sunbeam.core.deployment import Deployment +from sunbeam.feature_manager import FeatureManager +from sunbeam.features.dynamic_routing import feature as ndr +from sunbeam.features.interface.v1.base import FeatureError + +NODES = [ + {"name": "net-01", "machineid": 0, "role": ["network"]}, + {"name": "net-02", "machineid": 1, "role": ["network"], "arch": "arm64"}, + {"name": "compute-01", "machineid": 2, "role": ["compute"]}, +] + + +def trunk(*nodes, family="ipv4", vlan=120): + """Declare a managed trunk addressing fixture for the selected nodes.""" + addresses = { + node: { + "address": f"192.0.2.{offset}/28" + if family == "ipv4" + else f"2001:db8::{offset}/64" + } + for offset, node in enumerate(nodes, 3) + } + return { + "address-families": [family], + "peering": { + "provider-trunk": {"physnet": "physnet1", "vlan": vlan, "nodes": addresses} + }, + } + + +ALL_NETWORK_NODES = trunk("net-01", "net-02") +APPENDIX_A = """ +features: + dynamic-routing: + config: + router-id-pool: 198.19.0.0/16 + routing-domains: + red: + address-families: [ipv4] + peering: + provider-trunk: + physnet: physnet1 + vlan: 120 + nodes: + net-01: {address: 192.0.2.3/28} + net-02: {address: 192.0.2.4/28} + blue: + address-families: [ipv6] + peering: + dedicated-uplink: + nodes: + net-01: {} + net-02: {} +""" + + +def apply_calls(helper): + return [ + call for call in helper.run_action.call_args_list if call.args[2] == ndr.ACTION + ] + + +def placement(domains): + return ndr.DynamicRoutingConfig.model_validate({"routing-domains": domains}) + + +def status_unit(machine, subordinates): + return SimpleNamespace( + machine=str(machine), subordinates=dict.fromkeys(subordinates) + ) + + +def test_domain_placement_and_stable_identities(): + """Both domains may run independently on the same host.""" + config = placement( + {"client1": ALL_NETWORK_NODES, "internet": trunk("net-02", vlan=121)} + ) + instances = ndr.resolve_instances(config.routing_domains, NODES) + + assert [item["host"] for item in instances["net-01"]] == ["net-01.client1.v4"] + assert [item["host"] for item in instances["net-02"]] == [ + "net-02.client1.v4", + "net-02.internet.v4", + ] + assert instances["net-01"][0]["service-name"] == "agent-client1-v4" + assert instances["net-02"][1]["peering"]["provider-trunk"]["vlan"] == 121 + assert ndr.resolve_instances(config.routing_domains, NODES[::-1]) == instances + ndr.reserve_router_ids(None, {}, {}, instances) + assert ( + len({item["router-id"] for group in instances.values() for item in group}) == 3 + ) + + +@pytest.mark.parametrize( + "name,reason", + [("net-typo", "not registered"), ("compute-01", "does not have the network role")], +) +def test_ineligible_placement_has_context(name, reason): + """Check exact deployment names and the network role.""" + config = placement({"client1": trunk(name)}) + with pytest.raises(FeatureError, match=rf"client1.*{name}.*{reason}.*net-01"): + ndr.resolve_instances(config.routing_domains, NODES) + + +@pytest.mark.parametrize( + "settings", + [ + {}, + {"nodes": ["net-01"]}, + {"peering": {}}, + { + "peering": { + "provider-trunk": {"physnet": "physnet1", "vlan": 120, "nodes": {}} + } + }, + { + "peering": { + **ALL_NETWORK_NODES["peering"], + "dedicated-uplink": {"nodes": {"net-01": {}}}, + } + }, + {**ALL_NETWORK_NODES, "address-families": []}, + {**ALL_NETWORK_NODES, "address-families": ["ipv6", "ipv6"]}, + {**ALL_NETWORK_NODES, "address-families": ["ipv4", "ipv6"]}, + {**ALL_NETWORK_NODES, "address-families": ["ipv6", "ipv4"]}, + {**ALL_NETWORK_NODES, "address-families": ["ipv5"]}, + {**ALL_NETWORK_NODES, "address-families": ["ipv6"]}, + ], +) +def test_invalid_domain_inputs(settings): + """Reject unusable manifest entries before resolving Juju units.""" + with pytest.raises(ValidationError): + placement({"client1": settings}) + + +@pytest.fixture +def reconciler(monkeypatch): + """Provide a named mixed-architecture deployment with a test Neutron API.""" + deployment = Mock(openstack_machines_model="machines", external_keystone_model=None) + client = deployment.get_client.return_value + client.cluster.list_nodes.return_value = NODES + deployment.get_manifest.return_value.core.software.charms = {} + helper = Mock() + deployment.get_juju_helper.return_value = helper + helper.get_model_status.return_value.apps = { + "neutron": SimpleNamespace( + relations={"ovsdb-cms": [SimpleNamespace(related_app="sunbeam-ovn-proxy")]} + ), + "microovn": SimpleNamespace( + units={"microovn/0": status_unit(0, ["openstack-network-agents/0"])} + ), + "microovn-arm64": SimpleNamespace( + units={ + "microovn-arm64/0": status_unit(1, ["openstack-network-agents-arm64/0"]) + } + ), + } + helper.get_application_actions.return_value = [ + ndr.ACTION, + ndr.VALIDATE_ACTION, + ] + + def run_action(unit, model, action, params=None, **kwargs): + if action == ndr.VALIDATE_ACTION: + assert params["contract-version"] == 1 + instances = json.loads(params["instances"]) + for instance in instances: + uplink = instance["peering"].get("dedicated-uplink") + if uplink is not None: + uplink.setdefault( + "address", + "2001:db8::3" if unit.endswith("/0") else "2001:db8::4", + ) + return {**params, "instances": json.dumps(instances), "amqp-ready": True} + assert action == ndr.ACTION + assert params["contract-version"] == 1 + return {"configured": True} + + helper.run_action.side_effect = run_action + helper.get_app_config.return_value = {ndr.NEUTRON_OPTION: False} + deployment.get_tfhelper.return_value.output.return_value = { + "rabbitmq-offer-url": "admin/openstack.rabbitmq" + } + network = MagicMock() + network.bgp_speakers.side_effect = lambda **_: iter(()) + network.extensions.return_value = [ + SimpleNamespace(alias="bgp"), + SimpleNamespace(alias="bgp_dragent_scheduler"), + ] + session = MagicMock() + session.__enter__.return_value.network = network + monkeypatch.setattr(ndr, "JujuHelper", Mock(return_value=helper)) + monkeypatch.setattr(ndr, "get_admin_connection", Mock(return_value=session)) + monkeypatch.setattr(ndr, "run_preflight_checks", Mock()) + monkeypatch.setattr(ndr, "refresh_machine_collector_integrations", Mock()) + + feature = ndr.DynamicRoutingFeature() + state = {} + monkeypatch.setattr(feature, "get_feature_info", lambda client: dict(state)) + monkeypatch.setattr( + feature, "update_feature_info", lambda client, data: state.update(data) + ) + monkeypatch.setattr(feature, "wait_for_agents", Mock()) + return feature, deployment, helper, network, state + + +def test_read_back_saved_placement_if_action_fails(reconciler): + feature, deployment, helper, _, state = reconciler + desired = ndr.resolve_instances( + placement({"red": trunk("net-01")}).routing_domains, NODES + ) + ndr.reserve_router_ids(None, {}, {}, desired) + helper.run_action.side_effect = [ + ndr.ActionFailedException("Action response timed out"), + {"saved-instances": json.dumps(desired["net-01"])}, + ] + + with pytest.raises(FeatureError, match="saved its placement.*readiness"): + feature.apply_units( + deployment.get_client(), + helper, + "machines", + {"net-01": "openstack-network-agents/0"}, + {}, + desired, + ) + + assert helper.run_action.call_args.args[2] == ndr.VALIDATE_ACTION + assert state["instances"] == desired + + +def test_failed_action_restores_confirmed_previous_placement(reconciler): + feature, deployment, helper, _, state = reconciler + desired = ndr.resolve_instances( + placement({"red": trunk("net-01")}).routing_domains, NODES + ) + ndr.reserve_router_ids(None, {}, {}, desired) + helper.run_action.side_effect = [ + ndr.ActionFailedException("Action failed before saving"), + {"saved-instances": "[]"}, + ] + + with pytest.raises(ndr.ActionFailedException, match="before saving"): + feature.apply_units( + deployment.get_client(), + helper, + "machines", + {"net-01": "openstack-network-agents/0"}, + {}, + desired, + ) + + assert state["instances"] == {} + + +def test_enable_waits_for_amqp_credentials_before_placing_agents( + reconciler, monkeypatch +): + feature, deployment, helper, _, state = reconciler + mocked_action = helper.run_action.side_effect + tfhelper = deployment.get_tfhelper.return_value + probes = [] + + def run_action(unit, model, action, params=None, **kwargs): + if action == ndr.VALIDATE_ACTION and tfhelper.update_tfvars_and_apply_tf.called: + probes.append(unit) + return {"amqp-ready": len(probes) == 2} + if action == ndr.ACTION: + assert len(probes) == 2 + return mocked_action(unit, model, action, params) + + helper.run_action.side_effect = run_action + monkeypatch.setattr(ndr, "wait_fixed", lambda seconds: lambda _: 0) + + feature.apply_placement(deployment, placement({"red": trunk("net-01")})) + + assert probes == ["openstack-network-agents/0"] * 2 + assert len(state["instances"]["net-01"]) == 1 + assert tfhelper.mock_calls[:2] == [call.init(), call.output()] + assert tfhelper.mock_calls.index(call.init(), 2) < next( + index + for index, invocation in enumerate(tfhelper.mock_calls) + if invocation[0] == "update_tfvars_and_apply_tf" + ) + + +@pytest.mark.parametrize("shared_keystone", [False, True]) +def test_reconcile_and_force_removal(reconciler, capsys, shared_keystone): + """Removal refuses a bound speaker until the operator overrides explicitly.""" + feature, deployment, helper, network, state = reconciler + if shared_keystone: + deployment.external_keystone_model = "region-controller:admin/openstack" + deployment.get_juju_helper.return_value = Mock(name="region_controller") + keystone_helper = deployment.get_juju_helper.return_value + region = "secondary" if shared_keystone else "primary" + deployment.get_region_name.return_value = region + admin_connection = call(keystone_helper, deployment, region_name=region) + + feature.apply_placement( + deployment, + placement( + {"client1": ALL_NETWORK_NODES, "internet": trunk("net-02", vlan=121)} + ), + ) + helper.set_app_config.assert_called_once_with( + "neutron", ndr.OPENSTACK_MODEL, {ndr.NEUTRON_OPTION: True} + ) + assert deployment.get_tfhelper.return_value.update_tfvars.call_args.kwargs[ + "override_tfvars" + ] == {"neutron-config": {ndr.NEUTRON_OPTION: True}} + assert ( + deployment.get_tfhelper.return_value.update_tfvars_and_apply_tf.call_args.kwargs[ + "tf_apply_extra_args" + ] + == ["-target=juju_integration.amqp"] + ) + old = state["instances"] + assert [call.args[0] for call in apply_calls(helper)] == [ + "openstack-network-agents/0", + "openstack-network-agents-arm64/0", + ] + assert json.loads(helper.run_action.call_args.args[3]["instances"]) == old["net-02"] + deployment.get_juju_helper.assert_called_once_with(keystone=True) + assert ndr.get_admin_connection.call_args_list == [admin_connection] * 2 + feature.wait_for_agents.assert_called_once_with( + deployment, + keystone_helper, + {"net-01.client1.v4", "net-02.client1.v4", "net-02.internet.v4"}, + ) + + helper.run_action.reset_mock() + helper.set_app_config.reset_mock() + terraform = deployment.get_tfhelper.return_value.update_tfvars_and_apply_tf + terraform.reset_mock() + ndr.get_admin_connection.reset_mock() + network.agents.return_value = [ + SimpleNamespace(host="net-02.internet.v4", id="agent") + ] + network.get_bgp_speakers_hosted_by_dragent.return_value = [ + SimpleNamespace(name="internet", id="speaker") + ] + update = placement({"client1": ALL_NETWORK_NODES}) + with pytest.raises(FeatureError, match="--force"): + feature.apply_placement(deployment, update) + assert state["instances"] == old + assert not apply_calls(helper) + helper.set_app_config.assert_not_called() + terraform.assert_not_called() + assert ndr.get_admin_connection.call_args_list == [admin_connection] + assert "hosts speaker internet" in capsys.readouterr().err + + feature.apply_placement(deployment, update, force=True) + assert "hosts speaker internet" in capsys.readouterr().err + assert json.loads(helper.run_action.call_args.args[3]["instances"]) == [ + old["net-02"][0] + ] + network.remove_bgp_speaker_from_dragent.assert_not_called() + + ndr.get_admin_connection.reset_mock() + helper.set_app_config.reset_mock() + feature.apply_placement(deployment, ndr.DynamicRoutingConfig(), enabled=False) + assert ndr.get_admin_connection.call_args_list == [admin_connection] + helper.set_app_config.assert_called_once_with( + "neutron", ndr.OPENSTACK_MODEL, {ndr.NEUTRON_OPTION: False} + ) + assert not state["instances"] + + +def test_force_does_not_bypass_failed_binding_lookup(reconciler): + """Fail closed if a removal cannot be checked against Neutron.""" + feature, deployment, helper, network, state = reconciler + feature.apply_placement(deployment, placement({"client1": ALL_NETWORK_NODES})) + helper.run_action.reset_mock() + network.agents.side_effect = SDKException("unavailable") + + with pytest.raises(FeatureError, match="Unable to check Neutron speaker bindings"): + feature.apply_placement(deployment, placement({}), force=True) + + assert state["instances"] + assert not apply_calls(helper) + + +def test_missing_subordinate_blocks_all_changes(reconciler): + """Resolve both architectures and refuse a missing unit before applying.""" + feature, deployment, helper, _, state = reconciler + helper.get_model_status.return_value.apps.pop("microovn-arm64") + + with pytest.raises(FeatureError, match="net-02.*openstack-network-agents-arm64"): + feature.apply_placement(deployment, placement({"client1": ALL_NETWORK_NODES})) + + assert not state + helper.run_action.assert_not_called() + deployment.get_tfhelper.return_value.update_tfvars_and_apply_tf.assert_not_called() + + +def test_placement_lock_conflict_does_not_mutate_state(reconciler): + """Reject a concurrent operation before reading or applying its placement.""" + feature, deployment, helper, _, state = reconciler + cluster = deployment.get_client().cluster + cluster.lock_terraform_plan.side_effect = ndr.TerraformPlanLockConflictException( + "another owner" + ) + with pytest.raises(FeatureError, match="placement change is in progress"): + feature.apply_placement(deployment, placement({"client1": ALL_NETWORK_NODES})) + + cluster.unlock_terraform_plan.assert_not_called() + helper.run_action.assert_not_called() + assert not state + + +def test_paused_unit_does_not_report_success(reconciler): + """A prior heartbeat cannot turn a paused configure action into success.""" + feature, deployment, helper, _, state = reconciler + mocked_action = helper.run_action.side_effect + helper.run_action.side_effect = lambda unit, model, action, params=None, **kwargs: ( + {"configured": False} + if action == ndr.ACTION + else mocked_action(unit, model, action, params) + ) + config = placement({"client1": trunk("net-01")}) + + with pytest.raises(FeatureError, match=r"readiness.*peering.*AMQP"): + feature.apply_placement(deployment, config) + + feature.wait_for_agents.assert_not_called() + assert state["instances"]["net-01"][0]["host"] == "net-01.client1.v4" + cluster = deployment.get_client().cluster + assert ( + cluster.unlock_terraform_plan.call_args == cluster.lock_terraform_plan.call_args + ) + + +def test_wait_for_agents_requires_a_new_heartbeat(reconciler, monkeypatch): + """An alive record from before the apply cannot satisfy readiness.""" + feature, deployment, helper, network, _ = reconciler + host = "net-01.client1.v4" + old = SimpleNamespace(host=host, is_alive=True, last_heartbeat_at="old") + new = SimpleNamespace(host=host, is_alive=True, last_heartbeat_at="new") + network.agents.side_effect = [[old], [old], [new]] + wait_fixed = ndr.wait_fixed + monkeypatch.setattr(ndr, "wait_fixed", lambda _: wait_fixed(0)) + + ndr.DynamicRoutingFeature.wait_for_agents(feature, deployment, helper, {host}) + + assert network.agents.call_count == 3 + + +def test_ovn_k8s_blocks_enable_before_changes(reconciler): + """Reject a Kubernetes OVN control plane even if MicroOVN units exist.""" + feature, deployment, helper, _, state = reconciler + helper.get_model_status.return_value.apps["neutron"].relations = { + "ovsdb-cms": [SimpleNamespace(related_app="ovn-central")] + } + + with pytest.raises(FeatureError, match="requires MicroOVN"): + feature.apply_placement( + deployment, placement({"client1": ALL_NETWORK_NODES}), force=True + ) + + assert not state + helper.set_app_config.assert_not_called() + helper.run_action.assert_not_called() + deployment.get_tfhelper.assert_not_called() + + +def test_retry_reuses_declared_domains(reconciler): + """An interrupted first apply must leave the desired domains available on retry.""" + feature, deployment, helper, _, state = reconciler + mocked_action = helper.run_action.side_effect + + def interrupt_apply(unit, model, action, params=None, **kwargs): + if action == ndr.ACTION: + raise ndr.FeatureError("action interrupted") + return mocked_action(unit, model, action, params) + + helper.run_action.side_effect = interrupt_apply + with pytest.raises(FeatureError, match="interrupted"): + feature.apply_placement(deployment, placement({"client1": ALL_NETWORK_NODES})) + + saved_ids = state["router-ids"].copy() + helper.run_action.side_effect = mocked_action + feature.apply_placement(deployment, ndr.DynamicRoutingConfig()) + + assert state["router-ids"] == saved_ids + assert set(state["instances"]) == {"net-01", "net-02"} + + +def test_router_id_collision_and_exhaustion(): + """Keep a reservation when the next identity picks the same first ID.""" + nodes = [ + {"name": f"net-{number:04}", "machineid": number, "role": ["network"]} + for number in (108, 639) + ] + one = placement({"red": trunk("net-0108")}) + original = ndr.resolve_instances(one.routing_domains, nodes) + state = ndr.reserve_router_ids(None, {}, {}, original) + assert original["net-0108"][0]["router-id"] == "198.19.141.44" + + both = placement({"red": trunk("net-0108", "net-0639")}) + desired = ndr.resolve_instances(both.routing_domains, nodes) + added = ndr.reserve_router_ids(None, state, {}, desired) + assert added["router-ids"] == { + "net-0108.red.v4": "198.19.141.44", + "net-0639.red.v4": "198.19.141.45", + } + + small_pool = ipaddress.IPv4Network("192.0.2.0/30") + requested = {"net-01": [ndr.agent_instance("red", "ipv4", "net-01")]} + depleted = { + "router-id-pool": str(small_pool), + "router-ids": {"drained-a": "192.0.2.1", "drained-b": "192.0.2.2"}, + } + with pytest.raises(FeatureError, match="pool .* is exhausted"): + ndr.reserve_router_ids(small_pool, depleted, {}, requested) + + +def test_pool_change_requires_disable_and_retains_same_pool(reconciler): + """Keep the custom pool on a retry and block changing it while enabled.""" + feature, deployment, helper, _, state = reconciler + config = ndr.DynamicRoutingConfig.model_validate( + {"router-id-pool": "198.19.0.0/16", "routing-domains": {"red": trunk("net-01")}} + ) + feature.apply_placement(deployment, config) + assignments = state["router-ids"].copy() + feature.apply_placement(deployment, ndr.DynamicRoutingConfig()) + assert state["router-id-pool"] == "198.19.0.0/16" + assert state["router-ids"] == assignments + + altered = config.model_copy( + update={"router_id_pool": ipaddress.IPv4Network("198.18.0.0/16")} + ) + helper.run_action.reset_mock() + with pytest.raises(FeatureError, match="Disable dynamic routing before changing"): + feature.apply_placement(deployment, altered) + helper.run_action.assert_not_called() + + feature.apply_placement(deployment, ndr.DynamicRoutingConfig(), enabled=False) + assert state["router-ids"] == assignments + feature.apply_placement(deployment, altered) + assert state["router-id-pool"] == "198.18.0.0/16" + assert state["router-ids"] != assignments + + +def test_duplicate_declared_source_on_provider_segment(): + """The same L2 placement must not reuse a source across hosts.""" + declaration = trunk("net-01", "net-02") + nodes = declaration["peering"]["provider-trunk"]["nodes"] + nodes["net-02"]["address"] = nodes["net-01"]["address"] + with pytest.raises(FeatureError, match="duplicate peering address"): + ndr.resolve_instances(placement({"red": declaration}).routing_domains, NODES) + + +def test_missing_or_ambiguous_maas_uplink_tag(): + """Resolve dedicated interface tags without accepting ambiguous results.""" + domains = placement( + {"blue": {"peering": {"dedicated-uplink": {"nodes": {"net-01": {}}}}}} + ).routing_domains + with pytest.raises(FeatureError, match="explicit.*interface in Manual"): + ndr.resolve_instances(domains, NODES) + + tagged = {"name": "enp5s0.122", "tags": ["ndr:blue"]} + expected = ndr.resolve_instances(domains, NODES, {"net-01": [tagged]}) + assert expected["net-01"][0]["peering"] == { + "dedicated-uplink": {"interface": "enp5s0.122"} + } + for interfaces in ([], [tagged, {**tagged, "name": "enp5s0.123"}]): + with pytest.raises(FeatureError, match="exactly one MAAS interface.*ndr:blue"): + ndr.resolve_instances(domains, NODES, {"net-01": interfaces}) + + +@pytest.mark.parametrize("node", ["net-01", "net-02"]) +def test_changed_attachment_requires_drain(reconciler, node): + """A changed managed VLAN cannot retain an agent without a drain.""" + feature, deployment, helper, _, state = reconciler + feature.apply_placement(deployment, placement({"red": trunk("net-01")})) + helper.run_action.reset_mock() + helper.set_app_config.reset_mock() + previous_placement = state["instances"] + with pytest.raises(FeatureError, match="net-01.red.v4.*Drain"): + feature.apply_placement( + deployment, placement({"red": trunk(node, vlan=121)}), force=True + ) + helper.run_action.assert_not_called() + helper.set_app_config.assert_not_called() + assert state["instances"] == previous_placement + + +def test_changed_discovered_source_requires_drain(reconciler): + """Detect a change to a dedicated source omitted from the manifest.""" + feature, deployment, helper, _, state = reconciler + config = placement( + { + "blue": { + "address-families": ["ipv6"], + "peering": { + "dedicated-uplink": {"nodes": {"net-01": {"interface": "eth1"}}} + }, + } + } + ) + feature.apply_placement(deployment, config) + helper.run_action.reset_mock() + helper.set_app_config.reset_mock() + original = helper.run_action.side_effect + + def changed_address(unit, model, action, params=None, **kwargs): + result = original(unit, model, action, params) + if action == ndr.VALIDATE_ACTION: + instances = json.loads(result["instances"]) + instances[0]["peering"]["dedicated-uplink"]["address"] = "2001:db8::9" + result["instances"] = json.dumps(instances) + return result + + helper.run_action.side_effect = changed_address + with pytest.raises(FeatureError, match="net-01.blue.v6.*Drain"): + feature.apply_placement(deployment, config) + assert not apply_calls(helper) + helper.set_app_config.assert_not_called() + assert state["instances"]["net-01"][0]["peering"] == { + "dedicated-uplink": {"interface": "eth1", "address": "2001:db8::3"} + } + + +def test_invalid_contract_payload_is_rejected_before_juju_preflight(reconciler): + """Reject a link-local peering source before contacting the unit.""" + feature, deployment, helper, _, state = reconciler + domain = trunk("net-01") + domain["peering"]["provider-trunk"]["nodes"]["net-01"]["address"] = "169.254.1.3/24" + + with pytest.raises(FeatureError, match=r"agents/0.*address.*usable"): + feature.apply_placement(deployment, placement({"red": domain})) + + helper.run_action.assert_not_called() + helper.set_app_config.assert_not_called() + assert not state + + +def test_failed_unit_preflight_blocks_all_mutation(reconciler): + """Host preflight must succeed on every selected unit before applies.""" + feature, deployment, helper, _, state = reconciler + original = helper.run_action.side_effect + + def reject_last_unit(unit, model, action, params=None, **kwargs): + if unit == "openstack-network-agents-arm64/0" and action == ndr.VALIDATE_ACTION: + raise ndr.ActionFailedException("reserved port") + return original(unit, model, action, params) + + helper.run_action.side_effect = reject_last_unit + with pytest.raises(FeatureError, match="agents-arm64/0.*reserved port"): + feature.apply_placement(deployment, placement({"red": ALL_NETWORK_NODES})) + + assert not state + assert not apply_calls(helper) + helper.set_app_config.assert_not_called() + deployment.get_tfhelper.assert_not_called() + + +def test_neutron_extensions_gate_agent_start(reconciler, monkeypatch): + """Require both NDR extensions before starting DR agents.""" + feature, deployment, helper, network, state = reconciler + selection = placement({"red": trunk("net-01")}) + network.extensions.return_value = [SimpleNamespace(alias="bgp")] + stop_after_delay = ndr.stop_after_delay + monkeypatch.setattr(ndr, "stop_after_delay", lambda _: stop_after_delay(0)) + with pytest.raises( + FeatureError, match="missing NDR extensions: bgp_dragent_scheduler" + ): + feature.apply_placement(deployment, selection) + assert not apply_calls(helper) + deployment.get_tfhelper.return_value.update_tfvars_and_apply_tf.assert_not_called() + assert state["router-ids"] + network.bgp_speakers.assert_not_called() + + +def test_neutron_bgp_speaker_query_failure_blocks_agent_start(reconciler): + """Require a successful BGP speaker API request before configuring agents.""" + feature, deployment, helper, network, _ = reconciler + + def failing_speaker_list(*, limit): + assert limit == 1 + yield from () + raise HttpException(http_status=500) + + network.bgp_speakers.side_effect = failing_speaker_list + with pytest.raises(FeatureError, match=r"BGP API check failed.*500"): + feature.apply_placement(deployment, placement({"red": trunk("net-01")})) + + assert not apply_calls(helper) + deployment.get_tfhelper.return_value.update_tfvars_and_apply_tf.assert_not_called() + + +def test_enable_waits_for_neutron_api_after_plugin_restart(reconciler, monkeypatch): + """Allow a transient HTTP 503 while the Neutron charm restarts.""" + feature, deployment, helper, network, state = reconciler + wait_fixed = ndr.wait_fixed + monkeypatch.setattr(ndr, "wait_fixed", lambda _: wait_fixed(0)) + network.agents.side_effect = [HttpException(http_status=503), []] + network.extensions.side_effect = [ + HttpException(http_status=503), + [], + network.extensions.return_value, + network.extensions.return_value, + ] + network.bgp_speakers.side_effect = [HttpException(http_status=503), iter(())] + + feature.apply_placement(deployment, placement({"client1": trunk("net-01")})) + + assert network.agents.call_count == 2 + assert network.extensions.call_count == 4 + assert network.bgp_speakers.call_count == 2 + assert state["instances"]["net-01"][0]["host"] == "net-01.client1.v4" + assert len(apply_calls(helper)) == 1 + + +def test_reconcile_mixed_families_and_require_drain(reconciler): + """Allow mixed domains and require a separate apply to drain a family.""" + feature, deployment, helper, network, state = reconciler + ipv4 = placement({"client1": trunk("net-01")}) + feature.apply_placement(deployment, ipv4) + original = state["instances"]["net-01"][0] + + mixed = placement( + { + "client1": trunk("net-01"), + "internet": trunk("net-01", family="ipv6", vlan=121), + } + ) + feature.apply_placement(deployment, mixed) + + ipv4_agent, ipv6_agent = state["instances"]["net-01"] + assert ipv4_agent == original + assert ipv6_agent["host"] == "net-01.internet.v6" + assert ipv6_agent["router-id"] != original["router-id"] + + change_family = placement( + {"client1": trunk("net-01"), "internet": trunk("net-02", vlan=121)} + ) + prior_state = dict(state) + helper.run_action.reset_mock() + helper.set_app_config.reset_mock() + deployment.get_tfhelper.reset_mock() + for force in (False, True): + with pytest.raises(FeatureError, match="internet.*drain"): + feature.apply_placement(deployment, change_family, force=force) + + assert state == prior_state + helper.run_action.assert_not_called() + helper.set_app_config.assert_not_called() + deployment.get_tfhelper.assert_not_called() + + network.agents.return_value = [ + SimpleNamespace(host=ipv6_agent["host"], id="agent-v6") + ] + network.get_bgp_speakers_hosted_by_dragent.return_value = [ + SimpleNamespace(name="internet", id="speaker-v6") + ] + with pytest.raises(FeatureError, match="--force"): + feature.apply_placement(deployment, ipv4) + assert not apply_calls(helper) + + network.get_bgp_speakers_hosted_by_dragent.return_value = [] + mocked_action = helper.run_action.side_effect + + def interrupt_apply(unit, model, action, params=None, **kwargs): + if action == ndr.ACTION: + raise FeatureError("drain interrupted") + return mocked_action(unit, model, action, params) + + helper.run_action.side_effect = interrupt_apply + with pytest.raises(FeatureError, match="drain interrupted"): + feature.apply_placement(deployment, ipv4) + with pytest.raises(FeatureError, match="internet.*drain"): + feature.apply_placement(deployment, change_family, force=True) + + helper.run_action.side_effect = mocked_action + feature.apply_placement(deployment, ipv4) + payload = json.loads(helper.run_action.call_args.args[3]["instances"]) + assert payload == [original] + assert state["instances"] == {"net-01": [original]} + + feature.apply_placement(deployment, change_family) + assert state["instances"]["net-01"] == [original] + assert [agent["host"] for agent in state["instances"]["net-02"]] == [ + "net-02.internet.v4" + ] + + +def test_legacy_placement_requires_binding_check_before_renaming(reconciler, capsys): + """Report old bindings before replacing a prototype host identity.""" + feature, deployment, helper, network, state = reconciler + state.update( + { + "enabled": "true", + "routing-domains": {"client1": {"nodes": ["net-01"]}}, + "instances": { + "net-01": [ + { + **ndr.agent_instance("client1", "ipv4", "net-01"), + "host": "agent-client1-v4-net-01", + "router-id": "198.18.0.1", + } + ] + }, + } + ) + + network.agents.return_value = [ + SimpleNamespace(host="agent-client1-v4-net-01", id="legacy-agent") + ] + network.get_bgp_speakers_hosted_by_dragent.return_value = [ + SimpleNamespace(name="legacy-speaker", id="speaker") + ] + with pytest.raises(FeatureError, match="Drain legacy domains"): + feature.apply_placement(deployment, ndr.DynamicRoutingConfig()) + helper.run_action.assert_not_called() + with pytest.raises(FeatureError, match="--force"): + feature.apply_placement(deployment, placement({})) + assert not apply_calls(helper) + assert "hosts speaker legacy-speaker" in capsys.readouterr().err + + network.get_bgp_speakers_hosted_by_dragent.return_value = [] + feature.apply_placement(deployment, placement({})) + feature.apply_placement(deployment, placement({"client1": trunk("net-01")})) + assert state["instances"]["net-01"][0]["host"] == "net-01.client1.v4" + assert state["router-ids"]["agent-client1-v4-net-01"] == "198.18.0.1" + network.remove_bgp_speaker_from_dragent.assert_not_called() + + +def test_saved_dual_stack_placement_can_be_drained(reconciler): + """Keep legacy state usable for explicit drain and reapply.""" + feature, deployment, helper, _, state = reconciler + state.update( + { + "enabled": "true", + "routing-domains": { + "client1": {"nodes": ["net-01"], "address-families": ["ipv4", "ipv6"]} + }, + "instances": { + "net-01": [ + { + **ndr.agent_instance("client1", family, "net-01"), + "host": f"agent-client1-v{family[-1]}-net-01", + "router-id": "198.18.0.1" if family == "ipv4" else "198.18.0.2", + } + for family in ("ipv4", "ipv6") + ] + }, + } + ) + + with pytest.raises(FeatureError, match="Drain legacy domains"): + feature.apply_placement(deployment, ndr.DynamicRoutingConfig()) + helper.run_action.assert_not_called() + + feature.apply_placement(deployment, placement({})) + assert state["instances"] == {} + assert json.loads(helper.run_action.call_args.args[3]["instances"]) == [] + + feature.apply_placement(deployment, placement({"client1": trunk("net-01")})) + assert state["instances"]["net-01"][0]["host"] == "net-01.client1.v4" + + +def test_dynamic_routing_cli_without_gate(reconciler, monkeypatch, tmp_path, snap): + """Discover, enable and disable dynamic routing without a snap setting.""" + from sunbeam.main import enable + + feature, deployment, helper, _, state = reconciler + manager = FeatureManager() + monkeypatch.setattr(manager, "features", lambda: {"dynamic-routing": feature}) + monkeypatch.setattr(manager, "groups", dict) + deployment.get_client.return_value.cluster.get_feature_gate.return_value = None + snap.config.get.return_value = False + monkeypatch.setattr("sunbeam.feature_manager.Snap", lambda: snap) + manifest_file = tmp_path / "placement.yaml" + manifest_file.write_text(APPENDIX_A) + monkeypatch.setattr(ndr, "is_maas_deployment", lambda _: True) + monkeypatch.setattr(ndr, "MaasClient", Mock()) + list_machines = Mock( + return_value=[ + { + "hostname": node["name"], + "nics": [{"name": "enp5s0.122", "tags": ["ndr:blue"]}], + } + for node in NODES[:2] + ] + ) + monkeypatch.setattr(ndr, "list_machines", list_machines) + deployment.get_manifest.return_value = Deployment( + name="prototype", url="local", type="local" + ).parse_manifest(yaml.safe_load(manifest_file.read_text())) + + @click.group("init") + def cli(): + pass + + # Keep the production enable group's options without modifying its command registry. + enable_group = click.Group( + enable.name, params=enable.params, callback=enable.callback + ) + cli.add_command(enable_group) + cli.add_command(click.Group("disable")) + manager.register(cli, deployment) + + runner = CliRunner() + help_result = runner.invoke( + cli, ["enable", "dynamic-routing", "--help"], obj=deployment + ) + assert help_result.exit_code == 0, help_result.output + disable_help = runner.invoke( + cli, ["disable", "dynamic-routing", "--help"], obj=deployment + ) + assert disable_help.exit_code == 0, disable_help.output + for result in (help_result, disable_help): + assert "Retain their bindings." in " ".join(result.output.split()) + assert state == {} + helper.run_action.assert_not_called() + + result = runner.invoke( + cli, + ["enable", "--manifest", str(manifest_file), "dynamic-routing"], + obj=deployment, + ) + assert result.exit_code == 0, result.output + assert deployment.get_manifest.call_args_list[0].args == (manifest_file,) + assert set(state["instances"]) == {"net-01", "net-02"} + assert len(apply_calls(helper)) == 2 + assert list_machines.call_args.kwargs == {"hostname": ["net-01", "net-02"]} + assert state["router-id-pool"] == "198.19.0.0/16" + assert state["instances"]["net-01"][0]["peering"] == { + "dedicated-uplink": {"interface": "enp5s0.122", "address": "2001:db8::3"} + } + + # With no explicit path, a new cluster manifest is still authoritative. + updated = ndr.DynamicRoutingConfig.model_validate({"routing-domains": {}}) + deployment.get_manifest.return_value.get_feature("dynamic-routing").config = updated + result = runner.invoke(cli, ["enable", "dynamic-routing"], obj=deployment) + assert result.exit_code == 0, result.output + assert state["instances"] == {} + + result = runner.invoke( + cli, ["disable", "dynamic-routing", "--force"], obj=deployment + ) + assert result.exit_code == 0, result.output + assert state["enabled"] == "false" + assert state["instances"] == {} + + +def test_returning_agent_reports_binding_before_start(reconciler, capsys): + """Re-adding an identity may activate a retained operator binding.""" + feature, deployment, helper, network, _ = reconciler + network.agents.return_value = [ + SimpleNamespace(host="net-01.client1.v4", id="previous-agent") + ] + network.get_bgp_speakers_hosted_by_dragent.return_value = [ + SimpleNamespace(name="client1", id="existing-speaker") + ] + + mocked_action = helper.run_action.side_effect + + def confirm_notification(unit, model, action, params=None, **kwargs): + if action == ndr.ACTION and not apply_calls(helper)[:-1]: + assert "retained binding may resume advertising" in capsys.readouterr().err + return mocked_action(unit, model, action, params) + + helper.run_action.side_effect = confirm_notification + feature.apply_placement(deployment, placement({"client1": ALL_NETWORK_NODES})) + assert len(apply_calls(helper)) == 2 diff --git a/sunbeam-python/tests/unit/sunbeam/provider/local/test_commands.py b/sunbeam-python/tests/unit/sunbeam/provider/local/test_commands.py index 1fb43f56c..9a5b24ec0 100644 --- a/sunbeam-python/tests/unit/sunbeam/provider/local/test_commands.py +++ b/sunbeam-python/tests/unit/sunbeam/provider/local/test_commands.py @@ -202,6 +202,27 @@ def test_join_validates_compute_and_network_after_cluster_join( assert first_plan[0].__class__.__name__ == "ClusterJoinNodeStep" +@pytest.mark.parametrize("force_arg", [[], ["--force"]], ids=["normal", "force"]) +def test_remove_requires_ndr_placement_to_be_drained( + daemon_group_check, run_preflight, run_plan_cmd, juju_helper_cmd, force_arg +): + deployment = Mock() + deployment.get_ovn_manager.return_value.get_machines.return_value = [] + cluster = deployment.get_client.return_value.cluster + cluster.get_config.return_value = ( + '{"instances": {"node-1": [{"host": "node-1.red.v4"}]}}' + ) + + result = CliRunner().invoke(remove, [*force_arg, "node-1"], obj=deployment) + + assert result.exit_code == 1 + assert "Drain dynamic routing placement" in result.output + run_plan_cmd.assert_not_called() + cluster.unlock_terraform_plan.assert_called_once_with( + *cluster.lock_terraform_plan.call_args.args + ) + + class TestRemoveNodeRoleDistributor: def test_remove_cleans_role_distributor_before_machine_removal_and_reapplies( self, @@ -211,11 +232,19 @@ def test_remove_cleans_role_distributor_before_machine_removal_and_reapplies( juju_helper_cmd, ): deployment = Mock() + deployment.get_client.return_value.cluster.get_config.return_value = "{}" deployment.openstack_machines_model = "openstack-machines" deployment.get_manifest.return_value = Mock() deployment.get_tfhelper.return_value = Mock() deployment.get_ovn_manager.return_value.get_machines.return_value = ["1"] + cluster = deployment.get_client.return_value.cluster + + def run_plan_with_placement_lock(*args): + cluster.lock_terraform_plan.assert_called_once() + cluster.unlock_terraform_plan.assert_not_called() + + run_plan_cmd.side_effect = run_plan_with_placement_lock runner = CliRunner() result = runner.invoke(remove, ["node-1"], obj=deployment) @@ -250,6 +279,7 @@ def test_remove_reapplies_microovn_terraform_plan_after_cluster_removal( juju_helper_cmd, ): deployment = Mock() + deployment.get_client.return_value.cluster.get_config.return_value = "{}" deployment.openstack_machines_model = "openstack-machines" deployment.get_manifest.return_value = Mock() deployment.get_tfhelper.return_value = Mock() @@ -280,6 +310,7 @@ def test_remove_skips_role_distributor_when_microovn_has_no_machines( juju_helper_cmd, ): deployment = Mock() + deployment.get_client.return_value.cluster.get_config.return_value = "{}" deployment.openstack_machines_model = "openstack-machines" deployment.get_manifest.return_value = Mock() deployment.get_tfhelper.return_value = Mock() @@ -312,6 +343,7 @@ class TestConfigureSRIOVInfraValidation: def _deployment(self, pci_aliases=None): deployment = Mock() + deployment.get_client.return_value.cluster.get_config.return_value = "{}" client = deployment.get_client.return_value client.cluster.get_node_info.return_value = {"role": ["compute"]} manifest = deployment.get_manifest.return_value 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..f57d3c7f5 100644 --- a/sunbeam-python/tests/unit/sunbeam/provider/maas/test_maas.py +++ b/sunbeam-python/tests/unit/sunbeam/provider/maas/test_maas.py @@ -2551,6 +2551,29 @@ def mock_maas_machine(self, mocker): ) return maas_client, get_machine + @patch("sunbeam.provider.maas.commands.JujuHelper") + @patch("sunbeam.provider.maas.commands.run_preflight_checks") + @patch("sunbeam.provider.maas.commands.run_plan") + @pytest.mark.parametrize("force_arg", [[], ["--force"]], ids=["normal", "force"]) + def test_remove_requires_ndr_placement_to_be_drained( + self, run_plan_cmd, run_preflight, juju_helper, mock_maas_machine, force_arg + ): + deployment = Mock() + deployment.get_ovn_manager.return_value.get_machines.return_value = [] + cluster = deployment.get_client.return_value.cluster + cluster.get_config.return_value = ( + '{"instances": {"node-1": [{"host": "node-1.red.v4"}]}}' + ) + + result = CliRunner().invoke(remove_node, [*force_arg, "node-1"], obj=deployment) + + assert result.exit_code == 1 + assert "Drain dynamic routing placement" in result.output + assert run_plan_cmd.call_count == 1 + cluster.unlock_terraform_plan.assert_called_once_with( + *cluster.lock_terraform_plan.call_args.args + ) + @patch("sunbeam.provider.maas.commands.JujuHelper") @patch("sunbeam.provider.maas.commands.run_preflight_checks") @patch("sunbeam.provider.maas.commands.run_plan") @@ -2569,6 +2592,7 @@ def test_remove_orders_cleanup_steps( ): maas_client, get_machine = mock_maas_machine deployment = Mock() + deployment.get_client.return_value.cluster.get_config.return_value = "{}" deployment.openstack_machines_model = "openstack-machines" deployment.get_ovn_manager.return_value.get_machines.return_value = [] @@ -2643,6 +2667,7 @@ def test_remove_without_maas_machine_requires_force( _, get_machine = mock_maas_machine get_machine.side_effect = ValueError("Machine 'node-1' not found.") deployment = Mock() + deployment.get_client.return_value.cluster.get_config.return_value = "{}" deployment.get_ovn_manager.return_value.get_machines.return_value = [] result = CliRunner().invoke(remove_node, ["node-1"], obj=deployment) @@ -2660,6 +2685,7 @@ def test_forced_remove_without_maas_machine_uses_cluster_name( _, get_machine = mock_maas_machine get_machine.side_effect = ValueError("Machine 'node-1' not found.") deployment = Mock() + deployment.get_client.return_value.cluster.get_config.return_value = "{}" deployment.openstack_machines_model = "openstack-machines" deployment.get_ovn_manager.return_value.get_machines.return_value = [] @@ -2684,6 +2710,7 @@ def test_remove_cleans_role_distributor_before_machine_removal_and_reapplies( juju_helper, ): deployment = Mock() + deployment.get_client.return_value.cluster.get_config.return_value = "{}" deployment.openstack_machines_model = "openstack-machines" deployment.get_manifest.return_value = Mock() deployment.get_tfhelper.return_value = Mock() @@ -2727,6 +2754,7 @@ def test_remove_reapplies_microovn_terraform_plan_after_cluster_removal( juju_helper, ): deployment = Mock() + deployment.get_client.return_value.cluster.get_config.return_value = "{}" deployment.openstack_machines_model = "openstack-machines" deployment.get_manifest.return_value = Mock() deployment.get_tfhelper.return_value = Mock() @@ -2761,6 +2789,7 @@ def test_remove_skips_role_distributor_when_microovn_has_no_machines( juju_helper, ): deployment = Mock() + deployment.get_client.return_value.cluster.get_config.return_value = "{}" deployment.openstack_machines_model = "openstack-machines" deployment.get_manifest.return_value = Mock() deployment.get_tfhelper.return_value = Mock() diff --git a/sunbeam-python/uv.lock b/sunbeam-python/uv.lock index 7439f2102..43c5754ff 100644 --- a/sunbeam-python/uv.lock +++ b/sunbeam-python/uv.lock @@ -3074,6 +3074,7 @@ dependencies = [ { name = "requests-unixsocket" }, { name = "rich" }, { name = "snap-helpers" }, + { name = "sunbeam-ndr-contract" }, { name = "tenacity" }, ] @@ -3212,6 +3213,7 @@ requires-dist = [ { name = "setuptools-rust", marker = "extra == 'openstackclients'" }, { name = "setuptools-scm", marker = "extra == 'openstackclients'" }, { name = "snap-helpers", git = "https://github.com/albertodonato/snap-helpers?rev=76f8166b640163c0f20887829e31b2cafbfdec11" }, + { name = "sunbeam-ndr-contract", specifier = "==2027.1.0.dev0" }, { name = "tempest", marker = "extra == 'dev'", specifier = ">=17.1.0" }, { name = "tenacity" }, { name = "testtools", marker = "extra == 'dev'", specifier = ">=2.2.0" }, @@ -3224,6 +3226,15 @@ requires-dist = [ ] provides-extras = ["openstackclients", "dev", "tics"] +[[package]] +name = "sunbeam-ndr-contract" +version = "2027.1.0.dev0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/b4/73/71292096d2916434cb1c97c774db7b48d18d3f067a810e81f1b97ae0fc10/sunbeam_ndr_contract-2027.1.0.dev0.tar.gz", hash = "sha256:d116ce5e0cc847e42cc091486455209eaf3d83090f724eca5e481c97b0e161f4", size = 9343, upload-time = "2026-11-25T10:41:30.856Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cb/8a/af6613e210f431730d78f758e2f6486baefa18adc93d5c1e46dfdc40a2b7/sunbeam_ndr_contract-2027.1.0.dev0-py3-none-any.whl", hash = "sha256:e02b802d5cbd5306cfc04781e8bca96b78fb6871055993bede5c4c14d0e71c9b", size = 8913, upload-time = "2026-11-25T10:41:30.033Z" }, +] + [[package]] name = "tempest" version = "45.0.0"