From 7cc9833526e785fc07767a8d538527ad1341d573 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 23:52:52 -0600 Subject: [PATCH 1/2] feat: Add a test realizer for physical claims NSO's tests, and any team's, can now run a physical attachment end to end. The test realizer programs a simulated switch from each SwitchPortHold and follows the realizer contract: it carries a boot claim's network alone and untagged, moves a port in one change, withdraws Programmed before changing a port, counts a change only once it reads it back, and removes the detach finalizer only once the port no longer carries the claim's network. It runs in a cell only when explicitly enabled. Key changes: - add vlanID to the interface and claim status for the VLAN a physical network arrives on - add the physicalrealizer package: a one-port switch driver, an in-memory simulated switch with failure hooks and a change history, and a reconciler keyed by SwitchPortHold that reads holds and claims from the API server - add physicalRealizer.enabled and driver to the cell config, off by default - add PortChanging, BootAttachmentActive, PortCarriesNetwork and AttachmentPointAccepted to the API and the network-agent catalog - cover handover, release, a claim deleted mid-change, partial and failed changes, unreadable switches, failed withdrawals and port safety with envtest through the real claim controller Co-Authored-By: Claude Opus 5.5 --- api/v1alpha/networkinterface_types.go | 10 + api/v1alpha/networkinterfaceclaim_types.go | 35 ++ api/v1alpha/zz_generated.deepcopy.go | 10 + ....datumapis.com_networkinterfaceclaims.yaml | 10 + ...rking.datumapis.com_networkinterfaces.yaml | 10 + docs/api/networkinterfaceclaims.md | 14 + docs/api/networkinterfaces.md | 14 + internal/cmd/cell/cell.go | 10 + internal/cmd/cell/cell_test.go | 28 + internal/config/cell.go | 20 + internal/config/cell_test.go | 46 ++ internal/config/zz_generated.deepcopy.go | 16 + internal/controller/physicalrealizer_test.go | 562 ++++++++++++++++++ internal/networkagent/catalog.go | 37 ++ internal/physicalrealizer/driver.go | 58 ++ internal/physicalrealizer/plan.go | 161 +++++ internal/physicalrealizer/plan_test.go | 241 ++++++++ internal/physicalrealizer/reconciler.go | 324 ++++++++++ internal/physicalrealizer/reconciler_test.go | 53 ++ internal/physicalrealizer/simulated.go | 154 +++++ 20 files changed, 1813 insertions(+) create mode 100644 internal/controller/physicalrealizer_test.go create mode 100644 internal/physicalrealizer/driver.go create mode 100644 internal/physicalrealizer/plan.go create mode 100644 internal/physicalrealizer/plan_test.go create mode 100644 internal/physicalrealizer/reconciler.go create mode 100644 internal/physicalrealizer/reconciler_test.go create mode 100644 internal/physicalrealizer/simulated.go diff --git a/api/v1alpha/networkinterface_types.go b/api/v1alpha/networkinterface_types.go index aec67817..19d1b42e 100644 --- a/api/v1alpha/networkinterface_types.go +++ b/api/v1alpha/networkinterface_types.go @@ -547,6 +547,16 @@ type NetworkInterfaceStatus struct { // +kubebuilder:validation:Optional VPC string `json:"vpc,omitempty"` + // vlanID is the VLAN a Physical interface's network arrives on at its + // switch port. The physical realizer reports it no later than Prepared, so + // once Prepared is true an absent vlanID means the network arrives + // untagged. + // + // +kubebuilder:validation:Optional + // +kubebuilder:validation:Minimum=1 + // +kubebuilder:validation:Maximum=4094 + VLANID *int32 `json:"vlanID,omitempty"` + // conditions report the current state of the interface. Allocated means every // address is held. Prepared means the data plane is ready for a workload to // consume it. Programmed means the data plane carries the addresses. diff --git a/api/v1alpha/networkinterfaceclaim_types.go b/api/v1alpha/networkinterfaceclaim_types.go index c1f823c0..7d571e8c 100644 --- a/api/v1alpha/networkinterfaceclaim_types.go +++ b/api/v1alpha/networkinterfaceclaim_types.go @@ -95,6 +95,31 @@ const ( // port's SwitchPortHold to see what holds it. NetworkInterfaceClaimReasonAttachmentPointHeld = "AttachmentPointHeld" + // NetworkInterfaceClaimReasonPortChanging means the physical realizer is + // changing what the claim's switch port carries, so the port is between + // states until the realizer reads it back. + NetworkInterfaceClaimReasonPortChanging = "PortChanging" + + // NetworkInterfaceClaimReasonBootAttachmentActive means a boot claim holds + // the claim's switch port, so the port carries the boot network and not + // this claim's network until the boot claim is deleted. The claim keeps + // its addresses meanwhile. + NetworkInterfaceClaimReasonBootAttachmentActive = "BootAttachmentActive" + + // NetworkInterfaceClaimReasonPortUnverified means the physical realizer + // could not confirm what the claim's switch port carries, because the + // switch failed, only partly applied a change, or could not be read. It + // keeps retrying. + NetworkInterfaceClaimReasonPortUnverified = "PortUnverified" + + // NetworkInterfaceClaimReasonPortCarriesNetwork means the switch port + // carries the claim's network, as read back from the switch. + NetworkInterfaceClaimReasonPortCarriesNetwork = "PortCarriesNetwork" + + // NetworkInterfaceClaimReasonAttachmentPointAccepted means the physical + // realizer accepted the claim's switch port and can build its segment. + NetworkInterfaceClaimReasonAttachmentPointAccepted = "AttachmentPointAccepted" + // NetworkInterfaceClaimReasonAwaitingDetach means a physical claim is being // deleted and the realizer has not yet taken its network off the switch // port, so its addresses stay held. @@ -356,6 +381,16 @@ type NetworkInterfaceClaimStatus struct { // +kubebuilder:validation:Optional ExternalAddresses []NetworkInterfaceExternalAddress `json:"externalAddresses,omitempty"` + // vlanID is the VLAN a Physical claim's network arrives on at its switch + // port, copied from the bound interface's status by the physical realizer. + // Once Prepared is true an absent vlanID means the network arrives + // untagged. + // + // +kubebuilder:validation:Optional + // +kubebuilder:validation:Minimum=1 + // +kubebuilder:validation:Maximum=4094 + VLANID *int32 `json:"vlanID,omitempty"` + // conditions report the current state of the claim. Wait on Ready, which is // true once the claim is bound, its addresses are allocated, the data plane // is prepared for a workload, and the data plane carries the addresses. diff --git a/api/v1alpha/zz_generated.deepcopy.go b/api/v1alpha/zz_generated.deepcopy.go index 4daa09c3..87c83bef 100644 --- a/api/v1alpha/zz_generated.deepcopy.go +++ b/api/v1alpha/zz_generated.deepcopy.go @@ -1791,6 +1791,11 @@ func (in *NetworkInterfaceClaimStatus) DeepCopyInto(out *NetworkInterfaceClaimSt *out = make([]NetworkInterfaceExternalAddress, len(*in)) copy(*out, *in) } + if in.VLANID != nil { + in, out := &in.VLANID, &out.VLANID + *out = new(int32) + **out = **in + } if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions *out = make([]v1.Condition, len(*in)) @@ -1968,6 +1973,11 @@ func (in *NetworkInterfaceStatus) DeepCopyInto(out *NetworkInterfaceStatus) { *out = new(NetworkInterfaceAttachmentRef) **out = **in } + if in.VLANID != nil { + in, out := &in.VLANID, &out.VLANID + *out = new(int32) + **out = **in + } if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions *out = make([]v1.Condition, len(*in)) diff --git a/config/crd/bases/networking.datumapis.com_networkinterfaceclaims.yaml b/config/crd/bases/networking.datumapis.com_networkinterfaceclaims.yaml index 50d20720..9a2515e5 100644 --- a/config/crd/bases/networking.datumapis.com_networkinterfaceclaims.yaml +++ b/config/crd/bases/networking.datumapis.com_networkinterfaceclaims.yaml @@ -572,6 +572,16 @@ spec: required: - name type: object + vlanID: + description: |- + vlanID is the VLAN a Physical claim's network arrives on at its switch + port, copied from the bound interface's status by the physical realizer. + Once Prepared is true an absent vlanID means the network arrives + untagged. + format: int32 + maximum: 4094 + minimum: 1 + type: integer type: object required: - spec diff --git a/config/crd/bases/networking.datumapis.com_networkinterfaces.yaml b/config/crd/bases/networking.datumapis.com_networkinterfaces.yaml index 8a306c42..3a165e0f 100644 --- a/config/crd/bases/networking.datumapis.com_networkinterfaces.yaml +++ b/config/crd/bases/networking.datumapis.com_networkinterfaces.yaml @@ -532,6 +532,16 @@ spec: - Available - Bound type: string + vlanID: + description: |- + vlanID is the VLAN a Physical interface's network arrives on at its + switch port. The physical realizer reports it no later than Prepared, so + once Prepared is true an absent vlanID means the network arrives + untagged. + format: int32 + maximum: 4094 + minimum: 1 + type: integer vpc: description: |- vpc is the base62 identifier of the VPC backing this network in this diff --git a/docs/api/networkinterfaceclaims.md b/docs/api/networkinterfaceclaims.md index 1c70619a..4b97697e 100644 --- a/docs/api/networkinterfaceclaims.md +++ b/docs/api/networkinterfaceclaims.md @@ -548,6 +548,20 @@ namespace. Read it to reach fields the claim does not repeat, such as the MTU and the data-plane attachment.
false + + vlanID + integer + + vlanID is the VLAN a Physical claim's network arrives on at its switch +port, copied from the bound interface's status by the physical realizer. +Once Prepared is true an absent vlanID means the network arrives +untagged.
+
+ Format: int32
+ Minimum: 1
+ Maximum: 4094
+ + false diff --git a/docs/api/networkinterfaces.md b/docs/api/networkinterfaces.md index 71c7db2c..69e6a6e8 100644 --- a/docs/api/networkinterfaces.md +++ b/docs/api/networkinterfaces.md @@ -608,6 +608,20 @@ addresses with no claim bound.
Enum: Available, Bound
false + + vlanID + integer + + vlanID is the VLAN a Physical interface's network arrives on at its +switch port. The physical realizer reports it no later than Prepared, so +once Prepared is true an absent vlanID means the network arrives +untagged.
+
+ Format: int32
+ Minimum: 1
+ Maximum: 4094
+ + false vpc string diff --git a/internal/cmd/cell/cell.go b/internal/cmd/cell/cell.go index c9417948..cfaa698b 100644 --- a/internal/cmd/cell/cell.go +++ b/internal/cmd/cell/cell.go @@ -35,6 +35,7 @@ import ( "go.datum.net/network-services-operator/internal/configwatch" "go.datum.net/network-services-operator/internal/controller" galacticcontroller "go.datum.net/network-services-operator/internal/galactic/controller" + "go.datum.net/network-services-operator/internal/physicalrealizer" ) const leaderElectionID = "6a7d51cc.datumapis.com-cell" @@ -364,6 +365,15 @@ func controllerRegistrations( }}, ) } + if serverConfig.PhysicalRealizer.Enabled { + registrations = append(registrations, namedSetup{physicalrealizer.ControllerName, func() (bool, error) { + return true, (&physicalrealizer.Reconciler{ + Client: mgr.GetLocalManager().GetClient(), + APIReader: mgr.GetLocalManager().GetAPIReader(), + Driver: physicalrealizer.NewSimulatedSwitch(), + }).SetupWithManager(mgr.GetLocalManager()) + }}) + } registrations = append(registrations, namedSetup{"networkinterfaceclaim", func() (bool, error) { return true, (&controller.NetworkInterfaceClaimReconciler{ diff --git a/internal/cmd/cell/cell_test.go b/internal/cmd/cell/cell_test.go index 2dc5bee6..a15db20e 100644 --- a/internal/cmd/cell/cell_test.go +++ b/internal/cmd/cell/cell_test.go @@ -50,3 +50,31 @@ func TestInternalDNSDisabledNeedsNoHubOrDNSAPIs(t *testing.T) { } t.Fatal("DNS registration not found") } + +func TestThePhysicalRealizerRunsOnlyWhenEnabled(t *testing.T) { + for _, tt := range []struct { + name string + enabled bool + }{ + {name: "default"}, + {name: "enabled", enabled: true}, + } { + t.Run(tt.name, func(t *testing.T) { + cfg := config.CellControllerManager{} + if tt.enabled { + cfg.PhysicalRealizer = config.PhysicalRealizerConfig{ + Enabled: true, Driver: config.PhysicalRealizerDriverSimulated, + } + } + registered := slices.ContainsFunc(controllerRegistrations(nil, cfg, nil, nil), func(r namedSetup) bool { + return r.name == "physical-realizer" + }) + if registered != tt.enabled { + t.Errorf("physical realizer registered = %t, want %t", registered, tt.enabled) + } + }) + } + if slices.Contains(ControllerNames(), "physical-realizer") { + t.Error("the default cell lists the physical realizer among its controllers") + } +} diff --git a/internal/config/cell.go b/internal/config/cell.go index 2b2a75a8..7a4d9605 100644 --- a/internal/config/cell.go +++ b/internal/config/cell.go @@ -70,6 +70,23 @@ type CellControllerManager struct { // cell's Galactic gateways. It is disabled unless explicitly enabled, and // needs galactic.enabled. NetworkLoadBalancer NetworkLoadBalancerCellConfig `json:"networkLoadBalancer,omitempty"` + + // PhysicalRealizer runs the test realizer for physical interfaces, which + // programs a simulated switch from the cell's switch port holds. It is + // for tests only and is disabled unless explicitly enabled. + PhysicalRealizer PhysicalRealizerConfig `json:"physicalRealizer,omitempty"` +} + +// PhysicalRealizerDriverSimulated programs an in-memory switch. +const PhysicalRealizerDriverSimulated = "simulated" + +// +k8s:deepcopy-gen=true + +type PhysicalRealizerConfig struct { + Enabled bool `json:"enabled,omitempty"` + + // Driver is the switch the realizer programs. Only simulated exists. + Driver string `json:"driver,omitempty"` } // +k8s:deepcopy-gen=true @@ -154,6 +171,9 @@ func (c *CellControllerManager) Validate() error { if err := validateHostOnlyPorts(c.Galactic.HypervisorHostOnlyPorts); err != nil { return fmt.Errorf("galactic.hypervisorHostOnlyPorts: %w", err) } + if c.PhysicalRealizer.Enabled && c.PhysicalRealizer.Driver != PhysicalRealizerDriverSimulated { + return fmt.Errorf("physicalRealizer.driver must be %s", PhysicalRealizerDriverSimulated) + } return nil } diff --git a/internal/config/cell_test.go b/internal/config/cell_test.go index 6b1f431d..deb7d384 100644 --- a/internal/config/cell_test.go +++ b/internal/config/cell_test.go @@ -123,6 +123,25 @@ func TestCellControllerManager_Validate(t *testing.T) { }, wantSub: "networkLoadBalancer.ipv4VIPs needs networkLoadBalancer.enabled", }, + { + name: "simulated physical realizer", + mutate: func(c *CellControllerManager) { + c.PhysicalRealizer = PhysicalRealizerConfig{Enabled: true, Driver: PhysicalRealizerDriverSimulated} + }, + }, + { + name: "physical realizer without a driver", + mutate: func(c *CellControllerManager) { + c.PhysicalRealizer.Enabled = true + }, + wantSub: "physicalRealizer.driver must be simulated", + }, + { + name: "physical realizer driver while disabled", + mutate: func(c *CellControllerManager) { + c.PhysicalRealizer.Driver = "switch-example" + }, + }, } for _, tt := range tests { @@ -172,6 +191,33 @@ location: } } +func TestThePhysicalRealizerIsOffUnlessConfigured(t *testing.T) { + base := `apiVersion: apiserver.config.datumapis.com/v1alpha1 +kind: CellControllerManager +ipam: + kubeconfigPath: /etc/ipam-cluster/kubeconfig +federation: + kubeconfigPath: /etc/kubernetes/federation/auth/kubeconfig +` + var cfg CellControllerManager + decodeInto(t, []byte(base), &cfg) + if cfg.PhysicalRealizer.Enabled { + t.Fatal("the physical realizer is enabled by default") + } + + var enabled CellControllerManager + decodeInto(t, []byte(base+`physicalRealizer: + enabled: true + driver: simulated +`), &enabled) + if err := enabled.Validate(); err != nil { + t.Fatalf("expected the config to validate, got %v", err) + } + if !enabled.PhysicalRealizer.Enabled || enabled.PhysicalRealizer.Driver != PhysicalRealizerDriverSimulated { + t.Errorf("expected the physical realizer to decode, got %+v", enabled.PhysicalRealizer) + } +} + func TestDecodeCellControllerManager_RejectsControlPlaneFields(t *testing.T) { data := []byte(`apiVersion: apiserver.config.datumapis.com/v1alpha1 kind: CellControllerManager diff --git a/internal/config/zz_generated.deepcopy.go b/internal/config/zz_generated.deepcopy.go index 67a89102..a4ba1610 100644 --- a/internal/config/zz_generated.deepcopy.go +++ b/internal/config/zz_generated.deepcopy.go @@ -46,6 +46,7 @@ func (in *CellControllerManager) DeepCopyInto(out *CellControllerManager) { in.InternalDNS.DeepCopyInto(&out.InternalDNS) in.Galactic.DeepCopyInto(&out.Galactic) out.NetworkLoadBalancer = in.NetworkLoadBalancer + out.PhysicalRealizer = in.PhysicalRealizer } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CellControllerManager. @@ -961,6 +962,21 @@ func (in *OIDCValidationOptions) DeepCopy() *OIDCValidationOptions { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PhysicalRealizerConfig) DeepCopyInto(out *PhysicalRealizerConfig) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PhysicalRealizerConfig. +func (in *PhysicalRealizerConfig) DeepCopy() *PhysicalRealizerConfig { + if in == nil { + return nil + } + out := new(PhysicalRealizerConfig) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RedisConfig) DeepCopyInto(out *RedisConfig) { *out = *in diff --git a/internal/controller/physicalrealizer_test.go b/internal/controller/physicalrealizer_test.go new file mode 100644 index 00000000..f6401ba6 --- /dev/null +++ b/internal/controller/physicalrealizer_test.go @@ -0,0 +1,562 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +package controller + +import ( + "context" + "errors" + "testing" + + "github.com/stretchr/testify/require" + apierrors "k8s.io/apimachinery/pkg/api/errors" + apimeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + + networkingv1alpha "go.datum.net/network-services-operator/api/v1alpha" + "go.datum.net/network-services-operator/internal/physicalrealizer" +) + +const realizedPort = "Ethernet1/12" + +// realizedPortRun drives the test realizer for one port of a scenario's switch, +// and knows which project each scenario namespace belongs to. +type realizedPortRun struct { + s *scenario + sw *physicalrealizer.SimulatedSwitch + realizer *physicalrealizer.Reconciler + projects map[string]string + bootByName map[types.NamespacedName]bool +} + +func (s *scenario) realizedPort() *realizedPortRun { + sw := physicalrealizer.NewSimulatedSwitch() + return &realizedPortRun{ + s: s, + sw: sw, + realizer: &physicalrealizer.Reconciler{Client: s.client, APIReader: s.client, Driver: sw}, + projects: map[string]string{s.namespace: testProject}, + bootByName: map[types.NamespacedName]bool{}, + } +} + +func (r *realizedPortRun) sibling(project string) *scenario { + other := r.s.sibling(project) + r.projects[other.namespace] = project + return other +} + +func (r *realizedPortRun) port() physicalrealizer.Port { + return physicalrealizer.Port{Switch: r.s.switchName, Name: realizedPort} +} + +func (r *realizedPortRun) realize() error { + _, err := r.realizer.Reconcile(r.s.ctx, ctrl.Request{NamespacedName: client.ObjectKey{ + Name: networkingv1alpha.SwitchPortHoldName(r.s.switchName, realizedPort), + }}) + return err +} + +func (r *realizedPortRun) mustRealize() { + r.s.t.Helper() + require.NoError(r.s.t, r.realize()) + r.requireConsistent() +} + +func (r *realizedPortRun) carried() []physicalrealizer.Membership { + return r.sw.Carried(r.port()) +} + +func (r *realizedPortRun) changes() int { + return len(r.sw.History()) +} + +func networkOf(s *scenario) types.NamespacedName { + return types.NamespacedName{Namespace: s.namespace, Name: "default"} +} + +// requireConsistent checks that no claim on the port reports Programmed for a +// network the port does not carry. +func (r *realizedPortRun) requireConsistent() { + r.s.t.Helper() + var claims networkingv1alpha.NetworkInterfaceClaimList + require.NoError(r.s.t, r.s.client.List(r.s.ctx, &claims)) + carried := r.carried() + for _, claim := range claims.Items { + if claim.Spec.AttachmentPoint == nil || claim.Spec.AttachmentPoint.Switch != r.s.switchName { + continue + } + if !apimeta.IsStatusConditionTrue(claim.Status.Conditions, networkingv1alpha.NetworkInterfaceClaimProgrammed) { + continue + } + network := types.NamespacedName{Namespace: claim.Namespace, Name: claim.Spec.Network.Name} + require.Truef(r.s.t, carries(carried, network), + "claim %s/%s reports Programmed while the port carries %v", claim.Namespace, claim.Name, carried) + } +} + +func carries(carried []physicalrealizer.Membership, network types.NamespacedName) bool { + for _, m := range carried { + if m.Network == network { + return true + } + } + return false +} + +// requireSafeHistory checks every state the port ever reached: networks of one +// project at most, and a boot network only ever alone. +func (r *realizedPortRun) requireSafeHistory(bootNetworks ...types.NamespacedName) { + r.s.t.Helper() + for i, change := range r.sw.History() { + projects := map[string]bool{} + for _, m := range change.Carried { + project, known := r.projects[m.Network.Namespace] + require.Truef(r.s.t, known, "change %d carries %s, which no scenario owns", i, m.Network) + projects[project] = true + for _, boot := range bootNetworks { + if m.Network == boot { + require.Lenf(r.s.t, change.Carried, 1, "change %d carries the boot network with others: %v", i, change.Carried) + } + } + } + require.LessOrEqualf(r.s.t, len(projects), 1, "change %d carries two projects' networks: %v", i, change.Carried) + } +} + +func requireProgrammed(t *testing.T, conditions []metav1.Condition, status metav1.ConditionStatus, reason string) { + t.Helper() + programmed := apimeta.FindStatusCondition(conditions, networkingv1alpha.NetworkInterfaceClaimProgrammed) + require.NotNil(t, programmed) + require.Equal(t, status, programmed.Status, programmed.Message) + require.Equal(t, reason, programmed.Reason) +} + +func requirePrepared(t *testing.T, conditions []metav1.Condition) { + t.Helper() + prepared := apimeta.FindStatusCondition(conditions, networkingv1alpha.NetworkInterfaceClaimPrepared) + require.NotNil(t, prepared) + require.Equal(t, metav1.ConditionTrue, prepared.Status) + require.Equal(t, networkingv1alpha.NetworkInterfaceClaimReasonAttachmentPointAccepted, prepared.Reason) +} + +// requireReported checks the claim and the interface bound to it agree. +func (s *scenario) requireReported(name string, status metav1.ConditionStatus, reason string) *networkingv1alpha.NetworkInterfaceClaim { + s.t.Helper() + claim := s.getClaim(name) + requirePrepared(s.t, claim.Status.Conditions) + requireProgrammed(s.t, claim.Status.Conditions, status, reason) + iface, err := s.getInterface(name) + require.NoError(s.t, err) + requirePrepared(s.t, iface.Status.Conditions) + requireProgrammed(s.t, iface.Status.Conditions, status, reason) + require.Equal(s.t, iface.Status.VLANID, claim.Status.VLANID, "the claim repeats the interface's VLAN") + return claim +} + +func (s *scenario) hasDetachFinalizer(name string) bool { + s.t.Helper() + return controllerutil.ContainsFinalizer(s.getClaim(name), networkingv1alpha.NetworkInterfaceClaimDetachFinalizer) +} + +func (s *scenario) requireReady(name string) { + s.t.Helper() + ready := conditionOf(s.getClaim(name), networkingv1alpha.NetworkInterfaceClaimReady) + require.NotNil(s.t, ready) + require.Equal(s.t, metav1.ConditionTrue, ready.Status, ready.Message) +} + +func (s *scenario) bindPhysical(name string, purpose networkingv1alpha.NetworkInterfacePurpose) { + s.t.Helper() + s.reconcile(s.createClaim(name, s.physicalSpec(realizedPort, purpose))) + s.requireBound(name) +} + +func TestARealizedNetworkClaimIsProgrammed(t *testing.T) { + s := newScenario(t, true, ipv4Only) + run := s.realizedPort() + s.bindPhysical("server-data", "") + + run.mustRealize() + require.Equal(t, []physicalrealizer.Membership{{ + Network: networkOf(s), Isolation: networkingv1alpha.NetworkInterfaceIsolationShared, + }}, run.carried()) + claim := s.requireReported("server-data", metav1.ConditionTrue, networkingv1alpha.NetworkInterfaceClaimReasonPortCarriesNetwork) + require.Nil(t, claim.Status.VLANID, "the only network arrives untagged") + + s.reconcile(claim) + s.requireReady("server-data") + + before := run.changes() + run.mustRealize() + require.Equal(t, before, run.changes(), "a port that already carries its networks is left alone") +} + +func TestASecondNetworkArrivesTagged(t *testing.T) { + s := newScenario(t, true, ipv4Only) + run := s.realizedPort() + second := run.sibling(testProject) + s.bindPhysical("server-data", "") + second.bindPhysical("server-storage", "") + + run.mustRealize() + require.Nil(t, s.requireReported("server-data", metav1.ConditionTrue, + networkingv1alpha.NetworkInterfaceClaimReasonPortCarriesNetwork).Status.VLANID) + storage := second.requireReported("server-storage", metav1.ConditionTrue, + networkingv1alpha.NetworkInterfaceClaimReasonPortCarriesNetwork) + require.NotNil(t, storage.Status.VLANID) + + carried := run.carried() + require.Len(t, carried, 2) + for _, m := range carried { + if m.Network == networkOf(second) { + require.Equal(t, *storage.Status.VLANID, m.VLAN, "the reported VLAN is the one the switch carries") + } + } +} + +func TestAHandoverMovesThePortInOneStep(t *testing.T) { + customer := newScenario(t, true, ipv4Only) + run := customer.realizedPort() + provider := run.sibling(providerProject) + + provider.bindPhysical("install-1-boot", networkingv1alpha.NetworkInterfacePurposeBoot) + customer.bindPhysical("server-data", "") + run.mustRealize() + + require.Equal(t, []physicalrealizer.Membership{{ + Network: networkOf(provider), Isolation: networkingv1alpha.NetworkInterfaceIsolationPrivate, + }}, run.carried(), "the boot network alone, untagged and private") + provider.requireReported("install-1-boot", metav1.ConditionTrue, networkingv1alpha.NetworkInterfaceClaimReasonPortCarriesNetwork) + data := customer.requireReported("server-data", metav1.ConditionFalse, + networkingv1alpha.NetworkInterfaceClaimReasonBootAttachmentActive) + customer.reconcile(data) + data = customer.getClaim("server-data") + require.Len(t, data.Status.Addresses, 1, "a network claim under a boot claim keeps its addresses") + require.Equal(t, metav1.ConditionFalse, conditionOf(data, networkingv1alpha.NetworkInterfaceClaimReady).Status) + + require.NoError(t, provider.client.Delete(provider.ctx, provider.getClaim("install-1-boot"))) + provider.reconcile(provider.getClaim("install-1-boot")) + provider.requireAwaitingDetach("install-1-boot") + + var detachHeldAtApply []bool + run.sw.BeforeApply(func(physicalrealizer.Port, []physicalrealizer.Membership) { + detachHeldAtApply = append(detachHeldAtApply, provider.hasDetachFinalizer("install-1-boot")) + for _, name := range []string{"server-data"} { + programmed := conditionOf(customer.getClaim(name), networkingv1alpha.NetworkInterfaceClaimProgrammed) + require.NotEqual(t, metav1.ConditionTrue, programmed.Status, "a claim reports a port between states") + } + programmed := conditionOf(provider.getClaim("install-1-boot"), networkingv1alpha.NetworkInterfaceClaimProgrammed) + require.Equal(t, networkingv1alpha.NetworkInterfaceClaimReasonPortChanging, programmed.Reason, + "the boot claim is withdrawn before the port moves") + }) + before := run.changes() + run.mustRealize() + + require.Equal(t, before+1, run.changes(), "the port moves in one change") + require.Equal(t, []physicalrealizer.Membership{{ + Network: networkOf(customer), Isolation: networkingv1alpha.NetworkInterfaceIsolationShared, + }}, run.carried()) + require.Equal(t, []bool{true}, detachHeldAtApply) + require.False(t, provider.hasDetachFinalizer("install-1-boot"), "the boot claim is detached once read back") + customer.requireReported("server-data", metav1.ConditionTrue, networkingv1alpha.NetworkInterfaceClaimReasonPortCarriesNetwork) + + provider.reconcile(provider.getClaim("install-1-boot")) + require.True(t, provider.claimGone("install-1-boot")) + require.NotEmpty(t, provider.ipam.deleted()[providerProject], "the boot address is released") + customer.reconcile(customer.getClaim("server-data")) + customer.requireReady("server-data") + + run.requireSafeHistory(networkOf(provider)) +} + +func TestReleasingACustomerClaimEmptiesThePort(t *testing.T) { + s := newScenario(t, true, ipv4Only) + run := s.realizedPort() + s.bindPhysical("server-data", "") + run.mustRealize() + + require.NoError(t, s.client.Delete(s.ctx, s.getClaim("server-data"))) + s.reconcile(s.getClaim("server-data")) + s.requireAwaitingDetach("server-data") + + run.mustRealize() + require.Empty(t, run.carried()) + require.False(t, s.hasDetachFinalizer("server-data")) + programmed := conditionOf(s.getClaim("server-data"), networkingv1alpha.NetworkInterfaceClaimProgrammed) + require.Equal(t, metav1.ConditionFalse, programmed.Status) + + s.reconcile(s.getClaim("server-data")) + require.True(t, s.claimGone("server-data")) + _, err := s.getHold(realizedPort) + require.True(t, apierrors.IsNotFound(err)) + + before := run.changes() + run.mustRealize() + require.Equal(t, before, run.changes()) + require.Empty(t, run.carried()) +} + +func TestAClaimDeletedMidChangeLeavesThePortBeforeItsFinalizer(t *testing.T) { + customer := newScenario(t, true, ipv4Only) + run := customer.realizedPort() + provider := run.sibling(providerProject) + storage := run.sibling(testProject) + + provider.bindPhysical("install-1-boot", networkingv1alpha.NetworkInterfacePurposeBoot) + customer.bindPhysical("server-data", "") + storage.bindPhysical("server-storage", "") + run.mustRealize() + + require.NoError(t, provider.client.Delete(provider.ctx, provider.getClaim("install-1-boot"))) + provider.reconcile(provider.getClaim("install-1-boot")) + + applies := 0 + var storageDetachHeld []bool + run.sw.BeforeApply(func(physicalrealizer.Port, []physicalrealizer.Membership) { + applies++ + storageDetachHeld = append(storageDetachHeld, storage.hasDetachFinalizer("server-storage")) + if applies == 1 { + require.NoError(t, storage.client.Delete(storage.ctx, storage.getClaim("server-storage"))) + } + }) + before := len(run.sw.History()) + require.NoError(t, run.realize(), "one pass changes the port again") + + history := run.sw.History()[before:] + require.Len(t, history, 2) + require.ElementsMatch(t, []types.NamespacedName{networkOf(customer), networkOf(storage)}, networksOf(history[0].Carried)) + require.Equal(t, []types.NamespacedName{networkOf(customer)}, networksOf(history[1].Carried)) + require.Equal(t, []bool{true, true}, storageDetachHeld, "the finalizer stays until the second change is read back") + require.False(t, storage.hasDetachFinalizer("server-storage")) + require.False(t, provider.hasDetachFinalizer("install-1-boot")) + customer.requireReported("server-data", metav1.ConditionTrue, networkingv1alpha.NetworkInterfaceClaimReasonPortCarriesNetwork) + run.requireConsistent() + run.requireSafeHistory(networkOf(provider)) +} + +func networksOf(memberships []physicalrealizer.Membership) []types.NamespacedName { + networks := make([]types.NamespacedName, 0, len(memberships)) + for _, m := range memberships { + networks = append(networks, m.Network) + } + return networks +} + +func (r *realizedPortRun) handoverPending() (customer, provider *scenario) { + customer = r.s + provider = r.sibling(providerProject) + provider.bindPhysical("install-1-boot", networkingv1alpha.NetworkInterfacePurposeBoot) + customer.bindPhysical("server-data", "") + r.mustRealize() + require.NoError(r.s.t, provider.client.Delete(provider.ctx, provider.getClaim("install-1-boot"))) + provider.reconcile(provider.getClaim("install-1-boot")) + return customer, provider +} + +func TestAPartialChangeHoldsFinalizersUntilTheSwitchRecovers(t *testing.T) { + s := newScenario(t, true, ipv4Only) + run := s.realizedPort() + customer, provider := run.handoverPending() + + run.sw.PartlyApply(1) + require.Error(t, run.realize()) + run.requireConsistent() + require.Empty(t, run.carried(), "the partial change took the boot network off and added nothing") + require.True(t, provider.hasDetachFinalizer("install-1-boot"), "an unverified change keeps every finalizer") + requireProgrammed(t, customer.getClaim("server-data").Status.Conditions, metav1.ConditionFalse, + networkingv1alpha.NetworkInterfaceClaimReasonPortChanging) + + run.sw.FailApplies(2) + require.Error(t, run.realize()) + require.Error(t, run.realize()) + require.True(t, provider.hasDetachFinalizer("install-1-boot")) + requireProgrammed(t, customer.getClaim("server-data").Status.Conditions, metav1.ConditionFalse, + networkingv1alpha.NetworkInterfaceClaimReasonPortChanging) + + run.mustRealize() + require.Equal(t, []types.NamespacedName{networkOf(customer)}, networksOf(run.carried())) + require.False(t, provider.hasDetachFinalizer("install-1-boot")) + customer.requireReported("server-data", metav1.ConditionTrue, networkingv1alpha.NetworkInterfaceClaimReasonPortCarriesNetwork) + run.requireSafeHistory(networkOf(provider)) +} + +func TestASwitchThatCannotBeReadRemovesNoFinalizer(t *testing.T) { + s := newScenario(t, true, ipv4Only) + run := s.realizedPort() + s.bindPhysical("server-data", "") + run.mustRealize() + require.NoError(t, s.client.Delete(s.ctx, s.getClaim("server-data"))) + s.reconcile(s.getClaim("server-data")) + + run.sw.FailReads(true) + before := run.changes() + for range 3 { + require.ErrorIs(t, run.realize(), physicalrealizer.ErrSwitchUnreachable) + } + require.Equal(t, before, run.changes(), "nothing is changed on a port that cannot be read") + require.True(t, s.hasDetachFinalizer("server-data")) + requireProgrammed(t, s.getClaim("server-data").Status.Conditions, metav1.ConditionTrue, + networkingv1alpha.NetworkInterfaceClaimReasonPortCarriesNetwork) + + run.sw.FailReads(false) + run.sw.BeforeApply(func(physicalrealizer.Port, []physicalrealizer.Membership) { run.sw.FailReads(true) }) + require.ErrorIs(t, run.realize(), physicalrealizer.ErrSwitchUnreachable) + require.Empty(t, run.carried(), "the change landed") + require.True(t, s.hasDetachFinalizer("server-data"), "a change that cannot be read back proves nothing") + + run.sw.BeforeApply(nil) + run.sw.FailReads(false) + run.mustRealize() + require.False(t, s.hasDetachFinalizer("server-data")) +} + +// failingStatus fails every status write to the kind it names. +type failingStatus struct { + client.Client + kind client.Object +} + +type failingStatusWriter struct { + client.SubResourceWriter + kind client.Object +} + +var errStatusWrite = errors.New("status write refused") + +func (c failingStatus) Status() client.SubResourceWriter { + return failingStatusWriter{SubResourceWriter: c.Client.Status(), kind: c.kind} +} + +func (w failingStatusWriter) Update(ctx context.Context, obj client.Object, opts ...client.SubResourceUpdateOption) error { + if sameKind(obj, w.kind) { + return errStatusWrite + } + return w.SubResourceWriter.Update(ctx, obj, opts...) +} + +func (w failingStatusWriter) Patch(ctx context.Context, obj client.Object, patch client.Patch, opts ...client.SubResourcePatchOption) error { + if sameKind(obj, w.kind) { + return errStatusWrite + } + return w.SubResourceWriter.Patch(ctx, obj, patch, opts...) +} + +func sameKind(a, b client.Object) bool { + switch b.(type) { + case *networkingv1alpha.NetworkInterfaceClaim: + _, ok := a.(*networkingv1alpha.NetworkInterfaceClaim) + return ok + case *networkingv1alpha.NetworkInterface: + _, ok := a.(*networkingv1alpha.NetworkInterface) + return ok + } + return false +} + +func TestAFailedWithdrawalLeavesThePortAlone(t *testing.T) { + for name, kind := range map[string]client.Object{ + "claim": &networkingv1alpha.NetworkInterfaceClaim{}, + "interface": &networkingv1alpha.NetworkInterface{}, + } { + t.Run(name, func(t *testing.T) { + s := newScenario(t, true, ipv4Only) + run := s.realizedPort() + customer, provider := run.handoverPending() + carried := run.carried() + before := run.changes() + + run.realizer.Client = failingStatus{Client: s.client, kind: kind} + require.ErrorIs(t, run.realize(), errStatusWrite) + require.Equal(t, before, run.changes(), "the port is not touched when a withdrawal fails") + require.Equal(t, carried, run.carried()) + require.True(t, provider.hasDetachFinalizer("install-1-boot")) + + run.realizer.Client = s.client + run.mustRealize() + require.False(t, provider.hasDetachFinalizer("install-1-boot")) + customer.requireReported("server-data", metav1.ConditionTrue, networkingv1alpha.NetworkInterfaceClaimReasonPortCarriesNetwork) + }) + } +} + +func TestAPortNeverCarriesTwoProjectsOrBootWithCustomer(t *testing.T) { + customer := newScenario(t, true, ipv4Only) + run := customer.realizedPort() + provider := run.sibling(providerProject) + other := run.sibling(otherProject) + release := func(s *scenario, name string) { + t.Helper() + require.NoError(t, s.client.Delete(s.ctx, s.getClaim(name))) + s.reconcile(s.getClaim(name)) + run.mustRealize() + s.reconcile(s.getClaim(name)) + require.True(t, s.claimGone(name)) + } + + customer.bindPhysical("server-data", "") + waiting := other.createClaim("their-data", other.physicalSpec(realizedPort, "")) + other.reconcile(waiting) + other.requireWaiting("their-data") + run.mustRealize() + customer.requireReported("server-data", metav1.ConditionTrue, networkingv1alpha.NetworkInterfaceClaimReasonPortCarriesNetwork) + + provider.bindPhysical("reinstall-1-boot", networkingv1alpha.NetworkInterfacePurposeBoot) + run.mustRealize() + require.Equal(t, []types.NamespacedName{networkOf(provider)}, networksOf(run.carried())) + customer.requireReported("server-data", metav1.ConditionFalse, networkingv1alpha.NetworkInterfaceClaimReasonBootAttachmentActive) + + release(provider, "reinstall-1-boot") + require.Equal(t, []types.NamespacedName{networkOf(customer)}, networksOf(run.carried())) + + release(customer, "server-data") + require.Empty(t, run.carried()) + + other.reconcile(other.getClaim("their-data")) + other.requireBound("their-data") + run.mustRealize() + require.Equal(t, []types.NamespacedName{networkOf(other)}, networksOf(run.carried())) + other.requireReported("their-data", metav1.ConditionTrue, networkingv1alpha.NetworkInterfaceClaimReasonPortCarriesNetwork) + + release(other, "their-data") + provider.bindPhysical("wipe-1-boot", networkingv1alpha.NetworkInterfacePurposeBoot) + run.mustRealize() + require.Equal(t, []types.NamespacedName{networkOf(provider)}, networksOf(run.carried())) + + require.GreaterOrEqual(t, run.changes(), 6) + run.requireSafeHistory(networkOf(provider)) +} + +// claimCacheMissingDeletion answers claim reads the way a cache that has not +// seen a deletion yet does. +type claimCacheMissingDeletion struct { + client.Client +} + +func (c claimCacheMissingDeletion) Get(ctx context.Context, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if err := c.Client.Get(ctx, key, obj, opts...); err != nil { + return err + } + if claim, ok := obj.(*networkingv1alpha.NetworkInterfaceClaim); ok { + claim.DeletionTimestamp = nil + } + return nil +} + +func TestTheRealizerReadsFromTheAPIServer(t *testing.T) { + s := newScenario(t, true, ipv4Only) + run := s.realizedPort() + run.realizer.Client = staleHoldCache{claimCacheMissingDeletion{s.client}} + s.bindPhysical("server-data", "") + run.mustRealize() + require.Len(t, run.carried(), 1, "a hold the cache has not seen is still realized") + + require.NoError(t, s.client.Delete(s.ctx, s.getClaim("server-data"))) + s.reconcile(s.getClaim("server-data")) + run.mustRealize() + require.Empty(t, run.carried(), "a deletion the cache has not seen still takes the network off") + require.False(t, s.hasDetachFinalizer("server-data")) +} diff --git a/internal/networkagent/catalog.go b/internal/networkagent/catalog.go index 24a44eea..17e1ba34 100644 --- a/internal/networkagent/catalog.go +++ b/internal/networkagent/catalog.go @@ -580,8 +580,45 @@ func internetAccess(kind string) []ReasonInfo { } } +func switchPort(kind, prepared, programmed string) []ReasonInfo { + return []ReasonInfo{ + entry(kind, prepared, networkingv1alpha.NetworkInterfaceClaimReasonAttachmentPointAccepted, + healthy("The switch port this server's network interface is cabled to can be set up for its network.")), + entry(kind, programmed, networkingv1alpha.NetworkInterfaceClaimReasonPortCarriesNetwork, + healthy("The switch port this server's network interface is cabled to carries its network.")), + entry(kind, programmed, networkingv1alpha.NetworkInterfaceClaimReasonPortChanging, ReasonInfo{ + Actionability: ActionabilityTransient, + Scope: ScopeInstance, + Explanation: "The switch port this server's network interface is cabled to is being changed, so " + + "its network is not counted as carried until the change is confirmed.", + Remediation: remediationWait, + Skill: SkillInterfaceTriage, + ExpectedDuration: windowDataPlane, + }), + entry(kind, programmed, networkingv1alpha.NetworkInterfaceClaimReasonPortUnverified, ReasonInfo{ + Actionability: ActionabilityTransient, + Scope: ScopeInstance, + Explanation: "The platform could not confirm what the switch port this server's network interface " + + "is cabled to carries, so it keeps trying and holds the interface's addresses meanwhile.", + Remediation: remediationWait, + Skill: SkillInterfaceTriage, + ExpectedDuration: windowDataPlane, + }), + entry(kind, programmed, networkingv1alpha.NetworkInterfaceClaimReasonBootAttachmentActive, ReasonInfo{ + Actionability: ActionabilityInformational, + Explanation: "This server is being installed, so its switch port carries the install network " + + "instead of this network. The interface keeps its addresses, and the port moves to this " + + "network once the install finishes.", + }), + } +} + var interfaceCatalog = slices.Concat( claimRefusals(), + switchPort(KindNetworkInterfaceClaim, networkingv1alpha.NetworkInterfaceClaimPrepared, + networkingv1alpha.NetworkInterfaceClaimProgrammed), + switchPort(KindNetworkInterface, networkingv1alpha.NetworkInterfacePrepared, + networkingv1alpha.NetworkInterfaceProgrammed), internetAccess(KindNetworkInterface), internetAccess(KindNetworkInterfaceClaim), interfaceProgress(KindNetworkInterfaceClaim, networkingv1alpha.NetworkInterfaceClaimAllocated, diff --git a/internal/physicalrealizer/driver.go b/internal/physicalrealizer/driver.go new file mode 100644 index 00000000..e42bc721 --- /dev/null +++ b/internal/physicalrealizer/driver.go @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +// Package physicalrealizer is a test realizer for physical network interfaces. +// It programs switch ports from SwitchPortHolds through a Driver, and follows +// the same contract a production realizer must. +package physicalrealizer + +import ( + "context" + "slices" + "strings" + + "k8s.io/apimachinery/pkg/types" + + networkingv1alpha "go.datum.net/network-services-operator/api/v1alpha" +) + +// Port is one switch port, in the names network operations uses for it. +type Port struct { + Switch string + Name string +} + +// Membership is one network a port carries. A VLAN of zero means the network +// arrives untagged. +type Membership struct { + Network types.NamespacedName + VLAN int32 + Isolation networkingv1alpha.NetworkInterfaceIsolation +} + +// Driver changes and reads one switch port at a time. Apply replaces +// everything the port carries in one change. Read reports what the port +// carries now, which is the only proof a change took effect. +type Driver interface { + Apply(ctx context.Context, port Port, desired []Membership) error + Read(ctx context.Context, port Port) ([]Membership, error) +} + +func sortedMemberships(memberships []Membership) []Membership { + sorted := slices.Clone(memberships) + slices.SortFunc(sorted, func(a, b Membership) int { + return strings.Compare(a.Network.String(), b.Network.String()) + }) + return sorted +} + +func sameMemberships(a, b []Membership) bool { + return slices.Equal(sortedMemberships(a), sortedMemberships(b)) +} + +func membershipOf(memberships []Membership, network types.NamespacedName) (Membership, bool) { + index := slices.IndexFunc(memberships, func(m Membership) bool { return m.Network == network }) + if index < 0 { + return Membership{}, false + } + return memberships[index], true +} diff --git a/internal/physicalrealizer/plan.go b/internal/physicalrealizer/plan.go new file mode 100644 index 00000000..a6e902e5 --- /dev/null +++ b/internal/physicalrealizer/plan.go @@ -0,0 +1,161 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +package physicalrealizer + +import ( + "hash/fnv" + + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + + networkingv1alpha "go.datum.net/network-services-operator/api/v1alpha" +) + +const ( + firstSimulatedVLAN = 2 + simulatedVLANs = maxVLAN - firstSimulatedVLAN + 1 +) + +// recorded is one entry of a hold, and the claim it names if one exists. +type recorded struct { + entry networkingv1alpha.SwitchPortHoldClaimRef + boot bool + claim *networkingv1alpha.NetworkInterfaceClaim +} + +func (r recorded) network() types.NamespacedName { + return types.NamespacedName{Namespace: r.entry.Namespace, Name: r.entry.Network} +} + +// networks are every network the port may carry for this entry: the one the +// hold recorded, and the one a claim of the entry's name names now. +func (r recorded) networks() []types.NamespacedName { + networks := []types.NamespacedName{r.network()} + if r.claim != nil && r.claim.Spec.Network.Name != r.entry.Network { + networks = append(networks, types.NamespacedName{Namespace: r.entry.Namespace, Name: r.claim.Spec.Network.Name}) + } + return networks +} + +func (r recorded) onPort(hold *networkingv1alpha.SwitchPortHold) bool { + claim := r.claim + return claim != nil && + claim.Spec.AttachmentMode == networkingv1alpha.NetworkInterfaceAttachmentModePhysical && + claim.Spec.AttachmentPoint != nil && + claim.Spec.AttachmentPoint.Switch == hold.Spec.Switch && + claim.Spec.AttachmentPoint.Port == hold.Spec.Port && + controllerutil.ContainsFinalizer(claim, networkingv1alpha.NetworkInterfaceClaimDetachFinalizer) +} + +// counts reports whether the port may carry the entry's network: the claim is +// recorded as it is, still carries the detach finalizer, and is not being +// deleted. +func (r recorded) counts(hold *networkingv1alpha.SwitchPortHold) bool { + return r.onPort(hold) && + r.claim.DeletionTimestamp.IsZero() && + r.claim.Spec.Network.Name == r.entry.Network && + (r.claim.Spec.Purpose == networkingv1alpha.NetworkInterfacePurposeBoot) == r.boot +} + +// releasing reports whether the claim waits on the realizer to take its +// network off the port. +func (r recorded) releasing(hold *networkingv1alpha.SwitchPortHold) bool { + return r.onPort(hold) && !r.claim.DeletionTimestamp.IsZero() +} + +func (r recorded) isolation() networkingv1alpha.NetworkInterfaceIsolation { + if r.claim.Spec.Isolation != "" { + return r.claim.Spec.Isolation + } + if r.boot { + return networkingv1alpha.NetworkInterfaceIsolationPrivate + } + return networkingv1alpha.NetworkInterfaceIsolationShared +} + +// plan is what a port carries, worked out from its hold. +type plan struct { + boot *recorded + + // networks are the counted network claims and what each would arrive on. + // They keep their VLANs while a boot claim holds the port, so a server + // being installed can be configured for them. + networks []assigned +} + +type assigned struct { + recorded + membership Membership +} + +func planFor(hold *networkingv1alpha.SwitchPortHold, entries []recorded) plan { + var p plan + used := map[int32]bool{} + for i := range entries { + entry := entries[i] + if !entry.counts(hold) { + continue + } + if entry.boot { + p.boot = &entry + continue + } + membership := Membership{Network: entry.network(), Isolation: entry.isolation()} + if len(p.networks) > 0 { + membership.VLAN = simulatedVLAN(entry.network(), used) + } + p.networks = append(p.networks, assigned{recorded: entry, membership: membership}) + } + return p +} + +func (p plan) carried() []Membership { + if p.boot != nil { + return []Membership{{Network: p.boot.network(), Isolation: p.boot.isolation()}} + } + if len(p.networks) == 0 { + return nil + } + carried := make([]Membership, 0, len(p.networks)) + for _, network := range p.networks { + carried = append(carried, network.membership) + } + return carried +} + +func simulatedVLAN(network types.NamespacedName, used map[int32]bool) int32 { + hash := fnv.New32a() + _, _ = hash.Write([]byte(network.String())) + offset := hash.Sum32() % simulatedVLANs + for range simulatedVLANs { + vlan := firstSimulatedVLAN + int32(offset) + if !used[vlan] { + used[vlan] = true + return vlan + } + offset = (offset + 1) % simulatedVLANs + } + return 0 +} + +// changes reports whether moving the port from current to desired adds, +// removes or alters any network the entry may be carried on. +func (r recorded) changes(current, desired []Membership) bool { + for _, network := range r.networks() { + before, wasCarried := membershipOf(current, network) + after, isCarried := membershipOf(desired, network) + if wasCarried != isCarried || before != after { + return true + } + } + return false +} + +func (r recorded) carriedOn(carried []Membership) bool { + for _, network := range r.networks() { + if _, ok := membershipOf(carried, network); ok { + return true + } + } + return false +} diff --git a/internal/physicalrealizer/plan_test.go b/internal/physicalrealizer/plan_test.go new file mode 100644 index 00000000..83a23db8 --- /dev/null +++ b/internal/physicalrealizer/plan_test.go @@ -0,0 +1,241 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +package physicalrealizer + +import ( + "context" + "slices" + "testing" + + "github.com/stretchr/testify/require" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + ctrl "sigs.k8s.io/controller-runtime" + + networkingv1alpha "go.datum.net/network-services-operator/api/v1alpha" +) + +const ( + testSwitch = "rack-a1-tor-1" + testPort = "Ethernet1/12" +) + +func testHold() *networkingv1alpha.SwitchPortHold { + hold := &networkingv1alpha.SwitchPortHold{} + hold.Name = networkingv1alpha.SwitchPortHoldName(testSwitch, testPort) + hold.Spec.Switch = testSwitch + hold.Spec.Port = testPort + return hold +} + +func physicalClaim(namespace, name, network string, purpose networkingv1alpha.NetworkInterfacePurpose) *networkingv1alpha.NetworkInterfaceClaim { + claim := &networkingv1alpha.NetworkInterfaceClaim{} + claim.Namespace = namespace + claim.Name = name + claim.Finalizers = []string{networkingv1alpha.NetworkInterfaceClaimDetachFinalizer} + claim.Spec.Network.Name = network + claim.Spec.AttachmentMode = networkingv1alpha.NetworkInterfaceAttachmentModePhysical + claim.Spec.AttachmentPoint = &networkingv1alpha.NetworkInterfaceAttachmentPoint{ + MACAddress: "00:00:5e:00:53:01", Switch: testSwitch, Port: testPort, + } + claim.Spec.Purpose = purpose + return claim +} + +func entryFor(claim *networkingv1alpha.NetworkInterfaceClaim, boot bool) recorded { + return recorded{ + entry: networkingv1alpha.SwitchPortHoldClaimRef{ + Namespace: claim.Namespace, Name: claim.Name, Network: claim.Spec.Network.Name, + }, + boot: boot, + claim: claim, + } +} + +func network(namespace, name string) types.NamespacedName { + return types.NamespacedName{Namespace: namespace, Name: name} +} + +func TestABootClaimCarriesItsNetworkAloneAndUntagged(t *testing.T) { + boot := entryFor(physicalClaim("ns-provider-example", "install-1-boot", "boot", networkingv1alpha.NetworkInterfacePurposeBoot), true) + data := entryFor(physicalClaim("ns-customer-example", "server-data", "app", ""), false) + storage := entryFor(physicalClaim("ns-customer-example", "server-storage", "storage", ""), false) + + p := planFor(testHold(), []recorded{boot, data, storage}) + require.Equal(t, []Membership{{ + Network: network("ns-provider-example", "boot"), Isolation: networkingv1alpha.NetworkInterfaceIsolationPrivate, + }}, p.carried()) + require.Len(t, p.networks, 2, "network claims keep their VLANs while the boot claim holds the port") + require.Zero(t, p.networks[0].membership.VLAN) + require.NotZero(t, p.networks[1].membership.VLAN) +} + +func TestNetworkClaimsAreOneUntaggedAndTheRestTagged(t *testing.T) { + names := []string{"app", "storage", "backup", "metrics"} + entries := make([]recorded, 0, len(names)) + for _, name := range names { + entries = append(entries, entryFor(physicalClaim("ns-customer-example", "server-"+name, name, ""), false)) + } + + carried := planFor(testHold(), entries).carried() + require.Len(t, carried, 4) + require.Equal(t, network("ns-customer-example", "app"), carried[0].Network) + require.Zero(t, carried[0].VLAN, "the first network claim recorded arrives untagged") + seen := map[int32]bool{} + for _, m := range carried[1:] { + require.GreaterOrEqual(t, m.VLAN, int32(firstSimulatedVLAN)) + require.LessOrEqual(t, m.VLAN, int32(maxVLAN)) + require.False(t, seen[m.VLAN], "VLAN %d is used twice", m.VLAN) + seen[m.VLAN] = true + require.Equal(t, networkingv1alpha.NetworkInterfaceIsolationShared, m.Isolation) + } + require.NoError(t, validMemberships(carried)) + require.Equal(t, carried, planFor(testHold(), entries).carried(), "the VLANs are deterministic") +} + +func TestSimulatedVLANsProbePastACollision(t *testing.T) { + used := map[int32]bool{} + first := simulatedVLAN(network("ns-customer-example", "app"), used) + second := simulatedVLAN(network("ns-customer-example", "app"), used) + require.NotEqual(t, first, second) + require.Equal(t, first, simulatedVLAN(network("ns-customer-example", "app"), map[int32]bool{})) + + full := map[int32]bool{} + for vlan := int32(firstSimulatedVLAN); vlan < maxVLAN; vlan++ { + full[vlan] = true + } + require.Equal(t, int32(maxVLAN), simulatedVLAN(network("ns-customer-example", "app"), full)) +} + +func TestIsolationFollowsPurposeUnlessSet(t *testing.T) { + boot := entryFor(physicalClaim("ns-provider-example", "install-1-boot", "boot", networkingv1alpha.NetworkInterfacePurposeBoot), true) + require.Equal(t, networkingv1alpha.NetworkInterfaceIsolationPrivate, boot.isolation()) + boot.claim.Spec.Isolation = networkingv1alpha.NetworkInterfaceIsolationShared + require.Equal(t, networkingv1alpha.NetworkInterfaceIsolationShared, boot.isolation()) + + data := entryFor(physicalClaim("ns-customer-example", "server-data", "app", ""), false) + require.Equal(t, networkingv1alpha.NetworkInterfaceIsolationShared, data.isolation()) + data.claim.Spec.Isolation = networkingv1alpha.NetworkInterfaceIsolationPrivate + require.Equal(t, networkingv1alpha.NetworkInterfaceIsolationPrivate, data.isolation()) +} + +func TestOnlyCountedClaimsAreCarried(t *testing.T) { + deleting := physicalClaim("ns-customer-example", "server-data", "app", "") + deleting.DeletionTimestamp = ptrTo(metav1.Now()) + noFinalizer := physicalClaim("ns-customer-example", "server-data", "app", "") + noFinalizer.Finalizers = nil + otherPort := physicalClaim("ns-customer-example", "server-data", "app", "") + otherPort.Spec.AttachmentPoint.Port = "Ethernet1/13" + otherSwitch := physicalClaim("ns-customer-example", "server-data", "app", "") + otherSwitch.Spec.AttachmentPoint.Switch = "rack-a1-tor-2" + renamed := entryFor(physicalClaim("ns-customer-example", "server-data", "app", ""), false) + renamed.entry.Network = "retired" + notPhysical := physicalClaim("ns-customer-example", "server-data", "app", "") + notPhysical.Spec.AttachmentMode = networkingv1alpha.NetworkInterfaceAttachmentModeNetns + + for name, entry := range map[string]recorded{ + "being deleted": entryFor(deleting, false), + "without the detach finalizer": entryFor(noFinalizer, false), + "on another port": entryFor(otherPort, false), + "on another switch": entryFor(otherSwitch, false), + "naming another network": renamed, + "in another mode": entryFor(notPhysical, false), + "gone": {entry: renamed.entry}, + "a boot claim in a network slot": entryFor(physicalClaim("ns-customer-example", "server-data", "app", networkingv1alpha.NetworkInterfacePurposeBoot), false), + "a network claim in the boot slot": entryFor(physicalClaim("ns-customer-example", "server-data", "app", ""), true), + } { + t.Run(name, func(t *testing.T) { + require.False(t, entry.counts(testHold())) + require.Empty(t, planFor(testHold(), []recorded{entry}).carried()) + }) + } +} + +func TestADeletedClaimIsReleasingUntilItsNetworksAreOff(t *testing.T) { + claim := physicalClaim("ns-customer-example", "server-data", "app", "") + claim.DeletionTimestamp = ptrTo(metav1.Now()) + entry := entryFor(claim, false) + entry.entry.Network = "retired" + require.True(t, entry.releasing(testHold())) + + require.True(t, entry.carriedOn([]Membership{{Network: network("ns-customer-example", "retired")}}), + "the network the hold recorded may still be on the port") + require.True(t, entry.carriedOn([]Membership{{Network: network("ns-customer-example", "app")}}), + "so may the network the claim names") + require.False(t, entry.carriedOn([]Membership{{Network: network("ns-other-example", "app")}})) + + claim.Finalizers = nil + require.False(t, entry.releasing(testHold()), "a claim without the detach finalizer waits on nothing here") +} + +func TestAChangeTouchesClaimsWhoseNetworkMoves(t *testing.T) { + data := entryFor(physicalClaim("ns-customer-example", "server-data", "app", ""), false) + untagged := []Membership{{Network: network("ns-customer-example", "app")}} + tagged := []Membership{{Network: network("ns-customer-example", "app"), VLAN: 100}} + other := []Membership{{Network: network("ns-customer-example", "storage")}} + + require.True(t, data.changes(nil, untagged)) + require.True(t, data.changes(untagged, nil)) + require.True(t, data.changes(untagged, tagged)) + require.False(t, data.changes(untagged, append(slices.Clone(untagged), other[0]))) + require.False(t, data.changes(nil, other)) +} + +func TestTheSimulatedSwitchRecordsAndFails(t *testing.T) { + ctx := context.Background() + sw := NewSimulatedSwitch() + port := Port{Switch: testSwitch, Name: testPort} + app := Membership{Network: network("ns-customer-example", "app")} + storage := Membership{Network: network("ns-customer-example", "storage"), VLAN: 100} + + require.NoError(t, sw.Apply(ctx, port, []Membership{app})) + sw.FailApplies(1) + require.ErrorIs(t, sw.Apply(ctx, port, nil), ErrSwitchUnreachable) + require.Equal(t, []Membership{app}, sw.Carried(port), "a failed change leaves the port alone") + + sw.PartlyApply(1) + require.NoError(t, sw.Apply(ctx, port, []Membership{storage})) + carried, err := sw.Read(ctx, port) + require.NoError(t, err) + require.Empty(t, carried, "a partial change takes networks off and adds none") + + sw.FailReads(true) + _, err = sw.Read(ctx, port) + require.ErrorIs(t, err, ErrSwitchUnreachable) + sw.FailReads(false) + + require.Error(t, sw.Apply(ctx, port, []Membership{app, {Network: network("ns-customer-example", "storage")}}), + "two untagged networks are refused") + require.Error(t, sw.Apply(ctx, port, []Membership{app, app})) + require.Error(t, sw.Apply(ctx, port, []Membership{{Network: app.Network, VLAN: maxVLAN + 1}})) + + require.Equal(t, []Change{{Port: port, Carried: []Membership{app}}, {Port: port, Carried: []Membership{}}}, sw.History()) +} + +func TestClaimsAndInterfacesWakeTheirPortsHold(t *testing.T) { + claim := physicalClaim("ns-customer-example", "server-data", "app", "") + want := []string{networkingv1alpha.SwitchPortHoldName(testSwitch, testPort)} + names := func(requests []ctrl.Request) []string { + out := make([]string, 0, len(requests)) + for _, request := range requests { + out = append(out, request.Name) + } + return out + } + require.Equal(t, want, names(holdForClaim(context.Background(), claim))) + + iface := &networkingv1alpha.NetworkInterface{} + iface.Spec.AttachmentMode = networkingv1alpha.NetworkInterfaceAttachmentModePhysical + iface.Spec.AttachmentPoint = claim.Spec.AttachmentPoint + require.Equal(t, want, names(holdForInterface(context.Background(), iface))) + + claim.Spec.AttachmentMode = networkingv1alpha.NetworkInterfaceAttachmentModeNetns + require.Empty(t, holdForClaim(context.Background(), claim)) + require.Empty(t, holdForInterface(context.Background(), &networkingv1alpha.NetworkInterface{})) +} + +func TestSetupNeedsADriver(t *testing.T) { + require.Error(t, (&Reconciler{}).SetupWithManager(nil)) +} + +func ptrTo[T any](v T) *T { return &v } diff --git a/internal/physicalrealizer/reconciler.go b/internal/physicalrealizer/reconciler.go new file mode 100644 index 00000000..44ce62c9 --- /dev/null +++ b/internal/physicalrealizer/reconciler.go @@ -0,0 +1,324 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +package physicalrealizer + +import ( + "context" + "errors" + "fmt" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + apimeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + "sigs.k8s.io/controller-runtime/pkg/handler" + + networkingv1alpha "go.datum.net/network-services-operator/api/v1alpha" +) + +// ControllerName is the name the realizer registers under. +const ControllerName = "physical-realizer" + +// maxChangesPerPass bounds how often one pass changes a port again because +// its claims changed while it was changing it. +const maxChangesPerPass = 4 + +// Reconciler programs one switch port per SwitchPortHold. +type Reconciler struct { + Client client.Client + + // APIReader reads holds, claims and interfaces. It must not be a cache: a + // claim whose deletion the cache has not seen yet would be kept on its + // port, and one whose hold entry the cache has not seen would be dropped. + APIReader client.Reader + + Driver Driver +} + +// +kubebuilder:rbac:groups=networking.datumapis.com,resources=switchportholds,verbs=get;list;watch +// +kubebuilder:rbac:groups=networking.datumapis.com,resources=networkinterfaceclaims,verbs=get;list;watch;update;patch +// +kubebuilder:rbac:groups=networking.datumapis.com,resources=networkinterfaceclaims/status,verbs=get;update;patch +// +kubebuilder:rbac:groups=networking.datumapis.com,resources=networkinterfaceclaims/finalizers,verbs=update +// +kubebuilder:rbac:groups=networking.datumapis.com,resources=networkinterfaces,verbs=get;list;watch +// +kubebuilder:rbac:groups=networking.datumapis.com,resources=networkinterfaces/status,verbs=get;update;patch + +func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + hold := &networkingv1alpha.SwitchPortHold{} + if err := r.APIReader.Get(ctx, req.NamespacedName, hold); err != nil { + return ctrl.Result{}, client.IgnoreNotFound(err) + } + port := Port{Switch: hold.Spec.Switch, Name: hold.Spec.Port} + + carried, err := r.Driver.Read(ctx, port) + if err != nil { + return ctrl.Result{}, fmt.Errorf("failed reading switch port %s %s: %w", port.Switch, port.Name, err) + } + + for range maxChangesPerPass { + entries, err := r.observe(ctx, req.NamespacedName, hold) + if err != nil { + return ctrl.Result{}, err + } + desired := planFor(hold, entries).carried() + if sameMemberships(carried, desired) { + return ctrl.Result{}, r.settle(ctx, hold, entries, carried) + } + + if err := r.withdraw(ctx, hold, entries, carried, desired); err != nil { + return ctrl.Result{}, err + } + applyErr := r.Driver.Apply(ctx, port, desired) + readBack, err := r.Driver.Read(ctx, port) + if err != nil { + return ctrl.Result{}, errors.Join(applyErr, + fmt.Errorf("failed reading switch port %s %s back: %w", port.Switch, port.Name, err)) + } + if applyErr != nil { + return ctrl.Result{}, fmt.Errorf("failed changing switch port %s %s: %w", port.Switch, port.Name, applyErr) + } + if !sameMemberships(readBack, desired) { + return ctrl.Result{}, fmt.Errorf("switch port %s %s reads back %v after a change to %v", + port.Switch, port.Name, readBack, desired) + } + carried = readBack + } + return ctrl.Result{Requeue: true}, nil +} + +// observe reads the hold and every claim it records again, from the API +// server. A hold that is gone records nothing, so its port carries nothing. +func (r *Reconciler) observe( + ctx context.Context, + key client.ObjectKey, + hold *networkingv1alpha.SwitchPortHold, +) ([]recorded, error) { + if err := r.APIReader.Get(ctx, key, hold); err != nil { + if apierrors.IsNotFound(err) { + hold.Spec.Boot = nil + hold.Spec.NetworkClaims = nil + return nil, nil + } + return nil, fmt.Errorf("failed reading switch port hold %s: %w", key.Name, err) + } + + entries := make([]recorded, 0, len(hold.Spec.NetworkClaims)+1) + if hold.Spec.Boot != nil { + entries = append(entries, recorded{entry: *hold.Spec.Boot, boot: true}) + } + for _, entry := range hold.Spec.NetworkClaims { + entries = append(entries, recorded{entry: entry}) + } + for i := range entries { + claim := &networkingv1alpha.NetworkInterfaceClaim{} + claimKey := client.ObjectKey{Namespace: entries[i].entry.Namespace, Name: entries[i].entry.Name} + if err := r.APIReader.Get(ctx, claimKey, claim); err != nil { + if apierrors.IsNotFound(err) { + continue + } + return nil, fmt.Errorf("failed reading claim %s recorded on switch port hold %s: %w", claimKey, key.Name, err) + } + entries[i].claim = claim + } + return entries, nil +} + +// withdraw reports every claim the change touches as not programmed before +// the port moves, so none reports a port that is between states. +func (r *Reconciler) withdraw( + ctx context.Context, + hold *networkingv1alpha.SwitchPortHold, + entries []recorded, + current, desired []Membership, +) error { + for _, entry := range entries { + if !entry.onPort(hold) || !entry.changes(current, desired) { + continue + } + condition := metav1.Condition{ + Type: networkingv1alpha.NetworkInterfaceClaimProgrammed, + Status: metav1.ConditionFalse, + Reason: networkingv1alpha.NetworkInterfaceClaimReasonPortChanging, + Message: "The switch port is changing and is not confirmed to carry this network", + } + if err := r.report(ctx, entry.claim, nil, false, condition); err != nil { + return fmt.Errorf("failed withdrawing claim %s/%s before changing its port: %w", + entry.claim.Namespace, entry.claim.Name, err) + } + } + return nil +} + +// settle runs once the port is read back carrying what its hold asks for. +func (r *Reconciler) settle( + ctx context.Context, + hold *networkingv1alpha.SwitchPortHold, + entries []recorded, + carried []Membership, +) error { + for _, entry := range entries { + if !entry.releasing(hold) || entry.carriedOn(carried) { + continue + } + claim := entry.claim + controllerutil.RemoveFinalizer(claim, networkingv1alpha.NetworkInterfaceClaimDetachFinalizer) + if err := r.Client.Update(ctx, claim); err != nil && !apierrors.IsNotFound(err) { + return fmt.Errorf("failed removing the detach finalizer from claim %s/%s: %w", claim.Namespace, claim.Name, err) + } + } + + p := planFor(hold, entries) + if p.boot != nil { + if err := r.report(ctx, p.boot.claim, nil, true, carriesNetwork()); err != nil { + return err + } + } + for _, network := range p.networks { + programmed := carriesNetwork() + if p.boot != nil { + programmed = metav1.Condition{ + Type: networkingv1alpha.NetworkInterfaceClaimProgrammed, + Status: metav1.ConditionFalse, + Reason: networkingv1alpha.NetworkInterfaceClaimReasonBootAttachmentActive, + Message: "A boot claim holds the switch port, so the port carries the boot network instead", + } + } + var vlan *int32 + if network.membership.VLAN != 0 { + vlan = &network.membership.VLAN + } + if err := r.report(ctx, network.claim, vlan, true, programmed); err != nil { + return err + } + } + return nil +} + +func carriesNetwork() metav1.Condition { + return metav1.Condition{ + Type: networkingv1alpha.NetworkInterfaceClaimProgrammed, + Status: metav1.ConditionTrue, + Reason: networkingv1alpha.NetworkInterfaceClaimReasonPortCarriesNetwork, + Message: "The switch port carries this network, as read back from the switch", + } +} + +func prepared() metav1.Condition { + return metav1.Condition{ + Type: networkingv1alpha.NetworkInterfaceClaimPrepared, + Status: metav1.ConditionTrue, + Reason: networkingv1alpha.NetworkInterfaceClaimReasonAttachmentPointAccepted, + Message: "The switch port is accepted and its segment can be built", + } +} + +// report writes programmed, and with settled also Prepared and the VLAN, on +// the claim and on the interface bound to it. The interface goes first, so a +// provider reading the claim never sees more than the interface says. +func (r *Reconciler) report( + ctx context.Context, + claim *networkingv1alpha.NetworkInterfaceClaim, + vlan *int32, + settled bool, + programmed metav1.Condition, +) error { + if ref := claim.Status.NetworkInterfaceRef; ref != nil { + iface := &networkingv1alpha.NetworkInterface{} + err := r.APIReader.Get(ctx, client.ObjectKey{Namespace: claim.Namespace, Name: ref.Name}, iface) + switch { + case apierrors.IsNotFound(err): + case err != nil: + return fmt.Errorf("failed reading interface %s/%s: %w", claim.Namespace, ref.Name, err) + case iface.Spec.ClaimRef != nil && iface.Spec.ClaimRef.Name == claim.Name: + changed := false + if settled { + changed = setVLAN(&iface.Status.VLANID, vlan) + changed = setCondition(&iface.Status.Conditions, prepared(), iface.Generation) || changed + } + changed = setCondition(&iface.Status.Conditions, programmed, iface.Generation) || changed + if changed { + if err := r.Client.Status().Update(ctx, iface); err != nil && !apierrors.IsNotFound(err) { + return fmt.Errorf("failed updating interface %s/%s status: %w", iface.Namespace, iface.Name, err) + } + } + } + } + + changed := false + if settled { + changed = setVLAN(&claim.Status.VLANID, vlan) + changed = setCondition(&claim.Status.Conditions, prepared(), claim.Generation) || changed + } + changed = setCondition(&claim.Status.Conditions, programmed, claim.Generation) || changed + if !changed { + return nil + } + if err := r.Client.Status().Update(ctx, claim); err != nil && !apierrors.IsNotFound(err) { + return fmt.Errorf("failed updating claim %s/%s status: %w", claim.Namespace, claim.Name, err) + } + return nil +} + +func setCondition(conditions *[]metav1.Condition, condition metav1.Condition, generation int64) bool { + condition.ObservedGeneration = generation + return apimeta.SetStatusCondition(conditions, condition) +} + +func setVLAN(field **int32, vlan *int32) bool { + if (*field == nil) == (vlan == nil) && (vlan == nil || **field == *vlan) { + return false + } + if vlan == nil { + *field = nil + return true + } + value := *vlan + *field = &value + return true +} + +func holdForAttachmentPoint(point *networkingv1alpha.NetworkInterfaceAttachmentPoint) []ctrl.Request { + if point == nil { + return nil + } + return []ctrl.Request{{NamespacedName: client.ObjectKey{ + Name: networkingv1alpha.SwitchPortHoldName(point.Switch, point.Port), + }}} +} + +func holdForClaim(_ context.Context, obj client.Object) []ctrl.Request { + claim, ok := obj.(*networkingv1alpha.NetworkInterfaceClaim) + if !ok || claim.Spec.AttachmentMode != networkingv1alpha.NetworkInterfaceAttachmentModePhysical { + return nil + } + return holdForAttachmentPoint(claim.Spec.AttachmentPoint) +} + +func holdForInterface(_ context.Context, obj client.Object) []ctrl.Request { + iface, ok := obj.(*networkingv1alpha.NetworkInterface) + if !ok || iface.Spec.AttachmentMode != networkingv1alpha.NetworkInterfaceAttachmentModePhysical { + return nil + } + return holdForAttachmentPoint(iface.Spec.AttachmentPoint) +} + +// SetupWithManager registers the realizer. A claim being deleted or bound, +// and an interface being bound, wakes the hold of the port they name. +func (r *Reconciler) SetupWithManager(mgr ctrl.Manager) error { + if r.Driver == nil { + return errors.New("a switch driver is required") + } + if r.Client == nil { + r.Client = mgr.GetClient() + } + if r.APIReader == nil { + r.APIReader = mgr.GetAPIReader() + } + return ctrl.NewControllerManagedBy(mgr). + For(&networkingv1alpha.SwitchPortHold{}). + Watches(&networkingv1alpha.NetworkInterfaceClaim{}, handler.EnqueueRequestsFromMapFunc(holdForClaim)). + Watches(&networkingv1alpha.NetworkInterface{}, handler.EnqueueRequestsFromMapFunc(holdForInterface)). + Named(ControllerName). + Complete(r) +} diff --git a/internal/physicalrealizer/reconciler_test.go b/internal/physicalrealizer/reconciler_test.go new file mode 100644 index 00000000..e6ca09c7 --- /dev/null +++ b/internal/physicalrealizer/reconciler_test.go @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +package physicalrealizer + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + + networkingv1alpha "go.datum.net/network-services-operator/api/v1alpha" +) + +func TestADeletedClaimWhoseNetworkIsStillCarriedKeepsItsFinalizer(t *testing.T) { + ctx := context.Background() + scheme := runtime.NewScheme() + require.NoError(t, networkingv1alpha.AddToScheme(scheme)) + + data := physicalClaim("ns-customer-example", "server-data", "app", "") + leaving := physicalClaim("ns-customer-example", "server-data-old", "app", "") + leaving.DeletionTimestamp = ptrTo(metav1.Now()) + hold := testHold() + hold.Spec.ConsumerRef = &networkingv1alpha.SwitchPortHoldConsumerRef{ + APIGroup: "resourcemanager.miloapis.com", Kind: "Project", Name: "customer-example", + } + hold.Spec.NetworkClaims = []networkingv1alpha.SwitchPortHoldClaimRef{ + {Namespace: data.Namespace, Name: data.Name, Network: "app"}, + {Namespace: leaving.Namespace, Name: leaving.Name, Network: "retired"}, + } + + cl := fake.NewClientBuilder().WithScheme(scheme). + WithObjects(hold, data, leaving). + WithStatusSubresource(&networkingv1alpha.NetworkInterfaceClaim{}, &networkingv1alpha.NetworkInterface{}). + Build() + sw := NewSimulatedSwitch() + r := &Reconciler{Client: cl, APIReader: cl, Driver: sw} + + _, err := r.Reconcile(ctx, ctrl.Request{NamespacedName: client.ObjectKeyFromObject(hold)}) + require.NoError(t, err) + require.Equal(t, []Membership{{Network: network("ns-customer-example", "app"), + Isolation: networkingv1alpha.NetworkInterfaceIsolationShared}}, sw.Carried(Port{Switch: testSwitch, Name: testPort})) + + var stored networkingv1alpha.NetworkInterfaceClaim + require.NoError(t, cl.Get(ctx, client.ObjectKeyFromObject(leaving), &stored)) + require.True(t, controllerutil.ContainsFinalizer(&stored, networkingv1alpha.NetworkInterfaceClaimDetachFinalizer), + "the port still carries the network the deleted claim names") +} diff --git a/internal/physicalrealizer/simulated.go b/internal/physicalrealizer/simulated.go new file mode 100644 index 00000000..c7ea5e7a --- /dev/null +++ b/internal/physicalrealizer/simulated.go @@ -0,0 +1,154 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +package physicalrealizer + +import ( + "context" + "errors" + "fmt" + "slices" + "sync" +) + +const maxVLAN = 4094 + +// ErrSwitchUnreachable is what a simulated switch told to fail returns. +var ErrSwitchUnreachable = errors.New("simulated switch is unreachable") + +// Change is one state a simulated port reached. +type Change struct { + Port Port + Carried []Membership +} + +// SimulatedSwitch is an in-memory Driver. Its hooks make a change fail, apply +// only partly, or make reads fail, and it records every state a port reaches. +type SimulatedSwitch struct { + mu sync.Mutex + ports map[Port][]Membership + history []Change + failedApplies int + partialApplies int + failReads bool + beforeApply func(Port, []Membership) +} + +var _ Driver = (*SimulatedSwitch)(nil) + +func NewSimulatedSwitch() *SimulatedSwitch { + return &SimulatedSwitch{ports: map[Port][]Membership{}} +} + +// FailApplies makes the next n changes fail without touching the port. +func (s *SimulatedSwitch) FailApplies(n int) { + s.mu.Lock() + defer s.mu.Unlock() + s.failedApplies = n +} + +// PartlyApply makes the next n changes take networks off the port and add +// none, while reporting success. +func (s *SimulatedSwitch) PartlyApply(n int) { + s.mu.Lock() + defer s.mu.Unlock() + s.partialApplies = n +} + +// FailReads makes every read fail until it is called with false. +func (s *SimulatedSwitch) FailReads(fail bool) { + s.mu.Lock() + defer s.mu.Unlock() + s.failReads = fail +} + +// BeforeApply runs hook at the start of every change, before the port moves. +func (s *SimulatedSwitch) BeforeApply(hook func(Port, []Membership)) { + s.mu.Lock() + defer s.mu.Unlock() + s.beforeApply = hook +} + +// Carried reports what port carries, without the read hooks. +func (s *SimulatedSwitch) Carried(port Port) []Membership { + s.mu.Lock() + defer s.mu.Unlock() + return slices.Clone(s.ports[port]) +} + +// History returns every state any port reached, in order. +func (s *SimulatedSwitch) History() []Change { + s.mu.Lock() + defer s.mu.Unlock() + history := make([]Change, 0, len(s.history)) + for _, change := range s.history { + history = append(history, Change{Port: change.Port, Carried: slices.Clone(change.Carried)}) + } + return history +} + +func (s *SimulatedSwitch) Apply(_ context.Context, port Port, desired []Membership) error { + s.mu.Lock() + hook := s.beforeApply + s.mu.Unlock() + if hook != nil { + hook(port, slices.Clone(desired)) + } + + if err := validMemberships(desired); err != nil { + return err + } + + s.mu.Lock() + defer s.mu.Unlock() + if s.failedApplies > 0 { + s.failedApplies-- + return fmt.Errorf("changing %s %s: %w", port.Switch, port.Name, ErrSwitchUnreachable) + } + carried := sortedMemberships(desired) + if s.partialApplies > 0 { + s.partialApplies-- + current := s.ports[port] + carried = slices.DeleteFunc(carried, func(m Membership) bool { return !slices.Contains(current, m) }) + } + if len(carried) == 0 { + delete(s.ports, port) + } else { + s.ports[port] = carried + } + s.history = append(s.history, Change{Port: port, Carried: slices.Clone(carried)}) + return nil +} + +func (s *SimulatedSwitch) Read(_ context.Context, port Port) ([]Membership, error) { + s.mu.Lock() + defer s.mu.Unlock() + if s.failReads { + return nil, fmt.Errorf("reading %s %s: %w", port.Switch, port.Name, ErrSwitchUnreachable) + } + return slices.Clone(s.ports[port]), nil +} + +func validMemberships(memberships []Membership) error { + untagged := 0 + vlans := map[int32]bool{} + networks := map[string]bool{} + for _, m := range memberships { + if networks[m.Network.String()] { + return fmt.Errorf("network %s is listed twice", m.Network) + } + networks[m.Network.String()] = true + switch { + case m.VLAN == 0: + untagged++ + case m.VLAN < 0 || m.VLAN > maxVLAN: + return fmt.Errorf("VLAN %d is out of range", m.VLAN) + case vlans[m.VLAN]: + return fmt.Errorf("VLAN %d is listed twice", m.VLAN) + } + vlans[m.VLAN] = true + } + if untagged > 1 { + return fmt.Errorf("a port carries at most one untagged network, got %d", untagged) + } + return nil +} From 81f1511e8d43664dec314176b267cdd87c6005b7 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Thu, 26 Nov 2026 00:22:42 -0600 Subject: [PATCH 2/2] fix: Address review of the test realizer Review of the test realizer found that a port could keep a network after its hold vanished, that VLANs moved when another claim left, and that the project copy of an interface dropped its VLAN. Key changes: - sweep every port no hold names, on start, every 30 seconds and whenever a hold is gone, withdrawing its claims before clearing it; the realizer runs with one worker so the sweep and per-hold passes never race on a port - refuse a hold whose name is not its port's, and let it protect no port - tag every network claim on a VLAN hashed from its network, probed in name order, so a surviving claim keeps its VLAN - copy vlanID to the project copy of an interface - drop the unused PortUnverified reason - warn at startup that the simulated realizer programs nothing real, and log failed changes, mismatched read-backs, kept finalizers and swept ports - check port safety before every change in the tests, and cover the sweep, the name check, VLAN stability and NSO's status writes keeping what the realizer reports Co-Authored-By: Claude Opus 5.5 --- api/v1alpha/networkinterfaceclaim_types.go | 6 - internal/cmd/cell/cell.go | 3 + internal/config/cell.go | 1 - .../controller/networkinterface_projection.go | 9 + .../networkinterface_projection_test.go | 12 + internal/controller/physicalrealizer_test.go | 240 +++++++++++++----- internal/networkagent/catalog.go | 9 - internal/physicalrealizer/driver.go | 15 +- internal/physicalrealizer/plan.go | 38 +-- internal/physicalrealizer/plan_test.go | 64 ++++- internal/physicalrealizer/reconciler.go | 219 ++++++++++++---- internal/physicalrealizer/reconciler_test.go | 138 ++++++++-- internal/physicalrealizer/simulated.go | 28 +- 13 files changed, 587 insertions(+), 195 deletions(-) diff --git a/api/v1alpha/networkinterfaceclaim_types.go b/api/v1alpha/networkinterfaceclaim_types.go index 7d571e8c..0ce06ea0 100644 --- a/api/v1alpha/networkinterfaceclaim_types.go +++ b/api/v1alpha/networkinterfaceclaim_types.go @@ -106,12 +106,6 @@ const ( // its addresses meanwhile. NetworkInterfaceClaimReasonBootAttachmentActive = "BootAttachmentActive" - // NetworkInterfaceClaimReasonPortUnverified means the physical realizer - // could not confirm what the claim's switch port carries, because the - // switch failed, only partly applied a change, or could not be read. It - // keeps retrying. - NetworkInterfaceClaimReasonPortUnverified = "PortUnverified" - // NetworkInterfaceClaimReasonPortCarriesNetwork means the switch port // carries the claim's network, as read back from the switch. NetworkInterfaceClaimReasonPortCarriesNetwork = "PortCarriesNetwork" diff --git a/internal/cmd/cell/cell.go b/internal/cmd/cell/cell.go index cfaa698b..4e505abb 100644 --- a/internal/cmd/cell/cell.go +++ b/internal/cmd/cell/cell.go @@ -367,6 +367,9 @@ func controllerRegistrations( } if serverConfig.PhysicalRealizer.Enabled { registrations = append(registrations, namedSetup{physicalrealizer.ControllerName, func() (bool, error) { + setupLog.Error(nil, "THE PHYSICAL REALIZER IS THE SIMULATED TEST REALIZER: no switch is changed, "+ + "and every physical claim it reports programmed is fake. Never enable it in a real cell.", + "driver", serverConfig.PhysicalRealizer.Driver) return true, (&physicalrealizer.Reconciler{ Client: mgr.GetLocalManager().GetClient(), APIReader: mgr.GetLocalManager().GetAPIReader(), diff --git a/internal/config/cell.go b/internal/config/cell.go index 7a4d9605..669d0666 100644 --- a/internal/config/cell.go +++ b/internal/config/cell.go @@ -77,7 +77,6 @@ type CellControllerManager struct { PhysicalRealizer PhysicalRealizerConfig `json:"physicalRealizer,omitempty"` } -// PhysicalRealizerDriverSimulated programs an in-memory switch. const PhysicalRealizerDriverSimulated = "simulated" // +k8s:deepcopy-gen=true diff --git a/internal/controller/networkinterface_projection.go b/internal/controller/networkinterface_projection.go index a3dab07d..a4a26035 100644 --- a/internal/controller/networkinterface_projection.go +++ b/internal/controller/networkinterface_projection.go @@ -45,6 +45,7 @@ func projectedInterface(source *networkingv1alpha.NetworkInterface, location str Status: networkingv1alpha.NetworkInterfaceStatus{ DNS: source.Status.DNS.DeepCopy(), Phase: source.Status.Phase, + VLANID: copyVLANID(source.Status.VLANID), Conditions: append([]metav1.Condition(nil), source.Status.Conditions...), }, } @@ -52,6 +53,14 @@ func projectedInterface(source *networkingv1alpha.NetworkInterface, location str return projection } +func copyVLANID(vlan *int32) *int32 { + if vlan == nil { + return nil + } + copied := *vlan + return &copied +} + func projectionLabels(source *networkingv1alpha.NetworkInterface, location string) map[string]string { labels := map[string]string{} for key, value := range source.Labels { diff --git a/internal/controller/networkinterface_projection_test.go b/internal/controller/networkinterface_projection_test.go index 5129e21e..d5fac7b5 100644 --- a/internal/controller/networkinterface_projection_test.go +++ b/internal/controller/networkinterface_projection_test.go @@ -331,6 +331,18 @@ func TestProjectedInterfaceReportsDNSSettings(t *testing.T) { require.Equal(t, "fd53::53", source.Status.DNS.Nameservers[0], "the projection must own its DNS settings") } +func TestProjectedInterfaceReportsTheVLANItsNetworkArrivesOn(t *testing.T) { + vlan := int32(100) + source := &networkingv1alpha.NetworkInterface{Status: networkingv1alpha.NetworkInterfaceStatus{VLANID: &vlan}} + + projection := projectedInterface(source, "ord-1") + require.Equal(t, &vlan, projection.Status.VLANID, "a tagged network must not read as untagged on the copy") + *projection.Status.VLANID = 200 + require.Equal(t, int32(100), vlan, "the projection must own its VLAN") + + require.Nil(t, projectedInterface(&networkingv1alpha.NetworkInterface{}, "ord-1").Status.VLANID) +} + func TestCopyDropsWhatOnlyMeansSomethingOnTheCell(t *testing.T) { v := newVisibility(t) v.interfaceOnCell() diff --git a/internal/controller/physicalrealizer_test.go b/internal/controller/physicalrealizer_test.go index f6401ba6..ff06b046 100644 --- a/internal/controller/physicalrealizer_test.go +++ b/internal/controller/physicalrealizer_test.go @@ -5,6 +5,7 @@ package controller import ( "context" "errors" + "fmt" "testing" "github.com/stretchr/testify/require" @@ -22,25 +23,31 @@ import ( const realizedPort = "Ethernet1/12" -// realizedPortRun drives the test realizer for one port of a scenario's switch, -// and knows which project each scenario namespace belongs to. type realizedPortRun struct { - s *scenario - sw *physicalrealizer.SimulatedSwitch - realizer *physicalrealizer.Reconciler - projects map[string]string - bootByName map[types.NamespacedName]bool + s *scenario + sw *physicalrealizer.SimulatedSwitch + realizer *physicalrealizer.Reconciler + projects map[string]string + applies int + onApply func() } func (s *scenario) realizedPort() *realizedPortRun { sw := physicalrealizer.NewSimulatedSwitch() - return &realizedPortRun{ - s: s, - sw: sw, - realizer: &physicalrealizer.Reconciler{Client: s.client, APIReader: s.client, Driver: sw}, - projects: map[string]string{s.namespace: testProject}, - bootByName: map[types.NamespacedName]bool{}, + run := &realizedPortRun{ + s: s, + sw: sw, + realizer: &physicalrealizer.Reconciler{Client: s.client, APIReader: s.client, Driver: sw}, + projects: map[string]string{s.namespace: testProject}, } + sw.BeforeApply(func(_ physicalrealizer.Port, desired []physicalrealizer.Membership) { + run.applies++ + run.requireSafe("apply", desired) + if run.onApply != nil { + run.onApply() + } + }) + return run } func (r *realizedPortRun) sibling(project string) *scenario { @@ -78,8 +85,6 @@ func networkOf(s *scenario) types.NamespacedName { return types.NamespacedName{Namespace: s.namespace, Name: "default"} } -// requireConsistent checks that no claim on the port reports Programmed for a -// network the port does not carry. func (r *realizedPortRun) requireConsistent() { r.s.t.Helper() var claims networkingv1alpha.NetworkInterfaceClaimList @@ -107,23 +112,26 @@ func carries(carried []physicalrealizer.Membership, network types.NamespacedName return false } -// requireSafeHistory checks every state the port ever reached: networks of one -// project at most, and a boot network only ever alone. -func (r *realizedPortRun) requireSafeHistory(bootNetworks ...types.NamespacedName) { +func (r *realizedPortRun) requireSafe(what string, carried []physicalrealizer.Membership) { r.s.t.Helper() - for i, change := range r.sw.History() { - projects := map[string]bool{} - for _, m := range change.Carried { - project, known := r.projects[m.Network.Namespace] - require.Truef(r.s.t, known, "change %d carries %s, which no scenario owns", i, m.Network) - projects[project] = true - for _, boot := range bootNetworks { - if m.Network == boot { - require.Lenf(r.s.t, change.Carried, 1, "change %d carries the boot network with others: %v", i, change.Carried) - } - } + projects := map[string]bool{} + for _, m := range carried { + project, known := r.projects[m.Network.Namespace] + require.Truef(r.s.t, known, "%s carries %s, which no scenario owns", what, m.Network) + projects[project] = true + if project == providerProject { + require.Lenf(r.s.t, carried, 1, "%s carries the boot network with others: %v", what, carried) } - require.LessOrEqualf(r.s.t, len(projects), 1, "change %d carries two projects' networks: %v", i, change.Carried) + } + require.LessOrEqualf(r.s.t, len(projects), 1, "%s carries two projects' networks: %v", what, carried) +} + +func (r *realizedPortRun) requireSafeHistory() { + r.s.t.Helper() + history := r.sw.History() + require.GreaterOrEqual(r.s.t, r.applies, len(history), "every change was checked before it was applied") + for i, change := range history { + r.requireSafe(fmt.Sprintf("change %d", i), change.Carried) } } @@ -143,7 +151,6 @@ func requirePrepared(t *testing.T, conditions []metav1.Condition) { require.Equal(t, networkingv1alpha.NetworkInterfaceClaimReasonAttachmentPointAccepted, prepared.Reason) } -// requireReported checks the claim and the interface bound to it agree. func (s *scenario) requireReported(name string, status metav1.ConditionStatus, reason string) *networkingv1alpha.NetworkInterfaceClaim { s.t.Helper() claim := s.getClaim(name) @@ -175,17 +182,31 @@ func (s *scenario) bindPhysical(name string, purpose networkingv1alpha.NetworkIn s.requireBound(name) } +func (r *realizedPortRun) requireCarriedOn(s *scenario, name string) int32 { + s.t.Helper() + claim := s.getClaim(name) + require.NotNil(s.t, claim.Status.VLANID, "a network claim's network arrives tagged") + network := types.NamespacedName{Namespace: claim.Namespace, Name: claim.Spec.Network.Name} + for _, m := range r.carried() { + if m.Network == network { + require.Equal(s.t, *claim.Status.VLANID, m.VLAN, "the reported VLAN is the one the switch carries") + return m.VLAN + } + } + require.Failf(s.t, "not carried", "the port does not carry %s: %v", network, r.carried()) + return 0 +} + func TestARealizedNetworkClaimIsProgrammed(t *testing.T) { s := newScenario(t, true, ipv4Only) run := s.realizedPort() s.bindPhysical("server-data", "") run.mustRealize() - require.Equal(t, []physicalrealizer.Membership{{ - Network: networkOf(s), Isolation: networkingv1alpha.NetworkInterfaceIsolationShared, - }}, run.carried()) + require.Len(t, run.carried(), 1) + require.Equal(t, networkingv1alpha.NetworkInterfaceIsolationShared, run.carried()[0].Isolation) claim := s.requireReported("server-data", metav1.ConditionTrue, networkingv1alpha.NetworkInterfaceClaimReasonPortCarriesNetwork) - require.Nil(t, claim.Status.VLANID, "the only network arrives untagged") + run.requireCarriedOn(s, "server-data") s.reconcile(claim) s.requireReady("server-data") @@ -195,27 +216,30 @@ func TestARealizedNetworkClaimIsProgrammed(t *testing.T) { require.Equal(t, before, run.changes(), "a port that already carries its networks is left alone") } -func TestASecondNetworkArrivesTagged(t *testing.T) { +func TestASurvivingNetworkKeepsItsVLAN(t *testing.T) { s := newScenario(t, true, ipv4Only) run := s.realizedPort() - second := run.sibling(testProject) + storage := run.sibling(testProject) + backup := run.sibling(testProject) s.bindPhysical("server-data", "") - second.bindPhysical("server-storage", "") - + storage.bindPhysical("server-storage", "") + backup.bindPhysical("server-backup", "") run.mustRealize() - require.Nil(t, s.requireReported("server-data", metav1.ConditionTrue, - networkingv1alpha.NetworkInterfaceClaimReasonPortCarriesNetwork).Status.VLANID) - storage := second.requireReported("server-storage", metav1.ConditionTrue, - networkingv1alpha.NetworkInterfaceClaimReasonPortCarriesNetwork) - require.NotNil(t, storage.Status.VLANID) - carried := run.carried() - require.Len(t, carried, 2) - for _, m := range carried { - if m.Network == networkOf(second) { - require.Equal(t, *storage.Status.VLANID, m.VLAN, "the reported VLAN is the one the switch carries") - } + vlans := map[string]int32{} + for name, owner := range map[string]*scenario{"server-data": s, "server-storage": storage, "server-backup": backup} { + owner.requireReported(name, metav1.ConditionTrue, networkingv1alpha.NetworkInterfaceClaimReasonPortCarriesNetwork) + vlans[name] = run.requireCarriedOn(owner, name) } + require.Len(t, map[int32]bool{vlans["server-data"]: true, vlans["server-storage"]: true, vlans["server-backup"]: true}, 3) + + require.NoError(t, s.client.Delete(s.ctx, s.getClaim("server-data"))) + s.reconcile(s.getClaim("server-data")) + run.mustRealize() + require.Len(t, run.carried(), 2) + require.Equal(t, vlans["server-storage"], run.requireCarriedOn(storage, "server-storage"), "the first claim leaving re-tags nothing") + require.Equal(t, vlans["server-backup"], run.requireCarriedOn(backup, "server-backup")) + storage.requireReported("server-storage", metav1.ConditionTrue, networkingv1alpha.NetworkInterfaceClaimReasonPortCarriesNetwork) } func TestAHandoverMovesThePortInOneStep(t *testing.T) { @@ -233,6 +257,8 @@ func TestAHandoverMovesThePortInOneStep(t *testing.T) { provider.requireReported("install-1-boot", metav1.ConditionTrue, networkingv1alpha.NetworkInterfaceClaimReasonPortCarriesNetwork) data := customer.requireReported("server-data", metav1.ConditionFalse, networkingv1alpha.NetworkInterfaceClaimReasonBootAttachmentActive) + require.NotNil(t, data.Status.VLANID, "the server can be configured for its network while it installs") + installVLAN := *data.Status.VLANID customer.reconcile(data) data = customer.getClaim("server-data") require.Len(t, data.Status.Addresses, 1, "a network claim under a boot claim keeps its addresses") @@ -243,7 +269,7 @@ func TestAHandoverMovesThePortInOneStep(t *testing.T) { provider.requireAwaitingDetach("install-1-boot") var detachHeldAtApply []bool - run.sw.BeforeApply(func(physicalrealizer.Port, []physicalrealizer.Membership) { + run.onApply = func() { detachHeldAtApply = append(detachHeldAtApply, provider.hasDetachFinalizer("install-1-boot")) for _, name := range []string{"server-data"} { programmed := conditionOf(customer.getClaim(name), networkingv1alpha.NetworkInterfaceClaimProgrammed) @@ -252,14 +278,14 @@ func TestAHandoverMovesThePortInOneStep(t *testing.T) { programmed := conditionOf(provider.getClaim("install-1-boot"), networkingv1alpha.NetworkInterfaceClaimProgrammed) require.Equal(t, networkingv1alpha.NetworkInterfaceClaimReasonPortChanging, programmed.Reason, "the boot claim is withdrawn before the port moves") - }) + } before := run.changes() run.mustRealize() require.Equal(t, before+1, run.changes(), "the port moves in one change") - require.Equal(t, []physicalrealizer.Membership{{ - Network: networkOf(customer), Isolation: networkingv1alpha.NetworkInterfaceIsolationShared, - }}, run.carried()) + require.Equal(t, []types.NamespacedName{networkOf(customer)}, networksOf(run.carried())) + require.Equal(t, networkingv1alpha.NetworkInterfaceIsolationShared, run.carried()[0].Isolation) + require.Equal(t, installVLAN, run.requireCarriedOn(customer, "server-data"), "the network arrives on the VLAN reported during the install") require.Equal(t, []bool{true}, detachHeldAtApply) require.False(t, provider.hasDetachFinalizer("install-1-boot"), "the boot claim is detached once read back") customer.requireReported("server-data", metav1.ConditionTrue, networkingv1alpha.NetworkInterfaceClaimReasonPortCarriesNetwork) @@ -270,7 +296,7 @@ func TestAHandoverMovesThePortInOneStep(t *testing.T) { customer.reconcile(customer.getClaim("server-data")) customer.requireReady("server-data") - run.requireSafeHistory(networkOf(provider)) + run.requireSafeHistory() } func TestReleasingACustomerClaimEmptiesThePort(t *testing.T) { @@ -316,13 +342,13 @@ func TestAClaimDeletedMidChangeLeavesThePortBeforeItsFinalizer(t *testing.T) { applies := 0 var storageDetachHeld []bool - run.sw.BeforeApply(func(physicalrealizer.Port, []physicalrealizer.Membership) { + run.onApply = func() { applies++ storageDetachHeld = append(storageDetachHeld, storage.hasDetachFinalizer("server-storage")) if applies == 1 { require.NoError(t, storage.client.Delete(storage.ctx, storage.getClaim("server-storage"))) } - }) + } before := len(run.sw.History()) require.NoError(t, run.realize(), "one pass changes the port again") @@ -335,7 +361,7 @@ func TestAClaimDeletedMidChangeLeavesThePortBeforeItsFinalizer(t *testing.T) { require.False(t, provider.hasDetachFinalizer("install-1-boot")) customer.requireReported("server-data", metav1.ConditionTrue, networkingv1alpha.NetworkInterfaceClaimReasonPortCarriesNetwork) run.requireConsistent() - run.requireSafeHistory(networkOf(provider)) + run.requireSafeHistory() } func networksOf(memberships []physicalrealizer.Membership) []types.NamespacedName { @@ -381,7 +407,7 @@ func TestAPartialChangeHoldsFinalizersUntilTheSwitchRecovers(t *testing.T) { require.Equal(t, []types.NamespacedName{networkOf(customer)}, networksOf(run.carried())) require.False(t, provider.hasDetachFinalizer("install-1-boot")) customer.requireReported("server-data", metav1.ConditionTrue, networkingv1alpha.NetworkInterfaceClaimReasonPortCarriesNetwork) - run.requireSafeHistory(networkOf(provider)) + run.requireSafeHistory() } func TestASwitchThatCannotBeReadRemovesNoFinalizer(t *testing.T) { @@ -403,18 +429,17 @@ func TestASwitchThatCannotBeReadRemovesNoFinalizer(t *testing.T) { networkingv1alpha.NetworkInterfaceClaimReasonPortCarriesNetwork) run.sw.FailReads(false) - run.sw.BeforeApply(func(physicalrealizer.Port, []physicalrealizer.Membership) { run.sw.FailReads(true) }) + run.onApply = func() { run.sw.FailReads(true) } require.ErrorIs(t, run.realize(), physicalrealizer.ErrSwitchUnreachable) require.Empty(t, run.carried(), "the change landed") require.True(t, s.hasDetachFinalizer("server-data"), "a change that cannot be read back proves nothing") - run.sw.BeforeApply(nil) + run.onApply = nil run.sw.FailReads(false) run.mustRealize() require.False(t, s.hasDetachFinalizer("server-data")) } -// failingStatus fails every status write to the kind it names. type failingStatus struct { client.Client kind client.Object @@ -527,7 +552,7 @@ func TestAPortNeverCarriesTwoProjectsOrBootWithCustomer(t *testing.T) { require.Equal(t, []types.NamespacedName{networkOf(provider)}, networksOf(run.carried())) require.GreaterOrEqual(t, run.changes(), 6) - run.requireSafeHistory(networkOf(provider)) + run.requireSafeHistory() } // claimCacheMissingDeletion answers claim reads the way a cache that has not @@ -560,3 +585,90 @@ func TestTheRealizerReadsFromTheAPIServer(t *testing.T) { require.Empty(t, run.carried(), "a deletion the cache has not seen still takes the network off") require.False(t, s.hasDetachFinalizer("server-data")) } + +type realizedStatus struct { + vlan *int32 + prepared metav1.Condition + programmed metav1.Condition +} + +func realizedStatusOf(vlan *int32, conditions []metav1.Condition) realizedStatus { + status := realizedStatus{vlan: vlan} + if c := apimeta.FindStatusCondition(conditions, networkingv1alpha.NetworkInterfaceClaimPrepared); c != nil { + status.prepared = *c + } + if c := apimeta.FindStatusCondition(conditions, networkingv1alpha.NetworkInterfaceClaimProgrammed); c != nil { + status.programmed = *c + } + return status +} + +func TestTheOperatorKeepsWhatTheRealizerReports(t *testing.T) { + s := newScenario(t, true, ipv4Only) + run := s.realizedPort() + s.bindPhysical("server-data", "") + run.mustRealize() + + claim := s.getClaim("server-data") + iface, err := s.getInterface("server-data") + require.NoError(t, err) + wantClaim := realizedStatusOf(claim.Status.VLANID, claim.Status.Conditions) + wantInterface := realizedStatusOf(iface.Status.VLANID, iface.Status.Conditions) + require.NotNil(t, wantClaim.vlan) + require.Equal(t, metav1.ConditionTrue, wantClaim.programmed.Status) + + s.createSubnet("default-v4", s.networkContextName("default"), networkingv1alpha.IPv4Protocol, "192.0.2.0", 24) + for range 2 { + s.reconcile(s.getClaim("server-data")) + s.reconcileInterface("server-data") + } + + claim = s.getClaim("server-data") + iface, err = s.getInterface("server-data") + require.NoError(t, err) + require.NotEmpty(t, iface.Spec.Addresses[0].Gateway, "the operator wrote the interface after the realizer") + require.Equal(t, wantClaim, realizedStatusOf(claim.Status.VLANID, claim.Status.Conditions)) + require.Equal(t, wantInterface, realizedStatusOf(iface.Status.VLANID, iface.Status.Conditions)) + s.requireReady("server-data") +} + +func TestAPortWhoseHoldAnOperatorDeletesIsCleared(t *testing.T) { + s := newScenario(t, true, ipv4Only) + run := s.realizedPort() + s.bindPhysical("server-data", "") + run.mustRealize() + require.Len(t, run.carried(), 1) + + require.NoError(t, s.client.Delete(s.ctx, s.requireHold(realizedPort))) + run.mustRealize() + require.Empty(t, run.carried(), "a port no hold names carries nothing") + requireProgrammed(t, s.getClaim("server-data").Status.Conditions, metav1.ConditionFalse, + networkingv1alpha.NetworkInterfaceClaimReasonPortChanging) + + s.reconcile(s.getClaim("server-data")) + s.requireHold(realizedPort) + run.mustRealize() + run.requireCarriedOn(s, "server-data") +} + +func TestAPortReleasedByBreakGlassIsCleared(t *testing.T) { + s := newScenario(t, true, ipv4Only) + run := s.realizedPort() + s.bindPhysical("server-data", "") + run.mustRealize() + + s.detach("server-data") + require.NoError(t, s.client.Delete(s.ctx, s.getClaim("server-data"))) + s.reconcile(s.getClaim("server-data")) + require.True(t, s.claimGone("server-data")) + _, err := s.getHold(realizedPort) + require.True(t, apierrors.IsNotFound(err)) + require.Len(t, run.carried(), 1, "the realizer has not seen the release yet") + + run.mustRealize() + require.Empty(t, run.carried()) + + _, err = run.realizer.Reconcile(s.ctx, physicalrealizer.SweepRequest) + require.NoError(t, err) + require.Empty(t, run.carried()) +} diff --git a/internal/networkagent/catalog.go b/internal/networkagent/catalog.go index 17e1ba34..bee21116 100644 --- a/internal/networkagent/catalog.go +++ b/internal/networkagent/catalog.go @@ -595,15 +595,6 @@ func switchPort(kind, prepared, programmed string) []ReasonInfo { Skill: SkillInterfaceTriage, ExpectedDuration: windowDataPlane, }), - entry(kind, programmed, networkingv1alpha.NetworkInterfaceClaimReasonPortUnverified, ReasonInfo{ - Actionability: ActionabilityTransient, - Scope: ScopeInstance, - Explanation: "The platform could not confirm what the switch port this server's network interface " + - "is cabled to carries, so it keeps trying and holds the interface's addresses meanwhile.", - Remediation: remediationWait, - Skill: SkillInterfaceTriage, - ExpectedDuration: windowDataPlane, - }), entry(kind, programmed, networkingv1alpha.NetworkInterfaceClaimReasonBootAttachmentActive, ReasonInfo{ Actionability: ActionabilityInformational, Explanation: "This server is being installed, so its switch port carries the install network " + diff --git a/internal/physicalrealizer/driver.go b/internal/physicalrealizer/driver.go index e42bc721..a9ee4dfb 100644 --- a/internal/physicalrealizer/driver.go +++ b/internal/physicalrealizer/driver.go @@ -1,8 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-only -// Package physicalrealizer is a test realizer for physical network interfaces. -// It programs switch ports from SwitchPortHolds through a Driver, and follows -// the same contract a production realizer must. +// Package physicalrealizer is a test realizer that programs a simulated switch. package physicalrealizer import ( @@ -15,26 +13,25 @@ import ( networkingv1alpha "go.datum.net/network-services-operator/api/v1alpha" ) -// Port is one switch port, in the names network operations uses for it. type Port struct { Switch string Name string } -// Membership is one network a port carries. A VLAN of zero means the network -// arrives untagged. +// Membership is one network a port carries. A VLAN of zero is untagged. type Membership struct { Network types.NamespacedName VLAN int32 Isolation networkingv1alpha.NetworkInterfaceIsolation } -// Driver changes and reads one switch port at a time. Apply replaces -// everything the port carries in one change. Read reports what the port -// carries now, which is the only proof a change took effect. +// Driver changes one switch port at a time. Apply replaces everything a port +// carries in one change, and only Read proves it took effect. Ports lists every +// port that carries anything. type Driver interface { Apply(ctx context.Context, port Port, desired []Membership) error Read(ctx context.Context, port Port) ([]Membership, error) + Ports(ctx context.Context) ([]Port, error) } func sortedMemberships(memberships []Membership) []Membership { diff --git a/internal/physicalrealizer/plan.go b/internal/physicalrealizer/plan.go index a6e902e5..1220d254 100644 --- a/internal/physicalrealizer/plan.go +++ b/internal/physicalrealizer/plan.go @@ -4,6 +4,8 @@ package physicalrealizer import ( "hash/fnv" + "slices" + "strings" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" @@ -16,7 +18,6 @@ const ( simulatedVLANs = maxVLAN - firstSimulatedVLAN + 1 ) -// recorded is one entry of a hold, and the claim it names if one exists. type recorded struct { entry networkingv1alpha.SwitchPortHoldClaimRef boot bool @@ -27,8 +28,8 @@ func (r recorded) network() types.NamespacedName { return types.NamespacedName{Namespace: r.entry.Namespace, Name: r.entry.Network} } -// networks are every network the port may carry for this entry: the one the -// hold recorded, and the one a claim of the entry's name names now. +// An entry left under the claim's name may name an older network, and the port +// may still carry either. func (r recorded) networks() []types.NamespacedName { networks := []types.NamespacedName{r.network()} if r.claim != nil && r.claim.Spec.Network.Name != r.entry.Network { @@ -47,9 +48,6 @@ func (r recorded) onPort(hold *networkingv1alpha.SwitchPortHold) bool { controllerutil.ContainsFinalizer(claim, networkingv1alpha.NetworkInterfaceClaimDetachFinalizer) } -// counts reports whether the port may carry the entry's network: the claim is -// recorded as it is, still carries the detach finalizer, and is not being -// deleted. func (r recorded) counts(hold *networkingv1alpha.SwitchPortHold) bool { return r.onPort(hold) && r.claim.DeletionTimestamp.IsZero() && @@ -57,8 +55,6 @@ func (r recorded) counts(hold *networkingv1alpha.SwitchPortHold) bool { (r.claim.Spec.Purpose == networkingv1alpha.NetworkInterfacePurposeBoot) == r.boot } -// releasing reports whether the claim waits on the realizer to take its -// network off the port. func (r recorded) releasing(hold *networkingv1alpha.SwitchPortHold) bool { return r.onPort(hold) && !r.claim.DeletionTimestamp.IsZero() } @@ -73,13 +69,11 @@ func (r recorded) isolation() networkingv1alpha.NetworkInterfaceIsolation { return networkingv1alpha.NetworkInterfaceIsolationShared } -// plan is what a port carries, worked out from its hold. type plan struct { boot *recorded - // networks are the counted network claims and what each would arrive on. - // They keep their VLANs while a boot claim holds the port, so a server - // being installed can be configured for them. + // Network claims keep their VLANs while a boot claim holds the port, so a + // server being installed can be configured for them. networks []assigned } @@ -90,7 +84,6 @@ type assigned struct { func planFor(hold *networkingv1alpha.SwitchPortHold, entries []recorded) plan { var p plan - used := map[int32]bool{} for i := range entries { entry := entries[i] if !entry.counts(hold) { @@ -100,11 +93,20 @@ func planFor(hold *networkingv1alpha.SwitchPortHold, entries []recorded) plan { p.boot = &entry continue } - membership := Membership{Network: entry.network(), Isolation: entry.isolation()} - if len(p.networks) > 0 { - membership.VLAN = simulatedVLAN(entry.network(), used) + p.networks = append(p.networks, assigned{recorded: entry}) + } + + slices.SortFunc(p.networks, func(a, b assigned) int { + return strings.Compare(a.network().String(), b.network().String()) + }) + used := map[int32]bool{} + for i := range p.networks { + network := p.networks[i].network() + p.networks[i].membership = Membership{ + Network: network, + VLAN: simulatedVLAN(network, used), + Isolation: p.networks[i].isolation(), } - p.networks = append(p.networks, assigned{recorded: entry, membership: membership}) } return p } @@ -138,8 +140,6 @@ func simulatedVLAN(network types.NamespacedName, used map[int32]bool) int32 { return 0 } -// changes reports whether moving the port from current to desired adds, -// removes or alters any network the entry may be carried on. func (r recorded) changes(current, desired []Membership) bool { for _, network := range r.networks() { before, wasCarried := membershipOf(current, network) diff --git a/internal/physicalrealizer/plan_test.go b/internal/physicalrealizer/plan_test.go index 83a23db8..6cbebf06 100644 --- a/internal/physicalrealizer/plan_test.go +++ b/internal/physicalrealizer/plan_test.go @@ -4,6 +4,7 @@ package physicalrealizer import ( "context" + "fmt" "slices" "testing" @@ -66,23 +67,31 @@ func TestABootClaimCarriesItsNetworkAloneAndUntagged(t *testing.T) { Network: network("ns-provider-example", "boot"), Isolation: networkingv1alpha.NetworkInterfaceIsolationPrivate, }}, p.carried()) require.Len(t, p.networks, 2, "network claims keep their VLANs while the boot claim holds the port") - require.Zero(t, p.networks[0].membership.VLAN) + require.NotZero(t, p.networks[0].membership.VLAN) require.NotZero(t, p.networks[1].membership.VLAN) } -func TestNetworkClaimsAreOneUntaggedAndTheRestTagged(t *testing.T) { - names := []string{"app", "storage", "backup", "metrics"} +func customerEntries(names ...string) []recorded { entries := make([]recorded, 0, len(names)) for _, name := range names { entries = append(entries, entryFor(physicalClaim("ns-customer-example", "server-"+name, name, ""), false)) } + return entries +} + +func vlansOf(carried []Membership) map[types.NamespacedName]int32 { + vlans := map[types.NamespacedName]int32{} + for _, m := range carried { + vlans[m.Network] = m.VLAN + } + return vlans +} - carried := planFor(testHold(), entries).carried() +func TestEveryNetworkClaimArrivesTagged(t *testing.T) { + carried := planFor(testHold(), customerEntries("app", "storage", "backup", "metrics")).carried() require.Len(t, carried, 4) - require.Equal(t, network("ns-customer-example", "app"), carried[0].Network) - require.Zero(t, carried[0].VLAN, "the first network claim recorded arrives untagged") seen := map[int32]bool{} - for _, m := range carried[1:] { + for _, m := range carried { require.GreaterOrEqual(t, m.VLAN, int32(firstSimulatedVLAN)) require.LessOrEqual(t, m.VLAN, int32(maxVLAN)) require.False(t, seen[m.VLAN], "VLAN %d is used twice", m.VLAN) @@ -90,7 +99,46 @@ func TestNetworkClaimsAreOneUntaggedAndTheRestTagged(t *testing.T) { require.Equal(t, networkingv1alpha.NetworkInterfaceIsolationShared, m.Isolation) } require.NoError(t, validMemberships(carried)) - require.Equal(t, carried, planFor(testHold(), entries).carried(), "the VLANs are deterministic") + require.Len(t, planFor(testHold(), customerEntries("app")).carried(), 1) + require.NotZero(t, planFor(testHold(), customerEntries("app")).carried()[0].VLAN, "even a lone network is tagged") +} + +func TestASurvivingNetworkKeepsItsVLAN(t *testing.T) { + names := []string{"app", "storage", "backup", "metrics"} + all := vlansOf(planFor(testHold(), customerEntries(names...)).carried()) + reversed := vlansOf(planFor(testHold(), customerEntries("metrics", "backup", "storage", "app")).carried()) + require.Equal(t, all, reversed, "the order claims were recorded in does not matter") + + for i := range names { + survivors := slices.Delete(slices.Clone(names), i, i+1) + for network, vlan := range vlansOf(planFor(testHold(), customerEntries(survivors...)).carried()) { + require.Equal(t, all[network], vlan, "%s changed VLAN when %s left", network, names[i]) + } + } +} + +func TestCollidingNetworksAreTaggedInNameOrder(t *testing.T) { + slot := func(name string) int32 { + return simulatedVLAN(network("ns-customer-example", name), map[int32]bool{}) + } + seen := map[int32]string{} + var first, second string + for i := 0; first == ""; i++ { + name := fmt.Sprintf("net-%d", i) + if other, ok := seen[slot(name)]; ok { + first, second = other, name + } + seen[slot(name)] = name + } + if second < first { + first, second = second, first + } + + forward := vlansOf(planFor(testHold(), customerEntries(first, second)).carried()) + backward := vlansOf(planFor(testHold(), customerEntries(second, first)).carried()) + require.Equal(t, forward, backward) + require.Equal(t, slot(first), forward[network("ns-customer-example", first)], "the name sorted first takes its own VLAN") + require.NotEqual(t, forward[network("ns-customer-example", first)], forward[network("ns-customer-example", second)]) } func TestSimulatedVLANsProbePastACollision(t *testing.T) { diff --git a/internal/physicalrealizer/reconciler.go b/internal/physicalrealizer/reconciler.go index 44ce62c9..8c0253e2 100644 --- a/internal/physicalrealizer/reconciler.go +++ b/internal/physicalrealizer/reconciler.go @@ -6,32 +6,48 @@ import ( "context" "errors" "fmt" + "time" + "github.com/go-logr/logr" apierrors "k8s.io/apimachinery/pkg/api/errors" apimeta "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/util/workqueue" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" "sigs.k8s.io/controller-runtime/pkg/handler" + "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + "sigs.k8s.io/controller-runtime/pkg/source" + + "go.miloapis.com/instrumentation/labels" networkingv1alpha "go.datum.net/network-services-operator/api/v1alpha" ) -// ControllerName is the name the realizer registers under. -const ControllerName = "physical-realizer" +const ( + ControllerName = "physical-realizer" + + SweepInterval = 30 * time.Second + + maxChangesPerPass = 4 +) -// maxChangesPerPass bounds how often one pass changes a port again because -// its claims changed while it was changing it. -const maxChangesPerPass = 4 +// SweepRequest asks the realizer to clear every port no hold names. Holds are +// cluster-scoped, so a namespaced key never names one. +var SweepRequest = ctrl.Request{NamespacedName: types.NamespacedName{Namespace: ControllerName, Name: "sweep"}} -// Reconciler programs one switch port per SwitchPortHold. +// Reconciler programs one switch port per SwitchPortHold. It must run with a +// single worker: it is the only writer of what each port carries, and the +// sweep and the per-hold passes must never change one port at once. type Reconciler struct { Client client.Client - // APIReader reads holds, claims and interfaces. It must not be a cache: a - // claim whose deletion the cache has not seen yet would be kept on its - // port, and one whose hold entry the cache has not seen would be dropped. + // APIReader must not be a cache. A deletion the cache has not seen would + // keep a network on its port, and a hold it has not seen would be swept. APIReader client.Reader Driver Driver @@ -45,62 +61,151 @@ type Reconciler struct { // +kubebuilder:rbac:groups=networking.datumapis.com,resources=networkinterfaces/status,verbs=get;update;patch func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + if req == SweepRequest { + return ctrl.Result{RequeueAfter: SweepInterval}, r.sweep(ctx) + } + hold := &networkingv1alpha.SwitchPortHold{} if err := r.APIReader.Get(ctx, req.NamespacedName, hold); err != nil { - return ctrl.Result{}, client.IgnoreNotFound(err) + if apierrors.IsNotFound(err) { + return ctrl.Result{}, r.sweep(ctx) + } + return ctrl.Result{}, err } port := Port{Switch: hold.Spec.Switch, Name: hold.Spec.Port} + logger := log.FromContext(ctx, "switch", port.Switch, "port", port.Name) + + if !namesItsPort(hold) { + logger.Error(nil, "refusing a switch port hold whose name is not its port's", + labels.ResourceName, hold.Name, "expected", networkingv1alpha.SwitchPortHoldName(port.Switch, port.Name)) + return ctrl.Result{}, nil + } carried, err := r.Driver.Read(ctx, port) if err != nil { + logger.Error(err, "failed reading switch port") return ctrl.Result{}, fmt.Errorf("failed reading switch port %s %s: %w", port.Switch, port.Name, err) } for range maxChangesPerPass { - entries, err := r.observe(ctx, req.NamespacedName, hold) + entries, gone, err := r.observe(ctx, req.NamespacedName, hold) if err != nil { return ctrl.Result{}, err } + if gone { + return ctrl.Result{}, r.sweep(ctx) + } desired := planFor(hold, entries).carried() if sameMemberships(carried, desired) { - return ctrl.Result{}, r.settle(ctx, hold, entries, carried) + return ctrl.Result{}, r.settle(ctx, logger, hold, entries, carried) } if err := r.withdraw(ctx, hold, entries, carried, desired); err != nil { return ctrl.Result{}, err } - applyErr := r.Driver.Apply(ctx, port, desired) - readBack, err := r.Driver.Read(ctx, port) - if err != nil { - return ctrl.Result{}, errors.Join(applyErr, - fmt.Errorf("failed reading switch port %s %s back: %w", port.Switch, port.Name, err)) + if carried, err = r.change(ctx, logger, port, desired); err != nil { + return ctrl.Result{}, err } - if applyErr != nil { - return ctrl.Result{}, fmt.Errorf("failed changing switch port %s %s: %w", port.Switch, port.Name, applyErr) + } + return ctrl.Result{Requeue: true}, nil +} + +func namesItsPort(hold *networkingv1alpha.SwitchPortHold) bool { + return hold.Name == networkingv1alpha.SwitchPortHoldName(hold.Spec.Switch, hold.Spec.Port) +} + +func (r *Reconciler) change(ctx context.Context, logger logr.Logger, port Port, desired []Membership) ([]Membership, error) { + applyErr := r.Driver.Apply(ctx, port, desired) + if applyErr != nil { + logger.Error(applyErr, "failed changing switch port") + } + readBack, err := r.Driver.Read(ctx, port) + if err != nil { + logger.Error(err, "failed reading switch port back") + return nil, errors.Join(applyErr, + fmt.Errorf("failed reading switch port %s %s back: %w", port.Switch, port.Name, err)) + } + if applyErr != nil { + return nil, fmt.Errorf("failed changing switch port %s %s: %w", port.Switch, port.Name, applyErr) + } + if !sameMemberships(readBack, desired) { + logger.Error(nil, "switch port reads back other than what was applied", "applied", desired, "read", readBack) + return nil, fmt.Errorf("switch port %s %s reads back %v after a change to %v", + port.Switch, port.Name, readBack, desired) + } + return readBack, nil +} + +func (r *Reconciler) sweep(ctx context.Context) error { + ports, err := r.Driver.Ports(ctx) + if err != nil { + log.FromContext(ctx).Error(err, "failed listing switch ports to sweep") + return fmt.Errorf("failed listing switch ports: %w", err) + } + if len(ports) == 0 { + return nil + } + + var holds networkingv1alpha.SwitchPortHoldList + if err := r.APIReader.List(ctx, &holds); err != nil { + return fmt.Errorf("failed listing switch port holds: %w", err) + } + named := map[Port]bool{} + for i := range holds.Items { + if hold := &holds.Items[i]; namesItsPort(hold) { + named[Port{Switch: hold.Spec.Switch, Name: hold.Spec.Port}] = true + } + } + + var claims networkingv1alpha.NetworkInterfaceClaimList + if err := r.APIReader.List(ctx, &claims); err != nil { + return fmt.Errorf("failed listing claims: %w", err) + } + + var errs []error + for _, port := range ports { + if named[port] { + continue } - if !sameMemberships(readBack, desired) { - return ctrl.Result{}, fmt.Errorf("switch port %s %s reads back %v after a change to %v", - port.Switch, port.Name, readBack, desired) + logger := log.FromContext(ctx, "switch", port.Switch, "port", port.Name) + if err := r.withdrawPort(ctx, claims.Items, port); err != nil { + errs = append(errs, err) + continue } - carried = readBack + if _, err := r.change(ctx, logger, port, nil); err != nil { + errs = append(errs, err) + continue + } + logger.Info("cleared a switch port no hold names", labels.Outcome, "cleared") } - return ctrl.Result{Requeue: true}, nil + return errors.Join(errs...) +} + +func (r *Reconciler) withdrawPort(ctx context.Context, claims []networkingv1alpha.NetworkInterfaceClaim, port Port) error { + for i := range claims { + claim := &claims[i] + point := claim.Spec.AttachmentPoint + if claim.Spec.AttachmentMode != networkingv1alpha.NetworkInterfaceAttachmentModePhysical || + point == nil || point.Switch != port.Switch || point.Port != port.Name { + continue + } + if err := r.report(ctx, claim, nil, false, portChanging()); err != nil { + return fmt.Errorf("failed withdrawing claim %s/%s before clearing its port: %w", claim.Namespace, claim.Name, err) + } + } + return nil } -// observe reads the hold and every claim it records again, from the API -// server. A hold that is gone records nothing, so its port carries nothing. func (r *Reconciler) observe( ctx context.Context, key client.ObjectKey, hold *networkingv1alpha.SwitchPortHold, -) ([]recorded, error) { +) ([]recorded, bool, error) { if err := r.APIReader.Get(ctx, key, hold); err != nil { if apierrors.IsNotFound(err) { - hold.Spec.Boot = nil - hold.Spec.NetworkClaims = nil - return nil, nil + return nil, true, nil } - return nil, fmt.Errorf("failed reading switch port hold %s: %w", key.Name, err) + return nil, false, fmt.Errorf("failed reading switch port hold %s: %w", key.Name, err) } entries := make([]recorded, 0, len(hold.Spec.NetworkClaims)+1) @@ -117,15 +222,13 @@ func (r *Reconciler) observe( if apierrors.IsNotFound(err) { continue } - return nil, fmt.Errorf("failed reading claim %s recorded on switch port hold %s: %w", claimKey, key.Name, err) + return nil, false, fmt.Errorf("failed reading claim %s recorded on switch port hold %s: %w", claimKey, key.Name, err) } entries[i].claim = claim } - return entries, nil + return entries, false, nil } -// withdraw reports every claim the change touches as not programmed before -// the port moves, so none reports a port that is between states. func (r *Reconciler) withdraw( ctx context.Context, hold *networkingv1alpha.SwitchPortHold, @@ -136,13 +239,7 @@ func (r *Reconciler) withdraw( if !entry.onPort(hold) || !entry.changes(current, desired) { continue } - condition := metav1.Condition{ - Type: networkingv1alpha.NetworkInterfaceClaimProgrammed, - Status: metav1.ConditionFalse, - Reason: networkingv1alpha.NetworkInterfaceClaimReasonPortChanging, - Message: "The switch port is changing and is not confirmed to carry this network", - } - if err := r.report(ctx, entry.claim, nil, false, condition); err != nil { + if err := r.report(ctx, entry.claim, nil, false, portChanging()); err != nil { return fmt.Errorf("failed withdrawing claim %s/%s before changing its port: %w", entry.claim.Namespace, entry.claim.Name, err) } @@ -150,18 +247,23 @@ func (r *Reconciler) withdraw( return nil } -// settle runs once the port is read back carrying what its hold asks for. func (r *Reconciler) settle( ctx context.Context, + logger logr.Logger, hold *networkingv1alpha.SwitchPortHold, entries []recorded, carried []Membership, ) error { for _, entry := range entries { - if !entry.releasing(hold) || entry.carriedOn(carried) { + if !entry.releasing(hold) { continue } claim := entry.claim + if entry.carriedOn(carried) { + logger.Info("keeping the detach finalizer while the port carries the claim's network", + labels.ResourceNamespace, claim.Namespace, labels.ResourceName, claim.Name) + continue + } controllerutil.RemoveFinalizer(claim, networkingv1alpha.NetworkInterfaceClaimDetachFinalizer) if err := r.Client.Update(ctx, claim); err != nil && !apierrors.IsNotFound(err) { return fmt.Errorf("failed removing the detach finalizer from claim %s/%s: %w", claim.Namespace, claim.Name, err) @@ -184,17 +286,23 @@ func (r *Reconciler) settle( Message: "A boot claim holds the switch port, so the port carries the boot network instead", } } - var vlan *int32 - if network.membership.VLAN != 0 { - vlan = &network.membership.VLAN - } - if err := r.report(ctx, network.claim, vlan, true, programmed); err != nil { + vlan := network.membership.VLAN + if err := r.report(ctx, network.claim, &vlan, true, programmed); err != nil { return err } } return nil } +func portChanging() metav1.Condition { + return metav1.Condition{ + Type: networkingv1alpha.NetworkInterfaceClaimProgrammed, + Status: metav1.ConditionFalse, + Reason: networkingv1alpha.NetworkInterfaceClaimReasonPortChanging, + Message: "The switch port is changing and is not confirmed to carry this network", + } +} + func carriesNetwork() metav1.Condition { return metav1.Condition{ Type: networkingv1alpha.NetworkInterfaceClaimProgrammed, @@ -213,9 +321,7 @@ func prepared() metav1.Condition { } } -// report writes programmed, and with settled also Prepared and the VLAN, on -// the claim and on the interface bound to it. The interface goes first, so a -// provider reading the claim never sees more than the interface says. +// The interface is written first, so the claim never says more than it. func (r *Reconciler) report( ctx context.Context, claim *networkingv1alpha.NetworkInterfaceClaim, @@ -303,8 +409,11 @@ func holdForInterface(_ context.Context, obj client.Object) []ctrl.Request { return holdForAttachmentPoint(iface.Spec.AttachmentPoint) } -// SetupWithManager registers the realizer. A claim being deleted or bound, -// and an interface being bound, wakes the hold of the port they name. +func startSweeping(_ context.Context, queue workqueue.TypedRateLimitingInterface[reconcile.Request]) error { + queue.Add(SweepRequest) + return nil +} + func (r *Reconciler) SetupWithManager(mgr ctrl.Manager) error { if r.Driver == nil { return errors.New("a switch driver is required") @@ -319,6 +428,8 @@ func (r *Reconciler) SetupWithManager(mgr ctrl.Manager) error { For(&networkingv1alpha.SwitchPortHold{}). Watches(&networkingv1alpha.NetworkInterfaceClaim{}, handler.EnqueueRequestsFromMapFunc(holdForClaim)). Watches(&networkingv1alpha.NetworkInterface{}, handler.EnqueueRequestsFromMapFunc(holdForInterface)). + WatchesRawSource(source.Func(startSweeping)). + WithOptions(controller.Options{MaxConcurrentReconciles: 1}). Named(ControllerName). Complete(r) } diff --git a/internal/physicalrealizer/reconciler_test.go b/internal/physicalrealizer/reconciler_test.go index e6ca09c7..df5c2731 100644 --- a/internal/physicalrealizer/reconciler_test.go +++ b/internal/physicalrealizer/reconciler_test.go @@ -17,37 +17,143 @@ import ( networkingv1alpha "go.datum.net/network-services-operator/api/v1alpha" ) -func TestADeletedClaimWhoseNetworkIsStillCarriedKeepsItsFinalizer(t *testing.T) { - ctx := context.Background() +func fakeRealizer(t *testing.T, objects ...client.Object) (*Reconciler, client.Client, *SimulatedSwitch) { + t.Helper() scheme := runtime.NewScheme() require.NoError(t, networkingv1alpha.AddToScheme(scheme)) + cl := fake.NewClientBuilder().WithScheme(scheme). + WithObjects(objects...). + WithStatusSubresource(&networkingv1alpha.NetworkInterfaceClaim{}, &networkingv1alpha.NetworkInterface{}). + Build() + sw := NewSimulatedSwitch() + return &Reconciler{Client: cl, APIReader: cl, Driver: sw}, cl, sw +} - data := physicalClaim("ns-customer-example", "server-data", "app", "") - leaving := physicalClaim("ns-customer-example", "server-data-old", "app", "") - leaving.DeletionTimestamp = ptrTo(metav1.Now()) +func holdRecording(claims ...*networkingv1alpha.NetworkInterfaceClaim) *networkingv1alpha.SwitchPortHold { hold := testHold() hold.Spec.ConsumerRef = &networkingv1alpha.SwitchPortHoldConsumerRef{ APIGroup: "resourcemanager.miloapis.com", Kind: "Project", Name: "customer-example", } - hold.Spec.NetworkClaims = []networkingv1alpha.SwitchPortHoldClaimRef{ - {Namespace: data.Namespace, Name: data.Name, Network: "app"}, - {Namespace: leaving.Namespace, Name: leaving.Name, Network: "retired"}, + for _, claim := range claims { + hold.Spec.NetworkClaims = append(hold.Spec.NetworkClaims, networkingv1alpha.SwitchPortHoldClaimRef{ + Namespace: claim.Namespace, Name: claim.Name, Network: claim.Spec.Network.Name, + }) } + return hold +} - cl := fake.NewClientBuilder().WithScheme(scheme). - WithObjects(hold, data, leaving). - WithStatusSubresource(&networkingv1alpha.NetworkInterfaceClaim{}, &networkingv1alpha.NetworkInterface{}). - Build() - sw := NewSimulatedSwitch() - r := &Reconciler{Client: cl, APIReader: cl, Driver: sw} +var testPortKey = Port{Switch: testSwitch, Name: testPort} + +func TestADeletedClaimWhoseNetworkIsStillCarriedKeepsItsFinalizer(t *testing.T) { + ctx := context.Background() + data := physicalClaim("ns-customer-example", "server-data", "app", "") + leaving := physicalClaim("ns-customer-example", "server-data-old", "app", "") + leaving.DeletionTimestamp = ptrTo(metav1.Now()) + hold := holdRecording(data) + hold.Spec.NetworkClaims = append(hold.Spec.NetworkClaims, networkingv1alpha.SwitchPortHoldClaimRef{ + Namespace: leaving.Namespace, Name: leaving.Name, Network: "retired", + }) + r, cl, sw := fakeRealizer(t, hold, data, leaving) _, err := r.Reconcile(ctx, ctrl.Request{NamespacedName: client.ObjectKeyFromObject(hold)}) require.NoError(t, err) - require.Equal(t, []Membership{{Network: network("ns-customer-example", "app"), - Isolation: networkingv1alpha.NetworkInterfaceIsolationShared}}, sw.Carried(Port{Switch: testSwitch, Name: testPort})) + carried := sw.Carried(testPortKey) + require.Len(t, carried, 1) + require.Equal(t, network("ns-customer-example", "app"), carried[0].Network) var stored networkingv1alpha.NetworkInterfaceClaim require.NoError(t, cl.Get(ctx, client.ObjectKeyFromObject(leaving), &stored)) require.True(t, controllerutil.ContainsFinalizer(&stored, networkingv1alpha.NetworkInterfaceClaimDetachFinalizer), "the port still carries the network the deleted claim names") } + +func TestAHoldNotNamedForItsPortIsRefused(t *testing.T) { + ctx := context.Background() + data := physicalClaim("ns-customer-example", "server-data", "app", "") + hold := holdRecording(data) + hold.Name = networkingv1alpha.SwitchPortHoldName(testSwitch, "Ethernet1/99") + r, _, sw := fakeRealizer(t, hold, data) + stale := []Membership{{Network: network("ns-customer-example", "retired"), VLAN: 100}} + require.NoError(t, sw.Apply(ctx, testPortKey, stale)) + before := len(sw.History()) + + _, err := r.Reconcile(ctx, ctrl.Request{NamespacedName: client.ObjectKeyFromObject(hold)}) + require.NoError(t, err) + require.Len(t, sw.History(), before, "no port is touched for a hold named for another port") + require.Equal(t, stale, sw.Carried(testPortKey)) + + _, err = r.Reconcile(ctx, SweepRequest) + require.NoError(t, err) + require.Empty(t, sw.Carried(testPortKey), "a misnamed hold protects no port from the sweep") +} + +func TestTheSweepClearsOnlyPortsNoHoldNames(t *testing.T) { + ctx := context.Background() + data := physicalClaim("ns-customer-example", "server-data", "app", "") + hold := holdRecording(data) + r, _, sw := fakeRealizer(t, hold, data) + _, err := r.Reconcile(ctx, ctrl.Request{NamespacedName: client.ObjectKeyFromObject(hold)}) + require.NoError(t, err) + carried := sw.Carried(testPortKey) + require.Len(t, carried, 1) + + orphan := Port{Switch: testSwitch, Name: "Ethernet1/13"} + require.NoError(t, sw.Apply(ctx, orphan, []Membership{{Network: network("ns-customer-example", "app"), VLAN: 100}})) + + result, err := r.Reconcile(ctx, SweepRequest) + require.NoError(t, err) + require.Equal(t, SweepInterval, result.RequeueAfter, "the sweep runs again on its own") + require.Empty(t, sw.Carried(orphan)) + require.Equal(t, carried, sw.Carried(testPortKey), "a port a hold names is left alone") + + sw.FailReads(true) + _, err = r.Reconcile(ctx, SweepRequest) + require.ErrorIs(t, err, ErrSwitchUnreachable) +} + +func TestAPortWhoseHoldIsGoneAtTheStartIsCleared(t *testing.T) { + ctx := context.Background() + r, _, sw := fakeRealizer(t) + require.NoError(t, sw.Apply(ctx, testPortKey, []Membership{{Network: network("ns-customer-example", "app"), VLAN: 100}})) + + _, err := r.Reconcile(ctx, ctrl.Request{NamespacedName: client.ObjectKey{ + Name: networkingv1alpha.SwitchPortHoldName(testSwitch, testPort), + }}) + require.NoError(t, err) + require.Empty(t, sw.Carried(testPortKey)) +} + +// vanishingHold reads a hold once and deletes it right after, as an operator +// deleting it in the middle of a pass would. +type vanishingHold struct { + client.Client + read bool +} + +func (c *vanishingHold) Get(ctx context.Context, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if err := c.Client.Get(ctx, key, obj, opts...); err != nil { + return err + } + if hold, ok := obj.(*networkingv1alpha.SwitchPortHold); ok && !c.read { + c.read = true + return c.Delete(ctx, hold.DeepCopy()) + } + return nil +} + +func TestAPortWhoseHoldVanishesMidPassIsCleared(t *testing.T) { + ctx := context.Background() + data := physicalClaim("ns-customer-example", "server-data", "app", "") + hold := holdRecording(data) + r, cl, sw := fakeRealizer(t, hold, data) + _, err := r.Reconcile(ctx, ctrl.Request{NamespacedName: client.ObjectKeyFromObject(hold)}) + require.NoError(t, err) + require.Len(t, sw.Carried(testPortKey), 1) + + reader := &vanishingHold{Client: cl} + r.APIReader = reader + _, err = r.Reconcile(ctx, ctrl.Request{NamespacedName: client.ObjectKeyFromObject(hold)}) + require.NoError(t, err) + require.True(t, reader.read) + require.Empty(t, sw.Carried(testPortKey)) +} diff --git a/internal/physicalrealizer/simulated.go b/internal/physicalrealizer/simulated.go index c7ea5e7a..f93c2aae 100644 --- a/internal/physicalrealizer/simulated.go +++ b/internal/physicalrealizer/simulated.go @@ -7,22 +7,21 @@ import ( "errors" "fmt" "slices" + "strings" "sync" ) const maxVLAN = 4094 -// ErrSwitchUnreachable is what a simulated switch told to fail returns. var ErrSwitchUnreachable = errors.New("simulated switch is unreachable") -// Change is one state a simulated port reached. type Change struct { Port Port Carried []Membership } -// SimulatedSwitch is an in-memory Driver. Its hooks make a change fail, apply -// only partly, or make reads fail, and it records every state a port reaches. +// SimulatedSwitch is an in-memory Driver that records every state a port +// reaches, with hooks to fail or partly apply changes and to fail reads. type SimulatedSwitch struct { mu sync.Mutex ports map[Port][]Membership @@ -39,7 +38,6 @@ func NewSimulatedSwitch() *SimulatedSwitch { return &SimulatedSwitch{ports: map[Port][]Membership{}} } -// FailApplies makes the next n changes fail without touching the port. func (s *SimulatedSwitch) FailApplies(n int) { s.mu.Lock() defer s.mu.Unlock() @@ -54,28 +52,24 @@ func (s *SimulatedSwitch) PartlyApply(n int) { s.partialApplies = n } -// FailReads makes every read fail until it is called with false. func (s *SimulatedSwitch) FailReads(fail bool) { s.mu.Lock() defer s.mu.Unlock() s.failReads = fail } -// BeforeApply runs hook at the start of every change, before the port moves. func (s *SimulatedSwitch) BeforeApply(hook func(Port, []Membership)) { s.mu.Lock() defer s.mu.Unlock() s.beforeApply = hook } -// Carried reports what port carries, without the read hooks. func (s *SimulatedSwitch) Carried(port Port) []Membership { s.mu.Lock() defer s.mu.Unlock() return slices.Clone(s.ports[port]) } -// History returns every state any port reached, in order. func (s *SimulatedSwitch) History() []Change { s.mu.Lock() defer s.mu.Unlock() @@ -128,6 +122,22 @@ func (s *SimulatedSwitch) Read(_ context.Context, port Port) ([]Membership, erro return slices.Clone(s.ports[port]), nil } +func (s *SimulatedSwitch) Ports(_ context.Context) ([]Port, error) { + s.mu.Lock() + defer s.mu.Unlock() + if s.failReads { + return nil, fmt.Errorf("listing ports: %w", ErrSwitchUnreachable) + } + ports := make([]Port, 0, len(s.ports)) + for port := range s.ports { + ports = append(ports, port) + } + slices.SortFunc(ports, func(a, b Port) int { + return strings.Compare(a.Switch+"\x00"+a.Name, b.Switch+"\x00"+b.Name) + }) + return ports, nil +} + func validMemberships(memberships []Membership) error { untagged := 0 vlans := map[int32]bool{}