diff --git a/README.md b/README.md index b3da022..f83741f 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 | +| `StorageClass` | `IPAddressClass` | cluster | which pool, which driver (`spec.provisioner`), which reclaim policy, which load-balancer implementation (`spec.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,6 +76,9 @@ 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. ## Auto-claim for LoadBalancer Services @@ -96,9 +99,12 @@ nothing: owner. To keep the address, remove the claim's owner reference; it is an ordinary claim from then on. - Skipped: Services that already name a claim, set - `local.sdn.cozystack.io/auto-claim: "false"`, set - `spec.loadBalancerClass` or `spec.loadBalancerIP`, carry a MetalLB pool, - pin or sharing annotation, or already have an address. + `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. 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 062c369..5ffe6cb 100644 --- a/api/v1alpha1/ipaddressclass_types.go +++ b/api/v1alpha1/ipaddressclass_types.go @@ -38,6 +38,7 @@ 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 @@ -61,6 +62,18 @@ 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. diff --git a/api/v1alpha1/well_known.go b/api/v1alpha1/well_known.go index 05f5eb2..55d1e2d 100644 --- a/api/v1alpha1/well_known.go +++ b/api/v1alpha1/well_known.go @@ -112,4 +112,7 @@ const ( ReasonAutoClaimed = "AutoClaimed" ReasonAutoClaimNameTaken = "AutoClaimNameTaken" ReasonMultipleAutoClaimClasses = "MultipleAutoClaimClasses" + // ReasonLoadBalancerClassMismatch is recorded when a Service names a + // class whose loadBalancerClass differs from its own. + ReasonLoadBalancerClassMismatch = "LoadBalancerClassMismatch" ) diff --git a/api/v1alpha1/zz_generated.deepcopy.go b/api/v1alpha1/zz_generated.deepcopy.go index 57da440..c02cfa1 100644 --- a/api/v1alpha1/zz_generated.deepcopy.go +++ b/api/v1alpha1/zz_generated.deepcopy.go @@ -279,6 +279,11 @@ 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) 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 792d220..223b176 100644 --- a/chart/address-controller/crds/local.sdn.cozystack.io_ipaddressclasses.yaml +++ b/chart/address-controller/crds/local.sdn.cozystack.io_ipaddressclasses.yaml @@ -53,6 +53,18 @@ 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 @@ -91,6 +103,11 @@ 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) type: object served: true storage: true diff --git a/docs/design.md b/docs/design.md index 16c56b7..8cf5136 100644 --- a/docs/design.md +++ b/docs/design.md @@ -47,6 +47,13 @@ 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: @@ -411,8 +418,10 @@ 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. Disassociation must leave the address `Bound` — reserved, - inert. + 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. 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 @@ -476,8 +485,7 @@ A Service qualifies when it is a live `type: LoadBalancer` Service that: - carries no `local.sdn.cozystack.io/ip-address-claim` annotation, - does not carry `local.sdn.cozystack.io/auto-claim: "false"` (drivers stamp this on Services they create for their own bookkeeping), -- sets neither `spec.loadBalancerClass` (another implementation's) nor - `spec.loadBalancerIP` (asks for a specific address), +- does not set `spec.loadBalancerIP` (asks for a specific address), - carries none of the backend's pool, pin or sharing annotations: for MetalLB, `loadBalancerIPs`, `address-pool` and `allow-shared-ip` under `metallb.io/` or `metallb.universe.tf/`. Such a Service has chosen its @@ -490,7 +498,16 @@ The class is the one named by the Service's `local.sdn.cozystack.io/ip-address-class` annotation, else the single class marked `is-auto-claim-class`. With no marked class the Service is left alone; with several, a warning event is recorded on it and nothing is -claimed. +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 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 80301ed..068b83d 100644 --- a/docs/operating.md +++ b/docs/operating.md @@ -121,4 +121,4 @@ still set it, so every release states its schema changes: | release | schema change | |---|---| | v0.1.0 | initial `IPAddress`, `IPAddressClaim`, `IPAddressClass` | -| unreleased | `IPAddressClass.spec.releaseDelay` added; `IPAddress` gains a core-set `Bound` condition | +| unreleased | `IPAddressClass.spec.releaseDelay` added; `IPAddress` gains a core-set `Bound` condition; immutable `IPAddressClass.spec.loadBalancerClass` added | diff --git a/internal/controller/service_controller.go b/internal/controller/service_controller.go index 6f421eb..8543393 100644 --- a/internal/controller/service_controller.go +++ b/internal/controller/service_controller.go @@ -20,6 +20,7 @@ import ( "context" "slices" "sort" + "strconv" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -66,23 +67,31 @@ func (r *ServiceReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct return ctrl.Result{}, nil } - className := svc.Annotations[localv1alpha1.ServiceClassAnnotation] - if className == "" { - var err error - className, err = r.autoClaimClassName(ctx, svc) - if err != nil || className == "" { - return ctrl.Result{}, err + class, err := r.serviceClass(ctx, svc) + if err != nil || class == nil { + return ctrl.Result{}, err + } + if !sameLoadBalancerClass(svc.Spec.LoadBalancerClass, class.Spec.LoadBalancerClass) { + // 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] != "" { + 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)) } + return ctrl.Result{}, nil } claim := &localv1alpha1.IPAddressClaim{} - err := r.Get(ctx, types.NamespacedName{Namespace: svc.Namespace, Name: svc.Name}, claim) + err = r.Get(ctx, types.NamespacedName{Namespace: svc.Namespace, Name: svc.Name}, claim) switch { case apierrors.IsNotFound(err): claim = &localv1alpha1.IPAddressClaim{ ObjectMeta: metav1.ObjectMeta{Namespace: svc.Namespace, Name: svc.Name}, Spec: localv1alpha1.IPAddressClaimSpec{ - ClassName: className, + ClassName: class.Name, Family: familyForService(svc), }, } @@ -132,9 +141,9 @@ var backendAddressInputs = []string{ } // wantsAutoClaim reports whether a Service qualifies for auto-claim: a live -// LoadBalancer Service that names no claim, has not opted out, is not left -// to another load-balancer implementation, carries no backend pool or pin -// input, and has no address yet. The last rule keeps a Service addressed by +// LoadBalancer Service that names no claim, has not opted out, carries no +// backend pool or pin input, and has no address yet. Whether its +// loadBalancerClass matches the class's is checked once the class is known. The last rule keeps a Service addressed by // other means — before auto-claim existed, or from an auto-assigning pool — // from being moved to a new address. func wantsAutoClaim(svc *corev1.Service) bool { @@ -142,7 +151,6 @@ func wantsAutoClaim(svc *corev1.Service) bool { svc.DeletionTimestamp.IsZero() && svc.Annotations[localv1alpha1.ServiceClaimAnnotation] == "" && svc.Annotations[localv1alpha1.ServiceAutoClaimAnnotation] != "false" && - svc.Spec.LoadBalancerClass == nil && svc.Spec.LoadBalancerIP == "" && !slices.ContainsFunc(backendAddressInputs, func(key string) bool { _, ok := svc.Annotations[key] @@ -151,33 +159,75 @@ func wantsAutoClaim(svc *corev1.Service) bool { len(svc.Status.LoadBalancer.Ingress) == 0 } -// autoClaimClassName finds the single IPAddressClass marked for auto-claim. +// serviceClass returns the class a Service's auto-claim draws from: the one +// its class annotation names, else the single class marked for auto-claim. +// Nil means nothing is claimed for now. A named class that does not exist +// is recorded on the Service; creating it requeues the Service. +func (r *ServiceReconciler) serviceClass(ctx context.Context, svc *corev1.Service) (*localv1alpha1.IPAddressClass, error) { + name := svc.Annotations[localv1alpha1.ServiceClassAnnotation] + if name == "" { + return r.autoClaimClass(ctx, svc) + } + class := &localv1alpha1.IPAddressClass{} + err := r.Get(ctx, types.NamespacedName{Name: name}, class) + if apierrors.IsNotFound(err) { + r.Recorder.Eventf(svc, "Warning", localv1alpha1.ReasonClassNotFound, + "IPAddressClass %q not found", name) + return nil, nil + } + if err != nil { + return nil, err + } + 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 + } + return *a == *b +} + +func describeLoadBalancerClass(v *string) string { + if v == nil { + return "(unset)" + } + return strconv.Quote(*v) +} + +// autoClaimClass finds the single IPAddressClass marked for auto-claim. // None means auto-claim is off and the Service is left alone; more than one // is recorded on the Service and nothing is claimed. -func (r *ServiceReconciler) autoClaimClassName(ctx context.Context, svc *corev1.Service) (string, error) { +func (r *ServiceReconciler) autoClaimClass(ctx context.Context, svc *corev1.Service) (*localv1alpha1.IPAddressClass, error) { classes := &localv1alpha1.IPAddressClassList{} if err := r.List(ctx, classes); err != nil { - return "", err + return nil, err } // A deleted class is held only until its addresses are gone; drawing // new claims into it would keep it from draining. classes.Items = slices.DeleteFunc(classes.Items, classDeleting) - var marked []string + var marked []localv1alpha1.IPAddressClass for _, c := range classes.Items { if c.Annotations[localv1alpha1.IsAutoClaimClassAnnotation] == localv1alpha1.AnnotationTrue { - marked = append(marked, c.Name) + marked = append(marked, c) } } switch len(marked) { case 0: - return "", nil + return nil, nil case 1: - return marked[0], nil + return &marked[0], nil default: - sort.Strings(marked) + names := make([]string, 0, len(marked)) + for _, c := range marked { + names = append(names, c.Name) + } + sort.Strings(names) r.Recorder.Eventf(svc, "Warning", localv1alpha1.ReasonMultipleAutoClaimClasses, - "multiple IPAddressClasses marked for auto-claim: %v", marked) - return "", nil + "multiple IPAddressClasses marked for auto-claim: %v", names) + return nil, nil } } diff --git a/internal/controller/service_controller_test.go b/internal/controller/service_controller_test.go index d2bc2d9..a61014b 100644 --- a/internal/controller/service_controller_test.go +++ b/internal/controller/service_controller_test.go @@ -18,6 +18,8 @@ package controller import ( "context" + "fmt" + "strings" "testing" corev1 "k8s.io/api/core/v1" @@ -178,7 +180,9 @@ func TestAutoClaimWithMultipleMarkedClassesClaimsNothing(t *testing.T) { func TestAutoClaimUsesClassNamedByService(t *testing.T) { svc := loadBalancerService() svc.Annotations = map[string]string{localv1alpha1.ServiceClassAnnotation: otherClassName} - c := testClient(t, autoClaimClass(testClassName), svc) + named := publicClass(nil) + named.Name = otherClassName + c := testClient(t, autoClaimClass(testClassName), named, svc) reconcileService(t, serviceReconciler(c)) claim := getAutoClaim(t, c) @@ -190,6 +194,76 @@ func TestAutoClaimUsesClassNamedByService(t *testing.T) { } } +func TestAutoClaimWaitsForClassNamedByService(t *testing.T) { + svc := loadBalancerService() + svc.Annotations = map[string]string{localv1alpha1.ServiceClassAnnotation: otherClassName} + c := testClient(t, autoClaimClass(testClassName), svc) + r := serviceReconciler(c) + reconcileService(t, r) + + if claim := getAutoClaim(t, c); claim != nil { + t.Error("claim auto-provisioned from a class that does not exist") + } + if !recorded(r, "Warning "+localv1alpha1.ReasonClassNotFound) { + t.Errorf("no %s event recorded", localv1alpha1.ReasonClassNotFound) + } +} + +func TestAutoClaimMatchesLoadBalancerClass(t *testing.T) { + cases := map[string]struct { + service, 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}, + } + for name, tc := 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() + svc.Spec.LoadBalancerClass = tc.service + class := autoClaimClass(testClassName) + if named { + class.Annotations = nil + svc.Annotations = map[string]string{localv1alpha1.ServiceClassAnnotation: testClassName} + } + class.Spec.LoadBalancerClass = tc.class + c := testClient(t, class, svc) + r := serviceReconciler(c) + reconcileService(t, r) + + if claimed := getAutoClaim(t, c) != nil; claimed != tc.claimed { + t.Errorf("claimed = %t, want %t", claimed, tc.claimed) + } + // Only a class the Service named itself warrants a warning; + // the marked class simply does not serve this Service. + wantWarning := named && !tc.claimed + if got := recorded(r, "Warning "+localv1alpha1.ReasonLoadBalancerClassMismatch); got != wantWarning { + t.Errorf("%s event recorded = %t, want %t", localv1alpha1.ReasonLoadBalancerClassMismatch, got, wantWarning) + } + }) + } + } +} + +// recorded reports whether the reconciler recorded an event starting with +// prefix (" "), draining what it recorded so far. +func recorded(r *ServiceReconciler, prefix string) bool { + events := r.Recorder.(*record.FakeRecorder).Events + found := false + for { + select { + case e := <-events: + found = found || strings.HasPrefix(e, prefix+" ") + default: + return found + } + } +} + func TestAutoClaimRefusesForeignClaimOfSameName(t *testing.T) { foreign := pendingClaim(testClassName) foreign.Name = testServiceName diff --git a/test/crd/validation_test.go b/test/crd/validation_test.go new file mode 100644 index 0000000..be88c2a --- /dev/null +++ b/test/crd/validation_test.go @@ -0,0 +1,144 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +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 + +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" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" + + 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) { + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("KUBEBUILDER_ASSETS is not set; run through `make test`") + } + env := &envtest.Environment{CRDDirectoryPaths: []string{"../../chart/address-controller/crds"}} + cfg, err := env.Start() + if err != nil { + t.Fatalf("starting envtest: %v", err) + } + t.Cleanup(func() { _ = env.Stop() }) + + scheme := runtime.NewScheme() + if err := localv1alpha1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + c, err := client.New(cfg, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + 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}, + } + 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) + }) + } + + 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}, + } + 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) + }) + } +} + +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} +} + +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) + } +} + +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, + }, + } +}