From 42b86f4640e37bcb00e72b08c3def12cd86956ad Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 22:55:54 -0600 Subject: [PATCH 1/2] feat: Hold switch ports for physical claims NSO now binds physical claims instead of refusing them. A cell-local SwitchPortHold records which claims name each switch port, so one project's network claims and one boot claim at most can hold a port, and the realizer has one place to read what a port carries. Deleting a physical claim waits for the realizer to take its network off the port before any address is released. Key changes: - add the cluster-scoped SwitchPortHold, named from a hash of the switch and port, to the API and the cell CRD bundle - add the operator and detach finalizers in one write, and record a claim on its port's hold by compare-and-swap before allocating - make a claim that cannot share its port wait with AttachmentPointHeld, allocating nothing and naming nothing about the holder - refuse a claim whose hold name collides with another port's - hold a recorded claim's release with AwaitingDetach until the realizer removes the detach finalizer, and remove it from a claim no hold recorded - free and verify a recorded claim's addresses by its name when no interface was recorded, and keep the interface controller from freeing them early - leave the hold on release, deleting it only if unchanged since read, and drop entries whose claims are gone on every write - replace PhysicalAttachmentUnsupported with the two new reasons Co-Authored-By: Claude Opus 5.5 --- api/v1alpha/groupversion_info.go | 2 + api/v1alpha/networkinterfaceclaim_types.go | 14 +- api/v1alpha/switchporthold_types.go | 139 ++++ api/v1alpha/zz_generated.deepcopy.go | 118 +++ .../physical-attachment-admission/README.md | 4 +- ...working.datumapis.com_switchportholds.yaml | 174 ++++ config/crd/downstream/kustomization.yaml | 5 +- config/rbac/role.yaml | 1 + .../physicalattachment_test.go | 26 + internal/agent/catalog_test.go | 1 + .../controller/networkinterface_controller.go | 9 +- .../networkinterfaceclaim_controller.go | 138 +++- .../networkinterfaceclaim_controller_test.go | 55 +- .../networkinterfaceclaim_physical_test.go | 748 ++++++++++++++++++ .../networkinterfaceclaim_release_test.go | 102 +-- internal/controller/switchporthold.go | 327 ++++++++ internal/networkagent/catalog.go | 18 +- internal/networkagent/catalog_test.go | 1 + 18 files changed, 1739 insertions(+), 143 deletions(-) create mode 100644 api/v1alpha/switchporthold_types.go create mode 100644 config/crd/bases/networking.datumapis.com_switchportholds.yaml create mode 100644 internal/controller/networkinterfaceclaim_physical_test.go create mode 100644 internal/controller/switchporthold.go diff --git a/api/v1alpha/groupversion_info.go b/api/v1alpha/groupversion_info.go index c443e4a7..0b70a4cc 100644 --- a/api/v1alpha/groupversion_info.go +++ b/api/v1alpha/groupversion_info.go @@ -58,6 +58,8 @@ func addKnownTypes(scheme *runtime.Scheme) error { &SubnetList{}, &SubnetClaim{}, &SubnetClaimList{}, + &SwitchPortHold{}, + &SwitchPortHoldList{}, &TrafficProtectionPolicy{}, &TrafficProtectionPolicyList{}, ) diff --git a/api/v1alpha/networkinterfaceclaim_types.go b/api/v1alpha/networkinterfaceclaim_types.go index 38a0b383..c1f823c0 100644 --- a/api/v1alpha/networkinterfaceclaim_types.go +++ b/api/v1alpha/networkinterfaceclaim_types.go @@ -89,10 +89,16 @@ const ( // control plane is not bootstrapped rather than that it is slow to appear. NetworkInterfaceClaimReasonProjectNamespaceNotFound = "ProjectNamespaceNotFound" - // NetworkInterfaceClaimReasonPhysicalAttachmentUnsupported means the claim - // asks for a physical attachment, which this operator does not bind yet. - // Nothing is allocated for it. - NetworkInterfaceClaimReasonPhysicalAttachmentUnsupported = "PhysicalAttachmentUnsupported" + // NetworkInterfaceClaimReasonAttachmentPointHeld means the switch port the + // physical claim names is held by claims it cannot share the port with, so + // the claim waits and nothing is allocated for it. The provider reads the + // port's SwitchPortHold to see what holds it. + NetworkInterfaceClaimReasonAttachmentPointHeld = "AttachmentPointHeld" + + // 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. + NetworkInterfaceClaimReasonAwaitingDetach = "AwaitingDetach" ) // NetworkInterfaceAddressRequest asks for one address beyond the ones the diff --git a/api/v1alpha/switchporthold_types.go b/api/v1alpha/switchporthold_types.go new file mode 100644 index 00000000..67dd63da --- /dev/null +++ b/api/v1alpha/switchporthold_types.go @@ -0,0 +1,139 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +package v1alpha + +import ( + "crypto/sha256" + "encoding/hex" + "strconv" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +const switchPortHoldNameHashLength = 40 + +// SwitchPortHoldName is the name of the hold for a switch port. Port names can +// hold characters a Kubernetes name cannot, so the name is a hash. Each part is +// prefixed with its length, so no two pairs encode to the same bytes. +func SwitchPortHoldName(switchName, port string) string { + encoded := strconv.Itoa(len(switchName)) + ":" + switchName + strconv.Itoa(len(port)) + ":" + port + sum := sha256.Sum256([]byte(encoded)) + return "port-" + hex.EncodeToString(sum[:])[:switchPortHoldNameHashLength] +} + +// SwitchPortHoldClaimRef names a physical claim recorded on a hold. +type SwitchPortHoldClaimRef struct { + // namespace is the claim's namespace. + // + // +kubebuilder:validation:Required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=63 + Namespace string `json:"namespace"` + + // name is the claim's name. + // + // +kubebuilder:validation:Required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=253 + Name string `json:"name"` + + // network is the network the claim names, in the claim's namespace. + // + // +kubebuilder:validation:Required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=253 + Network string `json:"network"` +} + +// SwitchPortHoldConsumerRef names the project whose network claims hold a +// port. +type SwitchPortHoldConsumerRef struct { + // apiGroup is the API group of the project type. + // + // +kubebuilder:validation:Required + // +kubebuilder:validation:MinLength=1 + APIGroup string `json:"apiGroup"` + + // kind is the project type. + // + // +kubebuilder:validation:Required + // +kubebuilder:validation:MinLength=1 + Kind string `json:"kind"` + + // name is the project's name. + // + // +kubebuilder:validation:Required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=253 + Name string `json:"name"` +} + +// SwitchPortHoldSpec records the claims that name one switch port. +// +// +kubebuilder:validation:XValidation:message="consumerRef is set exactly when networkClaims records a claim",rule="has(self.consumerRef) == (has(self.networkClaims) && size(self.networkClaims) > 0)" +type SwitchPortHoldSpec struct { + // switch is the switch, stored in full. A hold whose stored pair differs + // from a claim's is a hash collision, and the claim is refused. + // + // +kubebuilder:validation:Required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=253 + // +kubebuilder:validation:XValidation:message="switch is immutable",rule="self == oldSelf" + Switch string `json:"switch"` + + // port is the switch port, stored in full. + // + // +kubebuilder:validation:Required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=253 + // +kubebuilder:validation:XValidation:message="port is immutable",rule="self == oldSelf" + Port string `json:"port"` + + // boot is the one boot claim on the port. While it is set the port carries + // its network and nothing else. + // + // +kubebuilder:validation:Optional + Boot *SwitchPortHoldClaimRef `json:"boot,omitempty"` + + // consumerRef is the project whose network claims hold the port. It is set + // with the first network claim and cleared with the last. + // + // +kubebuilder:validation:Optional + ConsumerRef *SwitchPortHoldConsumerRef `json:"consumerRef,omitempty"` + + // networkClaims are the network claims on the port, all from the project + // in consumerRef. + // + // +kubebuilder:validation:Optional + // +kubebuilder:validation:MaxItems=256 + // +listType=atomic + NetworkClaims []SwitchPortHoldClaimRef `json:"networkClaims,omitempty"` +} + +// +kubebuilder:object:root=true +// +kubebuilder:resource:scope=Cluster +// +kubebuilder:printcolumn:name="Switch",type=string,JSONPath=".spec.switch" +// +kubebuilder:printcolumn:name="Port",type=string,JSONPath=".spec.port" +// +kubebuilder:printcolumn:name="Boot",type=string,JSONPath=".spec.boot.name" +// +kubebuilder:printcolumn:name="Consumer",type=string,JSONPath=".spec.consumerRef.name" +// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp" + +// SwitchPortHold records the physical claims that name one switch port, which +// decides what the port carries. The operator is its only writer and changes +// it only by compare-and-swap. The physical realizer reads it. +type SwitchPortHold struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + // +kubebuilder:validation:Required + Spec SwitchPortHoldSpec `json:"spec"` +} + +// +kubebuilder:object:root=true + +// SwitchPortHoldList contains a list of SwitchPortHold. +type SwitchPortHoldList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []SwitchPortHold `json:"items"` +} diff --git a/api/v1alpha/zz_generated.deepcopy.go b/api/v1alpha/zz_generated.deepcopy.go index 4941bc39..4daa09c3 100644 --- a/api/v1alpha/zz_generated.deepcopy.go +++ b/api/v1alpha/zz_generated.deepcopy.go @@ -3957,6 +3957,124 @@ func (in *SubnetStatus) DeepCopy() *SubnetStatus { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *SwitchPortHold) DeepCopyInto(out *SwitchPortHold) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SwitchPortHold. +func (in *SwitchPortHold) DeepCopy() *SwitchPortHold { + if in == nil { + return nil + } + out := new(SwitchPortHold) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *SwitchPortHold) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *SwitchPortHoldClaimRef) DeepCopyInto(out *SwitchPortHoldClaimRef) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SwitchPortHoldClaimRef. +func (in *SwitchPortHoldClaimRef) DeepCopy() *SwitchPortHoldClaimRef { + if in == nil { + return nil + } + out := new(SwitchPortHoldClaimRef) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *SwitchPortHoldConsumerRef) DeepCopyInto(out *SwitchPortHoldConsumerRef) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SwitchPortHoldConsumerRef. +func (in *SwitchPortHoldConsumerRef) DeepCopy() *SwitchPortHoldConsumerRef { + if in == nil { + return nil + } + out := new(SwitchPortHoldConsumerRef) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *SwitchPortHoldList) DeepCopyInto(out *SwitchPortHoldList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]SwitchPortHold, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SwitchPortHoldList. +func (in *SwitchPortHoldList) DeepCopy() *SwitchPortHoldList { + if in == nil { + return nil + } + out := new(SwitchPortHoldList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *SwitchPortHoldList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *SwitchPortHoldSpec) DeepCopyInto(out *SwitchPortHoldSpec) { + *out = *in + if in.Boot != nil { + in, out := &in.Boot, &out.Boot + *out = new(SwitchPortHoldClaimRef) + **out = **in + } + if in.ConsumerRef != nil { + in, out := &in.ConsumerRef, &out.ConsumerRef + *out = new(SwitchPortHoldConsumerRef) + **out = **in + } + if in.NetworkClaims != nil { + in, out := &in.NetworkClaims, &out.NetworkClaims + *out = make([]SwitchPortHoldClaimRef, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SwitchPortHoldSpec. +func (in *SwitchPortHoldSpec) DeepCopy() *SwitchPortHoldSpec { + if in == nil { + return nil + } + out := new(SwitchPortHoldSpec) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TrafficProtectionPolicy) DeepCopyInto(out *TrafficProtectionPolicy) { *out = *in diff --git a/config/components/physical-attachment-admission/README.md b/config/components/physical-attachment-admission/README.md index 70fcb16c..a30b9f3d 100644 --- a/config/components/physical-attachment-admission/README.md +++ b/config/components/physical-attachment-admission/README.md @@ -10,7 +10,9 @@ isolation on any other mode, and keep the mode from changing. such as to remove its finalizers, but not create one. The claim's schema already keeps its spec from changing. - Only the realizer, or a break-glass operator, may remove the - `networking.datumapis.com/physical-detach` finalizer. + `networking.datumapis.com/physical-detach` finalizer. The operator is + exempt, and removes it only from a deleted claim that no `SwitchPortHold` + records, which no realizer ever acted on. - Only the operator may add that finalizer, or write a physical interface. - A claim with `purpose: Boot` is created only in a namespace whose project, decoded from its `meta.datumapis.com/upstream-cluster-name` label, is a diff --git a/config/crd/bases/networking.datumapis.com_switchportholds.yaml b/config/crd/bases/networking.datumapis.com_switchportholds.yaml new file mode 100644 index 00000000..84dde428 --- /dev/null +++ b/config/crd/bases/networking.datumapis.com_switchportholds.yaml @@ -0,0 +1,174 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.17.3 + name: switchportholds.networking.datumapis.com +spec: + group: networking.datumapis.com + names: + kind: SwitchPortHold + listKind: SwitchPortHoldList + plural: switchportholds + singular: switchporthold + scope: Cluster + versions: + - additionalPrinterColumns: + - jsonPath: .spec.switch + name: Switch + type: string + - jsonPath: .spec.port + name: Port + type: string + - jsonPath: .spec.boot.name + name: Boot + type: string + - jsonPath: .spec.consumerRef.name + name: Consumer + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha + schema: + openAPIV3Schema: + description: |- + SwitchPortHold records the physical claims that name one switch port, which + decides what the port carries. The operator is its only writer and changes + it only by compare-and-swap. The physical realizer reads it. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: SwitchPortHoldSpec records the claims that name one switch + port. + properties: + boot: + description: |- + boot is the one boot claim on the port. While it is set the port carries + its network and nothing else. + properties: + name: + description: name is the claim's name. + maxLength: 253 + minLength: 1 + type: string + namespace: + description: namespace is the claim's namespace. + maxLength: 63 + minLength: 1 + type: string + network: + description: network is the network the claim names, in the claim's + namespace. + maxLength: 253 + minLength: 1 + type: string + required: + - name + - namespace + - network + type: object + consumerRef: + description: |- + consumerRef is the project whose network claims hold the port. It is set + with the first network claim and cleared with the last. + properties: + apiGroup: + description: apiGroup is the API group of the project type. + minLength: 1 + type: string + kind: + description: kind is the project type. + minLength: 1 + type: string + name: + description: name is the project's name. + maxLength: 253 + minLength: 1 + type: string + required: + - apiGroup + - kind + - name + type: object + networkClaims: + description: |- + networkClaims are the network claims on the port, all from the project + in consumerRef. + items: + description: SwitchPortHoldClaimRef names a physical claim recorded + on a hold. + properties: + name: + description: name is the claim's name. + maxLength: 253 + minLength: 1 + type: string + namespace: + description: namespace is the claim's namespace. + maxLength: 63 + minLength: 1 + type: string + network: + description: network is the network the claim names, in the + claim's namespace. + maxLength: 253 + minLength: 1 + type: string + required: + - name + - namespace + - network + type: object + maxItems: 256 + type: array + x-kubernetes-list-type: atomic + port: + description: port is the switch port, stored in full. + maxLength: 253 + minLength: 1 + type: string + x-kubernetes-validations: + - message: port is immutable + rule: self == oldSelf + switch: + description: |- + switch is the switch, stored in full. A hold whose stored pair differs + from a claim's is a hash collision, and the claim is refused. + maxLength: 253 + minLength: 1 + type: string + x-kubernetes-validations: + - message: switch is immutable + rule: self == oldSelf + required: + - port + - switch + type: object + x-kubernetes-validations: + - message: consumerRef is set exactly when networkClaims records a claim + rule: has(self.consumerRef) == (has(self.networkClaims) && size(self.networkClaims) + > 0) + required: + - spec + type: object + served: true + storage: true + subresources: {} diff --git a/config/crd/downstream/kustomization.yaml b/config/crd/downstream/kustomization.yaml index 096c7072..9f796f86 100644 --- a/config/crd/downstream/kustomization.yaml +++ b/config/crd/downstream/kustomization.yaml @@ -29,7 +29,9 @@ # The cell set is derived from what the cell controller manager watches # (internal/cmd/cell/cell.go): NetworkInterfaceClaim, NetworkInterface, # NetworkContext and Subnet on the local cluster. It also watches -# ServingLocation, which the locations service installs. +# ServingLocation, which the locations service installs. It writes +# SwitchPortHold, the cell-local record of which physical claims hold each +# switch port. resources: # Gateway data plane - ../bases/networking.datumapis.com_edgereachabilities.yaml @@ -46,6 +48,7 @@ resources: # Network interface claim path, served on cells - ../bases/networking.datumapis.com_networkinterfaceclaims.yaml - ../bases/networking.datumapis.com_networkinterfaces.yaml + - ../bases/networking.datumapis.com_switchportholds.yaml - ../bases/networking.datumapis.com_networkloadbalancerbackendhealths.yaml - ../bases/networking.datumapis.com_networkloadbalancercellintents.yaml - ../bases/networking.datumapis.com_subnets.yaml diff --git a/config/rbac/role.yaml b/config/rbac/role.yaml index 0c652d13..88a9c618 100644 --- a/config/rbac/role.yaml +++ b/config/rbac/role.yaml @@ -330,6 +330,7 @@ rules: - networks - subnetclaims - subnets + - switchportholds - trafficprotectionpolicies verbs: - create diff --git a/internal/admissionpolicy/physicalattachment_test.go b/internal/admissionpolicy/physicalattachment_test.go index 5a47def4..134557f7 100644 --- a/internal/admissionpolicy/physicalattachment_test.go +++ b/internal/admissionpolicy/physicalattachment_test.go @@ -325,6 +325,32 @@ func TestOnlyTheOperatorAddsTheDetachFinalizer(t *testing.T) { requireRefused(t, e.as(realizer).Update(e.ctx, &claim)) } +// The operator adds both finalizers in one write when it first sees a physical +// claim, and removes the detach finalizer itself from a deleted claim no port +// ever carried. Both must stay admitted under a configured policy. +func TestTheOperatorsOwnFinalizerWritesAreAdmitted(t *testing.T) { + e := startEnv(t) + e.configure() + + require.NoError(t, e.as(provider).Create(e.ctx, physicalClaim(customerNamespace, "operator-finalizers"))) + key := client.ObjectKey{Namespace: customerNamespace, Name: "operator-finalizers"} + var claim networkingv1alpha.NetworkInterfaceClaim + require.NoError(t, e.admin.Get(e.ctx, key, &claim)) + claim.Finalizers = []string{ + "networking.datumapis.com/networkinterfaceclaim-release", + networkingv1alpha.NetworkInterfaceClaimDetachFinalizer, + } + require.NoError(t, e.as(operator).Update(e.ctx, &claim)) + + require.NoError(t, e.as(provider).Delete(e.ctx, &claim)) + require.NoError(t, e.admin.Get(e.ctx, key, &claim)) + require.False(t, claim.DeletionTimestamp.IsZero()) + claim.Finalizers = []string{"networking.datumapis.com/networkinterfaceclaim-release"} + require.NoError(t, e.as(operator).Update(e.ctx, &claim)) + claim.Finalizers = nil + require.NoError(t, e.as(operator).Update(e.ctx, &claim)) +} + func TestBootClaimsOnlyInProviderProjects(t *testing.T) { e := startEnv(t) e.configure() diff --git a/internal/agent/catalog_test.go b/internal/agent/catalog_test.go index eddaa57c..35f9da12 100644 --- a/internal/agent/catalog_test.go +++ b/internal/agent/catalog_test.go @@ -49,6 +49,7 @@ var outOfScopeAPIFiles = map[string]string{ "portrange_types.go": "port interval value and validation helpers; declares no condition reasons", "subnet_types.go": "address management below a network", "subnetclaim_types.go": "address management below a network", + "switchporthold_types.go": "which physical claims hold a switch port, in a cell", "trafficprotectionpolicy_types.go": "declares no reasons of its own; the controller writes upstream Gateway API policy reasons", "zz_generated.deepcopy.go": "generated", } diff --git a/internal/controller/networkinterface_controller.go b/internal/controller/networkinterface_controller.go index c16bb1f3..072cf956 100644 --- a/internal/controller/networkinterface_controller.go +++ b/internal/controller/networkinterface_controller.go @@ -171,7 +171,7 @@ func keptInterfacesOnNetworkContext(ctx context.Context, cl client.Client, obj c } // heldByLiveClaim reports whether a claim named in claimRef still exists and is -// not being deleted. +// not being deleted, or is a physical claim whose port is not yet detached. func (r *NetworkInterfaceReconciler) heldByLiveClaim( ctx context.Context, cl client.Client, @@ -192,8 +192,11 @@ func (r *NetworkInterfaceReconciler) heldByLiveClaim( } // A claim being deleted holds nothing. Its own release cannot free these - // addresses once the interface is gone. - return claim.DeletionTimestamp.IsZero(), nil + // addresses once the interface is gone. A physical claim still waiting for + // its port to be detached is the exception: the port may carry these + // addresses, and its release finds them by its own name once it is clear. + return claim.DeletionTimestamp.IsZero() || + controllerutil.ContainsFinalizer(&claim, networkingv1alpha.NetworkInterfaceClaimDetachFinalizer), nil } // SetupWithManager sets up the controller with the Manager. diff --git a/internal/controller/networkinterfaceclaim_controller.go b/internal/controller/networkinterfaceclaim_controller.go index fb16b972..0d5b4db4 100644 --- a/internal/controller/networkinterfaceclaim_controller.go +++ b/internal/controller/networkinterfaceclaim_controller.go @@ -90,6 +90,7 @@ type NetworkInterfaceClaimReconciler struct { // +kubebuilder:rbac:groups=networking.datumapis.com,resources=networkcontexts,verbs=get;list;watch;update;patch // +kubebuilder:rbac:groups=networking.datumapis.com,resources=networkcontexts/finalizers,verbs=update // +kubebuilder:rbac:groups=networking.datumapis.com,resources=subnets,verbs=get;list;watch +// +kubebuilder:rbac:groups=networking.datumapis.com,resources=switchportholds,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=locations.miloapis.com,resources=servinglocations,verbs=get;list;watch // +kubebuilder:rbac:groups=events.k8s.io,resources=events,verbs=create;patch @@ -104,7 +105,8 @@ func (r *NetworkInterfaceClaimReconciler) Reconcile(ctx context.Context, req mcr logger.V(1).Info("reconciling network interface claim") defer logger.V(1).Info("reconcile complete") - result, err := r.reconcileClaim(ctx, cl.GetClient(), cl.GetEventRecorder("networkinterfaceclaim-controller"), req.NamespacedName) + result, err := r.reconcileClaim(ctx, cl.GetClient(), cl.GetAPIReader(), + cl.GetEventRecorder("networkinterfaceclaim-controller"), req.NamespacedName) if retryResult, expected := networkInterfaceClaimWriteRace(err); expected { // Another reconciler or the API server won the write race. A fresh read is // required, but this is normal convergence rather than a controller error. @@ -123,9 +125,13 @@ func networkInterfaceClaimWriteRace(err error) (ctrl.Result, bool) { } } +// reconcileClaim reads holds through reader, which must not be a cache: a +// switch port hold is changed only by compare-and-swap against what the API +// server holds now. func (r *NetworkInterfaceClaimReconciler) reconcileClaim( ctx context.Context, cl client.Client, + reader client.Reader, recorder events.EventRecorder, key client.ObjectKey, ) (ctrl.Result, error) { @@ -135,30 +141,32 @@ func (r *NetworkInterfaceClaimReconciler) reconcileClaim( } if !claim.DeletionTimestamp.IsZero() { - return r.release(ctx, cl, &claim) + return r.release(ctx, cl, reader, &claim) } - if controllerutil.AddFinalizer(&claim, networkInterfaceClaimFinalizer) { + // Both finalizers land in one write, so a physical claim deleted before it + // has neither and took nothing. The API server refuses a new finalizer on + // an object being deleted, so the detach finalizer never reaches one. + added := controllerutil.AddFinalizer(&claim, networkInterfaceClaimFinalizer) + if isPhysical(&claim) { + added = controllerutil.AddFinalizer(&claim, networkingv1alpha.NetworkInterfaceClaimDetachFinalizer) || added + } + if added { if err := cl.Update(ctx, &claim); err != nil { return ctrl.Result{}, fmt.Errorf("failed adding finalizer: %w", err) } } - return r.fulfill(ctx, cl, recorder, &claim) + return r.fulfill(ctx, cl, reader, recorder, &claim) } func (r *NetworkInterfaceClaimReconciler) fulfill( ctx context.Context, cl client.Client, + reader client.Reader, recorder events.EventRecorder, claim *networkingv1alpha.NetworkInterfaceClaim, ) (ctrl.Result, error) { - if claim.Spec.AttachmentMode == networkingv1alpha.NetworkInterfaceAttachmentModePhysical { - return r.reject(ctx, cl, claim, - networkingv1alpha.NetworkInterfaceClaimReasonPhysicalAttachmentUnsupported, - "Physical attachment is not available yet, so no address is allocated for this claim") - } - location, err := r.location(ctx) if err != nil { var unresolved *locationidentity.LocationUnresolved @@ -206,6 +214,28 @@ func (r *NetworkInterfaceClaimReconciler) fulfill( terminating)) } + // Recording comes before any address or interface exists, so whether the + // hold ever recorded the claim is what says the realizer may have touched + // the port. + if isPhysical(claim) { + recorded, err := recordOnHold(ctx, cl, reader, claim, routing.project) + if err != nil { + var refused *bindingRefused + if errors.As(err, &refused) { + return r.reject(ctx, cl, claim, refused.reason, refused.message) + } + return ctrl.Result{}, err + } + if !recorded { + // The port may be held by another customer, so the message says + // nothing about what holds it. + return r.reject(ctx, cl, claim, + networkingv1alpha.NetworkInterfaceClaimReasonAttachmentPointHeld, + "The switch port this claim names is held by claims it cannot share the port with, "+ + "so no address is allocated until the port is free") + } + } + ipamClient, err := r.IPAM.ClientForProject(routing.project) if err != nil { return ctrl.Result{}, fmt.Errorf("failed building IPAM client: %w", err) @@ -1499,6 +1529,7 @@ func seedCondition(conditions *[]metav1.Condition, conditionType string, generat func (r *NetworkInterfaceClaimReconciler) release( ctx context.Context, cl client.Client, + reader client.Reader, claim *networkingv1alpha.NetworkInterfaceClaim, ) (ctrl.Result, error) { if !controllerutil.ContainsFinalizer(claim, networkInterfaceClaimFinalizer) { @@ -1509,6 +1540,19 @@ func (r *NetworkInterfaceClaimReconciler) release( return ctrl.Result{}, err } + physical := isPhysical(claim) + recorded := false + if physical { + hold, err := readHold(ctx, reader, claim) + if err != nil { + return ctrl.Result{}, err + } + recorded = hold != nil && holdRecords(hold, claim) + if detached, err := awaitDetach(ctx, cl, claim, recorded); err != nil || !detached { + return ctrl.Result{}, err + } + } + var iface networkingv1alpha.NetworkInterface interfaceKey := client.ObjectKey{Namespace: claim.Namespace, Name: interfaceNameForClaim(claim)} err := cl.Get(ctx, interfaceKey, &iface) @@ -1520,7 +1564,7 @@ func (r *NetworkInterfaceClaimReconciler) release( held := interfaceExists && iface.Spec.ClaimRef != nil && iface.Spec.ClaimRef.Name == claim.Name retain := claim.Spec.ReclaimPolicy == networkingv1alpha.NetworkInterfaceReclaimPolicyRetain - verify := claim.Spec.AttachmentMode == networkingv1alpha.NetworkInterfaceAttachmentModePhysical && !retain + verify := physical && !retain switch { case held && retain: @@ -1559,17 +1603,23 @@ func (r *NetworkInterfaceClaimReconciler) release( return ctrl.Result{}, err } + case verify && (recorded || claim.Status.NetworkInterfaceRef != nil): + // A physical claim allocates once it is recorded and before it + // records its interface, so a crash in between leaves addresses only + // its name can find. A claim the hold never recorded allocated none. + if err := r.releaseIPClaims(ctx, cl, claim.Namespace, claim.Name, claimEntries(claim)); err != nil { + return ctrl.Result{}, err + } + if result, err := r.awaitRelease(ctx, cl, claim, claim.Name, claimEntries(claim)); err != nil || !result.IsZero() { + return result, err + } + case !retain: // The interface is gone, or never named this claim. Either way the // addresses this claim allocated are named after it. if err := r.releaseClaimAllocations(ctx, cl, claim); err != nil { return ctrl.Result{}, err } - if verify && claim.Status.NetworkInterfaceRef != nil { - if result, err := r.awaitRelease(ctx, cl, claim, claim.Name, claimEntries(claim)); err != nil || !result.IsZero() { - return result, err - } - } } location, err := r.location(ctx) @@ -1580,6 +1630,12 @@ func (r *NetworkInterfaceClaimReconciler) release( return ctrl.Result{}, err } + if physical { + if err := leaveHold(ctx, cl, reader, claim); err != nil { + return ctrl.Result{}, err + } + } + controllerutil.RemoveFinalizer(claim, networkInterfaceClaimFinalizer) if err := cl.Update(ctx, claim); err != nil { // Deletion can complete after the initial read but before this finalizer @@ -1592,6 +1648,42 @@ func (r *NetworkInterfaceClaimReconciler) release( return ctrl.Result{}, nil } +// awaitDetach reports whether the port no longer carries the claim's network, +// which is when its addresses may be released. While the hold records the +// claim only the realizer can say so, by removing the detach finalizer. A claim +// the hold never recorded was never acted on, so its finalizer comes off here. +func awaitDetach( + ctx context.Context, + cl client.Client, + claim *networkingv1alpha.NetworkInterfaceClaim, + recorded bool, +) (bool, error) { + if !controllerutil.ContainsFinalizer(claim, networkingv1alpha.NetworkInterfaceClaimDetachFinalizer) { + return true, nil + } + + if !recorded { + controllerutil.RemoveFinalizer(claim, networkingv1alpha.NetworkInterfaceClaimDetachFinalizer) + if err := cl.Update(ctx, claim); err != nil { + return false, fmt.Errorf("failed removing the detach finalizer: %w", err) + } + return true, nil + } + + if apimeta.SetStatusCondition(&claim.Status.Conditions, metav1.Condition{ + Type: networkingv1alpha.NetworkInterfaceClaimReady, + Status: metav1.ConditionFalse, + Reason: networkingv1alpha.NetworkInterfaceClaimReasonAwaitingDetach, + ObservedGeneration: claim.Generation, + Message: "Waiting for the switch port to stop carrying this claim's network before its addresses are released", + }) { + if err := cl.Status().Update(ctx, claim); err != nil { + return false, fmt.Errorf("failed reporting a pending detach: %w", err) + } + } + return false, nil +} + // awaitRelease holds a physical claim until IPAM no longer holds any of its // addresses here, under any name they could carry. A provider reads the // claim's absence as proof the address is free, and IPAM finishes a delete on @@ -1717,8 +1809,7 @@ func markReleasing(ctx context.Context, cl client.Client, claim *networkingv1alp // A later step of the release names what it waits on in Ready, and // restating Releasing would hide it. if current := apimeta.FindStatusCondition(claim.Status.Conditions, conditionType); current != nil && - current.Status == metav1.ConditionFalse && - current.Reason == networkingv1alpha.NetworkInterfaceClaimReasonReleaseUnverified { + current.Status == metav1.ConditionFalse && releaseStepPending(claim, current.Reason) { continue } changed = apimeta.SetStatusCondition(&claim.Status.Conditions, metav1.Condition{ @@ -1738,6 +1829,17 @@ func markReleasing(ctx context.Context, cl client.Client, claim *networkingv1alp return nil } +func releaseStepPending(claim *networkingv1alpha.NetworkInterfaceClaim, reason string) bool { + switch reason { + case networkingv1alpha.NetworkInterfaceClaimReasonReleaseUnverified: + return true + case networkingv1alpha.NetworkInterfaceClaimReasonAwaitingDetach: + return controllerutil.ContainsFinalizer(claim, networkingv1alpha.NetworkInterfaceClaimDetachFinalizer) + default: + return false + } +} + func (r *NetworkInterfaceClaimReconciler) releaseAddresses( ctx context.Context, cl client.Client, diff --git a/internal/controller/networkinterfaceclaim_controller_test.go b/internal/controller/networkinterfaceclaim_controller_test.go index d41a047e..26e70d1b 100644 --- a/internal/controller/networkinterfaceclaim_controller_test.go +++ b/internal/controller/networkinterfaceclaim_controller_test.go @@ -433,6 +433,11 @@ type scenario struct { ipam *fakeIPAM reconciler *NetworkInterfaceClaimReconciler namespace string + + // switchName is a switch of this scenario's own. Holds are cluster-scoped + // and the planes outlive a test, so a shared switch would carry one test's + // holds into the next. + switchName string } // newScenario builds one namespace of objects. Set labelled to false for a @@ -479,6 +484,7 @@ func newScenario(t *testing.T, labelled bool, networkFamilies []networkingv1alph ipam: ipam, reconciler: &NetworkInterfaceClaimReconciler{Location: location, IPAM: ipam, localReader: cl}, namespace: namespaceName, + switchName: "rack-a1-tor-1-" + namespaceName, } // The claim reconciler runs in a cell and reads the propagated context, not @@ -556,7 +562,7 @@ func (s *scenario) createClaim(name string, spec networkingv1alpha.NetworkInterf func (s *scenario) reconcile(claim *networkingv1alpha.NetworkInterfaceClaim) { s.t.Helper() - _, err := s.reconciler.reconcileClaim(s.ctx, s.client, s.events, client.ObjectKeyFromObject(claim)) + _, err := s.reconciler.reconcileClaim(s.ctx, s.client, s.client, s.events, client.ObjectKeyFromObject(claim)) require.NoError(s.t, err) } @@ -732,7 +738,7 @@ func TestNetworkInterfaceClaimRejectsAMissingProjectNamespace(t *testing.T) { ReclaimPolicy: networkingv1alpha.NetworkInterfaceReclaimPolicyDelete, }) - result, err := s.reconciler.reconcileClaim(s.ctx, s.client, s.events, client.ObjectKeyFromObject(claim)) + result, err := s.reconciler.reconcileClaim(s.ctx, s.client, s.client, s.events, client.ObjectKeyFromObject(claim)) require.NoError(t, err, "a control plane without its namespace is a rejection, not a reconcile failure") require.NotZero(t, result.RequeueAfter, "nothing watches the project, so the rejection carries its own way back") @@ -1342,7 +1348,7 @@ func TestTransientProjectFailureDoesNotWedgeTheClaim(t *testing.T) { s.reconcile(claim) failing := &transientNamespaceClient{Client: s.client} - _, err := s.reconciler.reconcileClaim(s.ctx, failing, s.events, + _, err := s.reconciler.reconcileClaim(s.ctx, failing, s.client, s.events, client.ObjectKey{Namespace: s.namespace, Name: "blip"}) require.Error(t, err, "a failed read must be retried, not turned into a rejection") @@ -1367,7 +1373,7 @@ func TestRejectionRequeues(t *testing.T) { } require.NoError(t, s.client.Create(s.ctx, claim)) - result, err := s.reconciler.reconcileClaim(s.ctx, s.client, s.events, + result, err := s.reconciler.reconcileClaim(s.ctx, s.client, s.client, s.events, client.ObjectKeyFromObject(claim)) require.NoError(t, err) require.NotZero(t, result.RequeueAfter, @@ -1786,7 +1792,7 @@ func TestNetworkInterfaceClaimRejectsAMissingNetworkContext(t *testing.T) { ReclaimPolicy: networkingv1alpha.NetworkInterfaceReclaimPolicyDelete, }) - result, err := s.reconciler.reconcileClaim(s.ctx, s.client, s.events, client.ObjectKeyFromObject(claim)) + result, err := s.reconciler.reconcileClaim(s.ctx, s.client, s.client, s.events, client.ObjectKeyFromObject(claim)) require.NoError(t, err) require.NotZero(t, result.RequeueAfter) @@ -2584,45 +2590,6 @@ func physicalAttachmentPoint(port string) *networkingv1alpha.NetworkInterfaceAtt } } -// Nothing yet decides which project holds a switch port or detaches it before -// release, so a physical claim must not reach IPAM or produce an interface a -// realizer could act on. -func TestPhysicalClaimIsRefusedWithoutAllocating(t *testing.T) { - s := newScenario(t, true, []networkingv1alpha.IPFamily{networkingv1alpha.IPv4Protocol}) - - claim := s.createClaim("server-data", networkingv1alpha.NetworkInterfaceClaimSpec{ - InterfaceName: "data", - AttachmentMode: networkingv1alpha.NetworkInterfaceAttachmentModePhysical, - AttachmentPoint: physicalAttachmentPoint("Ethernet1/12"), - IPFamilies: []networkingv1alpha.IPFamily{networkingv1alpha.IPv4Protocol}, - ReclaimPolicy: networkingv1alpha.NetworkInterfaceReclaimPolicyDelete, - }) - s.reconcile(claim) - s.reconcile(claim) - - require.Zero(t, s.ipam.createdAnywhere()) - _, err := s.getInterface("server-data") - require.True(t, apierrors.IsNotFound(err), "no interface may exist for a refused physical claim") - - refused := s.getClaim("server-data") - for _, conditionType := range []string{ - networkingv1alpha.NetworkInterfaceClaimBound, - networkingv1alpha.NetworkInterfaceClaimAllocated, - networkingv1alpha.NetworkInterfaceClaimReady, - } { - condition := conditionOf(refused, conditionType) - require.NotNil(t, condition, conditionType) - require.Equal(t, metav1.ConditionFalse, condition.Status, conditionType) - require.Equal(t, networkingv1alpha.NetworkInterfaceClaimReasonPhysicalAttachmentUnsupported, condition.Reason, conditionType) - } - - s.deleteClaim(refused) - require.Zero(t, s.ipam.createdAnywhere()) - var gone networkingv1alpha.NetworkInterfaceClaim - require.True(t, apierrors.IsNotFound(s.client.Get(s.ctx, client.ObjectKeyFromObject(claim), &gone)), - "a refused physical claim allocated nothing and must delete at once") -} - func TestAdoptionRefusesADifferentAttachment(t *testing.T) { physical := networkingv1alpha.NetworkInterfaceAttachmentModePhysical netns := networkingv1alpha.NetworkInterfaceAttachmentModeNetns diff --git a/internal/controller/networkinterfaceclaim_physical_test.go b/internal/controller/networkinterfaceclaim_physical_test.go new file mode 100644 index 00000000..64d9a055 --- /dev/null +++ b/internal/controller/networkinterfaceclaim_physical_test.go @@ -0,0 +1,748 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +package controller + +import ( + "context" + "errors" + "fmt" + "sync" + "testing" + + "github.com/stretchr/testify/require" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + + ipamv1alpha1 "go.miloapis.com/ipam/pkg/apis/ipam/v1alpha1" + + networkingv1alpha "go.datum.net/network-services-operator/api/v1alpha" + "go.datum.net/network-services-operator/internal/downstreamclient" +) + +const ( + otherProject = "customer-other-example" + providerProject = "provider-example" +) + +var ipv4Only = []networkingv1alpha.IPFamily{networkingv1alpha.IPv4Protocol} + +func (s *scenario) attachmentPoint(port string) *networkingv1alpha.NetworkInterfaceAttachmentPoint { + return &networkingv1alpha.NetworkInterfaceAttachmentPoint{ + MACAddress: "00:00:5e:00:53:01", + Switch: s.switchName, + Port: port, + } +} + +func (s *scenario) physicalSpec(port string, purpose networkingv1alpha.NetworkInterfacePurpose) networkingv1alpha.NetworkInterfaceClaimSpec { + return networkingv1alpha.NetworkInterfaceClaimSpec{ + InterfaceName: "data", + AttachmentMode: networkingv1alpha.NetworkInterfaceAttachmentModePhysical, + AttachmentPoint: s.attachmentPoint(port), + Purpose: purpose, + IPFamilies: ipv4Only, + ReclaimPolicy: networkingv1alpha.NetworkInterfaceReclaimPolicyDelete, + } +} + +// createPhysicalClaim writes a physical claim on the default network, carrying both +// finalizers the way NSO's first write leaves it. +func (s *scenario) createPhysicalClaim( + name, port string, + purpose networkingv1alpha.NetworkInterfacePurpose, +) *networkingv1alpha.NetworkInterfaceClaim { + s.t.Helper() + claim := &networkingv1alpha.NetworkInterfaceClaim{} + claim.Namespace = s.namespace + claim.Name = name + claim.Finalizers = []string{networkInterfaceClaimFinalizer, networkingv1alpha.NetworkInterfaceClaimDetachFinalizer} + claim.Spec = s.physicalSpec(port, purpose) + claim.Spec.Network = networkingv1alpha.LocalNetworkRef{Name: "default"} + require.NoError(s.t, s.client.Create(s.ctx, claim)) + return claim +} + +// sibling is another namespace on the same planes and the same switch, +// belonging to the given project. +func (s *scenario) sibling(project string) *scenario { + s.t.Helper() + namespace := &corev1.Namespace{} + namespace.Name = "ns-" + scenarioSuffix(s.t) + namespace.Labels = map[string]string{ + downstreamclient.UpstreamOwnerNamespaceLabel: testProjectNS, + downstreamclient.UpstreamOwnerClusterNameLabel: "cluster-" + project, + } + require.NoError(s.t, s.client.Create(s.ctx, namespace)) + + network := &networkingv1alpha.Network{} + network.Namespace = namespace.Name + network.Name = "default" + network.Spec = networkingv1alpha.NetworkSpec{ + IPAM: networkingv1alpha.NetworkIPAM{Mode: networkingv1alpha.NetworkIPAMModeAuto}, + IPFamilies: ipv4Only, + MTU: 1440, + } + require.NoError(s.t, s.client.Create(s.ctx, network)) + + other := *s + other.namespace = namespace.Name + other.createNetworkContext("default", ipv4Only, 1440) + return &other +} + +func (s *scenario) getHold(port string) (*networkingv1alpha.SwitchPortHold, error) { + hold := &networkingv1alpha.SwitchPortHold{} + err := s.client.Get(s.ctx, client.ObjectKey{Name: networkingv1alpha.SwitchPortHoldName(s.switchName, port)}, hold) + return hold, err +} + +func (s *scenario) requireHold(port string) *networkingv1alpha.SwitchPortHold { + s.t.Helper() + hold, err := s.getHold(port) + require.NoError(s.t, err) + return hold +} + +// detach stands in for the realizer confirming the port no longer carries the +// claim's network. +func (s *scenario) detach(name string) { + s.t.Helper() + claim := s.getClaim(name) + require.True(s.t, controllerutil.RemoveFinalizer(claim, networkingv1alpha.NetworkInterfaceClaimDetachFinalizer), + "the claim must still carry the detach finalizer") + require.NoError(s.t, s.client.Update(s.ctx, claim)) +} + +func (s *scenario) requireAwaitingDetach(name string) { + s.t.Helper() + claim := s.getClaim(name) + require.Contains(s.t, claim.Finalizers, networkingv1alpha.NetworkInterfaceClaimDetachFinalizer) + ready := conditionOf(claim, networkingv1alpha.NetworkInterfaceClaimReady) + require.NotNil(s.t, ready) + require.Equal(s.t, metav1.ConditionFalse, ready.Status) + require.Equal(s.t, networkingv1alpha.NetworkInterfaceClaimReasonAwaitingDetach, ready.Reason) + prepared := conditionOf(claim, networkingv1alpha.NetworkInterfaceClaimPrepared) + require.NotNil(s.t, prepared) + require.Equal(s.t, networkingv1alpha.NetworkInterfaceClaimReasonReleasing, prepared.Reason) +} + +// deleteAndDetach deletes a recorded physical claim, checks NSO waits for the +// realizer, and then detaches it. +func (s *scenario) deleteAndDetach(claim *networkingv1alpha.NetworkInterfaceClaim) { + s.t.Helper() + require.NoError(s.t, s.client.Delete(s.ctx, claim)) + s.reconcile(claim) + s.requireAwaitingDetach(claim.Name) + s.detach(claim.Name) +} + +func (s *scenario) deletePhysicalClaim(claim *networkingv1alpha.NetworkInterfaceClaim) { + s.t.Helper() + s.deleteAndDetach(claim) + s.reconcile(claim) +} + +func (s *scenario) requireWaiting(name string, unnamed ...string) { + s.t.Helper() + claim := s.getClaim(name) + require.Nil(s.t, claim.Status.NetworkInterfaceRef) + for _, conditionType := range []string{ + networkingv1alpha.NetworkInterfaceClaimBound, + networkingv1alpha.NetworkInterfaceClaimAllocated, + networkingv1alpha.NetworkInterfaceClaimReady, + } { + condition := conditionOf(claim, conditionType) + require.NotNil(s.t, condition, conditionType) + require.Equal(s.t, metav1.ConditionFalse, condition.Status, conditionType) + require.Equal(s.t, networkingv1alpha.NetworkInterfaceClaimReasonAttachmentPointHeld, condition.Reason, conditionType) + for _, word := range unnamed { + require.NotContains(s.t, condition.Message, word, "a waiting claim must not learn what holds its port") + } + } + _, err := s.getInterface(name) + require.True(s.t, apierrors.IsNotFound(err), "a waiting claim must have no interface") +} + +func (s *scenario) requireBound(name string) *networkingv1alpha.NetworkInterfaceClaim { + s.t.Helper() + claim := s.getClaim(name) + require.NotNil(s.t, claim.Status.NetworkInterfaceRef, "%s must bind", name) + bound := conditionOf(claim, networkingv1alpha.NetworkInterfaceClaimBound) + require.NotNil(s.t, bound) + require.Equal(s.t, metav1.ConditionTrue, bound.Status) + return claim +} + +func entryOf(s *scenario, name, network string) networkingv1alpha.SwitchPortHoldClaimRef { + return networkingv1alpha.SwitchPortHoldClaimRef{Namespace: s.namespace, Name: name, Network: network} +} + +func TestSwitchPortHoldNamesAreUnambiguous(t *testing.T) { + name := networkingv1alpha.SwitchPortHoldName("rack-a1-tor-1", "Ethernet1/12") + require.Regexp(t, `^port-[0-9a-f]{40}$`, name) + require.Equal(t, name, networkingv1alpha.SwitchPortHoldName("rack-a1-tor-1", "Ethernet1/12")) + require.NotEqual(t, name, networkingv1alpha.SwitchPortHoldName("rack-a1-tor-1E", "thernet1/12"), + "moving a character from the port to the switch must name another port") + require.NotEqual(t, networkingv1alpha.SwitchPortHoldName("a1:", "b"), networkingv1alpha.SwitchPortHoldName("a", "1:b")) +} + +func TestPhysicalClaimBindsAfterRecordingItsPort(t *testing.T) { + s := newScenario(t, true, ipv4Only) + claim := s.createClaim("server-data", s.physicalSpec("Ethernet1/12", "")) + s.reconcile(claim) + + bound := s.requireBound("server-data") + require.ElementsMatch(t, []string{networkInterfaceClaimFinalizer, networkingv1alpha.NetworkInterfaceClaimDetachFinalizer}, + bound.Finalizers) + allocated := conditionOf(bound, networkingv1alpha.NetworkInterfaceClaimAllocated) + require.Equal(t, metav1.ConditionTrue, allocated.Status) + + hold := s.requireHold("Ethernet1/12") + require.Equal(t, s.switchName, hold.Spec.Switch) + require.Equal(t, "Ethernet1/12", hold.Spec.Port) + require.Nil(t, hold.Spec.Boot) + require.Equal(t, []networkingv1alpha.SwitchPortHoldClaimRef{entryOf(s, "server-data", "default")}, hold.Spec.NetworkClaims) + require.Equal(t, &networkingv1alpha.SwitchPortHoldConsumerRef{ + APIGroup: "resourcemanager.miloapis.com", Kind: "Project", Name: testProject, + }, hold.Spec.ConsumerRef) + + iface, err := s.getInterface("server-data") + require.NoError(t, err) + require.Equal(t, claim.Spec.AttachmentPoint, iface.Spec.AttachmentPoint) + require.Equal(t, networkingv1alpha.NetworkInterfaceAttachmentModePhysical, iface.Spec.AttachmentMode) + + before := hold.ResourceVersion + s.reconcile(claim) + require.Equal(t, before, s.requireHold("Ethernet1/12").ResourceVersion, "recording again must not rewrite the hold") +} + +func TestBootAndNetworkClaimsShareAPort(t *testing.T) { + customer := newScenario(t, true, ipv4Only) + provider := customer.sibling(providerProject) + + boot := provider.createClaim("install-1-boot", provider.physicalSpec("Ethernet1/12", networkingv1alpha.NetworkInterfacePurposeBoot)) + provider.reconcile(boot) + data := customer.createClaim("server-data", customer.physicalSpec("Ethernet1/12", "")) + customer.reconcile(data) + + provider.requireBound("install-1-boot") + customer.requireBound("server-data") + + hold := customer.requireHold("Ethernet1/12") + require.Equal(t, entryOf(provider, "install-1-boot", "default"), *hold.Spec.Boot) + require.Equal(t, []networkingv1alpha.SwitchPortHoldClaimRef{entryOf(customer, "server-data", "default")}, hold.Spec.NetworkClaims) + require.Equal(t, testProject, hold.Spec.ConsumerRef.Name, "the boot claim's project does not hold the port") + + provider.deletePhysicalClaim(provider.getClaim("install-1-boot")) + require.True(t, provider.claimGone("install-1-boot")) + hold = customer.requireHold("Ethernet1/12") + require.Nil(t, hold.Spec.Boot) + require.Len(t, hold.Spec.NetworkClaims, 1, "the network claim keeps the port once the boot claim is gone") +} + +func TestAnotherProjectWaitsForAHeldPort(t *testing.T) { + s := newScenario(t, true, ipv4Only) + other := s.sibling(otherProject) + + holder := s.createClaim("server-data", s.physicalSpec("Ethernet1/12", "")) + s.reconcile(holder) + s.requireBound("server-data") + + allocations := s.ipam.createdAnywhere() + waiting := other.createClaim("their-data", other.physicalSpec("Ethernet1/12", "")) + other.reconcile(waiting) + other.reconcile(waiting) + + other.requireWaiting("their-data", testProject, "server-data", s.namespace) + require.Equal(t, allocations, s.ipam.createdAnywhere(), "a waiting claim allocates nothing") + require.Empty(t, s.ipam.created()[otherProject]) + hold := s.requireHold("Ethernet1/12") + require.Equal(t, testProject, hold.Spec.ConsumerRef.Name) + require.Equal(t, []networkingv1alpha.SwitchPortHoldClaimRef{entryOf(s, "server-data", "default")}, hold.Spec.NetworkClaims) + + // Deleting the waiting claim needs no realizer: the hold never recorded it. + require.NoError(t, s.client.Delete(s.ctx, waiting)) + other.reconcile(waiting) + require.True(t, other.claimGone("their-data")) + require.Equal(t, hold.ResourceVersion, s.requireHold("Ethernet1/12").ResourceVersion) + + // The next claim takes the port once its last holder leaves. + s.deletePhysicalClaim(s.getClaim("server-data")) + _, err := s.getHold("Ethernet1/12") + require.True(t, apierrors.IsNotFound(err), "a hold that records nothing is deleted") + next := other.createClaim("their-data-2", other.physicalSpec("Ethernet1/12", "")) + other.reconcile(next) + other.requireBound("their-data-2") + require.Equal(t, otherProject, s.requireHold("Ethernet1/12").Spec.ConsumerRef.Name) +} + +func TestSameProjectSharesAPortOnDifferentNetworks(t *testing.T) { + s := newScenario(t, true, ipv4Only) + second := s.sibling(testProject) + + first := s.createClaim("server-data", s.physicalSpec("Ethernet1/12", "")) + s.reconcile(first) + other := second.createClaim("server-storage", second.physicalSpec("Ethernet1/12", "")) + second.reconcile(other) + + s.requireBound("server-data") + second.requireBound("server-storage") + require.Len(t, s.requireHold("Ethernet1/12").Spec.NetworkClaims, 2) +} + +func TestAPortCarriesANetworkOnce(t *testing.T) { + s := newScenario(t, true, ipv4Only) + first := s.createClaim("server-data", s.physicalSpec("Ethernet1/12", "")) + s.reconcile(first) + second := s.createClaim("server-data-again", s.physicalSpec("Ethernet1/12", "")) + s.reconcile(second) + + s.requireBound("server-data") + s.requireWaiting("server-data-again", testProject, s.namespace) + require.Len(t, s.requireHold("Ethernet1/12").Spec.NetworkClaims, 1) +} + +func TestASecondBootClaimWaits(t *testing.T) { + s := newScenario(t, true, ipv4Only) + first := s.createClaim("install-1-boot", s.physicalSpec("Ethernet1/12", networkingv1alpha.NetworkInterfacePurposeBoot)) + s.reconcile(first) + second := s.createClaim("wipe-1-boot", s.physicalSpec("Ethernet1/12", networkingv1alpha.NetworkInterfacePurposeBoot)) + s.reconcile(second) + + s.requireBound("install-1-boot") + s.requireWaiting("wipe-1-boot", "install-1-boot") + require.Equal(t, "install-1-boot", s.requireHold("Ethernet1/12").Spec.Boot.Name) + + s.deletePhysicalClaim(s.getClaim("install-1-boot")) + s.reconcile(second) + s.requireBound("wipe-1-boot") +} + +func TestAHashCollisionIsRefused(t *testing.T) { + s := newScenario(t, true, ipv4Only) + collided := &networkingv1alpha.SwitchPortHold{} + collided.Name = networkingv1alpha.SwitchPortHoldName(s.switchName, "Ethernet1/12") + collided.Spec.Switch = s.switchName + collided.Spec.Port = "Ethernet1/99" + require.NoError(t, s.client.Create(s.ctx, collided)) + + claim := s.createClaim("server-data", s.physicalSpec("Ethernet1/12", "")) + s.reconcile(claim) + + s.requireWaiting("server-data") + require.Zero(t, s.ipam.createdAnywhere()) + hold := s.requireHold("Ethernet1/12") + require.Equal(t, collided.ResourceVersion, hold.ResourceVersion, "another port's hold must be left alone") + + require.NoError(t, s.client.Delete(s.ctx, claim)) + s.reconcile(claim) + require.True(t, s.claimGone("server-data"), "a claim no hold recorded is released by NSO alone") + require.Equal(t, collided.ResourceVersion, s.requireHold("Ethernet1/12").ResourceVersion) +} + +func TestReleaseWaitsForTheRealizerToDetach(t *testing.T) { + s := newScenario(t, true, ipv4Only) + claim := s.createClaim("server-data", s.physicalSpec("Ethernet1/12", "")) + s.reconcile(claim) + s.requireBound("server-data") + names := physicalIPClaimNames("server-data") + + require.NoError(t, s.client.Delete(s.ctx, claim)) + s.reconcile(claim) + s.requireAwaitingDetach("server-data") + waiting := s.getClaim("server-data").ResourceVersion + s.reconcile(claim) + s.requireAwaitingDetach("server-data") + require.Equal(t, waiting, s.getClaim("server-data").ResourceVersion, "a pass that finds nothing new must not rewrite the claim") + + s.ipClaim(names[0]) + _, err := s.getInterface("server-data") + require.NoError(t, err, "the interface stays until the port is detached") + require.Empty(t, s.ipam.deleted()[testProject], "no address is released while the detach finalizer is present") + require.Len(t, s.requireHold("Ethernet1/12").Spec.NetworkClaims, 1) + + s.detach("server-data") + s.reconcile(claim) + require.True(t, s.claimGone("server-data")) + require.Zero(t, s.ipam.storedAnywhere(t)) + _, err = s.getInterface("server-data") + require.True(t, apierrors.IsNotFound(err)) + _, err = s.getHold("Ethernet1/12") + require.True(t, apierrors.IsNotFound(err), "the last claim to leave deletes the hold") +} + +func TestReleaseStepsThroughWhatItWaitsOn(t *testing.T) { + s := newScenario(t, true, ipv4Only) + claim, address := boundPhysicalClaim(s) + names := physicalIPClaimNames(physicalClaimName) + ipamClient, err := s.ipam.ClientForProject(testProject) + require.NoError(t, err) + lingering := &ipamv1alpha1.IPAllocation{} + lingering.Namespace = testProjectNS + lingering.Name = "lingering" + lingering.Spec.ClaimRef = &ipamv1alpha1.LocalRef{Name: names[0]} + require.NoError(t, ipamClient.Create(s.ctx, lingering)) + + s.deletePhysicalClaim(claim) + s.requireReleaseUnverified(address) + require.Len(t, s.requireHold("Ethernet1/12").Spec.NetworkClaims, 1, + "the claim leaves its hold only once its release is verified") +} + +func TestAnInterfaceDeletedBeforeDetachKeepsItsAddresses(t *testing.T) { + s := newScenario(t, true, ipv4Only) + claim, _ := boundPhysicalClaim(s) + names := physicalIPClaimNames(physicalClaimName) + + require.NoError(t, s.client.Delete(s.ctx, claim)) + s.reconcile(claim) + s.requireAwaitingDetach(physicalClaimName) + + iface, err := s.getInterface(physicalClaimName) + require.NoError(t, err) + require.NoError(t, s.client.Delete(s.ctx, iface)) + s.reconcileInterface(physicalClaimName) + s.ipClaim(names[0]) + require.Empty(t, s.ipam.deleted()[testProject], "the port may still carry the address") + + s.detach(physicalClaimName) + s.reconcile(claim) + require.True(t, s.claimGone(physicalClaimName)) + require.Zero(t, s.ipam.storedAnywhere(t), "the claim's own release frees what its interface held") +} + +// A crash after recording and before the interface exists leaves a record and +// no interface. The realizer may have acted on the record, so it alone may +// detach. +func TestARecordWithoutAnInterfaceStillWaitsForTheRealizer(t *testing.T) { + s := newScenario(t, true, ipv4Only) + claim := s.createPhysicalClaim("server-data", "Ethernet1/12", "") + recorded, err := recordOnHold(s.ctx, s.client, s.client, claim, testProject) + require.NoError(t, err) + require.True(t, recorded) + + require.NoError(t, s.client.Delete(s.ctx, claim)) + s.reconcile(claim) + s.requireAwaitingDetach("server-data") + + s.detach("server-data") + s.reconcile(claim) + require.True(t, s.claimGone("server-data")) + _, err = s.getHold("Ethernet1/12") + require.True(t, apierrors.IsNotFound(err)) +} + +// A crash after allocating and before recording the interface leaves IPAM +// claims that only the claim's name can find. +func TestAddressesAllocatedBeforeTheInterfaceAreReleasedAndVerified(t *testing.T) { + s := newScenario(t, true, ipv4Only) + claim := s.createPhysicalClaim("server-storage", "Ethernet1/12", "") + recorded, err := recordOnHold(s.ctx, s.client, s.client, claim, testProject) + require.NoError(t, err) + require.True(t, recorded) + + names := physicalIPClaimNames("server-storage") + ipamClient, err := s.ipam.ClientForProject(testProject) + require.NoError(t, err) + require.NoError(t, ipamClient.Create(s.ctx, physicalIPClaim(names[0], testLocationName))) + lingering := &ipamv1alpha1.IPAllocation{} + lingering.Namespace = testProjectNS + lingering.Name = "lingering" + lingering.Spec.ClaimRef = &ipamv1alpha1.LocalRef{Name: names[0]} + require.NoError(t, ipamClient.Create(s.ctx, lingering)) + require.Nil(t, s.getClaim("server-storage").Status.NetworkInterfaceRef) + + s.deletePhysicalClaim(claim) + require.False(t, s.claimGone("server-storage")) + ready := conditionOf(s.getClaim("server-storage"), networkingv1alpha.NetworkInterfaceClaimReady) + require.Equal(t, networkingv1alpha.NetworkInterfaceClaimReasonReleaseUnverified, ready.Reason) + require.Equal(t, []string{names[0]}, s.ipam.deleted()[testProject], "the IPAM claim is freed by the claim's name") + + require.NoError(t, ipamClient.Get(s.ctx, client.ObjectKeyFromObject(lingering), lingering)) + lingering.Spec.ClaimRef = nil + require.NoError(t, ipamClient.Update(s.ctx, lingering)) + s.reconcile(claim) + require.True(t, s.claimGone("server-storage")) +} + +func TestAStaleEntryIsDroppedOnTheNextWrite(t *testing.T) { + s := newScenario(t, true, ipv4Only) + other := s.sibling(otherProject) + + gone := s.createPhysicalClaim("server-data", "Ethernet1/12", "") + recorded, err := recordOnHold(s.ctx, s.client, s.client, gone, testProject) + require.NoError(t, err) + require.True(t, recorded) + gone.Finalizers = nil + require.NoError(t, s.client.Update(s.ctx, gone)) + require.NoError(t, s.client.Delete(s.ctx, gone)) + require.True(t, s.claimGone("server-data")) + + claim := other.createClaim("their-data", other.physicalSpec("Ethernet1/12", "")) + other.reconcile(claim) + other.requireBound("their-data") + hold := s.requireHold("Ethernet1/12") + require.Equal(t, []networkingv1alpha.SwitchPortHoldClaimRef{entryOf(other, "their-data", "default")}, hold.Spec.NetworkClaims) + require.Equal(t, otherProject, hold.Spec.ConsumerRef.Name) +} + +func TestAnEntryLeftByAnEarlierClaimOfTheNameIsReplaced(t *testing.T) { + s := newScenario(t, true, ipv4Only) + claim := s.createPhysicalClaim("server-data", "Ethernet1/12", "") + + hold := &networkingv1alpha.SwitchPortHold{} + hold.Name = networkingv1alpha.SwitchPortHoldName(s.switchName, "Ethernet1/12") + hold.Spec.Switch = s.switchName + hold.Spec.Port = "Ethernet1/12" + hold.Spec.ConsumerRef = &networkingv1alpha.SwitchPortHoldConsumerRef{APIGroup: miloProjectAPIGroup, Kind: miloProjectKind, Name: testProject} + hold.Spec.NetworkClaims = []networkingv1alpha.SwitchPortHoldClaimRef{entryOf(s, "server-data", "retired")} + require.NoError(t, s.client.Create(s.ctx, hold)) + + recorded, err := recordOnHold(s.ctx, s.client, s.client, claim, testProject) + require.NoError(t, err) + require.True(t, recorded) + require.Equal(t, []networkingv1alpha.SwitchPortHoldClaimRef{entryOf(s, "server-data", "default")}, + s.requireHold("Ethernet1/12").Spec.NetworkClaims) +} + +// recordUntilDecided retries the way the reconciler's requeue does, so a +// writer that lost every attempt still reaches an answer. +func recordUntilDecided(s *scenario, claim *networkingv1alpha.NetworkInterfaceClaim, project string) (bool, error) { + for { + recorded, err := recordOnHold(s.ctx, s.client, s.client, claim, project) + if apierrors.IsConflict(err) || apierrors.IsAlreadyExists(err) || apierrors.IsNotFound(err) { + continue + } + return recorded, err + } +} + +func TestTwoProjectsRacingForOnePortRecordOne(t *testing.T) { + s := newScenario(t, true, ipv4Only) + other := s.sibling(otherProject) + provider := s.sibling(providerProject) + + const iterations = 30 + for i := range iterations { + port := fmt.Sprintf("Ethernet1/%d", i+1) + // Half the ports start free, so both writers create; half start held by + // a boot claim, so both update. + if i%2 == 1 { + boot := provider.createPhysicalClaim(fmt.Sprintf("boot-%d", i), port, + networkingv1alpha.NetworkInterfacePurposeBoot) + recorded, err := recordOnHold(s.ctx, s.client, s.client, boot, providerProject) + require.NoError(t, err) + require.True(t, recorded) + } + + claims := []*networkingv1alpha.NetworkInterfaceClaim{ + s.createPhysicalClaim(fmt.Sprintf("ours-%d", i), port, ""), + other.createPhysicalClaim(fmt.Sprintf("theirs-%d", i), port, ""), + } + projects := []string{testProject, otherProject} + recorded := make([]bool, len(claims)) + errs := make([]error, len(claims)) + + start := make(chan struct{}) + var wg sync.WaitGroup + for j := range claims { + wg.Go(func() { + <-start + recorded[j], errs[j] = recordUntilDecided(s, claims[j], projects[j]) + }) + } + close(start) + wg.Wait() + require.NoError(t, errors.Join(errs...)) + + require.NotEqual(t, recorded[0], recorded[1], "exactly one project may hold port %s", port) + winner := 0 + if recorded[1] { + winner = 1 + } + hold := s.requireHold(port) + require.Equal(t, projects[winner], hold.Spec.ConsumerRef.Name) + require.Equal(t, []networkingv1alpha.SwitchPortHoldClaimRef{{ + Namespace: claims[winner].Namespace, Name: claims[winner].Name, Network: "default", + }}, hold.Spec.NetworkClaims) + } +} + +func TestARecordRacingTheLastLeaveNeverLosesTheHold(t *testing.T) { + s := newScenario(t, true, ipv4Only) + second := s.sibling(testProject) + + const iterations = 40 + for i := range iterations { + port := fmt.Sprintf("Ethernet2/%d", i+1) + leaving := s.createPhysicalClaim(fmt.Sprintf("leaving-%d", i), port, "") + recorded, err := recordOnHold(s.ctx, s.client, s.client, leaving, testProject) + require.NoError(t, err) + require.True(t, recorded) + joining := second.createPhysicalClaim(fmt.Sprintf("joining-%d", i), port, "") + + var joined bool + var joinErr, leaveErr error + start := make(chan struct{}) + var wg sync.WaitGroup + wg.Go(func() { + <-start + joined, joinErr = recordUntilDecided(s, joining, testProject) + }) + wg.Go(func() { + <-start + for { + leaveErr = leaveHold(s.ctx, s.client, s.client, leaving) + if !apierrors.IsConflict(leaveErr) { + return + } + } + }) + close(start) + wg.Wait() + require.NoError(t, joinErr) + require.NoError(t, leaveErr) + require.True(t, joined) + + hold, err := s.getHold(port) + require.NoError(t, err, "a hold must never be deleted under a recorded claim (port %s)", port) + require.Equal(t, []networkingv1alpha.SwitchPortHoldClaimRef{entryOf(second, joining.Name, "default")}, + hold.Spec.NetworkClaims) + } +} + +// interleavingClient runs another writer once, between a hold's read and the +// write that follows it, so an interleaving a race only sometimes produces +// happens every time. +type interleavingClient struct { + client.Client + beforeUpdate func() + beforeDelete func() +} + +func (c *interleavingClient) Update(ctx context.Context, obj client.Object, opts ...client.UpdateOption) error { + if _, ok := obj.(*networkingv1alpha.SwitchPortHold); ok && c.beforeUpdate != nil { + hook := c.beforeUpdate + c.beforeUpdate = nil + hook() + } + return c.Client.Update(ctx, obj, opts...) +} + +func (c *interleavingClient) Delete(ctx context.Context, obj client.Object, opts ...client.DeleteOption) error { + if _, ok := obj.(*networkingv1alpha.SwitchPortHold); ok && c.beforeDelete != nil { + hook := c.beforeDelete + c.beforeDelete = nil + hook() + } + return c.Client.Delete(ctx, obj, opts...) +} + +func TestARecordLandingBeforeTheLastLeaveDeletesKeepsTheHold(t *testing.T) { + s := newScenario(t, true, ipv4Only) + second := s.sibling(testProject) + leaving := s.createPhysicalClaim("leaving", "Ethernet1/12", "") + recorded, err := recordOnHold(s.ctx, s.client, s.client, leaving, testProject) + require.NoError(t, err) + require.True(t, recorded) + joining := second.createPhysicalClaim("joining", "Ethernet1/12", "") + + leaver := &interleavingClient{Client: s.client, beforeDelete: func() { + joined, err := recordOnHold(s.ctx, s.client, s.client, joining, testProject) + require.NoError(t, err) + require.True(t, joined) + }} + require.NoError(t, leaveHold(s.ctx, leaver, s.client, leaving)) + require.Nil(t, leaver.beforeDelete, "the record must land between the leave's read and its delete") + + hold, err := s.getHold("Ethernet1/12") + require.NoError(t, err, "a hold must never be deleted under a recorded claim") + require.Equal(t, []networkingv1alpha.SwitchPortHoldClaimRef{entryOf(second, "joining", "default")}, hold.Spec.NetworkClaims) +} + +func TestALeaveLandingBeforeARecordUpdatesLeavesANewHold(t *testing.T) { + s := newScenario(t, true, ipv4Only) + second := s.sibling(testProject) + leaving := s.createPhysicalClaim("leaving", "Ethernet1/12", "") + recorded, err := recordOnHold(s.ctx, s.client, s.client, leaving, testProject) + require.NoError(t, err) + require.True(t, recorded) + joining := second.createPhysicalClaim("joining", "Ethernet1/12", "") + + joiner := &interleavingClient{Client: s.client, beforeUpdate: func() { + require.NoError(t, leaveHold(s.ctx, s.client, s.client, leaving)) + }} + joined, err := recordOnHold(s.ctx, joiner, s.client, joining, testProject) + require.NoError(t, err) + require.True(t, joined) + require.Nil(t, joiner.beforeUpdate, "the leave must land between the record's read and its update") + + hold := s.requireHold("Ethernet1/12") + require.Equal(t, []networkingv1alpha.SwitchPortHoldClaimRef{entryOf(second, "joining", "default")}, hold.Spec.NetworkClaims) + require.Equal(t, testProject, hold.Spec.ConsumerRef.Name) +} + +func TestTheLastNetworkClaimLeavingClearsTheConsumer(t *testing.T) { + customer := newScenario(t, true, ipv4Only) + provider := customer.sibling(providerProject) + + boot := provider.createClaim("install-1-boot", provider.physicalSpec("Ethernet1/12", networkingv1alpha.NetworkInterfacePurposeBoot)) + provider.reconcile(boot) + data := customer.createClaim("server-data", customer.physicalSpec("Ethernet1/12", "")) + customer.reconcile(data) + require.NotNil(t, customer.requireHold("Ethernet1/12").Spec.ConsumerRef) + + customer.deletePhysicalClaim(customer.getClaim("server-data")) + require.True(t, customer.claimGone("server-data")) + hold := customer.requireHold("Ethernet1/12") + require.Equal(t, "install-1-boot", hold.Spec.Boot.Name) + require.Empty(t, hold.Spec.NetworkClaims) + require.Nil(t, hold.Spec.ConsumerRef, "a hold kept only by a boot claim names no project") +} + +func TestABootClaimReplacesANetworkEntryLeftUnderItsName(t *testing.T) { + s := newScenario(t, true, ipv4Only) + claim := s.createPhysicalClaim("install-1-boot", "Ethernet1/12", networkingv1alpha.NetworkInterfacePurposeBoot) + + hold := &networkingv1alpha.SwitchPortHold{} + hold.Name = networkingv1alpha.SwitchPortHoldName(s.switchName, "Ethernet1/12") + hold.Spec.Switch = s.switchName + hold.Spec.Port = "Ethernet1/12" + hold.Spec.ConsumerRef = &networkingv1alpha.SwitchPortHoldConsumerRef{APIGroup: miloProjectAPIGroup, Kind: miloProjectKind, Name: testProject} + hold.Spec.NetworkClaims = []networkingv1alpha.SwitchPortHoldClaimRef{entryOf(s, "install-1-boot", "default")} + require.NoError(t, s.client.Create(s.ctx, hold)) + + recorded, err := recordOnHold(s.ctx, s.client, s.client, claim, testProject) + require.NoError(t, err) + require.True(t, recorded) + stored := s.requireHold("Ethernet1/12") + require.Equal(t, entryOf(s, "install-1-boot", "default"), *stored.Spec.Boot) + require.Empty(t, stored.Spec.NetworkClaims) + require.Nil(t, stored.Spec.ConsumerRef) +} + +func TestPruningTheLastNetworkEntryClearsTheConsumer(t *testing.T) { + s := newScenario(t, true, ipv4Only) + provider := s.sibling(providerProject) + + gone := s.createPhysicalClaim("server-data", "Ethernet1/12", "") + recorded, err := recordOnHold(s.ctx, s.client, s.client, gone, testProject) + require.NoError(t, err) + require.True(t, recorded) + gone.Finalizers = nil + require.NoError(t, s.client.Update(s.ctx, gone)) + require.NoError(t, s.client.Delete(s.ctx, gone)) + require.True(t, s.claimGone("server-data")) + + boot := provider.createPhysicalClaim("install-1-boot", "Ethernet1/12", networkingv1alpha.NetworkInterfacePurposeBoot) + recorded, err = recordOnHold(s.ctx, s.client, s.client, boot, providerProject) + require.NoError(t, err) + require.True(t, recorded) + + hold := s.requireHold("Ethernet1/12") + require.Empty(t, hold.Spec.NetworkClaims) + require.Nil(t, hold.Spec.ConsumerRef, "the project leaves the port with its last network claim") +} diff --git a/internal/controller/networkinterfaceclaim_release_test.go b/internal/controller/networkinterfaceclaim_release_test.go index d59995ff..18f3db28 100644 --- a/internal/controller/networkinterfaceclaim_release_test.go +++ b/internal/controller/networkinterfaceclaim_release_test.go @@ -19,56 +19,17 @@ import ( const physicalClaimName = "server-data" -// boundPhysicalClaim stands up what a bound physical claim leaves behind: the -// claim, its interface, and an IPClaim under each of the given names. NSO -// refuses to bind physical claims until switch ports can be held, so the state -// is written directly, the way the bind path writes it. -func boundPhysicalClaim(s *scenario, ipClaimNames ...string) (*networkingv1alpha.NetworkInterfaceClaim, string) { +// boundPhysicalClaim binds a physical claim on the scenario's own port the way +// a provider's claim is bound, and returns it with the address it holds. +func boundPhysicalClaim(s *scenario) (*networkingv1alpha.NetworkInterfaceClaim, string) { s.t.Helper() - name := physicalClaimName - - claim := s.createClaim(name, networkingv1alpha.NetworkInterfaceClaimSpec{ - InterfaceName: "data", - AttachmentMode: networkingv1alpha.NetworkInterfaceAttachmentModePhysical, - AttachmentPoint: physicalAttachmentPoint("Ethernet1/12"), - IPFamilies: []networkingv1alpha.IPFamily{networkingv1alpha.IPv4Protocol}, - ReclaimPolicy: networkingv1alpha.NetworkInterfaceReclaimPolicyDelete, - }) + claim := s.createClaim(physicalClaimName, s.physicalSpec("Ethernet1/12", "")) s.reconcile(claim) - ipamClient, err := s.ipam.ClientForProject(testProject) - require.NoError(s.t, err) - var address string - for _, ipClaimName := range ipClaimNames { - ipClaim := physicalIPClaim(ipClaimName, testLocationName) - require.NoError(s.t, ipamClient.Create(s.ctx, ipClaim)) - require.NoError(s.t, ipamClient.Get(s.ctx, client.ObjectKeyFromObject(ipClaim), ipClaim)) - if address == "" { - address = ipClaim.Status.AllocatedCIDR - } - } - require.NotEmpty(s.t, address) - - claim = s.getClaim(name) - networkContext := &networkingv1alpha.NetworkContext{} - networkContext.Spec.Network.Name = "default" - iface := &networkingv1alpha.NetworkInterface{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: s.namespace, - Name: name, - Annotations: map[string]string{allocationClaimAnnotation: name}, - Finalizers: []string{networkInterfaceFinalizer}, - }, - Spec: interfaceSpecForClaim(claim, networkContext), - } - iface.Spec.Addresses = []networkingv1alpha.NetworkInterfaceAddress{{ - Family: networkingv1alpha.IPv4Protocol, Address: address, Primary: true, - }} - require.NoError(s.t, s.client.Create(s.ctx, iface)) - - claim.Status.NetworkInterfaceRef = &networkingv1alpha.LocalNetworkInterfaceRef{Name: name} - require.NoError(s.t, s.client.Status().Update(s.ctx, claim)) - return s.getClaim(name), address + claim = s.getClaim(physicalClaimName) + require.NotNil(s.t, claim.Status.NetworkInterfaceRef, "the physical claim must bind") + require.Len(s.t, claim.Status.Addresses, 1) + return claim, claim.Status.Addresses[0].Address } func physicalIPClaim(name, location string) *ipamv1alpha1.IPClaim { @@ -102,8 +63,9 @@ func (s *scenario) claimGone(name string) bool { return false } -func (s *scenario) requireReleaseUnverified(name, address string) { +func (s *scenario) requireReleaseUnverified(address string) { s.t.Helper() + name := physicalClaimName require.False(s.t, s.claimGone(name), "the claim must stay while IPAM holds its address") ready := conditionOf(s.getClaim(name), networkingv1alpha.NetworkInterfaceClaimReady) require.NotNil(s.t, ready) @@ -120,9 +82,10 @@ func (s *scenario) requireReleaseUnverified(name, address string) { func TestPhysicalReleaseCompletesOnceIPAMLetsGo(t *testing.T) { s := newScenario(t, true, []networkingv1alpha.IPFamily{networkingv1alpha.IPv4Protocol}) names := physicalIPClaimNames(physicalClaimName) - claim, _ := boundPhysicalClaim(s, names[0]) + claim, _ := boundPhysicalClaim(s) + s.ipClaim(names[0]) - s.deleteClaim(claim) + s.deletePhysicalClaim(claim) require.True(t, s.claimGone(physicalClaimName)) _, err := s.getInterface(physicalClaimName) @@ -133,11 +96,11 @@ func TestPhysicalReleaseCompletesOnceIPAMLetsGo(t *testing.T) { func TestPhysicalReleaseWaitsWhileIPAMRefusesTheDelete(t *testing.T) { s := newScenario(t, true, []networkingv1alpha.IPFamily{networkingv1alpha.IPv4Protocol}) names := physicalIPClaimNames(physicalClaimName) - claim, _ := boundPhysicalClaim(s, names[0]) + claim, _ := boundPhysicalClaim(s) s.ipam.refuseRelease(names[0], errors.New("ipam is unavailable")) - require.NoError(t, s.client.Delete(s.ctx, claim)) - _, err := s.reconciler.reconcileClaim(s.ctx, s.client, s.events, client.ObjectKeyFromObject(claim)) + s.deleteAndDetach(claim) + _, err := s.reconciler.reconcileClaim(s.ctx, s.client, s.client, s.events, client.ObjectKeyFromObject(claim)) require.Error(t, err) require.False(t, s.claimGone(physicalClaimName)) @@ -149,7 +112,7 @@ func TestPhysicalReleaseWaitsWhileIPAMRefusesTheDelete(t *testing.T) { func TestPhysicalReleaseWaitsForALingeringAllocation(t *testing.T) { s := newScenario(t, true, []networkingv1alpha.IPFamily{networkingv1alpha.IPv4Protocol}) names := physicalIPClaimNames(physicalClaimName) - claim, address := boundPhysicalClaim(s, names[0]) + claim, address := boundPhysicalClaim(s) ipamClient, err := s.ipam.ClientForProject(testProject) require.NoError(t, err) @@ -160,10 +123,10 @@ func TestPhysicalReleaseWaitsForALingeringAllocation(t *testing.T) { lingering.Spec.Scope = map[string]ipamv1alpha1.ScopeRef{ipamScopeRoleLocation: {Name: testLocationName}} require.NoError(t, ipamClient.Create(s.ctx, lingering)) - s.deleteClaim(claim) - s.requireReleaseUnverified(physicalClaimName, address) + s.deletePhysicalClaim(claim) + s.requireReleaseUnverified(address) s.reconcile(claim) - s.requireReleaseUnverified(physicalClaimName, address) + s.requireReleaseUnverified(address) require.NoError(t, ipamClient.Get(s.ctx, client.ObjectKeyFromObject(lingering), lingering)) lingering.Spec.ClaimRef = nil @@ -175,9 +138,12 @@ func TestPhysicalReleaseWaitsForALingeringAllocation(t *testing.T) { func TestPhysicalReleaseFreesEveryNameAnAddressIsHeldUnder(t *testing.T) { s := newScenario(t, true, []networkingv1alpha.IPFamily{networkingv1alpha.IPv4Protocol}) names := physicalIPClaimNames(physicalClaimName) - claim, _ := boundPhysicalClaim(s, names...) + claim, _ := boundPhysicalClaim(s) + ipamClient, err := s.ipam.ClientForProject(testProject) + require.NoError(t, err) + require.NoError(t, ipamClient.Create(s.ctx, physicalIPClaim(names[1], testLocationName))) - s.deleteClaim(claim) + s.deletePhysicalClaim(claim) require.False(t, s.claimGone(physicalClaimName), "one pass frees one name, so the claim waits for the other") s.reconcile(claim) @@ -188,14 +154,16 @@ func TestPhysicalReleaseFreesEveryNameAnAddressIsHeldUnder(t *testing.T) { func TestPhysicalReleaseIgnoresAnotherLocationsAllocation(t *testing.T) { s := newScenario(t, true, []networkingv1alpha.IPFamily{networkingv1alpha.IPv4Protocol}) names := physicalIPClaimNames(physicalClaimName) - claim, _ := boundPhysicalClaim(s, names[1]) - ipamClient, err := s.ipam.ClientForProject(testProject) require.NoError(t, err) foreign := physicalIPClaim(names[0], "location-elsewhere") require.NoError(t, ipamClient.Create(s.ctx, foreign)) - s.deleteClaim(claim) + claim, _ := boundPhysicalClaim(s) + require.NoError(t, ipamClient.Get(s.ctx, client.ObjectKey{Namespace: testProjectNS, Name: names[1]}, &ipamv1alpha1.IPClaim{}), + "the claim must be addressed under the name for this location") + + s.deletePhysicalClaim(claim) require.True(t, s.claimGone(physicalClaimName), "another location's same-named allocation is not this claim's") require.NoError(t, ipamClient.Get(s.ctx, client.ObjectKeyFromObject(foreign), foreign), "another location's allocation must be left alone") @@ -204,7 +172,7 @@ func TestPhysicalReleaseIgnoresAnotherLocationsAllocation(t *testing.T) { func TestPhysicalReleaseKeepsItsReasonAcrossPasses(t *testing.T) { s := newScenario(t, true, []networkingv1alpha.IPFamily{networkingv1alpha.IPv4Protocol}) names := physicalIPClaimNames(physicalClaimName) - claim, address := boundPhysicalClaim(s, names[0]) + claim, address := boundPhysicalClaim(s) ipamClient, err := s.ipam.ClientForProject(testProject) require.NoError(t, err) @@ -214,10 +182,10 @@ func TestPhysicalReleaseKeepsItsReasonAcrossPasses(t *testing.T) { lingering.Spec.ClaimRef = &ipamv1alpha1.LocalRef{Name: names[0]} require.NoError(t, ipamClient.Create(s.ctx, lingering)) - s.deleteClaim(claim) + s.deletePhysicalClaim(claim) first := s.getClaim(physicalClaimName).ResourceVersion s.reconcile(claim) - s.requireReleaseUnverified(physicalClaimName, address) + s.requireReleaseUnverified(address) require.Equal(t, first, s.getClaim(physicalClaimName).ResourceVersion, "a pass that finds nothing new must not rewrite the claim") } @@ -251,7 +219,7 @@ func TestVirtualReleaseIsUnchanged(t *testing.T) { func TestPhysicalReleaseWaitsWhenTheInterfaceIsAlreadyGone(t *testing.T) { s := newScenario(t, true, []networkingv1alpha.IPFamily{networkingv1alpha.IPv4Protocol}) names := physicalIPClaimNames(physicalClaimName) - claim, _ := boundPhysicalClaim(s, names[0]) + claim, _ := boundPhysicalClaim(s) ipamClient, err := s.ipam.ClientForProject(testProject) require.NoError(t, err) @@ -267,7 +235,7 @@ func TestPhysicalReleaseWaitsWhenTheInterfaceIsAlreadyGone(t *testing.T) { require.NoError(t, s.client.Update(s.ctx, iface)) require.NoError(t, s.client.Delete(s.ctx, iface)) - s.deleteClaim(claim) + s.deletePhysicalClaim(claim) require.False(t, s.claimGone(physicalClaimName)) ready := conditionOf(s.getClaim(physicalClaimName), networkingv1alpha.NetworkInterfaceClaimReady) require.Equal(t, networkingv1alpha.NetworkInterfaceClaimReasonReleaseUnverified, ready.Reason) diff --git a/internal/controller/switchporthold.go b/internal/controller/switchporthold.go new file mode 100644 index 00000000..ef2c5666 --- /dev/null +++ b/internal/controller/switchporthold.go @@ -0,0 +1,327 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +package controller + +import ( + "context" + "fmt" + "slices" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + "sigs.k8s.io/controller-runtime/pkg/client" + + networkingv1alpha "go.datum.net/network-services-operator/api/v1alpha" +) + +const ( + miloProjectAPIGroup = "resourcemanager.miloapis.com" + miloProjectKind = "Project" + + // Each attempt starts from a fresh read, so a conflict only means another + // writer moved first. A hold contended past this many attempts is left to + // the next reconcile. + switchPortHoldWriteAttempts = 5 +) + +func isPhysical(claim *networkingv1alpha.NetworkInterfaceClaim) bool { + return claim.Spec.AttachmentMode == networkingv1alpha.NetworkInterfaceAttachmentModePhysical +} + +func isBootClaim(claim *networkingv1alpha.NetworkInterfaceClaim) bool { + return claim.Spec.Purpose == networkingv1alpha.NetworkInterfacePurposeBoot +} + +func switchPortHoldKey(claim *networkingv1alpha.NetworkInterfaceClaim) client.ObjectKey { + point := claim.Spec.AttachmentPoint + return client.ObjectKey{Name: networkingv1alpha.SwitchPortHoldName(point.Switch, point.Port)} +} + +func holdEntryFor(claim *networkingv1alpha.NetworkInterfaceClaim) networkingv1alpha.SwitchPortHoldClaimRef { + return networkingv1alpha.SwitchPortHoldClaimRef{ + Namespace: claim.Namespace, + Name: claim.Name, + Network: claim.Spec.Network.Name, + } +} + +func sameClaim(entry networkingv1alpha.SwitchPortHoldClaimRef, claim *networkingv1alpha.NetworkInterfaceClaim) bool { + return entry.Namespace == claim.Namespace && entry.Name == claim.Name +} + +func holdIsForPort(hold *networkingv1alpha.SwitchPortHold, claim *networkingv1alpha.NetworkInterfaceClaim) bool { + point := claim.Spec.AttachmentPoint + return hold.Spec.Switch == point.Switch && hold.Spec.Port == point.Port +} + +// holdRecords reports whether the port's hold carries an entry under the +// claim's name. An entry under its name for another network counts too: the +// realizer may have acted on it, so only the realizer may say the port is clear. +func holdRecords(hold *networkingv1alpha.SwitchPortHold, claim *networkingv1alpha.NetworkInterfaceClaim) bool { + if !holdIsForPort(hold, claim) { + return false + } + if hold.Spec.Boot != nil && sameClaim(*hold.Spec.Boot, claim) { + return true + } + return slices.ContainsFunc(hold.Spec.NetworkClaims, func(entry networkingv1alpha.SwitchPortHoldClaimRef) bool { + return sameClaim(entry, claim) + }) +} + +// readHold reads the claim's hold from the API server, returning nil when the +// port has none. A cache could answer with a hold that another writer has +// since changed, and every decision here rests on the current one. +func readHold( + ctx context.Context, + reader client.Reader, + claim *networkingv1alpha.NetworkInterfaceClaim, +) (*networkingv1alpha.SwitchPortHold, error) { + hold := &networkingv1alpha.SwitchPortHold{} + if err := reader.Get(ctx, switchPortHoldKey(claim), hold); err != nil { + if apierrors.IsNotFound(err) { + return nil, nil + } + return nil, fmt.Errorf("failed reading switch port hold: %w", err) + } + return hold, nil +} + +// recordOnHold records the claim on its port's hold, creating the hold for a +// free port. It reports false when the port is held by claims this one cannot +// share it with, and leaves the hold as it was. +func recordOnHold( + ctx context.Context, + cl client.Client, + reader client.Reader, + claim *networkingv1alpha.NetworkInterfaceClaim, + project string, +) (bool, error) { + var lastErr error + for range switchPortHoldWriteAttempts { + hold, err := readHold(ctx, reader, claim) + if err != nil { + return false, err + } + + if hold == nil { + hold = &networkingv1alpha.SwitchPortHold{} + hold.Name = switchPortHoldKey(claim).Name + hold.Spec.Switch = claim.Spec.AttachmentPoint.Switch + hold.Spec.Port = claim.Spec.AttachmentPoint.Port + admitToHold(hold, claim, project) + clearEmptyConsumer(hold) + // Only one create of a name succeeds, so a port taken in between + // is read again and decided against what took it. + if err := cl.Create(ctx, hold); err != nil { + if apierrors.IsAlreadyExists(err) { + lastErr = err + continue + } + return false, fmt.Errorf("failed creating switch port hold: %w", err) + } + return true, nil + } + + if !holdIsForPort(hold, claim) { + return false, &bindingRefused{ + reason: networkingv1alpha.NetworkInterfaceClaimReasonAttachmentPointHeld, + message: "The record for this switch port has the name of a record for another port, " + + "so the claim cannot be recorded and no address is allocated for it", + } + } + + before := hold.Spec.DeepCopy() + if err := pruneHold(ctx, reader, hold, claim); err != nil { + return false, err + } + recorded := admitToHold(hold, claim, project) + clearEmptyConsumer(hold) + if equalHoldSpecs(before, &hold.Spec) { + return recorded, nil + } + + if err := cl.Update(ctx, hold); err != nil { + // A hold deleted since the read is a free port again, and a create + // on the next attempt takes it. + if apierrors.IsConflict(err) || apierrors.IsNotFound(err) { + lastErr = err + continue + } + return false, fmt.Errorf("failed recording the claim on its switch port hold: %w", err) + } + return recorded, nil + } + return false, lastErr +} + +// admitToHold records the claim if the port can carry it, reporting whether +// the hold now records it. A port carries one boot claim, and network claims +// from one project with each network at most once. +func admitToHold( + hold *networkingv1alpha.SwitchPortHold, + claim *networkingv1alpha.NetworkInterfaceClaim, + project string, +) bool { + entry := holdEntryFor(claim) + + // An entry under this claim's name for another network, or in the other + // slot, is left from an earlier claim of that name. + if isBootClaim(claim) { + removeNetworkClaim(hold, claim) + if hold.Spec.Boot != nil && !sameClaim(*hold.Spec.Boot, claim) { + return false + } + hold.Spec.Boot = &entry + return true + } + + if hold.Spec.Boot != nil && sameClaim(*hold.Spec.Boot, claim) { + hold.Spec.Boot = nil + } + if slices.Contains(hold.Spec.NetworkClaims, entry) { + return true + } + removeNetworkClaim(hold, claim) + + if len(hold.Spec.NetworkClaims) > 0 { + if hold.Spec.ConsumerRef == nil || hold.Spec.ConsumerRef.Name != project { + return false + } + if slices.ContainsFunc(hold.Spec.NetworkClaims, func(held networkingv1alpha.SwitchPortHoldClaimRef) bool { + return held.Namespace == entry.Namespace && held.Network == entry.Network + }) { + return false + } + } + + hold.Spec.ConsumerRef = &networkingv1alpha.SwitchPortHoldConsumerRef{ + APIGroup: miloProjectAPIGroup, + Kind: miloProjectKind, + Name: project, + } + hold.Spec.NetworkClaims = append(hold.Spec.NetworkClaims, entry) + return true +} + +func removeNetworkClaim(hold *networkingv1alpha.SwitchPortHold, claim *networkingv1alpha.NetworkInterfaceClaim) { + hold.Spec.NetworkClaims = slices.DeleteFunc(hold.Spec.NetworkClaims, func(entry networkingv1alpha.SwitchPortHoldClaimRef) bool { + return sameClaim(entry, claim) + }) +} + +// clearEmptyConsumer drops the project from a hold its last network claim has +// left, so a hold kept only by a boot claim names no project. +func clearEmptyConsumer(hold *networkingv1alpha.SwitchPortHold) { + if len(hold.Spec.NetworkClaims) == 0 { + hold.Spec.NetworkClaims = nil + hold.Spec.ConsumerRef = nil + } +} + +// pruneHold drops every entry whose claim is gone, read from the API server, so +// no entry outlives its claim. A claim of the same name that names another +// network, another port, or the other kind of claim is a different claim. The +// claim being written is never pruned here. +func pruneHold( + ctx context.Context, + reader client.Reader, + hold *networkingv1alpha.SwitchPortHold, + writing *networkingv1alpha.NetworkInterfaceClaim, +) error { + live := func(entry networkingv1alpha.SwitchPortHoldClaimRef, boot bool) (bool, error) { + if sameClaim(entry, writing) { + return true, nil + } + var claim networkingv1alpha.NetworkInterfaceClaim + if err := reader.Get(ctx, client.ObjectKey{Namespace: entry.Namespace, Name: entry.Name}, &claim); err != nil { + if apierrors.IsNotFound(err) { + return false, nil + } + return false, fmt.Errorf("failed reading claim %s/%s recorded on switch port hold %q: %w", + entry.Namespace, entry.Name, hold.Name, err) + } + return isPhysical(&claim) && claim.Spec.AttachmentPoint != nil && holdIsForPort(hold, &claim) && + claim.Spec.Network.Name == entry.Network && isBootClaim(&claim) == boot, nil + } + + if hold.Spec.Boot != nil { + keep, err := live(*hold.Spec.Boot, true) + if err != nil { + return err + } + if !keep { + hold.Spec.Boot = nil + } + } + + kept := hold.Spec.NetworkClaims[:0:0] + for _, entry := range hold.Spec.NetworkClaims { + keep, err := live(entry, false) + if err != nil { + return err + } + if keep { + kept = append(kept, entry) + } + } + hold.Spec.NetworkClaims = kept + return nil +} + +// leaveHold removes the claim's entries from its port's hold, and deletes the +// hold once it records nothing. The delete is conditional on the hold being +// unchanged since it was read, so a claim recorded in between keeps it. +func leaveHold( + ctx context.Context, + cl client.Client, + reader client.Reader, + claim *networkingv1alpha.NetworkInterfaceClaim, +) error { + var lastErr error + for range switchPortHoldWriteAttempts { + hold, err := readHold(ctx, reader, claim) + if err != nil { + return err + } + if hold == nil || !holdIsForPort(hold, claim) { + return nil + } + + before := hold.Spec.DeepCopy() + if hold.Spec.Boot != nil && sameClaim(*hold.Spec.Boot, claim) { + hold.Spec.Boot = nil + } + removeNetworkClaim(hold, claim) + if err := pruneHold(ctx, reader, hold, claim); err != nil { + return err + } + clearEmptyConsumer(hold) + + if hold.Spec.Boot == nil && len(hold.Spec.NetworkClaims) == 0 { + version := hold.ResourceVersion + err = cl.Delete(ctx, hold, client.Preconditions{ResourceVersion: &version}) + } else if !equalHoldSpecs(before, &hold.Spec) { + err = cl.Update(ctx, hold) + } + switch { + case err == nil, apierrors.IsNotFound(err): + return nil + case apierrors.IsConflict(err): + lastErr = err + continue + default: + return fmt.Errorf("failed removing the claim from its switch port hold: %w", err) + } + } + return lastErr +} + +func equalHoldSpecs(a, b *networkingv1alpha.SwitchPortHoldSpec) bool { + if (a.Boot == nil) != (b.Boot == nil) || (a.Boot != nil && *a.Boot != *b.Boot) { + return false + } + if (a.ConsumerRef == nil) != (b.ConsumerRef == nil) || (a.ConsumerRef != nil && *a.ConsumerRef != *b.ConsumerRef) { + return false + } + return slices.Equal(a.NetworkClaims, b.NetworkClaims) +} diff --git a/internal/networkagent/catalog.go b/internal/networkagent/catalog.go index 8fae67c1..24a44eea 100644 --- a/internal/networkagent/catalog.go +++ b/internal/networkagent/catalog.go @@ -483,11 +483,19 @@ func claimRefusals() []ReasonInfo { Remediation: remediationWait, Skill: SkillInterfaceTriage, ExpectedDuration: windowRemoval, }}, - {networkingv1alpha.NetworkInterfaceClaimReasonPhysicalAttachmentUnsupported, ReasonInfo{ - Actionability: ActionabilityPlatform, Scope: ScopeInstance, - Explanation: "This server's network interface asks to reach its network through a switch port, " + - "which the platform cannot attach yet, so no address was given to it.", - Remediation: remediationEscalate, Skill: SkillInterfaceTriage, + {networkingv1alpha.NetworkInterfaceClaimReasonAttachmentPointHeld, ReasonInfo{ + Actionability: ActionabilityTransient, Scope: ScopeInstance, + Explanation: "The switch port this server's network interface is cabled to is still in use for " + + "something it cannot share the port with, so no address has been given to it yet.", + Remediation: remediationWait, Skill: SkillInterfaceTriage, + ExpectedDuration: windowRemoval, + }}, + {networkingv1alpha.NetworkInterfaceClaimReasonAwaitingDetach, ReasonInfo{ + Actionability: ActionabilityTransient, Scope: ScopeInstance, + Explanation: "This server's network interface is being removed, and the platform is waiting for " + + "its switch port to stop carrying the network before it returns the address.", + Remediation: remediationWait, Skill: SkillInterfaceTriage, + ExpectedDuration: windowRemoval, }}, {reasonInterfaceHeldByAnother, ReasonInfo{ Actionability: ActionabilityPlatform, Scope: ScopeInstance, diff --git a/internal/networkagent/catalog_test.go b/internal/networkagent/catalog_test.go index 88912619..ca24e678 100644 --- a/internal/networkagent/catalog_test.go +++ b/internal/networkagent/catalog_test.go @@ -42,6 +42,7 @@ var outOfScopeAPIFiles = map[string]string{ "networkloadbalancercellintent_types.go": "hub-side NLB serving intent, not a network-agent customer API", "networkloadbalancerroute_types.go": "Network Load Balancer route status belongs to the load balancer product", "networkpolicy_types.go": "declares no status reasons", + "switchporthold_types.go": "cell-local record of what a switch port carries, with no status reasons", "trafficprotectionpolicy_types.go": "load balancer protection; the ALB agent's", "zz_generated.deepcopy.go": "generated", } From f26e1b29a589a51100ff2a5317ddbf59d49cd10e Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 23:17:06 -0600 Subject: [PATCH 2/2] fix: Address review of the switch port holds Review found the realizer could not read holds, nothing guarded reading holds uncached, every reconcile of a recorded claim re-read each other claim on its port, and a waiting claim added up to a minute to a boot-to-customer handover. Key changes: - let the data-plane role get, list and watch switch port holds - test that Reconcile reads holds through the API reader, on bind and release - return early when the hold already records the claim, skipping the prune - requeue a claim waiting for its port after 10 seconds - share the Milo project group and kind constants with internal DNS - trim comments to the ones that carry a reason Co-Authored-By: Claude Opus 5.5 --- .../rbac/networkinterface_dataplane_role.yaml | 5 +- internal/controller/internaldns_controller.go | 2 +- .../controller/networkinterface_controller.go | 5 +- .../networkinterfaceclaim_controller.go | 33 +++-- .../networkinterfaceclaim_holdreads_test.go | 126 ++++++++++++++++++ .../networkinterfaceclaim_physical_test.go | 10 +- .../networkinterfaceclaim_release_test.go | 2 - internal/controller/switchporthold.go | 47 ++++--- 8 files changed, 173 insertions(+), 57 deletions(-) create mode 100644 internal/controller/networkinterfaceclaim_holdreads_test.go diff --git a/config/rbac/networkinterface_dataplane_role.yaml b/config/rbac/networkinterface_dataplane_role.yaml index 24e32588..a5526f02 100644 --- a/config/rbac/networkinterface_dataplane_role.yaml +++ b/config/rbac/networkinterface_dataplane_role.yaml @@ -1,5 +1,7 @@ # Permissions for a data plane to report what it programmed. NSO seeds -# Programmed and never writes it again; this is the role for whoever does. +# Programmed and never writes it again; this is the role for whoever does. A +# physical realizer also reads the switch port holds to learn what each port +# carries. apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: @@ -13,6 +15,7 @@ rules: resources: - networkinterfaces - networkinterfaceclaims + - switchportholds verbs: - get - list diff --git a/internal/controller/internaldns_controller.go b/internal/controller/internaldns_controller.go index f5e1922c..66455e93 100644 --- a/internal/controller/internaldns_controller.go +++ b/internal/controller/internaldns_controller.go @@ -91,7 +91,7 @@ type APIProjectIdentityResolver struct { func (r *APIProjectIdentityResolver) ProjectUID(ctx context.Context, name string) (types.UID, error) { project := &unstructured.Unstructured{} project.SetGroupVersionKind(schema.GroupVersionKind{ - Group: "resourcemanager.miloapis.com", Version: "v1alpha1", Kind: "Project", + Group: miloProjectAPIGroup, Version: "v1alpha1", Kind: miloProjectKind, }) if err := r.Reader.Get(ctx, client.ObjectKey{Name: name}, project); err != nil { return "", err diff --git a/internal/controller/networkinterface_controller.go b/internal/controller/networkinterface_controller.go index 072cf956..2846ebf3 100644 --- a/internal/controller/networkinterface_controller.go +++ b/internal/controller/networkinterface_controller.go @@ -192,9 +192,8 @@ func (r *NetworkInterfaceReconciler) heldByLiveClaim( } // A claim being deleted holds nothing. Its own release cannot free these - // addresses once the interface is gone. A physical claim still waiting for - // its port to be detached is the exception: the port may carry these - // addresses, and its release finds them by its own name once it is clear. + // addresses once the interface is gone. A physical claim not yet detached + // is the exception: the port may still carry them. return claim.DeletionTimestamp.IsZero() || controllerutil.ContainsFinalizer(&claim, networkingv1alpha.NetworkInterfaceClaimDetachFinalizer), nil } diff --git a/internal/controller/networkinterfaceclaim_controller.go b/internal/controller/networkinterfaceclaim_controller.go index 0d5b4db4..ce8f86fa 100644 --- a/internal/controller/networkinterfaceclaim_controller.go +++ b/internal/controller/networkinterfaceclaim_controller.go @@ -70,6 +70,10 @@ const ( // IPAM sends no event when it finishes releasing, so a physical claim // waiting on it looks again. unverifiedReleaseRetryInterval = 10 * time.Second + + // Nothing watches holds, and a handover from boot to customer waits on + // this retry. + heldClaimRetryInterval = 10 * time.Second ) // NetworkInterfaceClaimReconciler binds a NetworkInterfaceClaim to a @@ -125,9 +129,6 @@ func networkInterfaceClaimWriteRace(err error) (ctrl.Result, bool) { } } -// reconcileClaim reads holds through reader, which must not be a cache: a -// switch port hold is changed only by compare-and-swap against what the API -// server holds now. func (r *NetworkInterfaceClaimReconciler) reconcileClaim( ctx context.Context, cl client.Client, @@ -144,9 +145,7 @@ func (r *NetworkInterfaceClaimReconciler) reconcileClaim( return r.release(ctx, cl, reader, &claim) } - // Both finalizers land in one write, so a physical claim deleted before it - // has neither and took nothing. The API server refuses a new finalizer on - // an object being deleted, so the detach finalizer never reaches one. + // One write for both, so a claim deleted before it took nothing. added := controllerutil.AddFinalizer(&claim, networkInterfaceClaimFinalizer) if isPhysical(&claim) { added = controllerutil.AddFinalizer(&claim, networkingv1alpha.NetworkInterfaceClaimDetachFinalizer) || added @@ -214,9 +213,8 @@ func (r *NetworkInterfaceClaimReconciler) fulfill( terminating)) } - // Recording comes before any address or interface exists, so whether the - // hold ever recorded the claim is what says the realizer may have touched - // the port. + // Whether the hold ever recorded the claim is what says the realizer may + // have touched the port, so recording comes before anything is allocated. if isPhysical(claim) { recorded, err := recordOnHold(ctx, cl, reader, claim, routing.project) if err != nil { @@ -229,10 +227,14 @@ func (r *NetworkInterfaceClaimReconciler) fulfill( if !recorded { // The port may be held by another customer, so the message says // nothing about what holds it. - return r.reject(ctx, cl, claim, + result, err := r.reject(ctx, cl, claim, networkingv1alpha.NetworkInterfaceClaimReasonAttachmentPointHeld, "The switch port this claim names is held by claims it cannot share the port with, "+ "so no address is allocated until the port is free") + if err == nil { + result.RequeueAfter = heldClaimRetryInterval + } + return result, err } } @@ -1604,9 +1606,8 @@ func (r *NetworkInterfaceClaimReconciler) release( } case verify && (recorded || claim.Status.NetworkInterfaceRef != nil): - // A physical claim allocates once it is recorded and before it - // records its interface, so a crash in between leaves addresses only - // its name can find. A claim the hold never recorded allocated none. + // A crash between allocating and recording the interface leaves + // addresses only the claim's name can find. if err := r.releaseIPClaims(ctx, cl, claim.Namespace, claim.Name, claimEntries(claim)); err != nil { return ctrl.Result{}, err } @@ -1648,10 +1649,8 @@ func (r *NetworkInterfaceClaimReconciler) release( return ctrl.Result{}, nil } -// awaitDetach reports whether the port no longer carries the claim's network, -// which is when its addresses may be released. While the hold records the -// claim only the realizer can say so, by removing the detach finalizer. A claim -// the hold never recorded was never acted on, so its finalizer comes off here. +// A claim the hold never recorded was never acted on by the realizer, so NSO +// removes its detach finalizer itself. func awaitDetach( ctx context.Context, cl client.Client, diff --git a/internal/controller/networkinterfaceclaim_holdreads_test.go b/internal/controller/networkinterfaceclaim_holdreads_test.go new file mode 100644 index 00000000..f3468ce7 --- /dev/null +++ b/internal/controller/networkinterfaceclaim_holdreads_test.go @@ -0,0 +1,126 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +package controller + +import ( + "context" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/require" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/cluster" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + "sigs.k8s.io/controller-runtime/pkg/recorder" + mcmanager "sigs.k8s.io/multicluster-runtime/pkg/manager" + "sigs.k8s.io/multicluster-runtime/pkg/multicluster" + mcreconcile "sigs.k8s.io/multicluster-runtime/pkg/reconcile" + + networkingv1alpha "go.datum.net/network-services-operator/api/v1alpha" +) + +// staleHoldCache answers every hold read the way a cache that has not seen the +// hold yet does. +type staleHoldCache struct { + client.Client +} + +func (c staleHoldCache) Get(ctx context.Context, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if _, ok := obj.(*networkingv1alpha.SwitchPortHold); ok { + return apierrors.NewNotFound(networkingv1alpha.GroupVersion.WithResource("switchportholds").GroupResource(), key.Name) + } + return c.Client.Get(ctx, key, obj, opts...) +} + +type cachedCluster struct { + cluster.Cluster + cached client.Client + live client.Reader +} + +func (c *cachedCluster) GetClient() client.Client { return c.cached } +func (c *cachedCluster) GetAPIReader() client.Reader { return c.live } +func (c *cachedCluster) GetEventRecorder(string) recorder.EventRecorder { return nil } + +type oneClusterManager struct { + mcmanager.Manager + cluster cluster.Cluster +} + +func (m *oneClusterManager) GetCluster(context.Context, multicluster.ClusterName) (cluster.Cluster, error) { + return m.cluster, nil +} + +// reconcileThroughManager runs the reconciler's entry point against a cluster +// whose cache has never seen a hold, so only reads made through the API reader +// find one. +func (s *scenario) reconcileThroughManager(name string) (reconcile.Result, error) { + s.t.Helper() + reconciler := *s.reconciler + reconciler.mgr = &oneClusterManager{cluster: &cachedCluster{cached: staleHoldCache{s.client}, live: s.client}} + return reconciler.Reconcile(s.ctx, mcreconcile.Request{ + Request: reconcile.Request{NamespacedName: client.ObjectKey{Namespace: s.namespace, Name: name}}, + }) +} + +func TestReleaseReadsTheHoldFromTheAPIServer(t *testing.T) { + s := newScenario(t, true, ipv4Only) + claim, _ := boundPhysicalClaim(s) + require.NoError(t, s.client.Delete(s.ctx, claim)) + + _, err := s.reconcileThroughManager(physicalClaimName) + require.NoError(t, err) + s.requireAwaitingDetach(physicalClaimName) +} + +func TestRecordingReadsTheHoldFromTheAPIServer(t *testing.T) { + s := newScenario(t, true, ipv4Only) + other := s.sibling(otherProject) + holder := s.createClaim("server-data", s.physicalSpec("Ethernet1/12", "")) + s.reconcile(holder) + other.createClaim("their-data", other.physicalSpec("Ethernet1/12", "")) + + _, err := other.reconcileThroughManager("their-data") + require.NoError(t, err) + other.requireWaiting("their-data") +} + +type claimReadCounter struct { + client.Reader + claimReads atomic.Int32 +} + +func (c *claimReadCounter) Get(ctx context.Context, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if _, ok := obj.(*networkingv1alpha.NetworkInterfaceClaim); ok { + c.claimReads.Add(1) + } + return c.Reader.Get(ctx, key, obj, opts...) +} + +func TestARecordedClaimReadsNoOtherClaims(t *testing.T) { + s := newScenario(t, true, ipv4Only) + second := s.sibling(testProject) + first := s.createClaim("server-data", s.physicalSpec("Ethernet1/12", "")) + s.reconcile(first) + second.reconcile(second.createClaim("server-storage", second.physicalSpec("Ethernet1/12", ""))) + require.Len(t, s.requireHold("Ethernet1/12").Spec.NetworkClaims, 2) + + counter := &claimReadCounter{Reader: s.client} + _, err := s.reconciler.reconcileClaim(s.ctx, s.client, counter, s.events, client.ObjectKeyFromObject(first)) + require.NoError(t, err) + require.Zero(t, counter.claimReads.Load(), "a claim already recorded must not re-check every other entry") +} + +func TestAWaitingClaimRetriesSoon(t *testing.T) { + s := newScenario(t, true, ipv4Only) + other := s.sibling(otherProject) + s.reconcile(s.createClaim("server-data", s.physicalSpec("Ethernet1/12", ""))) + waiting := other.createClaim("their-data", other.physicalSpec("Ethernet1/12", "")) + + result, err := s.reconciler.reconcileClaim(s.ctx, s.client, s.client, s.events, client.ObjectKeyFromObject(waiting)) + require.NoError(t, err) + other.requireWaiting("their-data") + require.Equal(t, 10*time.Second, result.RequeueAfter) +} diff --git a/internal/controller/networkinterfaceclaim_physical_test.go b/internal/controller/networkinterfaceclaim_physical_test.go index 64d9a055..8ab0b12e 100644 --- a/internal/controller/networkinterfaceclaim_physical_test.go +++ b/internal/controller/networkinterfaceclaim_physical_test.go @@ -48,8 +48,6 @@ func (s *scenario) physicalSpec(port string, purpose networkingv1alpha.NetworkIn } } -// createPhysicalClaim writes a physical claim on the default network, carrying both -// finalizers the way NSO's first write leaves it. func (s *scenario) createPhysicalClaim( name, port string, purpose networkingv1alpha.NetworkInterfacePurpose, @@ -65,8 +63,6 @@ func (s *scenario) createPhysicalClaim( return claim } -// sibling is another namespace on the same planes and the same switch, -// belonging to the given project. func (s *scenario) sibling(project string) *scenario { s.t.Helper() namespace := &corev1.Namespace{} @@ -106,8 +102,7 @@ func (s *scenario) requireHold(port string) *networkingv1alpha.SwitchPortHold { return hold } -// detach stands in for the realizer confirming the port no longer carries the -// claim's network. +// detach stands in for the realizer. func (s *scenario) detach(name string) { s.t.Helper() claim := s.getClaim(name) @@ -129,8 +124,6 @@ func (s *scenario) requireAwaitingDetach(name string) { require.Equal(s.t, networkingv1alpha.NetworkInterfaceClaimReasonReleasing, prepared.Reason) } -// deleteAndDetach deletes a recorded physical claim, checks NSO waits for the -// realizer, and then detaches it. func (s *scenario) deleteAndDetach(claim *networkingv1alpha.NetworkInterfaceClaim) { s.t.Helper() require.NoError(s.t, s.client.Delete(s.ctx, claim)) @@ -269,7 +262,6 @@ func TestAnotherProjectWaitsForAHeldPort(t *testing.T) { require.True(t, other.claimGone("their-data")) require.Equal(t, hold.ResourceVersion, s.requireHold("Ethernet1/12").ResourceVersion) - // The next claim takes the port once its last holder leaves. s.deletePhysicalClaim(s.getClaim("server-data")) _, err := s.getHold("Ethernet1/12") require.True(t, apierrors.IsNotFound(err), "a hold that records nothing is deleted") diff --git a/internal/controller/networkinterfaceclaim_release_test.go b/internal/controller/networkinterfaceclaim_release_test.go index 18f3db28..bfa965a7 100644 --- a/internal/controller/networkinterfaceclaim_release_test.go +++ b/internal/controller/networkinterfaceclaim_release_test.go @@ -19,8 +19,6 @@ import ( const physicalClaimName = "server-data" -// boundPhysicalClaim binds a physical claim on the scenario's own port the way -// a provider's claim is bound, and returns it with the address it holds. func boundPhysicalClaim(s *scenario) (*networkingv1alpha.NetworkInterfaceClaim, string) { s.t.Helper() claim := s.createClaim(physicalClaimName, s.physicalSpec("Ethernet1/12", "")) diff --git a/internal/controller/switchporthold.go b/internal/controller/switchporthold.go index ef2c5666..f25af2fe 100644 --- a/internal/controller/switchporthold.go +++ b/internal/controller/switchporthold.go @@ -17,9 +17,6 @@ const ( miloProjectAPIGroup = "resourcemanager.miloapis.com" miloProjectKind = "Project" - // Each attempt starts from a fresh read, so a conflict only means another - // writer moved first. A hold contended past this many attempts is left to - // the next reconcile. switchPortHoldWriteAttempts = 5 ) @@ -53,9 +50,8 @@ func holdIsForPort(hold *networkingv1alpha.SwitchPortHold, claim *networkingv1al return hold.Spec.Switch == point.Switch && hold.Spec.Port == point.Port } -// holdRecords reports whether the port's hold carries an entry under the -// claim's name. An entry under its name for another network counts too: the -// realizer may have acted on it, so only the realizer may say the port is clear. +// An entry under the claim's name for another network counts too: the realizer +// may have acted on it, so only the realizer may say the port is clear. func holdRecords(hold *networkingv1alpha.SwitchPortHold, claim *networkingv1alpha.NetworkInterfaceClaim) bool { if !holdIsForPort(hold, claim) { return false @@ -68,9 +64,8 @@ func holdRecords(hold *networkingv1alpha.SwitchPortHold, claim *networkingv1alph }) } -// readHold reads the claim's hold from the API server, returning nil when the -// port has none. A cache could answer with a hold that another writer has -// since changed, and every decision here rests on the current one. +// reader must not be a cache: a stale hold can say a claim was never recorded, +// and NSO would detach a port the realizer may still be carrying. func readHold( ctx context.Context, reader client.Reader, @@ -86,9 +81,6 @@ func readHold( return hold, nil } -// recordOnHold records the claim on its port's hold, creating the hold for a -// free port. It reports false when the port is held by claims this one cannot -// share it with, and leaves the hold as it was. func recordOnHold( ctx context.Context, cl client.Client, @@ -130,6 +122,10 @@ func recordOnHold( } } + if alreadyRecorded(hold, claim) { + return true, nil + } + before := hold.Spec.DeepCopy() if err := pruneHold(ctx, reader, hold, claim); err != nil { return false, err @@ -154,9 +150,16 @@ func recordOnHold( return false, lastErr } -// admitToHold records the claim if the port can carry it, reporting whether -// the hold now records it. A port carries one boot claim, and network claims -// from one project with each network at most once. +func alreadyRecorded(hold *networkingv1alpha.SwitchPortHold, claim *networkingv1alpha.NetworkInterfaceClaim) bool { + entry := holdEntryFor(claim) + sameName := func(held networkingv1alpha.SwitchPortHoldClaimRef) bool { return sameClaim(held, claim) } + if isBootClaim(claim) { + return hold.Spec.Boot != nil && *hold.Spec.Boot == entry && !slices.ContainsFunc(hold.Spec.NetworkClaims, sameName) + } + return hold.Spec.ConsumerRef != nil && slices.Contains(hold.Spec.NetworkClaims, entry) && + (hold.Spec.Boot == nil || !sameName(*hold.Spec.Boot)) +} + func admitToHold( hold *networkingv1alpha.SwitchPortHold, claim *networkingv1alpha.NetworkInterfaceClaim, @@ -209,8 +212,6 @@ func removeNetworkClaim(hold *networkingv1alpha.SwitchPortHold, claim *networkin }) } -// clearEmptyConsumer drops the project from a hold its last network claim has -// left, so a hold kept only by a boot claim names no project. func clearEmptyConsumer(hold *networkingv1alpha.SwitchPortHold) { if len(hold.Spec.NetworkClaims) == 0 { hold.Spec.NetworkClaims = nil @@ -218,10 +219,9 @@ func clearEmptyConsumer(hold *networkingv1alpha.SwitchPortHold) { } } -// pruneHold drops every entry whose claim is gone, read from the API server, so -// no entry outlives its claim. A claim of the same name that names another -// network, another port, or the other kind of claim is a different claim. The -// claim being written is never pruned here. +// A claim of an entry's name that names another network, another port, or the +// other kind of claim is a different claim, and the entry is as stale as one +// whose claim is gone. func pruneHold( ctx context.Context, reader client.Reader, @@ -268,9 +268,8 @@ func pruneHold( return nil } -// leaveHold removes the claim's entries from its port's hold, and deletes the -// hold once it records nothing. The delete is conditional on the hold being -// unchanged since it was read, so a claim recorded in between keeps it. +// The delete is conditional on the hold being unchanged since it was read, so a +// claim recorded in between keeps it. func leaveHold( ctx context.Context, cl client.Client,