From 2e059680bf5647310159175e72cfc4b199542763 Mon Sep 17 00:00:00 2001 From: Timofei Larkin Date: Fri, 27 Nov 2026 07:02:53 +0100 Subject: [PATCH 1/2] feat(api)!: report loadBalancerClass in IPAddressClass status, not spec MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The loadBalancerClass a Service consuming a claim must carry belongs to the provisioner's deployment: the driver is configured with the --lb-class of the implementation it fronts. Restating it on every class let a class name a value no driver serves, and its claims then stayed pending with nothing reporting why. This follows decision 0003 of the ip-address-claims design proposal (cozystack/community#35). - API: IPAddressClass.spec.loadBalancerClass and its immutability rule are removed. The class gains a status subresource, written by the provisioner and never by the core: status.loadBalancerClass, and an Accepted condition. The value is valid only while Accepted is True for the class's current generation, since an empty value otherwise cannot be told from an unreported one. AcceptedLoadBalancerClass() applies that rule for consumers. - Auto-claim claims nothing from a class its provisioner has not accepted, and matches the Service's loadBalancerClass against the reported value. A Service that names an unaccepted class gets a ClassNotAccepted warning event. - Docs: design.md §2, §7 (a seventh driver obligation, reporting the class) and §10, the README, and the operating guide's schema table. - The envtest CRD suite now checks that a write to the class does not reset the provisioner's status. The CRD no longer defines spec.loadBalancerClass, so the apiserver drops it from classes that set it. Assisted-By: LLM Signed-off-by: Timofei Larkin --- README.md | 16 ++- api/v1alpha1/ipaddressclass_types.go | 53 ++++++-- api/v1alpha1/well_known.go | 8 ++ api/v1alpha1/zz_generated.deepcopy.go | 28 +++- ...cal.sdn.cozystack.io_ipaddressclasses.yaml | 102 +++++++++++--- docs/design.md | 51 ++++--- docs/operating.md | 1 + .../ipaddressclaim_controller_test.go | 2 +- internal/controller/service_controller.go | 42 ++++-- .../controller/service_controller_test.go | 71 ++++++++-- test/crd/validation_test.go | 124 ++++++------------ 11 files changed, 332 insertions(+), 166 deletions(-) diff --git a/README.md b/README.md index f83741f..4a58f91 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ All kinds live in the `local.sdn.cozystack.io/v1alpha1` API group. | storage | addresses | scope | role | |---|---|---|---| -| `StorageClass` | `IPAddressClass` | cluster | which pool, which driver (`spec.provisioner`), which reclaim policy, which load-balancer implementation (`spec.loadBalancerClass`) | +| `StorageClass` | `IPAddressClass` | cluster | which pool, which driver (`spec.provisioner`), which reclaim policy; the driver reports its load-balancer implementation in `status.loadBalancerClass` | | `PersistentVolume` | `IPAddress` | cluster | the address itself, with a `claimRef`, a reclaim policy, and a `fromClass`/`providerRef` source union | | `PersistentVolumeClaim` | `IPAddressClaim` | namespaced | "give me one" — the whole tenant-facing API | @@ -76,9 +76,10 @@ core controller as follows: reconciles live Service assignments against the ledger and sets the `Conflict` phase when an address is held by a Service its binding does not authorize, and `Lost` when the backing allocation disappears. - A Service consuming a claim carries its class's `spec.loadBalancerClass` - (none when the class leaves it unset), so it reaches the load-balancer - implementation that owns the class's pool. The field is immutable. + A Service consuming a claim carries the `loadBalancerClass` the driver + reports in its class's `status.loadBalancerClass` (none when empty), so + it reaches the load-balancer implementation the driver fronts. The value + is valid once the class's `Accepted` condition is `True`. ## Auto-claim for LoadBalancer Services @@ -102,9 +103,10 @@ nothing: `local.sdn.cozystack.io/auto-claim: "false"`, set `spec.loadBalancerIP`, carry a MetalLB pool, pin or sharing annotation, or already have an address, and Services whose `spec.loadBalancerClass` differs from the - class's (both unset counts as a match). A Service that names its class - with the annotation gets a warning event for a mismatch or a missing - class. + class's `status.loadBalancerClass` (unset matches empty). Nothing is + claimed from a class its driver has not accepted yet. A Service that names + its class with the annotation gets a warning event for a mismatch, an + unaccepted class or a missing class. Apart from auto-claim, the core controller never touches Services. It never parses class parameters and never puts a packet on a wire. diff --git a/api/v1alpha1/ipaddressclass_types.go b/api/v1alpha1/ipaddressclass_types.go index 5ffe6cb..c853cf6 100644 --- a/api/v1alpha1/ipaddressclass_types.go +++ b/api/v1alpha1/ipaddressclass_types.go @@ -17,6 +17,7 @@ limitations under the License. package v1alpha1 import ( + "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" ) @@ -38,7 +39,6 @@ const ( ) // IPAddressClassSpec defines the desired state of IPAddressClass. -// +kubebuilder:validation:XValidation:rule="has(self.loadBalancerClass) == has(oldSelf.loadBalancerClass) && (!has(self.loadBalancerClass) || self.loadBalancerClass == oldSelf.loadBalancerClass)",message="loadBalancerClass is immutable",fieldPath=".loadBalancerClass" type IPAddressClassSpec struct { // provisioner names the per-class driver that fulfils claims of this // class, exactly as StorageClass.provisioner names a CSI driver. The @@ -62,18 +62,6 @@ type IPAddressClassSpec struct { // +optional ReleaseDelay *metav1.Duration `json:"releaseDelay,omitempty"` - // loadBalancerClass is the spec.loadBalancerClass a Service consuming a - // claim of this class must carry, so that the Service reaches the - // load-balancer implementation that owns this class's pool. Unset means - // the cluster's default implementation: such a Service carries no - // loadBalancerClass. The core controller never sets it on a Service. - // Immutable, including setting or unsetting it after creation: a - // Service's own loadBalancerClass cannot change once set, so a new value - // would strand every Service already rendered for the class. - // +optional - // +kubebuilder:validation:MinLength=1 - LoadBalancerClass *string `json:"loadBalancerClass,omitempty"` - // parameters is an opaque, driver-specific configuration blob (for // example the address ranges to carve from). The core controller never // interprets it. @@ -82,10 +70,33 @@ type IPAddressClassSpec struct { Parameters *runtime.RawExtension `json:"parameters,omitempty"` } +// IPAddressClassStatus is written by the provisioner that serves the class. +// The core controller never writes it. +type IPAddressClassStatus struct { + // loadBalancerClass is the spec.loadBalancerClass a Service consuming a + // claim of this class must carry, so that the Service reaches the + // load-balancer implementation the provisioner fronts. Empty means the + // cluster's default implementation, and such a Service carries none. It + // is meaningful only while the Accepted condition is True for the + // class's current generation: before that, an empty value is not yet + // reported rather than the default. + // +optional + LoadBalancerClass string `json:"loadBalancerClass,omitempty"` + + // conditions holds the provisioner's Accepted condition. + // +optional + // +listType=map + // +listMapKey=type + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + // +kubebuilder:object:root=true // +kubebuilder:resource:scope=Cluster +// +kubebuilder:subresource:status // +kubebuilder:printcolumn:name="Provisioner",type=string,JSONPath=`.spec.provisioner` // +kubebuilder:printcolumn:name="ReclaimPolicy",type=string,JSONPath=`.spec.reclaimPolicy` +// +kubebuilder:printcolumn:name="LoadBalancerClass",type=string,JSONPath=`.status.loadBalancerClass` +// +kubebuilder:printcolumn:name="Accepted",type=string,JSONPath=`.status.conditions[?(@.type=="Accepted")].status` // +kubebuilder:printcolumn:name="Age",type=date,JSONPath=`.metadata.creationTimestamp` // IPAddressClass describes an address source: which pool, which driver. @@ -96,7 +107,8 @@ type IPAddressClass struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` - Spec IPAddressClassSpec `json:"spec,omitempty"` + Spec IPAddressClassSpec `json:"spec,omitempty"` + Status IPAddressClassStatus `json:"status,omitempty"` } // +kubebuilder:object:root=true @@ -111,3 +123,16 @@ type IPAddressClassList struct { func init() { SchemeBuilder.Register(&IPAddressClass{}, &IPAddressClassList{}) } + +// AcceptedLoadBalancerClass returns the loadBalancerClass the class's +// provisioner reports, and whether it has reported one: the Accepted +// condition is True for the class's current generation. A consumer that +// creates a Service for a claim of the class waits until ok is true, since +// a Service's loadBalancerClass cannot change after creation. +func (c *IPAddressClass) AcceptedLoadBalancerClass() (lbClass string, ok bool) { + cond := meta.FindStatusCondition(c.Status.Conditions, ConditionAccepted) + if cond == nil || cond.Status != metav1.ConditionTrue || cond.ObservedGeneration != c.Generation { + return "", false + } + return c.Status.LoadBalancerClass, true +} diff --git a/api/v1alpha1/well_known.go b/api/v1alpha1/well_known.go index 55d1e2d..c7908b2 100644 --- a/api/v1alpha1/well_known.go +++ b/api/v1alpha1/well_known.go @@ -89,8 +89,13 @@ const ( ConditionClassResolved = "ClassResolved" // ConditionBound reports whether every requested family is bound. ConditionBound = "Bound" + // ConditionAccepted, on an IPAddressClass, is set by the provisioner + // that serves the class. True means the provisioner serves it and + // status.loadBalancerClass holds the value its consumers must carry. + ConditionAccepted = "Accepted" ReasonResolved = "Resolved" + ReasonAccepted = "Accepted" ReasonClassNotFound = "ClassNotFound" ReasonNoDefaultClass = "NoDefaultClass" ReasonMultipleDefaultClasses = "MultipleDefaultClasses" @@ -115,4 +120,7 @@ const ( // ReasonLoadBalancerClassMismatch is recorded when a Service names a // class whose loadBalancerClass differs from its own. ReasonLoadBalancerClassMismatch = "LoadBalancerClassMismatch" + // ReasonClassNotAccepted is recorded when a Service names a class its + // provisioner has not accepted yet. + ReasonClassNotAccepted = "ClassNotAccepted" ) diff --git a/api/v1alpha1/zz_generated.deepcopy.go b/api/v1alpha1/zz_generated.deepcopy.go index c02cfa1..164447a 100644 --- a/api/v1alpha1/zz_generated.deepcopy.go +++ b/api/v1alpha1/zz_generated.deepcopy.go @@ -219,6 +219,7 @@ func (in *IPAddressClass) DeepCopyInto(out *IPAddressClass) { out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IPAddressClass. @@ -279,11 +280,6 @@ func (in *IPAddressClassSpec) DeepCopyInto(out *IPAddressClassSpec) { *out = new(v1.Duration) **out = **in } - if in.LoadBalancerClass != nil { - in, out := &in.LoadBalancerClass, &out.LoadBalancerClass - *out = new(string) - **out = **in - } if in.Parameters != nil { in, out := &in.Parameters, &out.Parameters *out = new(runtime.RawExtension) @@ -301,6 +297,28 @@ func (in *IPAddressClassSpec) DeepCopy() *IPAddressClassSpec { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *IPAddressClassStatus) DeepCopyInto(out *IPAddressClassStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IPAddressClassStatus. +func (in *IPAddressClassStatus) DeepCopy() *IPAddressClassStatus { + if in == nil { + return nil + } + out := new(IPAddressClassStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *IPAddressList) DeepCopyInto(out *IPAddressList) { *out = *in diff --git a/chart/address-controller/crds/local.sdn.cozystack.io_ipaddressclasses.yaml b/chart/address-controller/crds/local.sdn.cozystack.io_ipaddressclasses.yaml index 223b176..35d5e1d 100644 --- a/chart/address-controller/crds/local.sdn.cozystack.io_ipaddressclasses.yaml +++ b/chart/address-controller/crds/local.sdn.cozystack.io_ipaddressclasses.yaml @@ -21,6 +21,12 @@ spec: - jsonPath: .spec.reclaimPolicy name: ReclaimPolicy type: string + - jsonPath: .status.loadBalancerClass + name: LoadBalancerClass + type: string + - jsonPath: .status.conditions[?(@.type=="Accepted")].status + name: Accepted + type: string - jsonPath: .metadata.creationTimestamp name: Age type: date @@ -53,18 +59,6 @@ spec: spec: description: IPAddressClassSpec defines the desired state of IPAddressClass. properties: - loadBalancerClass: - description: |- - loadBalancerClass is the spec.loadBalancerClass a Service consuming a - claim of this class must carry, so that the Service reaches the - load-balancer implementation that owns this class's pool. Unset means - the cluster's default implementation: such a Service carries no - loadBalancerClass. The core controller never sets it on a Service. - Immutable, including setting or unsetting it after creation: a - Service's own loadBalancerClass cannot change once set, so a new value - would strand every Service already rendered for the class. - minLength: 1 - type: string parameters: description: |- parameters is an opaque, driver-specific configuration blob (for @@ -103,12 +97,84 @@ spec: required: - provisioner type: object - x-kubernetes-validations: - - fieldPath: .loadBalancerClass - message: loadBalancerClass is immutable - rule: has(self.loadBalancerClass) == has(oldSelf.loadBalancerClass) - && (!has(self.loadBalancerClass) || self.loadBalancerClass == oldSelf.loadBalancerClass) + status: + description: |- + IPAddressClassStatus is written by the provisioner that serves the class. + The core controller never writes it. + properties: + conditions: + description: conditions holds the provisioner's Accepted condition. + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + loadBalancerClass: + description: |- + loadBalancerClass is the spec.loadBalancerClass a Service consuming a + claim of this class must carry, so that the Service reaches the + load-balancer implementation the provisioner fronts. Empty means the + cluster's default implementation, and such a Service carries none. It + is meaningful only while the Accepted condition is True for the + class's current generation: before that, an empty value is not yet + reported rather than the default. + type: string + type: object type: object served: true storage: true - subresources: {} + subresources: + status: {} diff --git a/docs/design.md b/docs/design.md index 8cf5136..075260b 100644 --- a/docs/design.md +++ b/docs/design.md @@ -47,13 +47,6 @@ StorageClass names a CSI driver. provisioned `IPAddress`, where it takes effect. What each policy actually reclaims — the API object, the ledger entry, backend state — is spelled out in §6. -- `spec.loadBalancerClass` (immutable, including setting or unsetting it) - — the `spec.loadBalancerClass` a Service consuming a claim of this class - must carry, so the Service reaches the load-balancer implementation that - owns the class's pool. Unset means the cluster's default implementation, - and the Service carries none. Immutable because a Service's own - `loadBalancerClass` cannot change once set: a new value would strand - every Service already rendered for the class. - `spec.parameters` — an opaque object (unknown fields preserved), never read by the core. Shape is defined by the driver. - The annotation `ipaddressclass.local.sdn.cozystack.io/is-default-class: @@ -61,6 +54,21 @@ StorageClass names a CSI driver. - The annotation `ipaddressclass.local.sdn.cozystack.io/is-auto-claim-class: "true"` marks the class auto-claims draw from (§10). Independent of the default class; at most one class may carry it. +- `status` is written by the provisioner that serves the class, never by + the core: + - `status.loadBalancerClass` — the `spec.loadBalancerClass` a Service + consuming a claim of this class must carry, so the Service reaches the + load-balancer implementation the provisioner fronts. Empty means the + cluster's default implementation, and the Service carries none. The + value belongs to the provisioner's deployment, not to the class, so + the admin does not restate it per class. + - The `Accepted` condition — `True` once the provisioner serves the + class, with `observedGeneration` set. `status.loadBalancerClass` is + meaningful only while it is `True` for the class's current generation; + before that, an empty value is unreported rather than the default. A + consumer that creates a Service for a claim of the class waits for it, + because a Service's `loadBalancerClass` cannot change after creation. + `IPAddressClass.AcceptedLoadBalancerClass()` applies this rule. ### IPAddress @@ -418,15 +426,20 @@ integration. Its obligations: Service's *own* namespace — cross-namespace sharing is not a thing), translate it into the backend's pin mechanism, maintain `status.associatedTo`, and enforce that one claim serves one workload - at a time. A Service whose `spec.loadBalancerClass` differs from its - claim's class's `spec.loadBalancerClass` reaches another implementation - and is not associated. Disassociation must leave the address `Bound` — - reserved, inert. + at a time. A Service whose `spec.loadBalancerClass` differs from the + value the driver reports in its class's `status.loadBalancerClass` + reaches another implementation and is not associated. Disassociation + must leave the address `Bound` — reserved, inert. 6. **Detect, and clear, conflicts.** If the backend hands the reserved address to a workload the binding does not authorize, set phase `Conflict` (and `Lost` if the backing reservation disappears). The core will never override these; the driver clears them by setting the phase back to a core-owned value once the condition has passed. +7. **Report the class.** On every class it serves, write + `status.loadBalancerClass` (the `loadBalancerClass` of the + implementation it fronts, empty for the cluster default) and set the + `Accepted` condition with the class's `observedGeneration` (§2). + Consumers of the class's claims wait for it before creating a Service. Static pre-provisioning needs no driver at all: an admin may create `Available` addresses by hand and the core matches them (§4 step 7). @@ -501,13 +514,15 @@ alone; with several, a warning event is recorded on it and nothing is claimed. A named class that does not exist is reported the same way, and the Service is claimed once the class is created. -The Service's `spec.loadBalancerClass` must equal the class's, both unset -counting as equal; otherwise the Service reaches another load-balancer -implementation than the one owning the class's pool, and nothing is -claimed. The core cannot fix the Service, whose `loadBalancerClass` is -immutable once set. A mismatch with the marked class is silent, since that -class simply does not serve the Service; a mismatch with a class the -Service named is a warning event. +The class must be accepted by its provisioner (§2); until then nothing is +claimed, and the class's status update requeues the Service. The Service's +`spec.loadBalancerClass` must then equal the class's +`status.loadBalancerClass`, unset matching empty; otherwise the Service +reaches another load-balancer implementation than the one the provisioner +fronts, and nothing is claimed. The core cannot fix the Service, whose +`loadBalancerClass` is immutable once set. For the marked class both cases +are silent, since that class does not serve the Service; for a class the +Service named, an unaccepted class and a mismatch are warning events. The core then creates an `IPAddressClaim` named after the Service, in the Service's namespace, with that `className`, the family derived from the diff --git a/docs/operating.md b/docs/operating.md index 1f95acd..ef545fb 100644 --- a/docs/operating.md +++ b/docs/operating.md @@ -122,3 +122,4 @@ still set it, so every release states its schema changes: |---|---| | v0.1.0 | initial `IPAddress`, `IPAddressClaim`, `IPAddressClass` | | v0.2.0 | `IPAddressClass.spec.releaseDelay` added; `IPAddress` gains a core-set `Bound` condition; immutable `IPAddressClass.spec.loadBalancerClass` added | +| unreleased | `IPAddressClass.spec.loadBalancerClass` removed, and dropped from stored classes; `IPAddressClass` gains a status subresource with the driver-written `status.loadBalancerClass` and `Accepted` condition | diff --git a/internal/controller/ipaddressclaim_controller_test.go b/internal/controller/ipaddressclaim_controller_test.go index 92771c2..d06e193 100644 --- a/internal/controller/ipaddressclaim_controller_test.go +++ b/internal/controller/ipaddressclaim_controller_test.go @@ -59,7 +59,7 @@ func testClient(t *testing.T, objs ...client.Object) client.Client { t.Helper() return fake.NewClientBuilder(). WithScheme(testScheme(t)). - WithStatusSubresource(&localv1alpha1.IPAddress{}, &localv1alpha1.IPAddressClaim{}). + WithStatusSubresource(&localv1alpha1.IPAddress{}, &localv1alpha1.IPAddressClaim{}, &localv1alpha1.IPAddressClass{}). WithIndex(&localv1alpha1.IPAddress{}, IPAddressClaimRefIndex, claimRefIndex). WithIndex(&localv1alpha1.IPAddress{}, IPAddressClassNameIndex, classNameIndex). WithObjects(objs...). diff --git a/internal/controller/service_controller.go b/internal/controller/service_controller.go index 8543393..bdf5512 100644 --- a/internal/controller/service_controller.go +++ b/internal/controller/service_controller.go @@ -71,15 +71,26 @@ func (r *ServiceReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct if err != nil || class == nil { return ctrl.Result{}, err } - if !sameLoadBalancerClass(svc.Spec.LoadBalancerClass, class.Spec.LoadBalancerClass) { + named := svc.Annotations[localv1alpha1.ServiceClassAnnotation] != "" + lbClass, accepted := class.AcceptedLoadBalancerClass() + if !accepted { + // Until the provisioner reports its loadBalancerClass, a match + // cannot be checked. The class's status update requeues the Service. + if named { + r.Recorder.Eventf(svc, "Warning", localv1alpha1.ReasonClassNotAccepted, + "IPAddressClass %q has not been accepted by its provisioner %q", class.Name, class.Spec.Provisioner) + } + return ctrl.Result{}, nil + } + if !sameLoadBalancerClass(svc.Spec.LoadBalancerClass, lbClass) { // The Service reaches another load-balancer implementation than - // the one owning the class's pool. Left alone when the class is the - // marked one; reported when the Service named it. - if svc.Annotations[localv1alpha1.ServiceClassAnnotation] != "" { + // the one the class's provisioner fronts. Left alone when the class + // is the marked one; reported when the Service named it. + if named { r.Recorder.Eventf(svc, "Warning", localv1alpha1.ReasonLoadBalancerClassMismatch, "Service loadBalancerClass %s does not match IPAddressClass %q loadBalancerClass %s", describeLoadBalancerClass(svc.Spec.LoadBalancerClass), class.Name, - describeLoadBalancerClass(class.Spec.LoadBalancerClass)) + describeLoadBalancerClass(classLoadBalancerClass(lbClass))) } return ctrl.Result{}, nil } @@ -181,13 +192,22 @@ func (r *ServiceReconciler) serviceClass(ctx context.Context, svc *corev1.Servic return class, nil } -// sameLoadBalancerClass reports whether two loadBalancerClass values are -// equal, both unset counting as equal. -func sameLoadBalancerClass(a, b *string) bool { - if a == nil || b == nil { - return a == b +// sameLoadBalancerClass reports whether a Service's loadBalancerClass equals +// a class's reported one, an unset Service field matching an empty value. +func sameLoadBalancerClass(svc *string, class string) bool { + if svc == nil { + return class == "" + } + return *svc == class +} + +// classLoadBalancerClass turns a class's reported value into the Service +// field it stands for: empty is unset. +func classLoadBalancerClass(v string) *string { + if v == "" { + return nil } - return *a == *b + return &v } func describeLoadBalancerClass(v *string) string { diff --git a/internal/controller/service_controller_test.go b/internal/controller/service_controller_test.go index a61014b..536fbd7 100644 --- a/internal/controller/service_controller_test.go +++ b/internal/controller/service_controller_test.go @@ -34,6 +34,7 @@ import ( ) const ( + testLBClass = "example.com/lb" testServiceName = "web-lb" testServiceUID = "svc-uid-1" serviceKind = "Service" @@ -81,11 +82,24 @@ func getAutoClaim(t *testing.T, c client.Client) *localv1alpha1.IPAddressClaim { } func autoClaimClass(name string) *localv1alpha1.IPAddressClass { - class := publicClass(map[string]string{localv1alpha1.IsAutoClaimClassAnnotation: localv1alpha1.AnnotationTrue}) + class := accepted(publicClass(map[string]string{localv1alpha1.IsAutoClaimClassAnnotation: localv1alpha1.AnnotationTrue}), "") class.Name = name return class } +// accepted marks a class as accepted by its provisioner for its current +// generation, reporting lbClass. +func accepted(class *localv1alpha1.IPAddressClass, lbClass string) *localv1alpha1.IPAddressClass { + class.Status.LoadBalancerClass = lbClass + class.Status.Conditions = []metav1.Condition{{ + Type: localv1alpha1.ConditionAccepted, + Status: metav1.ConditionTrue, + Reason: localv1alpha1.ReasonAccepted, + ObservedGeneration: class.Generation, + }} + return class +} + func loadBalancerService() *corev1.Service { return &corev1.Service{ ObjectMeta: metav1.ObjectMeta{Name: testServiceName, Namespace: testNamespace, UID: testServiceUID}, @@ -180,7 +194,7 @@ func TestAutoClaimWithMultipleMarkedClassesClaimsNothing(t *testing.T) { func TestAutoClaimUsesClassNamedByService(t *testing.T) { svc := loadBalancerService() svc.Annotations = map[string]string{localv1alpha1.ServiceClassAnnotation: otherClassName} - named := publicClass(nil) + named := accepted(publicClass(nil), "") named.Name = otherClassName c := testClient(t, autoClaimClass(testClassName), named, svc) reconcileService(t, serviceReconciler(c)) @@ -209,16 +223,53 @@ func TestAutoClaimWaitsForClassNamedByService(t *testing.T) { } } +func TestAutoClaimWaitsForAcceptedClass(t *testing.T) { + cases := map[string]func(*localv1alpha1.IPAddressClass){ + "no status": func(c *localv1alpha1.IPAddressClass) { c.Status = localv1alpha1.IPAddressClassStatus{} }, + "not accepted": func(c *localv1alpha1.IPAddressClass) { + c.Status.Conditions[0].Status = metav1.ConditionFalse + }, + "accepted for an older generation": func(c *localv1alpha1.IPAddressClass) { + c.Generation = 2 + c.Status.Conditions[0].ObservedGeneration = 1 + }, + } + for name, mutate := range cases { + for _, named := range []bool{false, true} { + t.Run(fmt.Sprintf("%s, class named by Service %t", name, named), func(t *testing.T) { + svc := loadBalancerService() + class := autoClaimClass(testClassName) + if named { + class.Annotations = nil + svc.Annotations = map[string]string{localv1alpha1.ServiceClassAnnotation: testClassName} + } + mutate(class) + c := testClient(t, class, svc) + r := serviceReconciler(c) + reconcileService(t, r) + + if claim := getAutoClaim(t, c); claim != nil { + t.Error("claim auto-provisioned from a class its provisioner has not accepted") + } + if got := recorded(r, "Warning "+localv1alpha1.ReasonClassNotAccepted); got != named { + t.Errorf("%s event recorded = %t, want %t", localv1alpha1.ReasonClassNotAccepted, got, named) + } + }) + } + } +} + func TestAutoClaimMatchesLoadBalancerClass(t *testing.T) { cases := map[string]struct { - service, class *string - claimed bool + service *string + class string + claimed bool }{ - "both unset": {nil, nil, true}, - "equal": {new("example.com/lb"), new("example.com/lb"), true}, - "class sets one, Service none": {nil, new("example.com/lb"), false}, - "Service sets one, class none": {new("example.com/lb"), nil, false}, - "different": {new("example.com/other"), new("example.com/lb"), false}, + "both unset": {nil, "", true}, + "equal": {new(testLBClass), testLBClass, true}, + "class reports one, Service none": {nil, testLBClass, false}, + "Service sets one, class none": {new(testLBClass), "", false}, + "different": {new("example.com/other"), testLBClass, false}, } for name, tc := range cases { for _, named := range []bool{false, true} { @@ -230,7 +281,7 @@ func TestAutoClaimMatchesLoadBalancerClass(t *testing.T) { class.Annotations = nil svc.Annotations = map[string]string{localv1alpha1.ServiceClassAnnotation: testClassName} } - class.Spec.LoadBalancerClass = tc.class + accepted(class, tc.class) c := testClient(t, class, svc) r := serviceReconciler(c) reconcileService(t, r) diff --git a/test/crd/validation_test.go b/test/crd/validation_test.go index be88c2a..44f1258 100644 --- a/test/crd/validation_test.go +++ b/test/crd/validation_test.go @@ -14,17 +14,14 @@ See the License for the specific language governing permissions and limitations under the License. */ -// Package crd runs the chart's CRD validation rules against a real -// kube-apiserver (envtest). +// Package crd runs the chart's CRDs against a real kube-apiserver (envtest). package crd import ( "context" - "encoding/json" "os" "testing" - apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" @@ -34,13 +31,11 @@ import ( localv1alpha1 "github.com/cozystack/address-controller/api/v1alpha1" ) -// The two classes the update cases patch. -const ( - withoutLBClass = "unset" - withLBClass = "set" -) - -func TestIPAddressClassLoadBalancerClass(t *testing.T) { +// TestIPAddressClassStatusSubresource checks that the provisioner's status +// survives writes to the class itself: the core controller updates a class to +// manage its finalizer, and such an update must not reset what the +// provisioner reported. +func TestIPAddressClassStatusSubresource(t *testing.T) { if os.Getenv("KUBEBUILDER_ASSETS") == "" { t.Skip("KUBEBUILDER_ASSETS is not set; run through `make test`") } @@ -61,84 +56,49 @@ func TestIPAddressClassLoadBalancerClass(t *testing.T) { } ctx := context.Background() - for name, value := range map[string]*string{withoutLBClass: nil, withLBClass: new("example.com/lb")} { - if err := c.Create(ctx, class(name, value)); err != nil { - t.Fatalf("creating class %s: %v", name, err) - } - } - - creates := []struct { - name string - lbClass *string - admit bool - }{ - {"create without loadBalancerClass", nil, true}, - {"create with loadBalancerClass", new("example.com/lb"), true}, - {"create with empty loadBalancerClass", new(""), false}, + class := &localv1alpha1.IPAddressClass{ + ObjectMeta: metav1.ObjectMeta{Name: "public"}, + Spec: localv1alpha1.IPAddressClassSpec{ + Provisioner: "example.com/driver", + ReclaimPolicy: localv1alpha1.ReclaimRetain, + }, } - for _, tc := range creates { - t.Run(tc.name, func(t *testing.T) { - obj := class("", tc.lbClass) - obj.GenerateName = "probe-" - check(t, c.Create(ctx, obj, client.DryRunAll), tc.admit) - }) + if err := c.Create(ctx, class); err != nil { + t.Fatalf("creating class: %v", err) } - - updates := []struct { - name string - class string - spec map[string]any - admit bool - }{ - {"set on a class created without it", withoutLBClass, lbClassPatch("example.com/lb"), false}, - {"other field changed, still unset", withoutLBClass, reclaimDelete, true}, - {"changed to another value", withLBClass, lbClassPatch("example.com/other"), false}, - {"removed", withLBClass, lbClassPatch(nil), false}, - {"rewritten to the same value", withLBClass, lbClassPatch("example.com/lb"), true}, - {"other field changed, value kept", withLBClass, reclaimDelete, true}, + class.Status = localv1alpha1.IPAddressClassStatus{ + LoadBalancerClass: "example.com/lb", + Conditions: []metav1.Condition{{ + Type: localv1alpha1.ConditionAccepted, + Status: metav1.ConditionTrue, + Reason: localv1alpha1.ReasonAccepted, + ObservedGeneration: class.Generation, + LastTransitionTime: metav1.Now(), + }}, } - for _, tc := range updates { - t.Run(tc.name, func(t *testing.T) { - raw, err := json.Marshal(map[string]any{"spec": tc.spec}) - if err != nil { - t.Fatal(err) - } - obj := &localv1alpha1.IPAddressClass{} - if err := c.Get(ctx, types.NamespacedName{Name: tc.class}, obj); err != nil { - t.Fatal(err) - } - check(t, c.Patch(ctx, obj, client.RawPatch(types.MergePatchType, raw), client.DryRunAll), tc.admit) - }) + if err := c.Status().Update(ctx, class); err != nil { + t.Fatalf("writing status: %v", err) } -} - -var reclaimDelete = map[string]any{"reclaimPolicy": "Delete"} -// lbClassPatch is a merge patch of spec setting loadBalancerClass, or removing -// it when value is nil. -func lbClassPatch(value any) map[string]any { - return map[string]any{"loadBalancerClass": value} -} + class.Finalizers = []string{"example.com/finalizer"} + class.Status = localv1alpha1.IPAddressClassStatus{} + if err := c.Update(ctx, class); err != nil { + t.Fatalf("updating class: %v", err) + } -func check(t *testing.T, err error, admit bool) { - t.Helper() - switch { - case admit && err != nil: - t.Errorf("refused, want admitted: %v", err) - case !admit && err == nil: - t.Error("admitted, want refused") - case !admit && !apierrors.IsInvalid(err): - t.Errorf("refused for another reason than validation: %v", err) + got := &localv1alpha1.IPAddressClass{} + if err := c.Get(ctx, types.NamespacedName{Name: class.Name}, got); err != nil { + t.Fatal(err) + } + lbClass, ok := got.AcceptedLoadBalancerClass() + if !ok || lbClass != "example.com/lb" { + t.Errorf("after an update of the class, AcceptedLoadBalancerClass() = %q, %t; want %q, true", + lbClass, ok, "example.com/lb") } -} -func class(name string, loadBalancerClass *string) *localv1alpha1.IPAddressClass { - return &localv1alpha1.IPAddressClass{ - ObjectMeta: metav1.ObjectMeta{Name: name}, - Spec: localv1alpha1.IPAddressClassSpec{ - Provisioner: "example.com/driver", - ReclaimPolicy: localv1alpha1.ReclaimRetain, - LoadBalancerClass: loadBalancerClass, - }, + // Clear the finalizer so the environment can stop cleanly. + got.Finalizers = nil + if err := c.Update(ctx, got); err != nil { + t.Fatal(err) } } From 6c5b1e07d6c3b6f592d4059724dd1a1f8c0b160d Mon Sep 17 00:00:00 2001 From: Timofei Larkin Date: Fri, 27 Nov 2026 07:03:10 +0100 Subject: [PATCH 2/2] chore(release): set the chart version for v0.3.0 Cozystack vendors chart/address-controller/ from the tagged commit, so Chart.yaml's version and appVersion, and the Makefile's CHART_VERSION, must match the v0.3.0 tag. The operating guide's schema table moves its unreleased row to v0.3.0. Assisted-By: LLM Signed-off-by: Timofei Larkin --- Makefile | 2 +- chart/address-controller/Chart.yaml | 4 ++-- docs/operating.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index 535c3f3..4a4728b 100644 --- a/Makefile +++ b/Makefile @@ -10,7 +10,7 @@ PLATFORMS ?= linux/amd64,linux/arm64 CHART := chart/address-controller # Override to package a different version than the one in Chart.yaml. -CHART_VERSION ?= 0.2.0 +CHART_VERSION ?= 0.3.0 # Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set) ifeq (,$(shell go env GOBIN)) diff --git a/chart/address-controller/Chart.yaml b/chart/address-controller/Chart.yaml index 820993b..64f07d1 100644 --- a/chart/address-controller/Chart.yaml +++ b/chart/address-controller/Chart.yaml @@ -2,8 +2,8 @@ apiVersion: v2 name: address-controller description: Core controllers for IP addresses as a first-class resource — IPAddressClass, IPAddress, IPAddressClaim (local.sdn.cozystack.io) type: application -version: 0.2.0 -appVersion: "0.2.0" +version: 0.3.0 +appVersion: "0.3.0" # CEL validation rules on the CRDs (immutability, union exactness) need 1.29+. kubeVersion: ">=1.29.0-0" keywords: diff --git a/docs/operating.md b/docs/operating.md index ef545fb..8afe850 100644 --- a/docs/operating.md +++ b/docs/operating.md @@ -122,4 +122,4 @@ still set it, so every release states its schema changes: |---|---| | v0.1.0 | initial `IPAddress`, `IPAddressClaim`, `IPAddressClass` | | v0.2.0 | `IPAddressClass.spec.releaseDelay` added; `IPAddress` gains a core-set `Bound` condition; immutable `IPAddressClass.spec.loadBalancerClass` added | -| unreleased | `IPAddressClass.spec.loadBalancerClass` removed, and dropped from stored classes; `IPAddressClass` gains a status subresource with the driver-written `status.loadBalancerClass` and `Accepted` condition | +| v0.3.0 | `IPAddressClass.spec.loadBalancerClass` removed, and dropped from stored classes; `IPAddressClass` gains a status subresource with the driver-written `status.loadBalancerClass` and `Accepted` condition |