From 9f001356181d8e6fb596d7047cd5bcd7c999f12f Mon Sep 17 00:00:00 2001 From: Timofei Larkin Date: Fri, 18 Sep 2026 14:37:54 +0300 Subject: [PATCH] feat(api): add EndpointAttachment to attach addresses to app endpoints A managed application's tenant-facing Services are its endpoints, and the only way to publish one externally has been the chart boolean `external`, which publishes one chart-chosen endpoint on one address from no particular pool through five different render paths. EndpointAttachment attaches one address, minted from an IPAddressClass or bound from a reserved IPAddressClaim, to one tenant-facing Service by rendering an additive LoadBalancer Service that mirrors the endpoint's selector and ports. The mechanism therefore needs no per-engine render knowledge and never touches the application's own objects, and a reserved address survives every attachment and moves between applications. The Service carries the loadBalancerClass the claim's class reports in status, so it reaches the load balancer that owns the class's pool; since a Service's loadBalancerClass is immutable, nothing new is rendered before the class's provisioner accepts the class for its current generation. The rendered Service asks for the claim's IP families, since one left to the cluster's primary family cannot be assigned an address of the other. The endpoint check requires both the lineage labels and the tenantresource marker: lineage alone also covers operator-internal Services. A LoadBalancer Service a tenant Kubernetes cluster's cloud-controller-manager creates carries the cluster's labels and the marker too, so the cluster.x-k8s.io/tenant-service-name label it writes excludes it. Identity is by owner reference throughout, so a Service carrying the ownership label without the reference is never adopted, and a same-name recreated application does not inherit the previous incarnation's attachments. The VM datapath modes render the cozy-proxy Service contract unchanged and are gated on a platform declaration rather than CNI detection: a proxy skips a Service delegated to a name it does not claim while the load balancer still attracts the address. Exclusivity is keyed on the backend pod in both modes because cozy-proxy's egress map holds one address per pod, and holds IPv4 only, so a method attachment off a VPC refuses an IPv6 or Dual claim. A delegation no attachment renders, such as a chart Service with external: true, always takes the pod, since nothing would ever withdraw it; between attachments the oldest wins. A whole-IP attachment with several ready backends keeps its address dark instead of picking one. A cozyplane VPC changes that for whole-IP: the VM's only interface is in the VPC, so the launcher pod address a cozy-proxy Service maps to never reaches it. Where a backend pod carries the VM chart's sdn.cozystack.io/vpc annotation and the cluster serves cozyplane's FloatingIP, the attachment owns a FloatingIP on the VM's VPC address wearing its claim instead, and mirrors its readiness once its status is for its current generation: a re-pointed FloatingIP keeps the old target's status until cozyplane observes the change. FloatingIP is read as unstructured and used only when served, so the controller keeps no dependency on cozyplane. A live migration's two launcher pods share the VM's VPC address and count as one target, and a stopped VM keeps its binding rather than flipping to a cozy-proxy Service. Only a backend pod says whether a VM is in a VPC, so a method attachment that has published nothing yet waits for one; otherwise an attachment created before its VM starts would pin the claim to a cozy-proxy Service first. PortList is refused there: a FloatingIP binds every port and cozy-proxy cannot reach the VPC address. So is a Dual claim, since a FloatingIP wears one address. The kube-ovn VPC keeps the pod-network interface and adds VPC subnets as secondary interfaces, so the cozy-proxy path still delivers to the VM there. The e2e suite is the only one that needs the address substrate, so it owns both of its optional packages in test selection: the e2e install enables them, a selection that leaves the suite out disables them, and post-install prep gives the sandbox a default IPAddressClass on a pool MetalLB does not auto-assign from. The cozyplane VPC suite stays parked, because no e2e lane installs that networking variant. The kind lives in local.sdn.cozystack.io, the CRD-served half of the sdn family the address substrate and cozyplane share, so stock ResourceQuota counts keep working. Assisted-by: LLM Signed-off-by: Timofei Larkin --- .../v1alpha1/endpointattachment_types.go | 262 ++++ api/localsdn/v1alpha1/groupversion_info.go | 36 + .../v1alpha1/zz_generated.deepcopy.go | 189 +++ cmd/cozystack-controller/main.go | 22 + docs/agents/e2e-testing.md | 2 +- .../endpointattachment-vpc/README.md | 27 + .../endpointattachment-vpc/attach-dual.yaml | 15 + .../attach-portlist.yaml | 13 + .../attach-wholeip.yaml | 12 + .../chainsaw-test.yaml.disabled | 244 ++++ .../endpointattachment-vpc/routes.yaml | 22 + .../endpointattachment-vpc/vmdisk.yaml | 11 + .../endpointattachment-vpc/vminstance.yaml | 27 + .../endpointattachment-vpc/vpc.yaml | 7 + .../e2e-chainsaw/endpointattachment/README.md | 29 + .../attach-a-names-b-rw.yaml | 11 + .../attach-a-ro-minted.yaml | 13 + .../endpointattachment/attach-a-rw-held.yaml | 12 + .../endpointattachment/attach-b-rw-held.yaml | 12 + .../attach-vm-portlist.yaml | 13 + .../attach-vm-wholeip-second.yaml | 12 + .../endpointattachment/attach-vm-wholeip.yaml | 12 + .../endpointattachment/chainsaw-test.yaml | 499 ++++++++ .../endpointattachment/claim-held.yaml | 6 + .../endpointattachment/postgres-a.yaml | 23 + .../endpointattachment/postgres-b.yaml | 23 + .../endpointattachment/vmdisk.yaml | 11 + .../endpointattachment/vminstance.yaml | 28 + hack/e2e-platform-packages.sh | 2 + hack/e2e-post-install-prep.sh | 49 + hack/e2e-tenant-super-admin-write-verbs.yaml | 8 + hack/select-e2e.sh | 3 + hack/select-install.sh | 5 + hack/update-codegen.sh | 2 +- .../endpointattachment/crdcel_test.go | 290 +++++ .../endpointattachment/floatingip.go | 413 ++++++ .../endpointattachment/floatingip_test.go | 565 ++++++++ .../reconcile_edges_test.go | 984 ++++++++++++++ .../endpointattachment/reconciler.go | 879 +++++++++++++ .../endpointattachment/reconciler_test.go | 1133 +++++++++++++++++ .../controller/endpointattachment/render.go | 454 +++++++ .../controller/endpointattachment/status.go | 89 ++ .../endpointattachment/substrate.go | 232 ++++ .../controller/endpointattachment/util.go | 130 ++ .../platform/templates/bundles/system.yaml | 24 +- ...les_endpoint_attachment_datapath_test.yaml | 209 +++ .../tests/bundles_telemetry_optout_test.yaml | 4 +- .../templates/clusterroles.yaml | 16 + ....sdn.cozystack.io_endpointattachments.yaml | 272 ++++ .../templates/deployment.yaml | 6 + .../cozystack-controller/templates/rbac.yaml | 25 + .../tests/rbac_floatingip_test.yaml | 23 + .../system/cozystack-controller/values.yaml | 13 + 53 files changed, 7417 insertions(+), 6 deletions(-) create mode 100644 api/localsdn/v1alpha1/endpointattachment_types.go create mode 100644 api/localsdn/v1alpha1/groupversion_info.go create mode 100644 api/localsdn/v1alpha1/zz_generated.deepcopy.go create mode 100644 hack/e2e-chainsaw/endpointattachment-vpc/README.md create mode 100644 hack/e2e-chainsaw/endpointattachment-vpc/attach-dual.yaml create mode 100644 hack/e2e-chainsaw/endpointattachment-vpc/attach-portlist.yaml create mode 100644 hack/e2e-chainsaw/endpointattachment-vpc/attach-wholeip.yaml create mode 100644 hack/e2e-chainsaw/endpointattachment-vpc/chainsaw-test.yaml.disabled create mode 100644 hack/e2e-chainsaw/endpointattachment-vpc/routes.yaml create mode 100644 hack/e2e-chainsaw/endpointattachment-vpc/vmdisk.yaml create mode 100644 hack/e2e-chainsaw/endpointattachment-vpc/vminstance.yaml create mode 100644 hack/e2e-chainsaw/endpointattachment-vpc/vpc.yaml create mode 100644 hack/e2e-chainsaw/endpointattachment/README.md create mode 100644 hack/e2e-chainsaw/endpointattachment/attach-a-names-b-rw.yaml create mode 100644 hack/e2e-chainsaw/endpointattachment/attach-a-ro-minted.yaml create mode 100644 hack/e2e-chainsaw/endpointattachment/attach-a-rw-held.yaml create mode 100644 hack/e2e-chainsaw/endpointattachment/attach-b-rw-held.yaml create mode 100644 hack/e2e-chainsaw/endpointattachment/attach-vm-portlist.yaml create mode 100644 hack/e2e-chainsaw/endpointattachment/attach-vm-wholeip-second.yaml create mode 100644 hack/e2e-chainsaw/endpointattachment/attach-vm-wholeip.yaml create mode 100644 hack/e2e-chainsaw/endpointattachment/chainsaw-test.yaml create mode 100644 hack/e2e-chainsaw/endpointattachment/claim-held.yaml create mode 100644 hack/e2e-chainsaw/endpointattachment/postgres-a.yaml create mode 100644 hack/e2e-chainsaw/endpointattachment/postgres-b.yaml create mode 100644 hack/e2e-chainsaw/endpointattachment/vmdisk.yaml create mode 100644 hack/e2e-chainsaw/endpointattachment/vminstance.yaml create mode 100644 internal/controller/endpointattachment/crdcel_test.go create mode 100644 internal/controller/endpointattachment/floatingip.go create mode 100644 internal/controller/endpointattachment/floatingip_test.go create mode 100644 internal/controller/endpointattachment/reconcile_edges_test.go create mode 100644 internal/controller/endpointattachment/reconciler.go create mode 100644 internal/controller/endpointattachment/reconciler_test.go create mode 100644 internal/controller/endpointattachment/render.go create mode 100644 internal/controller/endpointattachment/status.go create mode 100644 internal/controller/endpointattachment/substrate.go create mode 100644 internal/controller/endpointattachment/util.go create mode 100644 packages/core/platform/tests/bundles_endpoint_attachment_datapath_test.yaml create mode 100644 packages/system/cozystack-controller/definitions/local.sdn.cozystack.io_endpointattachments.yaml create mode 100644 packages/system/cozystack-controller/tests/rbac_floatingip_test.yaml diff --git a/api/localsdn/v1alpha1/endpointattachment_types.go b/api/localsdn/v1alpha1/endpointattachment_types.go new file mode 100644 index 000000000..9db6504b0 --- /dev/null +++ b/api/localsdn/v1alpha1/endpointattachment_types.go @@ -0,0 +1,262 @@ +/* +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 v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// EndpointApplicationReference names the managed application whose endpoint +// is attached. All three fields are compared against the lineage labels the +// platform stamps on the application's objects. +type EndpointApplicationReference struct { + // Group of the application's API. + // +kubebuilder:default=apps.cozystack.io + // +optional + Group string `json:"group,omitempty"` + + // Kind of the application, e.g. Postgres. + // +kubebuilder:validation:MinLength=1 + Kind string `json:"kind"` + + // Name of the application instance in this namespace. + // +kubebuilder:validation:MinLength=1 + Name string `json:"name"` +} + +// EndpointReference selects one endpoint of the application. It is a struct +// so that a named-endpoint vocabulary can be added beside serviceName later. +type EndpointReference struct { + // ServiceName is a tenant-facing Service of the application, in the + // attachment's namespace. + // +kubebuilder:validation:MinLength=1 + ServiceName string `json:"serviceName"` +} + +// AddressFamily is the IP family an address claim requests. +// +kubebuilder:validation:Enum=IPv4;IPv6;Dual +type AddressFamily string + +const ( + AddressFamilyIPv4 AddressFamily = "IPv4" + AddressFamilyIPv6 AddressFamily = "IPv6" + AddressFamilyDual AddressFamily = "Dual" +) + +// ExposureMethod selects a VM datapath mode rendered through the cozy-proxy +// Service contract. The values are the vm-instance chart's externalMethod +// vocabulary. +// +kubebuilder:validation:Enum=WholeIP;PortList +type ExposureMethod string + +const ( + ExposureMethodWholeIP ExposureMethod = "WholeIP" + ExposureMethodPortList ExposureMethod = "PortList" +) + +// LoadBalancerAttachment attaches a dedicated address through one additive +// type: LoadBalancer Service that mirrors the endpoint Service. +// +// className, claimName and family select the address and are immutable: +// changing any of them could re-mint or release an address a client has +// allow-listed. ports, method and allowICMP only shape the rendered Service. +// +kubebuilder:validation:XValidation:rule="!(has(self.className) && has(self.claimName))",message="className and claimName are mutually exclusive" +// +kubebuilder:validation:XValidation:rule="has(self.className) == has(oldSelf.className) && (!has(self.className) || self.className == oldSelf.className)",message="className is immutable" +// +kubebuilder:validation:XValidation:rule="has(self.claimName) == has(oldSelf.claimName) && (!has(self.claimName) || self.claimName == oldSelf.claimName)",message="claimName is immutable" +// +kubebuilder:validation:XValidation:rule="has(self.family) == has(oldSelf.family) && (!has(self.family) || self.family == oldSelf.family)",message="family is immutable" +// +kubebuilder:validation:XValidation:rule="!has(self.allowICMP) || (has(self.method) && self.method == 'PortList')",message="allowICMP applies to method PortList only" +// +kubebuilder:validation:XValidation:rule="!(has(self.method) && self.method == 'PortList') || (has(self.ports) && size(self.ports) > 0)",message="method PortList requires ports" +type LoadBalancerAttachment struct { + // ClassName mints a fresh IPAddressClaim from this IPAddressClass. Empty + // with no claimName mints from the default class. + // +optional + ClassName string `json:"className,omitempty"` + + // ClaimName binds a pre-reserved IPAddressClaim in this namespace instead + // of minting one. The claim outlives the attachment. + // +optional + ClaimName string `json:"claimName,omitempty"` + + // Family is passed to a minted claim and validated against a referenced + // one. + // +optional + Family AddressFamily `json:"family,omitempty"` + + // Ports is a subset of the endpoint's ports to publish. It is the only + // port source when the endpoint has nothing meaningful to mirror (a VM's + // sentinel-port Service). + // +kubebuilder:validation:MaxItems=256 + // +kubebuilder:validation:items:Minimum=1 + // +kubebuilder:validation:items:Maximum=65535 + // +listType=set + // +optional + Ports []int32 `json:"ports,omitempty"` + + // Method selects a VM datapath mode. WholeIP renders 1:1 NAT of every + // port to a single backend; PortList renders the listed ports. + // +optional + Method ExposureMethod `json:"method,omitempty"` + + // AllowICMP lets ICMP through in PortList mode. + // +optional + AllowICMP *bool `json:"allowICMP,omitempty"` +} + +// EndpointAttachmentSpec defines the desired state of EndpointAttachment. +// +// The mechanism is a union with loadBalancer as its only member today. A +// future member is added by extending the list in the exactly-one rule. +// +kubebuilder:validation:XValidation:rule="[has(self.loadBalancer)].filter(m, m).size() == 1",message="exactly one mechanism member must be set" +// +kubebuilder:validation:XValidation:rule="has(self.loadBalancer) == has(oldSelf.loadBalancer)",message="the mechanism member is immutable" +type EndpointAttachmentSpec struct { + // ApplicationRef names the application in this namespace. Immutable. + // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="applicationRef is immutable" + ApplicationRef EndpointApplicationReference `json:"applicationRef"` + + // Endpoint selects which tenant-facing Service of the application to + // attach the address to. + Endpoint EndpointReference `json:"endpoint"` + + // LoadBalancer attaches a dedicated address through an additive + // LoadBalancer Service. + // +optional + LoadBalancer *LoadBalancerAttachment `json:"loadBalancer,omitempty"` +} + +// EndpointAttachmentPhase is a printed summary of the conditions. +// +kubebuilder:validation:Enum=Pending;Attached;Detached +type EndpointAttachmentPhase string + +const ( + // EndpointAttachmentPending: not yet both resolved and provisioned. + EndpointAttachmentPending EndpointAttachmentPhase = "Pending" + // EndpointAttachmentAttached: Resolved and Provisioned are both true. + EndpointAttachmentAttached EndpointAttachmentPhase = "Attached" + // EndpointAttachmentDetached: the endpoint Service went away after the + // attachment had rendered; the address is kept, nothing is published. + EndpointAttachmentDetached EndpointAttachmentPhase = "Detached" +) + +// Condition types and reasons reported on an EndpointAttachment. +const ( + // ConditionResolved is true when the endpoint Service exists and passes + // the tenant-facing authorization check. + ConditionResolved = "Resolved" + // ConditionProvisioned is true when the claim is bound and the rendered + // Service carries its address. It asserts address and Service wiring + // only; end-to-end reachability additionally depends on the CNI's own + // policy objects. + ConditionProvisioned = "Provisioned" + + ReasonResolved = "Resolved" + ReasonApplicationNotFound = "ApplicationNotFound" + ReasonApplicationIncarnationChange = "ApplicationIncarnationChanged" + ReasonEndpointNotFound = "EndpointNotFound" + ReasonEndpointLineageMismatch = "EndpointLineageMismatch" + ReasonEndpointNotTenantFacing = "EndpointNotTenantFacing" + + ReasonProvisioned = "Provisioned" + ReasonEndpointDetached = "EndpointDetached" + ReasonNothingToPublish = "NothingToPublish" + ReasonDatapathUnavailable = "DatapathContractUnavailable" + ReasonMultipleBackends = "MultipleBackends" + ReasonBackendAlreadyDelegated = "BackendAlreadyDelegated" + ReasonClaimNotFound = "ClaimNotFound" + ReasonClaimPending = "ClaimPending" + ReasonClassNotAccepted = "ClassNotAccepted" + ReasonFamilyUnsupportedByDatapath = "FamilyUnsupportedByDatapath" + ReasonClaimInUse = "ClaimInUse" + ReasonFamilyConflict = "FamilyConflict" + ReasonWaitingForAddress = "WaitingForAddress" + ReasonRenderFailed = "RenderFailed" + ReasonWaitingForBackend = "WaitingForBackend" + ReasonWithdrawalPending = "WithdrawalPending" + + // Reasons on the path where a whole-IP backend sits in a cozyplane VPC + // and the address is bound through a FloatingIP. + ReasonMethodUnsupportedInVPC = "MethodUnsupportedInVPC" + ReasonVPCNotInNamespace = "VPCNotInNamespace" + ReasonWaitingForVPCAddress = "WaitingForVPCAddress" + ReasonFloatingIPNotReady = "FloatingIPNotReady" + ReasonDualStackUnsupportedInVPC = "DualStackUnsupportedInVPC" +) + +// EndpointAttachmentStatus defines the observed state of EndpointAttachment. +type EndpointAttachmentStatus struct { + // ObservedGeneration is the spec generation the status reflects. + // +optional + ObservedGeneration int64 `json:"observedGeneration,omitempty"` + + // Phase summarises the conditions. + // +optional + Phase EndpointAttachmentPhase `json:"phase,omitempty"` + + // ServiceName is the rendered LoadBalancer Service. + // +optional + ServiceName string `json:"serviceName,omitempty"` + + // ClaimName is the IPAddressClaim the rendered Service consumes, minted + // or referenced. + // +optional + ClaimName string `json:"claimName,omitempty"` + + // Addresses mirrors the claim's bound addresses. + // +optional + Addresses []string `json:"addresses,omitempty"` + + // Conditions follow metav1.Condition semantics. + // +optional + // +listType=map + // +listMapKey=type + Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type"` +} + +// +kubebuilder:object:root=true +// +kubebuilder:subresource:status +// +kubebuilder:printcolumn:name="Application",type="string",JSONPath=".spec.applicationRef.name" +// +kubebuilder:printcolumn:name="Endpoint",type="string",JSONPath=".spec.endpoint.serviceName" +// +kubebuilder:printcolumn:name="Phase",type="string",JSONPath=".status.phase" +// +kubebuilder:printcolumn:name="Addresses",type="string",JSONPath=".status.addresses" +// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp" + +// EndpointAttachment attaches an external address to one tenant-facing +// endpoint of one managed application. +type EndpointAttachment struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + // Spec is required: were it optional, removing it would skip the + // immutability rules nested inside it, and restoring it would run them + // with no old value to compare against. + + // +required + Spec EndpointAttachmentSpec `json:"spec"` + Status EndpointAttachmentStatus `json:"status,omitempty"` +} + +// +kubebuilder:object:root=true + +// EndpointAttachmentList contains a list of EndpointAttachment. +type EndpointAttachmentList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []EndpointAttachment `json:"items"` +} + +func init() { + SchemeBuilder.Register(&EndpointAttachment{}, &EndpointAttachmentList{}) +} diff --git a/api/localsdn/v1alpha1/groupversion_info.go b/api/localsdn/v1alpha1/groupversion_info.go new file mode 100644 index 000000000..a54d33d04 --- /dev/null +++ b/api/localsdn/v1alpha1/groupversion_info.go @@ -0,0 +1,36 @@ +/* +Copyright 2025. + +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 v1alpha1 contains the CRD-served kinds of the sdn family that cozystack-controller owns. +// +kubebuilder:object:generate=true +// +groupName=local.sdn.cozystack.io +package v1alpha1 + +import ( + "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-runtime/pkg/scheme" +) + +var ( + // GroupVersion is group version used to register these objects. + GroupVersion = schema.GroupVersion{Group: "local.sdn.cozystack.io", Version: "v1alpha1"} + + // SchemeBuilder is used to add go types to the GroupVersionKind scheme. + SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion} + + // AddToScheme adds the types in this group-version to the given scheme. + AddToScheme = SchemeBuilder.AddToScheme +) diff --git a/api/localsdn/v1alpha1/zz_generated.deepcopy.go b/api/localsdn/v1alpha1/zz_generated.deepcopy.go new file mode 100644 index 000000000..d93e7382f --- /dev/null +++ b/api/localsdn/v1alpha1/zz_generated.deepcopy.go @@ -0,0 +1,189 @@ +//go:build !ignore_autogenerated + +/* +Copyright 2025 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. +*/ + +// Code generated by controller-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *EndpointApplicationReference) DeepCopyInto(out *EndpointApplicationReference) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EndpointApplicationReference. +func (in *EndpointApplicationReference) DeepCopy() *EndpointApplicationReference { + if in == nil { + return nil + } + out := new(EndpointApplicationReference) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *EndpointAttachment) DeepCopyInto(out *EndpointAttachment) { + *out = *in + 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 EndpointAttachment. +func (in *EndpointAttachment) DeepCopy() *EndpointAttachment { + if in == nil { + return nil + } + out := new(EndpointAttachment) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *EndpointAttachment) 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 *EndpointAttachmentList) DeepCopyInto(out *EndpointAttachmentList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]EndpointAttachment, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EndpointAttachmentList. +func (in *EndpointAttachmentList) DeepCopy() *EndpointAttachmentList { + if in == nil { + return nil + } + out := new(EndpointAttachmentList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *EndpointAttachmentList) 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 *EndpointAttachmentSpec) DeepCopyInto(out *EndpointAttachmentSpec) { + *out = *in + out.ApplicationRef = in.ApplicationRef + out.Endpoint = in.Endpoint + if in.LoadBalancer != nil { + in, out := &in.LoadBalancer, &out.LoadBalancer + *out = new(LoadBalancerAttachment) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EndpointAttachmentSpec. +func (in *EndpointAttachmentSpec) DeepCopy() *EndpointAttachmentSpec { + if in == nil { + return nil + } + out := new(EndpointAttachmentSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *EndpointAttachmentStatus) DeepCopyInto(out *EndpointAttachmentStatus) { + *out = *in + if in.Addresses != nil { + in, out := &in.Addresses, &out.Addresses + *out = make([]string, len(*in)) + copy(*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 EndpointAttachmentStatus. +func (in *EndpointAttachmentStatus) DeepCopy() *EndpointAttachmentStatus { + if in == nil { + return nil + } + out := new(EndpointAttachmentStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *EndpointReference) DeepCopyInto(out *EndpointReference) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EndpointReference. +func (in *EndpointReference) DeepCopy() *EndpointReference { + if in == nil { + return nil + } + out := new(EndpointReference) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *LoadBalancerAttachment) DeepCopyInto(out *LoadBalancerAttachment) { + *out = *in + if in.Ports != nil { + in, out := &in.Ports, &out.Ports + *out = make([]int32, len(*in)) + copy(*out, *in) + } + if in.AllowICMP != nil { + in, out := &in.AllowICMP, &out.AllowICMP + *out = new(bool) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LoadBalancerAttachment. +func (in *LoadBalancerAttachment) DeepCopy() *LoadBalancerAttachment { + if in == nil { + return nil + } + out := new(LoadBalancerAttachment) + in.DeepCopyInto(out) + return out +} diff --git a/cmd/cozystack-controller/main.go b/cmd/cozystack-controller/main.go index df9c408a7..20611eb1c 100644 --- a/cmd/cozystack-controller/main.go +++ b/cmd/cozystack-controller/main.go @@ -42,9 +42,11 @@ import ( gatewayv1alpha1 "github.com/cozystack/cozystack/api/gateway/v1alpha1" internalv1alpha1 "github.com/cozystack/cozystack/api/internalapi/v1alpha1" + localsdnv1alpha1 "github.com/cozystack/cozystack/api/localsdn/v1alpha1" cozystackiov1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" "github.com/cozystack/cozystack/internal/controller" "github.com/cozystack/cozystack/internal/controller/cacert" + "github.com/cozystack/cozystack/internal/controller/endpointattachment" "github.com/cozystack/cozystack/internal/controller/tenantgateway" "github.com/cozystack/cozystack/internal/controller/tenantlogrouting" "github.com/cozystack/cozystack/internal/controller/tenantquota" @@ -71,6 +73,7 @@ func init() { utilruntime.Must(cozystackiov1alpha1.AddToScheme(scheme)) utilruntime.Must(gatewayv1alpha1.AddToScheme(scheme)) utilruntime.Must(internalv1alpha1.AddToScheme(scheme)) + utilruntime.Must(localsdnv1alpha1.AddToScheme(scheme)) utilruntime.Must(gatewayv1.Install(scheme)) utilruntime.Must(gatewayv1alpha2.Install(scheme)) utilruntime.Must(gatewayv1beta1.Install(scheme)) @@ -91,6 +94,8 @@ func main() { var telemetryInterval string var quotaBufferPercent int64 var seaweedfsMetricsEndpoint string + var cozyProxyContractImplemented bool + var endpointAttachmentNodePorts bool var tlsOpts []func(*tls.Config) flag.StringVar(&metricsAddr, "metrics-bind-address", "0", "The address the metrics endpoint binds to. "+ "Use :8443 for HTTPS or :8080 for HTTP, or leave as 0 to disable the metrics service.") @@ -114,6 +119,11 @@ func main() { "Base URL of a Prometheus-compatible query API to fetch SeaweedFS bucket size metrics from, e.g. https://vm.example.com/path/to/prometheus (/api/v1/query is appended). "+ "Overrides discovery via the namespace.cozystack.io/monitoring label; use when SeaweedFS and the monitoring stack that scrapes it run in a separate cluster. "+ "Basic auth may be embedded as userinfo (https://user:pass@host/...). Empty keeps label-based discovery.") + flag.BoolVar(&cozyProxyContractImplemented, "cozy-proxy-contract-implemented", false, + "Declare that a service proxy answering to the cozy-proxy service-proxy-name is deployed, so EndpointAttachments may render method: WholeIP|PortList Services. "+ + "Without it such attachments render no Service and report DatapathContractUnavailable: a load balancer would still attract the address while every proxy skipped the Service.") + flag.BoolVar(&endpointAttachmentNodePorts, "endpoint-attachment-allocate-node-ports", false, + "Allocate node ports on the LoadBalancer Services EndpointAttachments render. Off by default, matching the platform convention; needed only by load balancers that forward through node ports (Hetzner RobotLB).") opts := zap.Options{ Development: false, } @@ -357,6 +367,18 @@ func main() { os.Exit(1) } + if err = (&endpointattachment.Reconciler{ + Client: mgr.GetClient(), + Scheme: mgr.GetScheme(), + Reader: mgr.GetAPIReader(), + Recorder: mgr.GetEventRecorderFor("endpointattachment-controller"), + CozyProxyContractImplemented: cozyProxyContractImplemented, + AllocateLoadBalancerNodePorts: endpointAttachmentNodePorts, + }).SetupWithManager(mgr); err != nil { + setupLog.Error(err, "unable to create controller", "controller", "EndpointAttachment") + os.Exit(1) + } + // +kubebuilder:scaffold:builder if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil { diff --git a/docs/agents/e2e-testing.md b/docs/agents/e2e-testing.md index f5c793125..2b1b6d153 100644 --- a/docs/agents/e2e-testing.md +++ b/docs/agents/e2e-testing.md @@ -12,7 +12,7 @@ Every convention below follows from that finding: **fail fast, fail loud, make t ## The Proxmox lane -`hack/e2e-chainsaw/kubernetes-proxmox/` covers the Proxmox substrate and is the one suite in this tree that the normal lanes cannot run. It needs a Proxmox hypervisor, and the `oracle-vm-*` runners have none, so it ships as `chainsaw-test.yaml.disabled`: neither Chainsaw nor the selector counts a `.disabled` file as a test, and nothing else in the directory or below it is one, which registers it nowhere and makes it unselectable rather than merely unselected. `.github/workflows/e2e-proxmox.yaml` drops the suffix on a self-hosted runner that has one. +`hack/e2e-chainsaw/kubernetes-proxmox/` covers the Proxmox substrate and is one of two suites in this tree that the normal lanes cannot run. It needs a Proxmox hypervisor, and the `oracle-vm-*` runners have none, so it ships as `chainsaw-test.yaml.disabled`: neither Chainsaw nor the selector counts a `.disabled` file as a test, and nothing else in the directory or below it is one, which registers it nowhere and makes it unselectable rather than merely unselected. `.github/workflows/e2e-proxmox.yaml` drops the suffix on a self-hosted runner that has one. The other, `hack/e2e-chainsaw/endpointattachment-vpc/`, needs the cozyplane networking variant, which no lane installs; it is parked the same way and has no lane of its own. Two properties of that workflow are security boundaries rather than preferences. It is never triggered by `pull_request`, because a self-hosted runner executes what the workflow checks out and this one stages a hypervisor token and a live kubeconfig — a fork PR trigger would hand both to its author. And its concurrency group never cancels in progress, because a killed run leaks VMs on the hypervisor rather than merely losing a result. diff --git a/hack/e2e-chainsaw/endpointattachment-vpc/README.md b/hack/e2e-chainsaw/endpointattachment-vpc/README.md new file mode 100644 index 000000000..77be15030 --- /dev/null +++ b/hack/e2e-chainsaw/endpointattachment-vpc/README.md @@ -0,0 +1,27 @@ +# EndpointAttachment in a cozyplane VPC E2E (disabled / opt-in) + +`chainsaw-test.yaml.disabled` exercises `EndpointAttachment` against a VM whose only interface is in a cozyplane VPC. The launcher pod's address, which a cozy-proxy Service maps to, never reaches such a guest, so a `WholeIP` attachment binds a cozyplane `FloatingIP` on the VM's VPC address instead. The Test refuses `PortList` with `MethodUnsupportedInVPC` and a `Dual` claim with `DualStackUnsupportedInVPC`, with no FloatingIP bound for either. Before the VM starts, it declares the VPC's default `RouteTable` with a `0.0.0.0/0` route to `internet`: cozyplane sends a FloatingIP's replies out of the VPC only through such a route, and the VPC application renders none, so without it the FloatingIP is bound and Ready while the address never answers. It then attaches `WholeIP`, expects a Ready FloatingIP that wears the attachment's address and targets the VM's VPC address, with no Service of the attachment's own, and dials the guest's port 22 on that address. + +It is parked apart from `hack/e2e-chainsaw/endpointattachment/` rather than beside it, because it needs the cozyplane networking variant and no e2e lane installs that. On any other variant the cluster serves no `FloatingIP`, and a `VMInstance`'s `networks` name a different kind of VPC, so the Test cannot pass there. The `.disabled` suffix keeps it out of Chainsaw's default discovery and `hack/select-e2e.sh` does not enumerate it. + +## Preconditions + +- The cozyplane networking variant, with the aggregated `sdn.cozystack.io` API serving `VPC`, `RouteTable`, `Route` and `FloatingIP`. +- The applications the fixtures create: `VirtualPrivateCloud` (`cozystack.virtualprivatecloud-application` in its `cozyplane` variant), and `VMDisk` and `VMInstance` (`cozystack.vm-disk-application` and `cozystack.vm-instance-application`, with KubeVirt and CDI). The engine that ships the controller, `cozystack.cozystack-engine`, and the `tenant-test` namespace as configured in `hack/e2e-chainsaw/.chainsaw.yaml`. +- The address substrate as for `hack/e2e-chainsaw/endpointattachment/`: `cozystack.address-controller` and `cozystack.metallb-iad`, with one `IPAddressClass` annotated as the default whose pool is routable from the machine running Chainsaw. The reachability probe dials the attached address from that machine. The `Dual` refusal needs no IPv6 in the class: the attachment is refused before its claim has to bind. +- `nc` and `kubectl` on the machine running Chainsaw. + +cozy-proxy is not needed: the VPC path renders no cozy-proxy Service. + +## Running + +```sh +chainsaw test --config hack/e2e-chainsaw/.chainsaw.yaml --test-file chainsaw-test.yaml.disabled \ + --set-string storageClass= hack/e2e-chainsaw/endpointattachment-vpc +``` + +`storageClass` is the StorageClass the VM disk imports into, as `make test-chainsaw` passes it to every suite. + +## Cleanup + +Chainsaw deletes the VirtualPrivateCloud, VMDisk, VMInstance and EndpointAttachment objects it applied. The FloatingIP and the minted claims are owned by their attachments and go with them; the Test also waits for the whole-IP attachment's FloatingIP to be collected. What happens to each `IPAddress` afterwards follows the class's reclaim policy, as described for `hack/e2e-chainsaw/endpointattachment/`. diff --git a/hack/e2e-chainsaw/endpointattachment-vpc/attach-dual.yaml b/hack/e2e-chainsaw/endpointattachment-vpc/attach-dual.yaml new file mode 100644 index 000000000..30c37c5de --- /dev/null +++ b/hack/e2e-chainsaw/endpointattachment-vpc/attach-dual.yaml @@ -0,0 +1,15 @@ +# The minted claim is Dual: a FloatingIP binds one address, so this is +# refused before the claim needs to bind, whatever families the class holds. +apiVersion: local.sdn.cozystack.io/v1alpha1 +kind: EndpointAttachment +metadata: + name: ea-vpc-dual +spec: + applicationRef: + kind: VMInstance + name: ea-vpc-vm + endpoint: + serviceName: vm-instance-ea-vpc-vm + loadBalancer: + method: WholeIP + family: Dual diff --git a/hack/e2e-chainsaw/endpointattachment-vpc/attach-portlist.yaml b/hack/e2e-chainsaw/endpointattachment-vpc/attach-portlist.yaml new file mode 100644 index 000000000..dabddcd83 --- /dev/null +++ b/hack/e2e-chainsaw/endpointattachment-vpc/attach-portlist.yaml @@ -0,0 +1,13 @@ +apiVersion: local.sdn.cozystack.io/v1alpha1 +kind: EndpointAttachment +metadata: + name: ea-vpc-portlist +spec: + applicationRef: + kind: VMInstance + name: ea-vpc-vm + endpoint: + serviceName: vm-instance-ea-vpc-vm + loadBalancer: + method: PortList + ports: [22] diff --git a/hack/e2e-chainsaw/endpointattachment-vpc/attach-wholeip.yaml b/hack/e2e-chainsaw/endpointattachment-vpc/attach-wholeip.yaml new file mode 100644 index 000000000..692b542fe --- /dev/null +++ b/hack/e2e-chainsaw/endpointattachment-vpc/attach-wholeip.yaml @@ -0,0 +1,12 @@ +apiVersion: local.sdn.cozystack.io/v1alpha1 +kind: EndpointAttachment +metadata: + name: ea-vpc-wholeip +spec: + applicationRef: + kind: VMInstance + name: ea-vpc-vm + endpoint: + serviceName: vm-instance-ea-vpc-vm + loadBalancer: + method: WholeIP diff --git a/hack/e2e-chainsaw/endpointattachment-vpc/chainsaw-test.yaml.disabled b/hack/e2e-chainsaw/endpointattachment-vpc/chainsaw-test.yaml.disabled new file mode 100644 index 000000000..b07ed3c69 --- /dev/null +++ b/hack/e2e-chainsaw/endpointattachment-vpc/chainsaw-test.yaml.disabled @@ -0,0 +1,244 @@ +# EndpointAttachment on the cozyplane networking variant. Parked as .disabled +# apart from the endpointattachment suite: no e2e lane installs cozyplane, and +# on any other variant the cluster serves no FloatingIP and a VMInstance's +# networks name a different kind of VPC. See README.md. +# +# A VM whose only interface is in a cozyplane VPC. The launcher pod address a +# cozy-proxy Service maps to never reaches the guest, so a whole-IP attachment +# binds a FloatingIP on the VM's VPC address instead; the two modes that +# cannot work there are refused before anything is bound. +apiVersion: chainsaw.kyverno.io/v1alpha1 +kind: Test +metadata: + name: endpointattachment-vpc +spec: + catch: + - events: {} + - describe: + apiVersion: local.sdn.cozystack.io/v1alpha1 + kind: EndpointAttachment + - describe: + apiVersion: kubevirt.io/v1 + kind: VirtualMachineInstance + name: vm-instance-ea-vpc-vm + - get: + apiVersion: sdn.cozystack.io/v1alpha1 + kind: FloatingIP + - describe: + apiVersion: sdn.cozystack.io/v1alpha1 + kind: Route + - get: + apiVersion: v1 + kind: Service + steps: + - name: create-vpc-vm + try: + - apply: + file: vpc.yaml + - assert: + timeout: 6m + resource: + apiVersion: helm.toolkit.fluxcd.io/v2 + kind: HelmRelease + metadata: + name: virtualprivatecloud-ea-vpc + status: + (conditions[?type == 'Ready']): + - status: "True" + - apply: + file: routes.yaml + - assert: + resource: + apiVersion: sdn.cozystack.io/v1alpha1 + kind: Route + metadata: + name: ea-vpc-internet + status: + state: Active + - apply: + file: vmdisk.yaml + - assert: + timeout: 6m + resource: + apiVersion: helm.toolkit.fluxcd.io/v2 + kind: HelmRelease + metadata: + name: vm-disk-ea-vpc-vm + status: + (conditions[?type == 'Ready']): + - status: "True" + - assert: + timeout: 5m + resource: + apiVersion: cdi.kubevirt.io/v1beta1 + kind: DataVolume + metadata: + name: vm-disk-ea-vpc-vm + status: + (conditions[?type == 'Ready']): + - status: "True" + - apply: + file: vminstance.yaml + - assert: + timeout: 6m + resource: + apiVersion: helm.toolkit.fluxcd.io/v2 + kind: HelmRelease + metadata: + name: vm-instance-ea-vpc-vm + status: + (conditions[?type == 'Ready']): + - status: "True" + - assert: + timeout: 5m + resource: + apiVersion: kubevirt.io/v1 + kind: VirtualMachine + metadata: + name: vm-instance-ea-vpc-vm + status: + (conditions[?type == 'Ready']): + - status: "True" + # The controller decides on the VPC path from the launcher pod, and binds + # only once cozyplane has stamped the pod's VPC address on it. + - assert: + timeout: 2m + resource: + apiVersion: v1 + kind: Pod + metadata: + labels: + vm.kubevirt.io/name: vm-instance-ea-vpc-vm + annotations: + sdn.cozystack.io/vpc: virtualprivatecloud-ea-vpc + '("sdn.cozystack.io/vpc-ip" != null)': true + + # PortList filters ports through cozy-proxy, which cannot reach a VPC + # address, so it is refused and nothing is bound. + - name: refuse-portlist-in-vpc + try: + - apply: + file: attach-portlist.yaml + - assert: + timeout: 2m + resource: + apiVersion: local.sdn.cozystack.io/v1alpha1 + kind: EndpointAttachment + metadata: + name: ea-vpc-portlist + status: + phase: Pending + (conditions[?type == 'Provisioned']): + - status: "False" + reason: MethodUnsupportedInVPC + - error: + resource: + apiVersion: sdn.cozystack.io/v1alpha1 + kind: FloatingIP + metadata: + labels: + cozystack.io/endpoint-attachment: ea-vpc-portlist + - error: + resource: + apiVersion: v1 + kind: Service + metadata: + labels: + cozystack.io/endpoint-attachment: ea-vpc-portlist + - delete: + ref: + apiVersion: local.sdn.cozystack.io/v1alpha1 + kind: EndpointAttachment + name: ea-vpc-portlist + + # A FloatingIP wears one address, so a Dual claim is refused. + - name: refuse-dual-in-vpc + try: + - apply: + file: attach-dual.yaml + - assert: + timeout: 2m + resource: + apiVersion: local.sdn.cozystack.io/v1alpha1 + kind: EndpointAttachment + metadata: + name: ea-vpc-dual + status: + phase: Pending + (conditions[?type == 'Provisioned']): + - status: "False" + reason: DualStackUnsupportedInVPC + - error: + resource: + apiVersion: sdn.cozystack.io/v1alpha1 + kind: FloatingIP + metadata: + labels: + cozystack.io/endpoint-attachment: ea-vpc-dual + - delete: + ref: + apiVersion: local.sdn.cozystack.io/v1alpha1 + kind: EndpointAttachment + name: ea-vpc-dual + + # WholeIP: a FloatingIP binds the attachment's address to the VM's VPC + # address, renders no cozy-proxy Service, and the address reaches the guest. + - name: attach-wholeip-in-vpc + try: + - apply: + file: attach-wholeip.yaml + - assert: + timeout: 4m + resource: + apiVersion: local.sdn.cozystack.io/v1alpha1 + kind: EndpointAttachment + metadata: + name: ea-vpc-wholeip + status: + phase: Attached + (addresses[0] != null): true + - script: + timeout: 1m + content: | + set -eu + ip=$(kubectl get endpointattachments.local.sdn.cozystack.io ea-vpc-wholeip --namespace "$NAMESPACE" --output jsonpath='{.status.addresses[0]}') + test -n "$ip" + vpcip=$(kubectl get pod --namespace "$NAMESPACE" --selector vm.kubevirt.io/name=vm-instance-ea-vpc-vm --output jsonpath='{.items[0].metadata.annotations.sdn\.cozystack\.io/vpc-ip}') + test -n "$vpcip" + fip=$(kubectl get floatingips.sdn.cozystack.io --namespace "$NAMESPACE" --selector cozystack.io/endpoint-attachment=ea-vpc-wholeip --output jsonpath='{range .items[*]}{.status.phase} {.status.address} {.spec.target} {.spec.vpcRef.name}{"\n"}{end}') + [ "$fip" = "Ready $ip $vpcip virtualprivatecloud-ea-vpc" ] + # The FloatingIP owns the Service that wears the claim; the + # attachment renders none of its own. + svcs=$(kubectl get service --namespace "$NAMESPACE" --selector cozystack.io/endpoint-attachment=ea-vpc-wholeip --output name) + [ -z "$svcs" ] + check: + ($error == null): true + - script: + timeout: 3m + content: | + set -eu + ip=$(kubectl get endpointattachments.local.sdn.cozystack.io ea-vpc-wholeip --namespace "$NAMESPACE" --output jsonpath='{.status.addresses[0]}') + # sshd inside the guest comes up after cloud-init; no condition + # models "the guest listens", so the port is polled. + # TODO(e2e-replace-fixed-timeouts): replace with a guest-readiness signal if KubeVirt grows one. + for _ in $(seq 1 60); do + if nc -z -w 3 "$ip" 22; then exit 0; fi + sleep 3 + done + echo "port 22 on $ip never answered through the FloatingIP" >&2 + exit 1 + check: + ($error == null): true + - delete: + ref: + apiVersion: local.sdn.cozystack.io/v1alpha1 + kind: EndpointAttachment + name: ea-vpc-wholeip + - error: + timeout: 2m + resource: + apiVersion: sdn.cozystack.io/v1alpha1 + kind: FloatingIP + metadata: + labels: + cozystack.io/endpoint-attachment: ea-vpc-wholeip diff --git a/hack/e2e-chainsaw/endpointattachment-vpc/routes.yaml b/hack/e2e-chainsaw/endpointattachment-vpc/routes.yaml new file mode 100644 index 000000000..a975b1b54 --- /dev/null +++ b/hack/e2e-chainsaw/endpointattachment-vpc/routes.yaml @@ -0,0 +1,22 @@ +# A FloatingIP's replies leave the VPC only through a route whose target is +# internet; without one the address is bound and Ready but never answers. The +# VPC application renders no route table, so the Test declares the default one. +apiVersion: sdn.cozystack.io/v1alpha1 +kind: RouteTable +metadata: + name: ea-vpc-main +spec: + vpcRef: + name: virtualprivatecloud-ea-vpc + default: true +--- +apiVersion: sdn.cozystack.io/v1alpha1 +kind: Route +metadata: + name: ea-vpc-internet +spec: + routeTableRef: + name: ea-vpc-main + destination: 0.0.0.0/0 + target: + internet: {} diff --git a/hack/e2e-chainsaw/endpointattachment-vpc/vmdisk.yaml b/hack/e2e-chainsaw/endpointattachment-vpc/vmdisk.yaml new file mode 100644 index 000000000..dce7a8d22 --- /dev/null +++ b/hack/e2e-chainsaw/endpointattachment-vpc/vmdisk.yaml @@ -0,0 +1,11 @@ +apiVersion: apps.cozystack.io/v1alpha1 +kind: VMDisk +metadata: + name: ea-vpc-vm +spec: + source: + http: + url: https://cloud-images.ubuntu.com/noble/current/noble-server-cloudimg-amd64.img + optical: false + storage: 5Gi + storageClass: ($values.storageClass) diff --git a/hack/e2e-chainsaw/endpointattachment-vpc/vminstance.yaml b/hack/e2e-chainsaw/endpointattachment-vpc/vminstance.yaml new file mode 100644 index 000000000..88c9ade30 --- /dev/null +++ b/hack/e2e-chainsaw/endpointattachment-vpc/vminstance.yaml @@ -0,0 +1,27 @@ +apiVersion: apps.cozystack.io/v1alpha1 +kind: VMInstance +metadata: + name: ea-vpc-vm +spec: + external: false + running: true + instanceType: "u1.medium" + instanceProfile: ubuntu + networks: + - name: ea-vpc + disks: + - name: ea-vpc-vm + gpus: [] + sshKeys: + - ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPht0dPk5qQ+54g1hSX7A6AUxXJW5T6n/3d7Ga2F8gTF + test@test + cloudInit: | + #cloud-config + users: + - name: test + shell: /bin/bash + sudo: ['ALL=(ALL) NOPASSWD: ALL'] + groups: sudo + ssh_authorized_keys: + - ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPht0dPk5qQ+54g1hSX7A6AUxXJW5T6n/3d7Ga2F8gTF test@test + cloudInitSeed: "" diff --git a/hack/e2e-chainsaw/endpointattachment-vpc/vpc.yaml b/hack/e2e-chainsaw/endpointattachment-vpc/vpc.yaml new file mode 100644 index 000000000..99d7f0084 --- /dev/null +++ b/hack/e2e-chainsaw/endpointattachment-vpc/vpc.yaml @@ -0,0 +1,7 @@ +apiVersion: apps.cozystack.io/v1alpha1 +kind: VirtualPrivateCloud +metadata: + name: ea-vpc +spec: + cidrs: + - 10.77.0.0/24 diff --git a/hack/e2e-chainsaw/endpointattachment/README.md b/hack/e2e-chainsaw/endpointattachment/README.md new file mode 100644 index 000000000..2d0cf8b02 --- /dev/null +++ b/hack/e2e-chainsaw/endpointattachment/README.md @@ -0,0 +1,29 @@ +# EndpointAttachment E2E + +`chainsaw-test.yaml` exercises `EndpointAttachment` against a live cluster in two Tests. The postgres Test is the design's contract in one sequence: an attachment that names one application and points at the tenant-facing Service of another is refused with `EndpointLineageMismatch` and renders nothing; a minted address publishes the read replicas of one application and is collected with its attachment; a reserved `IPAddressClaim` is attached to one application's primary, detached, still holds the same address, and is then attached to a different application's primary, which the same address now serves; deleting an application collects its attachment and leaves the reserved claim alone. The vminstance Test drives the two datapath modes against cozy-proxy as deployed: `PortList` publishes one port, `WholeIP` publishes every port, and a second whole-IP attachment on the same VM is refused with `BackendAlreadyDelegated` while the first keeps serving. The cozyplane VPC path lives in its own parked suite, `hack/e2e-chainsaw/endpointattachment-vpc/`, because no e2e lane installs that networking variant. + +Every attachment draws its address through the address substrate (`IPAddressClaim` / `IPAddressClass` / `IPAddress` under `local.sdn.cozystack.io`, community #35), whose packages, `cozystack.address-controller` and `cozystack.metallb-iad`, are optional. The e2e install enables both (`hack/e2e-platform-packages.sh`), and a selected run keeps them only when this suite is selected, since it is the only suite that needs them: `hack/select-install.sh` maps the suite to both packages and `hack/select-e2e.sh` maps both back to it, so a change to either selects this suite. Whenever metallb-iad is installed, `hack/e2e-post-install-prep.sh` creates the default `IPAddressClass` `sandbox` on a MetalLB pool of its own that does not auto-assign, `192.168.123.190-199`, announced on the sandbox bridge. The applications and cozy-proxy are the suite's runtime requirements in `hack/select-install.sh`, so a change to one of them does not select it. + +## Preconditions + +- The applications the fixtures create and their operators: `Postgres` (`cozystack.postgres-application`, with the CloudNativePG operator of `cozystack.postgres-operator`), and `VMDisk` and `VMInstance` (`cozystack.vm-disk-application` and `cozystack.vm-instance-application`, with KubeVirt and CDI). The engine that ships the controller, `cozystack.cozystack-engine`, and the `tenant-test` namespace as configured in `hack/e2e-chainsaw/.chainsaw.yaml`. +- The `cozystack.address-controller` and `cozystack.metallb-iad` packages enabled through `bundles.enabledPackages`, with one `IPAddressClass` annotated as the default whose pool is routable from the machine running Chainsaw; the sandbox gets both as described above. The VM reachability probes dial the attached addresses from that machine; the database probes dial them from pods in the tenant namespace. +- cozy-proxy deployed and the platform declaring it: the vminstance Test needs `cozystackController.endpointAttachments.cozyProxyContractImplemented: true` on the cozystack-controller, which the platform's system bundle sets wherever it emits the cozy-proxy Package: on the full variants unless disabled, and on the slim ones when opted in. +- `nc` and `kubectl` on the machine running Chainsaw. The database probes run `psql` inside the application pods. + +## Scope note on the VM Test + +The design's original VM scenario attached a second address in `PortList` mode to a VM whose chart Service was already `external: true` and expected both addresses reachable. That cannot pass against current cozy-proxy: its rule installer keeps one 1:1 slot per pod in both modes and a second delegated Service on the same pod evicts the first from both the ingress and the egress map, so the two reconcile loops flap over the slot. The Test therefore keeps the VM's chart Service internal and lets the attachment be the only delegated Service on the pod, which is also what the controller's `BackendAlreadyDelegated` refusal enforces from its side. Widening to several addresses per pod waits on a datapath that keeps only the egress half exclusive. + +## Running + +```sh +chainsaw test --config hack/e2e-chainsaw/.chainsaw.yaml \ + --set-string storageClass= hack/e2e-chainsaw/endpointattachment +``` + +`storageClass` is the StorageClass the VM disk imports into, as `make test-chainsaw` passes it to every suite. In CI, `make test-chainsaw CHAINSAW_SUITES=endpointattachment` runs it. + +## Cleanup + +Chainsaw deletes the Postgres, VMDisk, VMInstance, IPAddressClaim and EndpointAttachment objects it applied. The rendered Services and minted claims are owned by their attachments and go with them. The sandbox class reclaims with `Delete`, so each address returns to the pool when its claim goes. Under the default `Retain` reclaim policy instead, every `IPAddress` the suite used is left `Released` once its claim is deleted: the one behind the reserved claim, and the ones behind the claims the attachments minted. Unless the `IPAddressClass` sets `releaseDelay`, each stays unusable until an admin clears its `claimRef`, so repeated runs drain the pool; with `releaseDelay` set, each returns to `Available` once the delay has passed. diff --git a/hack/e2e-chainsaw/endpointattachment/attach-a-names-b-rw.yaml b/hack/e2e-chainsaw/endpointattachment/attach-a-names-b-rw.yaml new file mode 100644 index 000000000..c5342c770 --- /dev/null +++ b/hack/e2e-chainsaw/endpointattachment/attach-a-names-b-rw.yaml @@ -0,0 +1,11 @@ +apiVersion: local.sdn.cozystack.io/v1alpha1 +kind: EndpointAttachment +metadata: + name: ea-a-names-b +spec: + applicationRef: + kind: Postgres + name: ea-a + endpoint: + serviceName: postgres-ea-b-rw + loadBalancer: {} diff --git a/hack/e2e-chainsaw/endpointattachment/attach-a-ro-minted.yaml b/hack/e2e-chainsaw/endpointattachment/attach-a-ro-minted.yaml new file mode 100644 index 000000000..98443f79f --- /dev/null +++ b/hack/e2e-chainsaw/endpointattachment/attach-a-ro-minted.yaml @@ -0,0 +1,13 @@ +# Mints a claim from the default IPAddressClass and publishes the read +# replicas of ea-a on it. The claim is owned by the attachment and goes with it. +apiVersion: local.sdn.cozystack.io/v1alpha1 +kind: EndpointAttachment +metadata: + name: ea-a-ro +spec: + applicationRef: + kind: Postgres + name: ea-a + endpoint: + serviceName: postgres-ea-a-ro + loadBalancer: {} diff --git a/hack/e2e-chainsaw/endpointattachment/attach-a-rw-held.yaml b/hack/e2e-chainsaw/endpointattachment/attach-a-rw-held.yaml new file mode 100644 index 000000000..fb5ef79fa --- /dev/null +++ b/hack/e2e-chainsaw/endpointattachment/attach-a-rw-held.yaml @@ -0,0 +1,12 @@ +apiVersion: local.sdn.cozystack.io/v1alpha1 +kind: EndpointAttachment +metadata: + name: ea-a-rw-held +spec: + applicationRef: + kind: Postgres + name: ea-a + endpoint: + serviceName: postgres-ea-a-rw + loadBalancer: + claimName: ea-held diff --git a/hack/e2e-chainsaw/endpointattachment/attach-b-rw-held.yaml b/hack/e2e-chainsaw/endpointattachment/attach-b-rw-held.yaml new file mode 100644 index 000000000..4cffc5b3a --- /dev/null +++ b/hack/e2e-chainsaw/endpointattachment/attach-b-rw-held.yaml @@ -0,0 +1,12 @@ +apiVersion: local.sdn.cozystack.io/v1alpha1 +kind: EndpointAttachment +metadata: + name: ea-b-rw-held +spec: + applicationRef: + kind: Postgres + name: ea-b + endpoint: + serviceName: postgres-ea-b-rw + loadBalancer: + claimName: ea-held diff --git a/hack/e2e-chainsaw/endpointattachment/attach-vm-portlist.yaml b/hack/e2e-chainsaw/endpointattachment/attach-vm-portlist.yaml new file mode 100644 index 000000000..c4c808c7b --- /dev/null +++ b/hack/e2e-chainsaw/endpointattachment/attach-vm-portlist.yaml @@ -0,0 +1,13 @@ +apiVersion: local.sdn.cozystack.io/v1alpha1 +kind: EndpointAttachment +metadata: + name: ea-vm-ssh +spec: + applicationRef: + kind: VMInstance + name: ea-vm + endpoint: + serviceName: vm-instance-ea-vm + loadBalancer: + method: PortList + ports: [22] diff --git a/hack/e2e-chainsaw/endpointattachment/attach-vm-wholeip-second.yaml b/hack/e2e-chainsaw/endpointattachment/attach-vm-wholeip-second.yaml new file mode 100644 index 000000000..0f188afd2 --- /dev/null +++ b/hack/e2e-chainsaw/endpointattachment/attach-vm-wholeip-second.yaml @@ -0,0 +1,12 @@ +apiVersion: local.sdn.cozystack.io/v1alpha1 +kind: EndpointAttachment +metadata: + name: ea-vm-wholeip-second +spec: + applicationRef: + kind: VMInstance + name: ea-vm + endpoint: + serviceName: vm-instance-ea-vm + loadBalancer: + method: WholeIP diff --git a/hack/e2e-chainsaw/endpointattachment/attach-vm-wholeip.yaml b/hack/e2e-chainsaw/endpointattachment/attach-vm-wholeip.yaml new file mode 100644 index 000000000..d8b30fdcb --- /dev/null +++ b/hack/e2e-chainsaw/endpointattachment/attach-vm-wholeip.yaml @@ -0,0 +1,12 @@ +apiVersion: local.sdn.cozystack.io/v1alpha1 +kind: EndpointAttachment +metadata: + name: ea-vm-wholeip +spec: + applicationRef: + kind: VMInstance + name: ea-vm + endpoint: + serviceName: vm-instance-ea-vm + loadBalancer: + method: WholeIP diff --git a/hack/e2e-chainsaw/endpointattachment/chainsaw-test.yaml b/hack/e2e-chainsaw/endpointattachment/chainsaw-test.yaml new file mode 100644 index 000000000..772ef6e65 --- /dev/null +++ b/hack/e2e-chainsaw/endpointattachment/chainsaw-test.yaml @@ -0,0 +1,499 @@ +# EndpointAttachment e2e. Every address comes from the address substrate +# (address-controller, the metallb-iad driver and a default IPAddressClass), +# which the sandbox installs whenever this suite is selected; see README.md. +# kubectl calls name the substrate kinds with their group: Cluster API IPAM +# serves an IPAddressClaim kind too, and the bare name resolves to it. +# +# The first Test is the proposal's contract in one sequence: an address minted +# with an attachment dies with it, a reserved address survives every +# attachment, and the same reserved address moves to a different application. +# Every assertion is on behaviour (phase, addresses, what the address serves); +# nothing greps rendered manifests for implementation strings. +apiVersion: chainsaw.kyverno.io/v1alpha1 +kind: Test +metadata: + name: endpointattachment-postgres +spec: + catch: + - events: {} + - describe: + apiVersion: local.sdn.cozystack.io/v1alpha1 + kind: EndpointAttachment + - describe: + apiVersion: local.sdn.cozystack.io/v1alpha1 + kind: IPAddressClaim + - get: + apiVersion: v1 + kind: Service + steps: + - name: create-postgres + try: + - apply: + file: postgres-a.yaml + - apply: + file: postgres-b.yaml + - assert: + timeout: 6m + resource: + apiVersion: helm.toolkit.fluxcd.io/v2 + kind: HelmRelease + metadata: + name: postgres-ea-a + status: + (conditions[?type == 'Ready']): + - status: "True" + - assert: + timeout: 6m + resource: + apiVersion: helm.toolkit.fluxcd.io/v2 + kind: HelmRelease + metadata: + name: postgres-ea-b + status: + (conditions[?type == 'Ready']): + - status: "True" + - assert: + timeout: 3m + resource: + apiVersion: v1 + kind: Endpoints + metadata: + name: postgres-ea-a-ro + (subsets[0].addresses[0].ip != null): true + - assert: + timeout: 3m + resource: + apiVersion: v1 + kind: Endpoints + metadata: + name: postgres-ea-b-rw + (subsets[0].addresses[0].ip != null): true + + # Lineage: ea-b's primary is tenant-facing, but not ea-a's, so an attachment + # naming ea-a is refused and renders nothing. + - name: refuse-other-applications-endpoint + try: + - apply: + file: attach-a-names-b-rw.yaml + - assert: + timeout: 1m + resource: + apiVersion: local.sdn.cozystack.io/v1alpha1 + kind: EndpointAttachment + metadata: + name: ea-a-names-b + status: + phase: Pending + (conditions[?type == 'Resolved']): + - status: "False" + reason: EndpointLineageMismatch + - error: + resource: + apiVersion: v1 + kind: Service + metadata: + labels: + cozystack.io/endpoint-attachment: ea-a-names-b + - delete: + ref: + apiVersion: local.sdn.cozystack.io/v1alpha1 + kind: EndpointAttachment + name: ea-a-names-b + + # Minted address: the read replicas of ea-a get an address from the default + # class, and the address serves a replica. + - name: attach-replicas-minted + try: + - apply: + file: attach-a-ro-minted.yaml + - assert: + timeout: 4m + resource: + apiVersion: local.sdn.cozystack.io/v1alpha1 + kind: EndpointAttachment + metadata: + name: ea-a-ro + labels: + apps.cozystack.io/application.kind: Postgres + apps.cozystack.io/application.name: ea-a + status: + phase: Attached + (addresses[0] != null): true + (claimName != null): true + - script: + timeout: 2m + content: | + set -eu + ip=$(kubectl -n "$NAMESPACE" get endpointattachments.local.sdn.cozystack.io ea-a-ro -o jsonpath='{.status.addresses[0]}') + pod=$(kubectl -n "$NAMESPACE" get pod -l cnpg.io/cluster=postgres-ea-a,cnpg.io/instanceRole=primary -o name | head -n1) + # The chart generates each user's password into its credentials Secret. + pw=$(kubectl get secret postgres-ea-a-credentials --namespace "$NAMESPACE" --output jsonpath='{.data.testuser}' | base64 -d) + # The attached address must answer as a replica, not as the primary + # the pod itself is: "t" from pg_is_in_recovery() proves the + # -ro selector was mirrored, not the -rw one. + kubectl -n "$NAMESPACE" exec "$pod" -c postgres -- \ + env PGPASSWORD="$pw" psql -h "$ip" -U testuser -d testdb -tAc 'SELECT pg_is_in_recovery()' + check: + ($error == null): true + (trim_space($stdout)): "t" + + # Deleting the attachment collects its Service and its minted claim. The + # claim's name is generated, so it is read in the same step that deletes + # the attachment rather than handed over through a file another run could + # overwrite. + # TODO(e2e-replace-fixed-timeouts): model "owned claim collected" declaratively once the name can be templated. + - name: detach-minted + try: + - script: + timeout: 3m + content: | + set -eu + claim=$(kubectl get endpointattachments.local.sdn.cozystack.io ea-a-ro --namespace "$NAMESPACE" --output jsonpath='{.status.claimName}') + test -n "$claim" + kubectl delete endpointattachments.local.sdn.cozystack.io ea-a-ro --namespace "$NAMESPACE" --wait=true + # Done only when a lookup succeeds and finds nothing: a failed + # lookup is not evidence the claim is gone, so it keeps polling. + until found=$(kubectl get ipaddressclaims.local.sdn.cozystack.io "$claim" --namespace "$NAMESPACE" --ignore-not-found --output name) && [ -z "$found" ]; do sleep 2; done + check: + ($error == null): true + - error: + timeout: 2m + resource: + apiVersion: v1 + kind: Service + metadata: + labels: + cozystack.io/endpoint-attachment: ea-a-ro + + # Reserved address: held before any attachment. + - name: reserve-address + try: + - apply: + file: claim-held.yaml + - assert: + timeout: 2m + resource: + apiVersion: local.sdn.cozystack.io/v1alpha1 + kind: IPAddressClaim + metadata: + name: ea-held + status: + phase: Bound + (addresses[0].address != null): true + # The address is recorded on the claim itself, so that later steps can + # prove it never changed without state outside the cluster. + - script: + content: | + set -eu + ip=$(kubectl get ipaddressclaims.local.sdn.cozystack.io ea-held --namespace "$NAMESPACE" --output jsonpath='{.status.addresses[0].address}') + test -n "$ip" + kubectl annotate ipaddressclaims.local.sdn.cozystack.io ea-held --namespace "$NAMESPACE" --overwrite "e2e.cozystack.io/reserved-address=$ip" + check: + ($error == null): true + + # Hold: the primary of ea-a on the reserved address. + - name: attach-primary-held + try: + - apply: + file: attach-a-rw-held.yaml + - assert: + timeout: 4m + resource: + apiVersion: local.sdn.cozystack.io/v1alpha1 + kind: EndpointAttachment + metadata: + name: ea-a-rw-held + status: + phase: Attached + claimName: ea-held + - script: + timeout: 2m + content: | + set -eu + ip=$(kubectl get ipaddressclaims.local.sdn.cozystack.io ea-held --namespace "$NAMESPACE" --output jsonpath='{.metadata.annotations.e2e\.cozystack\.io/reserved-address}') + test -n "$ip" + got=$(kubectl -n "$NAMESPACE" get endpointattachments.local.sdn.cozystack.io ea-a-rw-held -o jsonpath='{.status.addresses[0]}') + [ "$got" = "$ip" ] + pod=$(kubectl -n "$NAMESPACE" get pod -l cnpg.io/cluster=postgres-ea-b -o name | head -n1) + # Probe from ea-b's pod so the answer cannot come from the local + # instance: the reserved address must reach ea-a's primary. + pw=$(kubectl get secret postgres-ea-a-credentials --namespace "$NAMESPACE" --output jsonpath='{.data.testuser}' | base64 -d) + kubectl -n "$NAMESPACE" exec "$pod" -c postgres -- \ + env PGPASSWORD="$pw" psql -h "$ip" -U testuser -d testdb -tAc "SELECT current_setting('cluster_name') || ' ' || pg_is_in_recovery()" + check: + ($error == null): true + (trim_space($stdout)): "postgres-ea-a false" + + # Detach: the reserved claim still holds the same address, nothing serves it. + - name: detach-held + try: + - delete: + ref: + apiVersion: local.sdn.cozystack.io/v1alpha1 + kind: EndpointAttachment + name: ea-a-rw-held + - assert: + timeout: 1m + resource: + apiVersion: local.sdn.cozystack.io/v1alpha1 + kind: IPAddressClaim + metadata: + name: ea-held + (ownerReferences == null): true + status: + phase: Bound + - script: + timeout: 2m + content: | + set -eu + ip=$(kubectl get ipaddressclaims.local.sdn.cozystack.io ea-held --namespace "$NAMESPACE" --output jsonpath='{.metadata.annotations.e2e\.cozystack\.io/reserved-address}') + test -n "$ip" + got=$(kubectl -n "$NAMESPACE" get ipaddressclaims.local.sdn.cozystack.io ea-held -o jsonpath='{.status.addresses[0].address}') + [ "$got" = "$ip" ] + check: + ($error == null): true + - error: + timeout: 2m + resource: + apiVersion: v1 + kind: Service + metadata: + labels: + cozystack.io/endpoint-attachment: ea-a-rw-held + + # Move: the same reserved address now serves a different application. + - name: reattach-held-to-other-application + try: + - apply: + file: attach-b-rw-held.yaml + - assert: + timeout: 4m + resource: + apiVersion: local.sdn.cozystack.io/v1alpha1 + kind: EndpointAttachment + metadata: + name: ea-b-rw-held + status: + phase: Attached + claimName: ea-held + - script: + timeout: 2m + content: | + set -eu + ip=$(kubectl get ipaddressclaims.local.sdn.cozystack.io ea-held --namespace "$NAMESPACE" --output jsonpath='{.metadata.annotations.e2e\.cozystack\.io/reserved-address}') + test -n "$ip" + got=$(kubectl -n "$NAMESPACE" get endpointattachments.local.sdn.cozystack.io ea-b-rw-held -o jsonpath='{.status.addresses[0]}') + [ "$got" = "$ip" ] + pod=$(kubectl -n "$NAMESPACE" get pod -l cnpg.io/cluster=postgres-ea-a,cnpg.io/instanceRole=primary -o name | head -n1) + pw=$(kubectl get secret postgres-ea-b-credentials --namespace "$NAMESPACE" --output jsonpath='{.data.testuser}' | base64 -d) + kubectl -n "$NAMESPACE" exec "$pod" -c postgres -- \ + env PGPASSWORD="$pw" psql -h "$ip" -U testuser -d testdb -tAc "SELECT current_setting('cluster_name') || ' ' || pg_is_in_recovery()" + check: + ($error == null): true + (trim_space($stdout)): "postgres-ea-b false" + + # GC: deleting the application collects its attachment; the reserved claim + # is untouched. + - name: delete-application-collects-attachment + try: + - delete: + ref: + apiVersion: apps.cozystack.io/v1alpha1 + kind: Postgres + name: ea-b + - error: + timeout: 5m + resource: + apiVersion: local.sdn.cozystack.io/v1alpha1 + kind: EndpointAttachment + metadata: + name: ea-b-rw-held + - assert: + resource: + apiVersion: local.sdn.cozystack.io/v1alpha1 + kind: IPAddressClaim + metadata: + name: ea-held + status: + phase: Bound +--- +# The VM datapath modes against cozy-proxy as deployed. The VM keeps +# external: false, so the attachment is the only delegated Service on its pod: +# current cozy-proxy holds one 1:1 slot per pod in both modes, and a chart +# Service beside an attachment would steal it (see README.md). +apiVersion: chainsaw.kyverno.io/v1alpha1 +kind: Test +metadata: + name: endpointattachment-vminstance +spec: + catch: + - events: {} + - describe: + apiVersion: local.sdn.cozystack.io/v1alpha1 + kind: EndpointAttachment + - describe: + apiVersion: kubevirt.io/v1 + kind: VirtualMachineInstance + name: vm-instance-ea-vm + - get: + apiVersion: v1 + kind: Service + steps: + - name: create-vm + try: + - apply: + file: vmdisk.yaml + - assert: + timeout: 6m + resource: + apiVersion: helm.toolkit.fluxcd.io/v2 + kind: HelmRelease + metadata: + name: vm-disk-ea-vm + status: + (conditions[?type == 'Ready']): + - status: "True" + - assert: + timeout: 5m + resource: + apiVersion: cdi.kubevirt.io/v1beta1 + kind: DataVolume + metadata: + name: vm-disk-ea-vm + status: + (conditions[?type == 'Ready']): + - status: "True" + - apply: + file: vminstance.yaml + - assert: + timeout: 6m + resource: + apiVersion: helm.toolkit.fluxcd.io/v2 + kind: HelmRelease + metadata: + name: vm-instance-ea-vm + status: + (conditions[?type == 'Ready']): + - status: "True" + - assert: + timeout: 5m + resource: + apiVersion: kubevirt.io/v1 + kind: VirtualMachine + metadata: + name: vm-instance-ea-vm + status: + (conditions[?type == 'Ready']): + - status: "True" + + # PortList: one listed port reachable on the attached address. + - name: attach-portlist + try: + - apply: + file: attach-vm-portlist.yaml + - assert: + timeout: 4m + resource: + apiVersion: local.sdn.cozystack.io/v1alpha1 + kind: EndpointAttachment + metadata: + name: ea-vm-ssh + status: + phase: Attached + (addresses[0] != null): true + - script: + timeout: 3m + content: | + set -eu + ip=$(kubectl -n "$NAMESPACE" get endpointattachments.local.sdn.cozystack.io ea-vm-ssh -o jsonpath='{.status.addresses[0]}') + # sshd inside the guest comes up after cloud-init; no condition + # models "the guest listens", so the port is polled. + # TODO(e2e-replace-fixed-timeouts): replace with a guest-readiness signal if KubeVirt grows one. + for _ in $(seq 1 60); do + if nc -z -w 3 "$ip" 22; then exit 0; fi + sleep 3 + done + echo "port 22 on $ip never answered" >&2 + exit 1 + check: + ($error == null): true + - delete: + ref: + apiVersion: local.sdn.cozystack.io/v1alpha1 + kind: EndpointAttachment + name: ea-vm-ssh + - error: + timeout: 2m + resource: + apiVersion: v1 + kind: Service + metadata: + labels: + cozystack.io/endpoint-attachment: ea-vm-ssh + + # WholeIP: every port reachable, then a second whole-IP attachment on the + # same VM is refused with its own reason and the first keeps serving. + - name: attach-wholeip + try: + - apply: + file: attach-vm-wholeip.yaml + - assert: + timeout: 4m + resource: + apiVersion: local.sdn.cozystack.io/v1alpha1 + kind: EndpointAttachment + metadata: + name: ea-vm-wholeip + status: + phase: Attached + (addresses[0] != null): true + - script: + timeout: 3m + content: | + set -eu + ip=$(kubectl -n "$NAMESPACE" get endpointattachments.local.sdn.cozystack.io ea-vm-wholeip -o jsonpath='{.status.addresses[0]}') + # TODO(e2e-replace-fixed-timeouts): same guest-listens wait as above. + for _ in $(seq 1 60); do + if nc -z -w 3 "$ip" 22; then exit 0; fi + sleep 3 + done + echo "port 22 on $ip never answered through the whole-IP mapping" >&2 + exit 1 + check: + ($error == null): true + - apply: + file: attach-vm-wholeip-second.yaml + - assert: + timeout: 2m + resource: + apiVersion: local.sdn.cozystack.io/v1alpha1 + kind: EndpointAttachment + metadata: + name: ea-vm-wholeip-second + status: + phase: Pending + (conditions[?type == 'Resolved']): + - status: "True" + (conditions[?type == 'Provisioned']): + - status: "False" + reason: BackendAlreadyDelegated + - assert: + resource: + apiVersion: local.sdn.cozystack.io/v1alpha1 + kind: EndpointAttachment + metadata: + name: ea-vm-wholeip + status: + phase: Attached + - script: + timeout: 1m + content: | + set -eu + # Assigned on its own line so that a failed lookup fails the step + # instead of reading as an empty list. + svcs=$(kubectl get service --namespace "$NAMESPACE" --selector cozystack.io/endpoint-attachment=ea-vm-wholeip-second --output name) + [ -z "$svcs" ] + ip=$(kubectl -n "$NAMESPACE" get endpointattachments.local.sdn.cozystack.io ea-vm-wholeip -o jsonpath='{.status.addresses[0]}') + nc -z -w 3 "$ip" 22 + check: + ($error == null): true diff --git a/hack/e2e-chainsaw/endpointattachment/claim-held.yaml b/hack/e2e-chainsaw/endpointattachment/claim-held.yaml new file mode 100644 index 000000000..aa480b231 --- /dev/null +++ b/hack/e2e-chainsaw/endpointattachment/claim-held.yaml @@ -0,0 +1,6 @@ +# A reserved address: created before any attachment, outlives every one. +apiVersion: local.sdn.cozystack.io/v1alpha1 +kind: IPAddressClaim +metadata: + name: ea-held +spec: {} diff --git a/hack/e2e-chainsaw/endpointattachment/postgres-a.yaml b/hack/e2e-chainsaw/endpointattachment/postgres-a.yaml new file mode 100644 index 000000000..30a8862af --- /dev/null +++ b/hack/e2e-chainsaw/endpointattachment/postgres-a.yaml @@ -0,0 +1,23 @@ +apiVersion: apps.cozystack.io/v1alpha1 +kind: Postgres +metadata: + name: ea-a +spec: + external: false + size: 10Gi + replicas: 2 + storageClass: "" + quorum: + minSyncReplicas: 0 + maxSyncReplicas: 0 + users: + testuser: {} + databases: + testdb: + roles: + admin: + - testuser + backup: + enabled: false + resources: {} + resourcesPreset: "nano" diff --git a/hack/e2e-chainsaw/endpointattachment/postgres-b.yaml b/hack/e2e-chainsaw/endpointattachment/postgres-b.yaml new file mode 100644 index 000000000..c5830298e --- /dev/null +++ b/hack/e2e-chainsaw/endpointattachment/postgres-b.yaml @@ -0,0 +1,23 @@ +apiVersion: apps.cozystack.io/v1alpha1 +kind: Postgres +metadata: + name: ea-b +spec: + external: false + size: 10Gi + replicas: 1 + storageClass: "" + quorum: + minSyncReplicas: 0 + maxSyncReplicas: 0 + users: + testuser: {} + databases: + testdb: + roles: + admin: + - testuser + backup: + enabled: false + resources: {} + resourcesPreset: "nano" diff --git a/hack/e2e-chainsaw/endpointattachment/vmdisk.yaml b/hack/e2e-chainsaw/endpointattachment/vmdisk.yaml new file mode 100644 index 000000000..1749c67b5 --- /dev/null +++ b/hack/e2e-chainsaw/endpointattachment/vmdisk.yaml @@ -0,0 +1,11 @@ +apiVersion: apps.cozystack.io/v1alpha1 +kind: VMDisk +metadata: + name: ea-vm +spec: + source: + http: + url: https://cloud-images.ubuntu.com/noble/current/noble-server-cloudimg-amd64.img + optical: false + storage: 5Gi + storageClass: ($values.storageClass) diff --git a/hack/e2e-chainsaw/endpointattachment/vminstance.yaml b/hack/e2e-chainsaw/endpointattachment/vminstance.yaml new file mode 100644 index 000000000..4e2310594 --- /dev/null +++ b/hack/e2e-chainsaw/endpointattachment/vminstance.yaml @@ -0,0 +1,28 @@ +# external stays false: the attachment is the only external Service on this +# VM. Current cozy-proxy holds one 1:1 slot per pod, so a chart-rendered +# external Service beside an attachment would steal it back and forth. +apiVersion: apps.cozystack.io/v1alpha1 +kind: VMInstance +metadata: + name: ea-vm +spec: + external: false + running: true + instanceType: "u1.medium" + instanceProfile: ubuntu + disks: + - name: ea-vm + gpus: [] + sshKeys: + - ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPht0dPk5qQ+54g1hSX7A6AUxXJW5T6n/3d7Ga2F8gTF + test@test + cloudInit: | + #cloud-config + users: + - name: test + shell: /bin/bash + sudo: ['ALL=(ALL) NOPASSWD: ALL'] + groups: sudo + ssh_authorized_keys: + - ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPht0dPk5qQ+54g1hSX7A6AUxXJW5T6n/3d7Ga2F8gTF test@test + cloudInitSeed: "" diff --git a/hack/e2e-platform-packages.sh b/hack/e2e-platform-packages.sh index 06a9f16db..5fe18739d 100755 --- a/hack/e2e-platform-packages.sh +++ b/hack/e2e-platform-packages.sh @@ -76,6 +76,8 @@ spec: bundles: enabledPackages: - cozystack.external-dns-application + - cozystack.address-controller + - cozystack.metallb-iad EOF if [ -n "$disabled" ]; then diff --git a/hack/e2e-post-install-prep.sh b/hack/e2e-post-install-prep.sh index 34f50f8ac..359f5cf75 100755 --- a/hack/e2e-post-install-prep.sh +++ b/hack/e2e-post-install-prep.sh @@ -370,4 +370,53 @@ spec: avoidBuggyIPs: false EOF +# The address substrate is installed only for the suites that draw addresses +# from it (hack/select-install.sh), and metallb-iad pulls address-controller in +# with it. Its class must name a pool MetalLB never assigns from on its own, so +# that pool is kept apart from the auto-assigning one above. +case " ${COZY_DISABLED_PACKAGES:-} " in + *" cozystack.metallb-iad "*) ;; + *) + if ! wait_for_object 600 "IPAddressClass CRD" crd ipaddressclasses.local.sdn.cozystack.io; then + for ns in cozy-address-controller cozy-metallb-iad; do + timeout -k 5 30 kubectl get hr -n "$ns" --request-timeout=10s 2>&1 | tail -n 30 >&2 + done + exit 1 + fi + echo "[post-install-prep] applying the default IPAddressClass and its MetalLB pool" + $KUBECTL_BOUND kubectl apply --request-timeout=60s -f - <<'EOF' +--- +apiVersion: metallb.io/v1beta1 +kind: IPAddressPool +metadata: + name: address-substrate + namespace: cozy-metallb +spec: + addresses: [192.168.123.190-192.168.123.199] + autoAssign: false + avoidBuggyIPs: false +--- +apiVersion: metallb.io/v1beta1 +kind: L2Advertisement +metadata: + name: address-substrate + namespace: cozy-metallb +spec: + ipAddressPools: [address-substrate] +--- +apiVersion: local.sdn.cozystack.io/v1alpha1 +kind: IPAddressClass +metadata: + name: sandbox + annotations: + ipaddressclass.local.sdn.cozystack.io/is-default-class: "true" +spec: + provisioner: metallb.drivers.local.sdn.cozystack.io + reclaimPolicy: Delete + parameters: + pool: address-substrate +EOF + ;; +esac + echo "[post-install-prep] done" diff --git a/hack/e2e-tenant-super-admin-write-verbs.yaml b/hack/e2e-tenant-super-admin-write-verbs.yaml index c700fa62b..5675e99d7 100644 --- a/hack/e2e-tenant-super-admin-write-verbs.yaml +++ b/hack/e2e-tenant-super-admin-write-verbs.yaml @@ -15,8 +15,16 @@ writeVerbs: - "backupjobs.backups.cozystack.io - update" - "credentials.core.cozystack.io/mint - create" - "credentials.core.cozystack.io/revoke - create" +- "endpointattachments.local.sdn.cozystack.io - create" +- "endpointattachments.local.sdn.cozystack.io - delete" +- "endpointattachments.local.sdn.cozystack.io - patch" +- "endpointattachments.local.sdn.cozystack.io - update" - "endpoints - delete" - "events - delete" +- "ipaddressclaims.local.sdn.cozystack.io - create" +- "ipaddressclaims.local.sdn.cozystack.io - delete" +- "ipaddressclaims.local.sdn.cozystack.io - patch" +- "ipaddressclaims.local.sdn.cozystack.io - update" - "persistentvolumes - delete" - "plans.backups.cozystack.io - create" - "plans.backups.cozystack.io - delete" diff --git a/hack/select-e2e.sh b/hack/select-e2e.sh index 59db4fe25..871053d84 100755 --- a/hack/select-e2e.sh +++ b/hack/select-e2e.sh @@ -270,6 +270,9 @@ src_to_suites() { # create KubernetesNodes natively. kubernetes-nodes-application) echo "kubernetes-latest kubernetes-previous computeplane" ;; securitygroup-controller) echo securitygroup ;; + # endpointattachment is the only suite that installs the address + # substrate, so it is the one that covers both packages. + address-controller|metallb-iad) echo endpointattachment ;; # The kafka app source covers both the app suite and the metadata-backup # roundtrip, so an edit to packages/apps/kafka (or kafka-operator, which # reaches this source) selects both. diff --git a/hack/select-install.sh b/hack/select-install.sh index 15acf8aca..1f3f5a19a 100755 --- a/hack/select-install.sh +++ b/hack/select-install.sh @@ -128,6 +128,9 @@ suite_to_source() { echo "cozystack.vm-instance-application cozystack.vm-disk-application" return ;; securitygroup) echo cozystack.securitygroup-controller ; return ;; + # The address substrate is what this suite draws every address from, and + # no other suite installs it. + endpointattachment) echo "cozystack.address-controller cozystack.metallb-iad" ; return ;; kafka-metadata) echo cozystack.kafka-application ; return ;; esac for cand in "cozystack.$1-application" "cozystack.$1"; do @@ -144,6 +147,8 @@ suite_runtime_sources() { clickhouse|etcd|kafka|kafka-metadata|mariadb|mongodb|postgres|rabbitmq|redis|valkey|vminstance) echo cozystack.backupstrategy-controller ;; gateway) echo cozystack.kubeovn-webhook ;; + endpointattachment) + echo "cozystack.postgres-application cozystack.vm-instance-application cozystack.vm-disk-application cozystack.cozy-proxy" ;; esac } diff --git a/hack/update-codegen.sh b/hack/update-codegen.sh index 95fcee632..06385f6e9 100755 --- a/hack/update-codegen.sh +++ b/hack/update-codegen.sh @@ -92,7 +92,7 @@ kube::codegen::gen_client \ "${SCRIPT_ROOT}/pkg/apis" $CONTROLLER_GEN object:headerFile="hack/boilerplate.go.txt" paths="./api/..." -$CONTROLLER_GEN rbac:roleName=manager-role crd paths="./api/v1alpha1/..." paths="./api/backups/..." paths="./api/gateway/..." paths="./api/internalapi/..." paths="./api/migration/..." output:crd:artifacts:config=${TMPDIR} +$CONTROLLER_GEN rbac:roleName=manager-role crd paths="./api/v1alpha1/..." paths="./api/backups/..." paths="./api/gateway/..." paths="./api/internalapi/..." paths="./api/localsdn/..." paths="./api/migration/..." output:crd:artifacts:config=${TMPDIR} mv ${TMPDIR}/cozystack.io_packages.yaml ${OPERATOR_CRDDIR}/cozystack.io_packages.yaml mv ${TMPDIR}/cozystack.io_packagesources.yaml ${OPERATOR_CRDDIR}/cozystack.io_packagesources.yaml diff --git a/internal/controller/endpointattachment/crdcel_test.go b/internal/controller/endpointattachment/crdcel_test.go new file mode 100644 index 000000000..304b3c0d6 --- /dev/null +++ b/internal/controller/endpointattachment/crdcel_test.go @@ -0,0 +1,290 @@ +/* +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 endpointattachment + +import ( + "context" + "os" + "testing" + + apiextensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + apiextvalidation "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation" + "k8s.io/apiextensions-apiserver/pkg/apiserver/schema" + schemacel "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel" + "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/listtype" + apiservervalidation "k8s.io/apiextensions-apiserver/pkg/apiserver/validation" + "k8s.io/apimachinery/pkg/util/validation/field" + celconfig "k8s.io/apiserver/pkg/apis/cel" + "sigs.k8s.io/yaml" +) + +// crdPath is the generated CRD the controller ships. The rules under test +// are compiled from the XValidation markers on the API types, so reading +// the generated file is what detects a marker that silently failed to +// generate. +const crdPath = "../../../packages/system/cozystack-controller/definitions/local.sdn.cozystack.io_endpointattachments.yaml" + +type admissionCheck struct { + cel *schemacel.Validator + structural *schema.Structural + schema apiservervalidation.SchemaValidator +} + +// versionSchema returns the v1alpha1 schema of the shipped CRD, from the +// resource root. +func versionSchema(t *testing.T) *apiextensionsv1.JSONSchemaProps { + t.Helper() + raw, err := os.ReadFile(crdPath) + if err != nil { + t.Fatalf("read CRD: %v", err) + } + var crd apiextensionsv1.CustomResourceDefinition + if err := yaml.Unmarshal(raw, &crd); err != nil { + t.Fatalf("unmarshal CRD: %v", err) + } + for i := range crd.Spec.Versions { + v := &crd.Spec.Versions[i] + if v.Name == "v1alpha1" && v.Schema != nil && v.Schema.OpenAPIV3Schema != nil { + return v.Schema.OpenAPIV3Schema + } + } + t.Fatal("v1alpha1 schema not found in CRD") + return nil +} + +// specValidator compiles the spec subtree alone, which is enough for the +// rules nested inside it. +func specValidator(t *testing.T) *admissionCheck { + t.Helper() + p, ok := versionSchema(t).Properties["spec"] + if !ok { + t.Fatal("v1alpha1 spec schema not found in CRD") + } + if len(p.XValidations) == 0 { + t.Fatal("spec schema carries no x-kubernetes-validations; the XValidation markers did not generate") + } + return compile(t, &p) +} + +// rootValidator compiles the whole resource, which is what admission +// validates: a rule nested in spec never runs when spec itself is absent. +func rootValidator(t *testing.T) *admissionCheck { + t.Helper() + return compile(t, versionSchema(t)) +} + +func compile(t *testing.T, props *apiextensionsv1.JSONSchemaProps) *admissionCheck { + t.Helper() + var internal apiextensions.JSONSchemaProps + if err := apiextensionsv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(props, &internal, nil); err != nil { + t.Fatalf("convert schema: %v", err) + } + structural, err := schema.NewStructural(&internal) + if err != nil { + t.Fatalf("structural schema: %v", err) + } + schemaValidator, _, err := apiservervalidation.NewSchemaValidator(&internal) + if err != nil { + t.Fatalf("schema validator: %v", err) + } + return &admissionCheck{ + cel: schemacel.NewValidator(structural, true, celconfig.PerCallLimit), + structural: structural, + schema: schemaValidator, + } +} + +// rejects reports whether admission would refuse the object. old is nil for +// a create; on an update the transition rules (oldSelf) run as well. +func (a *admissionCheck) rejects(t *testing.T, obj, old map[string]interface{}) bool { + t.Helper() + if errs := apiservervalidation.ValidateCustomResource(nil, obj, a.schema); len(errs) > 0 { + return true + } + // Uniqueness in a listType=set is a structural check of its own, which + // neither the OpenAPI schema nor CEL performs. + if errs := listtype.ValidateListSetsAndMaps(nil, a.structural, obj); len(errs) > 0 { + return true + } + var oldObj interface{} + if old != nil { + oldObj = old + } + errs, _ := a.cel.Validate(context.TODO(), field.NewPath("root"), a.structural, obj, oldObj, celconfig.RuntimeCELCostBudget) + return len(errs) > 0 +} + +func spec(lb map[string]interface{}) map[string]interface{} { + s := map[string]interface{}{ + "applicationRef": map[string]interface{}{"group": "apps.cozystack.io", "kind": "Postgres", "name": "mydb"}, + "endpoint": map[string]interface{}{"serviceName": "postgres-mydb-ro"}, + } + if lb != nil { + s["loadBalancer"] = lb + } + return s +} + +func TestCreateAdmission(t *testing.T) { + a := specValidator(t) + tests := []struct { + name string + spec map[string]interface{} + wantReject bool + }{ + {name: "minimal member mints from the default class", spec: spec(map[string]interface{}{})}, + {name: "className alone", spec: spec(map[string]interface{}{"className": "public"})}, + {name: "claimName alone", spec: spec(map[string]interface{}{"claimName": "held"})}, + {name: "className and claimName together", spec: spec(map[string]interface{}{"className": "public", "claimName": "held"}), wantReject: true}, + {name: "no mechanism member", spec: spec(nil), wantReject: true}, + {name: "PortList with ports", spec: spec(map[string]interface{}{"method": "PortList", "ports": []interface{}{int64(22)}})}, + {name: "PortList without ports", spec: spec(map[string]interface{}{"method": "PortList"}), wantReject: true}, + {name: "PortList with one port", spec: spec(map[string]interface{}{"method": "PortList", "ports": []interface{}{int64(22)}})}, + {name: "PortList with a duplicate port", spec: spec(map[string]interface{}{"method": "PortList", "ports": []interface{}{int64(22), int64(22)}}), wantReject: true}, + {name: "WholeIP without ports", spec: spec(map[string]interface{}{"method": "WholeIP"})}, + {name: "allowICMP with PortList", spec: spec(map[string]interface{}{"method": "PortList", "ports": []interface{}{int64(22)}, "allowICMP": true})}, + {name: "allowICMP with WholeIP", spec: spec(map[string]interface{}{"method": "WholeIP", "allowICMP": true}), wantReject: true}, + {name: "allowICMP without method", spec: spec(map[string]interface{}{"allowICMP": false}), wantReject: true}, + {name: "unknown method", spec: spec(map[string]interface{}{"method": "Magic"}), wantReject: true}, + {name: "unknown family", spec: spec(map[string]interface{}{"family": "IPv5"}), wantReject: true}, + {name: "port out of range", spec: spec(map[string]interface{}{"ports": []interface{}{int64(70000)}}), wantReject: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := a.rejects(t, tt.spec, nil); got != tt.wantReject { + t.Fatalf("rejects=%v, want %v", got, tt.wantReject) + } + }) + } +} + +// TestUpdateAdmission pins the immutability split: the fields that select +// the address (applicationRef, className, claimName, family, the member +// itself) are frozen, while the render knobs (ports, method, allowICMP and +// the endpoint) stay mutable. +func TestUpdateAdmission(t *testing.T) { + a := specValidator(t) + base := spec(map[string]interface{}{"className": "public", "family": "IPv4", "ports": []interface{}{int64(5432)}}) + mutate := func(f func(s map[string]interface{})) map[string]interface{} { + s := spec(map[string]interface{}{"className": "public", "family": "IPv4", "ports": []interface{}{int64(5432)}}) + f(s) + return s + } + lb := func(s map[string]interface{}) map[string]interface{} { + return s["loadBalancer"].(map[string]interface{}) + } + tests := []struct { + name string + new map[string]interface{} + wantReject bool + }{ + {name: "unchanged", new: mutate(func(map[string]interface{}) {})}, + {name: "applicationRef name changes", new: mutate(func(s map[string]interface{}) { + s["applicationRef"].(map[string]interface{})["name"] = "other" + }), wantReject: true}, + {name: "className changes", new: mutate(func(s map[string]interface{}) { lb(s)["className"] = "partner" }), wantReject: true}, + {name: "className dropped", new: mutate(func(s map[string]interface{}) { delete(lb(s), "className") }), wantReject: true}, + {name: "family changes", new: mutate(func(s map[string]interface{}) { lb(s)["family"] = "IPv6" }), wantReject: true}, + {name: "claimName added beside className", new: mutate(func(s map[string]interface{}) { lb(s)["claimName"] = "held" }), wantReject: true}, + {name: "ports change", new: mutate(func(s map[string]interface{}) { lb(s)["ports"] = []interface{}{int64(5432), int64(9187)} })}, + {name: "ports dropped", new: mutate(func(s map[string]interface{}) { delete(lb(s), "ports") })}, + {name: "endpoint retargets", new: mutate(func(s map[string]interface{}) { + s["endpoint"].(map[string]interface{})["serviceName"] = "postgres-mydb-rw" + })}, + {name: "member removed", new: mutate(func(s map[string]interface{}) { delete(s, "loadBalancer") }), wantReject: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := a.rejects(t, tt.new, base); got != tt.wantReject { + t.Fatalf("rejects=%v, want %v", got, tt.wantReject) + } + }) + } + t.Run("claimName to className switch", func(t *testing.T) { + old := spec(map[string]interface{}{"claimName": "held"}) + if !a.rejects(t, spec(map[string]interface{}{"className": "public"}), old) { + t.Fatal("switching from a referenced claim to a minted one must be refused") + } + }) +} + +// resource wraps a spec the way admission sees the whole object; a nil spec +// leaves the field out. +func resource(spec map[string]interface{}) map[string]interface{} { + obj := map[string]interface{}{ + "apiVersion": "local.sdn.cozystack.io/v1alpha1", + "kind": "EndpointAttachment", + "metadata": map[string]interface{}{"name": "mydb-replicas", "namespace": "tenant-a"}, + } + if spec != nil { + obj["spec"] = spec + } + return obj +} + +// TestWholeResourceAdmission validates from the resource root. Removing spec +// would skip every rule nested inside it, and restoring it would run them +// with no old value, so spec must be refused as absent on create and on +// update, while the render knobs inside it stay mutable. +func TestWholeResourceAdmission(t *testing.T) { + a := rootValidator(t) + held := spec(map[string]interface{}{"claimName": "held", "ports": []interface{}{int64(5432)}}) + tests := []struct { + name string + obj, old map[string]interface{} + wantReject bool + }{ + {name: "create with spec", obj: resource(held)}, + {name: "create without spec", obj: resource(nil), wantReject: true}, + {name: "update removing spec", obj: resource(nil), old: resource(held), wantReject: true}, + {name: "update switching claimName", obj: resource(spec(map[string]interface{}{"claimName": "other", "ports": []interface{}{int64(5432)}})), old: resource(held), wantReject: true}, + {name: "update switching claimName to className", obj: resource(spec(map[string]interface{}{"className": "public", "ports": []interface{}{int64(5432)}})), old: resource(held), wantReject: true}, + {name: "update changing ports", obj: resource(spec(map[string]interface{}{"claimName": "held", "ports": []interface{}{int64(5432), int64(9187)}})), old: resource(held)}, + {name: "update retargeting the endpoint", obj: func() map[string]interface{} { + s := spec(map[string]interface{}{"claimName": "held", "ports": []interface{}{int64(5432)}}) + s["endpoint"] = map[string]interface{}{"serviceName": "postgres-mydb-rw"} + return resource(s) + }(), old: resource(held)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := a.rejects(t, tt.obj, tt.old); got != tt.wantReject { + t.Fatalf("rejects=%v, want %v", got, tt.wantReject) + } + }) + } +} + +func TestCRDPassesInstallTimeValidation(t *testing.T) { + raw, err := os.ReadFile(crdPath) + if err != nil { + t.Fatalf("read CRD: %v", err) + } + var v1crd apiextensionsv1.CustomResourceDefinition + if err := yaml.Unmarshal(raw, &v1crd); err != nil { + t.Fatalf("unmarshal CRD: %v", err) + } + v1crd.Status.StoredVersions = []string{"v1alpha1"} + var internal apiextensions.CustomResourceDefinition + if err := apiextensionsv1.Convert_v1_CustomResourceDefinition_To_apiextensions_CustomResourceDefinition(&v1crd, &internal, nil); err != nil { + t.Fatalf("convert CRD: %v", err) + } + for _, e := range apiextvalidation.ValidateCustomResourceDefinition(context.TODO(), &internal) { + t.Errorf("apiserver would reject this CRD: %v", e) + } +} diff --git a/internal/controller/endpointattachment/floatingip.go b/internal/controller/endpointattachment/floatingip.go new file mode 100644 index 000000000..fd4db886d --- /dev/null +++ b/internal/controller/endpointattachment/floatingip.go @@ -0,0 +1,413 @@ +/* +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 endpointattachment + +import ( + "context" + "fmt" + "sort" + "strings" + + corev1 "k8s.io/api/core/v1" + discoveryv1 "k8s.io/api/discovery/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/localsdn/v1alpha1" +) + +// A VM whose launcher pod cozyplane attaches to a VPC has only its VPC +// address: the pod's own IP, which a cozy-proxy Service would map to, never +// reaches the guest. cozyplane binds a public address to a VPC workload +// through its FloatingIP, which owns its own LoadBalancer Service and wears +// the attachment's claim there. The kind is read as unstructured and used only +// when the cluster serves it, so this controller carries no dependency on +// cozyplane. +const ( + // vpcAnnotation is the pod annotation through which the VM chart asks + // cozyplane for a VPC attachment: "" in the pod's namespace, or + // "/". + vpcAnnotation = "sdn.cozystack.io/vpc" + // vpcIPAnnotation is where cozyplane's CNI copies the pod's VPC address + // once it has attached the pod. + vpcIPAnnotation = "sdn.cozystack.io/vpc-ip" + + floatingIPPhaseReady = "Ready" + + // endpointAnnotation records, on a FloatingIP this controller owns, the + // endpoint Service it was bound for. A stopped VM has no pod to say which + // endpoint a binding serves, so it is read from here. + endpointAnnotation = "cozystack.io/endpoint-attachment-endpoint" +) + +var floatingIPGVK = schema.GroupVersion{Group: "sdn.cozystack.io", Version: "v1alpha1"}.WithKind("FloatingIP") + +func newFloatingIP() *unstructured.Unstructured { + u := &unstructured.Unstructured{} + u.SetGroupVersionKind(floatingIPGVK) + return u +} + +// vpcTarget is the one thing a FloatingIP binds: an address inside a VPC. +type vpcTarget struct { + VPC string + IP string +} + +// vpcBackends describes how an endpoint's backend pods sit in cozyplane VPCs. +type vpcBackends struct { + // InVPC is true when any backend pod asks for a VPC attachment. + InVPC bool + // Pods counts the backend pods considered. + Pods int + // Targets are the distinct VPC addresses the backends hold. A live + // migration's source and target launcher pods share one, because the VM's + // VPC address is pinned to the VM and not to the pod. + Targets []vpcTarget + // Mixed is true when some backends are in a VPC and some are not. + Mixed bool + // Waiting names VPC backends cozyplane has not yet given an address. + Waiting []string + // Foreign names a VPC owned by another namespace, as "/". + Foreign string +} + +// resolveVPCBackends reads the endpoint's backend pods. Not-ready endpoints +// count, so that a booting VM is recognised before its first readiness probe; +// terminating ones do not. +func (r *Reconciler) resolveVPCBackends(ctx context.Context, ea *cozyv1alpha1.EndpointAttachment, svc *corev1.Service) (vpcBackends, error) { + var out vpcBackends + slices := &discoveryv1.EndpointSliceList{} + if err := r.List(ctx, slices, client.InNamespace(svc.Namespace), + client.MatchingLabels{discoveryv1.LabelServiceName: svc.Name}); err != nil { + return out, err + } + seenPods := map[string]bool{} + seenTargets := map[vpcTarget]bool{} + outside := 0 + for _, s := range slices.Items { + for _, e := range s.Endpoints { + if e.TargetRef == nil || e.TargetRef.Kind != "Pod" || seenPods[e.TargetRef.Name] { + continue + } + if e.Conditions.Terminating != nil && *e.Conditions.Terminating { + continue + } + seenPods[e.TargetRef.Name] = true + pod := &corev1.Pod{} + if err := r.Get(ctx, types.NamespacedName{Namespace: svc.Namespace, Name: e.TargetRef.Name}, pod); err != nil { + if apierrors.IsNotFound(err) { + continue + } + return out, err + } + out.Pods++ + ref, ok := pod.Annotations[vpcAnnotation] + if !ok { + outside++ + continue + } + out.InVPC = true + vpc := ref + if ns, name, cut := strings.Cut(ref, "/"); cut { + if ns != ea.Namespace { + out.Foreign = ref + } + vpc = name + } + ip := pod.Annotations[vpcIPAnnotation] + if ip == "" { + out.Waiting = append(out.Waiting, pod.Name) + continue + } + t := vpcTarget{VPC: vpc, IP: ip} + if !seenTargets[t] { + seenTargets[t] = true + out.Targets = append(out.Targets, t) + } + } + } + out.Mixed = out.InVPC && outside > 0 + sort.Slice(out.Targets, func(i, j int) bool { return out.Targets[i].IP < out.Targets[j].IP }) + sort.Strings(out.Waiting) + return out, nil +} + +// floatingIPServed reports whether the cluster serves cozyplane's FloatingIP. +func (r *Reconciler) floatingIPServed() (bool, error) { + return kindServed(r.RESTMapper(), floatingIPGVK) +} + +// ownedFloatingIP finds the FloatingIP this attachment controls, by +// controller owner reference. It returns nil when the kind is not served. +func (r *Reconciler) ownedFloatingIP(ctx context.Context, ea *cozyv1alpha1.EndpointAttachment) (*unstructured.Unstructured, bool, error) { + served, err := r.floatingIPServed() + if err != nil || !served { + return nil, served, err + } + list := &unstructured.UnstructuredList{} + list.SetGroupVersionKind(floatingIPGVK.GroupVersion().WithKind("FloatingIPList")) + if err := r.List(ctx, list, client.InNamespace(ea.Namespace)); err != nil { + if isNoKindMatch(err) { + return nil, false, nil + } + return nil, true, err + } + for i := range list.Items { + if isControlledBy(&list.Items[i], ea) { + return &list.Items[i], true, nil + } + } + return nil, true, nil +} + +func (r *Reconciler) withdrawFloatingIP(ctx context.Context, ea *cozyv1alpha1.EndpointAttachment, fip *unstructured.Unstructured) error { + if fip == nil { + return nil + } + // Foreground deletion keeps the FloatingIP listed until the garbage + // collector has removed the Service it owns, which wears the claim. A + // replacement consumer waits on the FloatingIP being gone, so it cannot + // overlap that Service, whether or not the substrate has recorded it as + // the claim's holder. + if err := r.Delete(ctx, fip, client.PropagationPolicy(metav1.DeletePropagationForeground)); client.IgnoreNotFound(err) != nil { + return fmt.Errorf("withdraw FloatingIP %s: %w", fip.GetName(), err) + } + r.event(ea, corev1.EventTypeNormal, "Withdrawn", "withdrew FloatingIP %s", fip.GetName()) + return nil +} + +// bindsEndpoint reports whether a FloatingIP was bound for this endpoint. One +// without the record was made before it existed, for an endpoint that can no +// longer be told, so it is not kept on that alone. +func bindsEndpoint(fip *unstructured.Unstructured, endpoint string) bool { + return fip.GetAnnotations()[endpointAnnotation] == endpoint +} + +// floatingIPGenerateName leaves one character more than other children do: +// cozyplane names the Service it owns after the FloatingIP plus "-", and the +// apiserver validates that prefix as a DNS-1035 label too. +func floatingIPGenerateName(name string) string { + prefix := childGenerateName(name) + if len(prefix) > maxGenerateNamePrefix-1 { + prefix = prefix[:maxGenerateNamePrefix-2] + "-" + } + return prefix +} + +func floatingIPSpec(t vpcTarget, claim, lbClass string) map[string]interface{} { + spec := map[string]interface{}{ + "vpcRef": map[string]interface{}{"name": t.VPC}, + "target": t.IP, + "addressClaimName": claim, + } + if lbClass != "" { + spec["loadBalancerClass"] = lbClass + } + return spec +} + +// reconcileVPCAttachment publishes a whole-IP attachment whose backend sits in +// a cozyplane VPC through a FloatingIP instead of a cozy-proxy Service. +func (r *Reconciler) reconcileVPCAttachment(ctx context.Context, ea *cozyv1alpha1.EndpointAttachment, own *corev1.Service, + fip *unstructured.Unstructured, served bool, vb vpcBackends, view claimView, lbClass, endpoint string) (ctrl.Result, error) { + lb := ea.Spec.LoadBalancer + // The claim has one consumer at a time, and the FloatingIP's own Service + // is that consumer here. A Service this attachment rendered earlier goes + // first, and nothing new is created until it has gone: an accepted delete + // leaves a Service with a finalizer in place for a while. + if own != nil { + if err := r.withdraw(ctx, ea, own); err != nil { + return ctrl.Result{}, err + } + setUnprovisioned(ea, cozyv1alpha1.ReasonWithdrawalPending, + fmt.Sprintf("waiting for Service %s to be removed before IPAddressClaim %s is bound in the VPC", own.Name, view.Name)) + return ctrl.Result{RequeueAfter: withdrawalRequeue}, nil + } + if !served { + setUnprovisioned(ea, cozyv1alpha1.ReasonDatapathUnavailable, + "the backend asks for a cozyplane VPC attachment, but this cluster does not serve sdn.cozystack.io FloatingIP; a cozy-proxy Service could not reach the VM's VPC address, so none is rendered") + return ctrl.Result{RequeueAfter: requeueBackstop}, nil + } + if lb.Method != cozyv1alpha1.ExposureMethodWholeIP { + setUnprovisioned(ea, cozyv1alpha1.ReasonMethodUnsupportedInVPC, + fmt.Sprintf("method %s filters ports through cozy-proxy, which cannot reach a backend inside a cozyplane VPC, and a FloatingIP binds every port; use method WholeIP, or omit method and list ports", lb.Method)) + return ctrl.Result{}, r.withdrawFloatingIP(ctx, ea, fip) + } + // A FloatingIP wears one address, so it can never carry both of a Dual + // claim's; binding one anyway would leave the attachment pending forever. + if view.Family == string(cozyv1alpha1.AddressFamilyDual) || len(view.Addresses) > 1 { + setUnprovisioned(ea, cozyv1alpha1.ReasonDualStackUnsupportedInVPC, + fmt.Sprintf("IPAddressClaim %s holds a Dual address, and a cozyplane FloatingIP binds one address; use an IPv4 or IPv6 claim for a backend in a VPC", view.Name)) + return ctrl.Result{}, r.withdrawFloatingIP(ctx, ea, fip) + } + if vb.Foreign != "" { + setUnprovisioned(ea, cozyv1alpha1.ReasonVPCNotInNamespace, + fmt.Sprintf("the backend is attached to VPC %s; a FloatingIP binds a VPC in its own namespace only, and must sit beside claim %s in %s", vb.Foreign, view.Name, ea.Namespace)) + return ctrl.Result{}, r.withdrawFloatingIP(ctx, ea, fip) + } + if len(vb.Targets) > 1 || vb.Mixed { + what := describeTargets(vb.Targets) + if vb.Mixed { + what = "backends both inside and outside a VPC" + } + setUnprovisioned(ea, cozyv1alpha1.ReasonMultipleBackends, + fmt.Sprintf("the endpoint resolves to more than one binding target (%s); a FloatingIP binds one, so the address stays held by claim %s and nothing is bound", what, view.Name)) + return ctrl.Result{}, r.withdrawFloatingIP(ctx, ea, fip) + } + if len(vb.Targets) == 0 || len(vb.Waiting) > 0 { + // A stopped VM, or a launcher pod cozyplane has not stamped yet. The + // VM keeps its VPC address, so a binding made for this endpoint + // stays as it is; nothing is created or re-pointed until every + // backend has its address, since an unstamped one may turn out to + // hold a different one. + if fip != nil && bindsEndpoint(fip, endpoint) { + return r.reportFloatingIP(ea, fip, view), nil + } + if err := r.withdrawFloatingIP(ctx, ea, fip); err != nil { + return ctrl.Result{}, err + } + setUnprovisioned(ea, cozyv1alpha1.ReasonWaitingForVPCAddress, + fmt.Sprintf("waiting for cozyplane to assign a VPC address to %s", strings.Join(vb.Waiting, ","))) + return ctrl.Result{RequeueAfter: requeueBackstop}, nil + } + + desired := floatingIPSpec(vb.Targets[0], view.Name, lbClass) + if fip == nil { + u := newFloatingIP() + u.SetNamespace(ea.Namespace) + u.SetGenerateName(floatingIPGenerateName(ea.Name)) + u.SetLabels(map[string]string{OwnerLabel: ownerLabelValue(ea.Name)}) + u.SetAnnotations(map[string]string{endpointAnnotation: endpoint}) + u.SetOwnerReferences([]metav1.OwnerReference{controllerOwnerReference(ea)}) + u.Object["spec"] = desired + if err := r.Create(ctx, u); err != nil { + setUnprovisioned(ea, cozyv1alpha1.ReasonRenderFailed, fmt.Sprintf("creating the FloatingIP failed: %v", err)) + return ctrl.Result{}, fmt.Errorf("create FloatingIP: %w", err) + } + r.event(ea, corev1.EventTypeNormal, "Rendered", "created FloatingIP %s binding %s in VPC %s", u.GetName(), vb.Targets[0].IP, vb.Targets[0].VPC) + fip = u + } else if current, _, _ := unstructured.NestedMap(fip.Object, "spec"); !floatingIPSpecMatches(current, desired) || fip.GetAnnotations()[endpointAnnotation] != endpoint { + fip.Object["spec"] = desired + ann := fip.GetAnnotations() + if ann == nil { + ann = map[string]string{} + } + ann[endpointAnnotation] = endpoint + fip.SetAnnotations(ann) + if err := r.Update(ctx, fip); err != nil { + setUnprovisioned(ea, cozyv1alpha1.ReasonRenderFailed, fmt.Sprintf("updating FloatingIP %s failed: %v", fip.GetName(), err)) + return ctrl.Result{}, fmt.Errorf("update FloatingIP %s: %w", fip.GetName(), err) + } + } + return r.reportFloatingIP(ea, fip, view), nil +} + +// floatingIPSpecMatches compares the fields this controller writes, so fields +// cozyplane defaults are not fought over. +func floatingIPSpecMatches(current, desired map[string]interface{}) bool { + for _, k := range []string{"target", "addressClaimName", "loadBalancerClass"} { + cv, _, _ := unstructured.NestedString(current, k) + dv, _, _ := unstructured.NestedString(desired, k) + if cv != dv { + return false + } + } + cv, _, _ := unstructured.NestedString(current, "vpcRef", "name") + dv, _, _ := unstructured.NestedString(desired, "vpcRef", "name") + return cv == dv +} + +// reportFloatingIP mirrors the FloatingIP's readiness into Provisioned. The +// attachment is provisioned once the FloatingIP is Ready wearing the claim's +// address. +func (r *Reconciler) reportFloatingIP(ea *cozyv1alpha1.EndpointAttachment, fip *unstructured.Unstructured, view claimView) ctrl.Result { + ea.Status.ServiceName = "" + phase, _, _ := unstructured.NestedString(fip.Object, "status", "phase") + address, _, _ := unstructured.NestedString(fip.Object, "status", "address") + vpc, _, _ := unstructured.NestedString(fip.Object, "spec", "vpcRef", "name") + target, _, _ := unstructured.NestedString(fip.Object, "spec", "target") + if !view.Bound { + setUnprovisioned(ea, cozyv1alpha1.ReasonClaimPending, + fmt.Sprintf("IPAddressClaim %s is not bound (%s); FloatingIP %s waits for it", view.Name, view.WaitingReason, fip.GetName())) + return ctrl.Result{RequeueAfter: requeueBackstop} + } + // A spec update keeps the old status, so a Ready computed for the previous + // target would otherwise read as this one's. + observed, _, _ := unstructured.NestedInt64(fip.Object, "status", "observedGeneration") + if observed != fip.GetGeneration() { + setUnprovisioned(ea, cozyv1alpha1.ReasonFloatingIPNotReady, + fmt.Sprintf("FloatingIP %s binding %s in VPC %s has not yet observed generation %d (its status is for %d)", fip.GetName(), target, vpc, fip.GetGeneration(), observed)) + return ctrl.Result{RequeueAfter: requeueBackstop} + } + if phase == floatingIPPhaseReady && address != "" && len(ea.Status.Addresses) > 0 && + len(missingAddresses(ea.Status.Addresses, []string{address})) == 0 { + setProvisioned(ea, fmt.Sprintf("FloatingIP %s binds %s to %s in VPC %s", fip.GetName(), address, target, vpc)) + return r.settled(r.claimWatched && r.floatingIPWatched) + } + why := phase + if why == "" { + why = "Pending" + } + if c := firstFalseCondition(fip); c != "" { + why += ": " + c + } + if address != "" && len(missingAddresses(ea.Status.Addresses, []string{address})) > 0 { + why += fmt.Sprintf("; it wears %s, which does not cover %s", address, strings.Join(missingAddresses(ea.Status.Addresses, []string{address}), ",")) + } + setUnprovisioned(ea, cozyv1alpha1.ReasonFloatingIPNotReady, + fmt.Sprintf("FloatingIP %s binding %s in VPC %s is %s", fip.GetName(), target, vpc, why)) + return ctrl.Result{RequeueAfter: requeueBackstop} +} + +func firstFalseCondition(u *unstructured.Unstructured) string { + conds, _, _ := unstructured.NestedSlice(u.Object, "status", "conditions") + for _, c := range conds { + m, ok := c.(map[string]interface{}) + if !ok { + continue + } + if status, _ := m["status"].(string); status == string(metav1.ConditionTrue) { + continue + } + condType, _ := m["type"].(string) + reason, _ := m["reason"].(string) + msg, _ := m["message"].(string) + out := condType + if reason != "" { + out += " " + reason + } + if msg != "" { + out += " (" + msg + ")" + } + return out + } + return "" +} + +func describeTargets(ts []vpcTarget) string { + parts := make([]string, 0, len(ts)) + for _, t := range ts { + parts = append(parts, t.VPC+"/"+t.IP) + } + return strings.Join(parts, ",") +} diff --git a/internal/controller/endpointattachment/floatingip_test.go b/internal/controller/endpointattachment/floatingip_test.go new file mode 100644 index 000000000..e1e8b8f38 --- /dev/null +++ b/internal/controller/endpointattachment/floatingip_test.go @@ -0,0 +1,565 @@ +/* +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 endpointattachment + +import ( + "context" + "strings" + "testing" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/equality" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + apivalidation "k8s.io/apimachinery/pkg/api/validation" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/localsdn/v1alpha1" +) + +const ( + vpcName = "virtualprivatecloud-net" + vpcIP = "10.10.0.4" +) + +// newCozyplaneClient builds a client on a cluster that serves cozyplane's +// FloatingIP. +func newCozyplaneClient(t *testing.T, objs ...client.Object) client.Client { + t.Helper() + m := meta.NewDefaultRESTMapper(nil) + m.Add(floatingIPGVK, meta.RESTScopeNamespace) + return fake.NewClientBuilder(). + WithScheme(newScheme(t)). + WithRESTMapper(m). + WithStatusSubresource(&cozyv1alpha1.EndpointAttachment{}). + WithObjects(withBackendPods(objs)...). + Build() +} + +// launcherPod is a VM's launcher pod. A non-empty vpc models the cozyplane +// flavour of the VM chart, which asks for a VPC attachment by annotation; ip +// is what cozyplane's CNI stamps back once it has attached the pod. +func launcherPod(name, vpc, ip string, annotations map[string]string) *corev1.Pod { + ann := map[string]string{} + for k, v := range annotations { + ann[k] = v + } + if vpc != "" { + ann[vpcAnnotation] = vpc + } + if ip != "" { + ann[vpcIPAnnotation] = ip + } + return &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: name, UID: types.UID("pod-" + name), Annotations: ann}} +} + +func wholeIPVM(method cozyv1alpha1.ExposureMethod) (*cozyv1alpha1.EndpointAttachment, []client.Object) { + lb := cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held", Method: method} + if method == cozyv1alpha1.ExposureMethodPortList { + lb.Ports = []int32{22} + } + ea := attachment("box-ip", "ea-1", "VMInstance", "box", "vm-instance-box", lb) + return ea, []client.Object{ + helmRelease("vm-instance-box", "hr-1", "VMInstance", "box"), + endpoint("vm-instance-box", "VMInstance", "box", map[string]string{"vm": "box"}, SentinelPort), + claimObject("held", "public", "IPv4", true, "203.0.113.7"), + classObject("public", ""), + ea, + } +} + +func ownedFloatingIPs(t *testing.T, c client.Client, ea *cozyv1alpha1.EndpointAttachment) []unstructured.Unstructured { + t.Helper() + list := &unstructured.UnstructuredList{} + list.SetGroupVersionKind(floatingIPGVK.GroupVersion().WithKind("FloatingIPList")) + if err := c.List(context.TODO(), list, client.InNamespace(ns)); err != nil { + t.Fatalf("list FloatingIPs: %v", err) + } + var out []unstructured.Unstructured + for _, u := range list.Items { + if isControlledBy(&u, ea) { + out = append(out, u) + } + } + return out +} + +func onlyFloatingIP(t *testing.T, c client.Client, ea *cozyv1alpha1.EndpointAttachment) *unstructured.Unstructured { + t.Helper() + got := ownedFloatingIPs(t, c, ea) + if len(got) != 1 { + t.Fatalf("expected exactly one owned FloatingIP, got %d", len(got)) + } + return &got[0] +} + +// existingFloatingIP is a FloatingIP the attachment created on an earlier +// reconcile. +func existingFloatingIP(ea *cozyv1alpha1.EndpointAttachment, target string) *unstructured.Unstructured { + u := newFloatingIP() + u.SetNamespace(ns) + u.SetName("box-ip-fip01") + u.SetUID("fip-1") + u.SetOwnerReferences([]metav1.OwnerReference{controllerOwnerReference(ea)}) + u.SetAnnotations(map[string]string{endpointAnnotation: ea.Spec.Endpoint.ServiceName}) + u.Object["spec"] = floatingIPSpec(vpcTarget{VPC: vpcName, IP: target}, "held", "") + return u +} + +func setFloatingIPStatus(t *testing.T, c client.Client, fip *unstructured.Unstructured, phase, address string, conds ...map[string]interface{}) { + t.Helper() + live := newFloatingIP() + if err := c.Get(context.TODO(), client.ObjectKeyFromObject(fip), live); err != nil { + t.Fatalf("get FloatingIP: %v", err) + } + status := map[string]interface{}{"phase": phase} + if address != "" { + status["address"] = address + } + var list []interface{} + for _, c := range conds { + list = append(list, c) + } + if list != nil { + status["conditions"] = list + } + live.Object["status"] = status + if err := c.Update(context.TODO(), live); err != nil { + t.Fatalf("set FloatingIP status: %v", err) + } +} + +// TestVPCWholeIPBindsFloatingIP is the cozyplane path: a whole-IP backend in a +// VPC gets a FloatingIP on its VPC address wearing the attachment's claim, +// and no cozy-proxy Service, whatever the cozy-proxy declaration says. +func TestVPCWholeIPBindsFloatingIP(t *testing.T) { + ea, objs := wholeIPVM(cozyv1alpha1.ExposureMethodWholeIP) + c := newCozyplaneClient(t, append(objs, + launcherPod("virt-launcher-box", vpcName, vpcIP, nil), + endpointSlice("vm-instance-box-1", "vm-instance-box", true, "virt-launcher-box"))...) + + got := run(t, c, &Reconciler{CozyProxyContractImplemented: false}, ea) + if n := len(renderedServices(t, c, ea)); n != 0 { + t.Fatalf("a VPC backend must not get a cozy-proxy Service, got %d", n) + } + fip := onlyFloatingIP(t, c, ea) + spec, _, _ := unstructured.NestedMap(fip.Object, "spec") + if v, _, _ := unstructured.NestedString(spec, "vpcRef", "name"); v != vpcName { + t.Fatalf("vpcRef = %q, want %q", v, vpcName) + } + if v, _, _ := unstructured.NestedString(spec, "target"); v != vpcIP { + t.Fatalf("target = %q, want %q", v, vpcIP) + } + if v, _, _ := unstructured.NestedString(spec, "addressClaimName"); v != "held" { + t.Fatalf("addressClaimName = %q, want the attachment's claim", v) + } + if fip.GetLabels()[OwnerLabel] != ea.Name { + t.Fatalf("ownership label = %v", fip.GetLabels()) + } + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonFloatingIPNotReady) + + setFloatingIPStatus(t, c, fip, "Pending", "", map[string]interface{}{ + "type": "TargetExclusive", "status": "False", "reason": "Contended", "message": "another FloatingIP binds the target", + }) + got = run(t, c, nil, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonFloatingIPNotReady) + if msg := meta.FindStatusCondition(got.Status.Conditions, cozyv1alpha1.ConditionProvisioned).Message; !strings.Contains(msg, "TargetExclusive") { + t.Fatalf("the FloatingIP's failing condition must reach the attachment, got %q", msg) + } + + setFloatingIPStatus(t, c, fip, "Ready", "203.0.113.7") + got = run(t, c, nil, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionTrue, cozyv1alpha1.ReasonProvisioned) + if got.Status.Phase != cozyv1alpha1.EndpointAttachmentAttached { + t.Fatalf("phase = %s, want Attached", got.Status.Phase) + } + if got.Status.ServiceName != "" || len(got.Status.Addresses) != 1 || got.Status.Addresses[0] != "203.0.113.7" { + t.Fatalf("status = %+v", got.Status) + } +} + +// TestVPCClaimWornByOwnFloatingIP: once cozyplane associates the claim with +// the Service its FloatingIP owns, the attachment must not read that as the +// claim being in use elsewhere. +func TestVPCClaimWornByOwnFloatingIP(t *testing.T) { + ea, objs := wholeIPVM(cozyv1alpha1.ExposureMethodWholeIP) + fip := existingFloatingIP(ea, vpcIP) + fipSvc := &corev1.Service{ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: "box-ip-fip01-abcde", UID: "fip-svc", + OwnerReferences: []metav1.OwnerReference{{APIVersion: "sdn.cozystack.io/v1alpha1", Kind: "FloatingIP", Name: fip.GetName(), UID: fip.GetUID(), Controller: new(true)}}}} + c := newCozyplaneClient(t, append(objs, fip, fipSvc, + addressObject("203.0.113.7", &types.NamespacedName{Namespace: ns, Name: fipSvc.Name}), + launcherPod("virt-launcher-box", vpcName, vpcIP, nil), + endpointSlice("vm-instance-box-1", "vm-instance-box", true, "virt-launcher-box"))...) + setFloatingIPStatus(t, c, fip, "Ready", "203.0.113.7") + + got := run(t, c, nil, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionTrue, cozyv1alpha1.ReasonProvisioned) +} + +// TestVPCReplacesRenderedService: a VM that joins a VPC after its +// attachment rendered a cozy-proxy Service gets the Service withdrawn before +// the FloatingIP wears the claim. +func TestVPCReplacesRenderedService(t *testing.T) { + ea, objs := wholeIPVM(cozyv1alpha1.ExposureMethodWholeIP) + c := newCozyplaneClient(t, append(objs, + launcherPod("virt-launcher-box", "", "", nil), + endpointSlice("vm-instance-box-1", "vm-instance-box", true, "virt-launcher-box"))...) + r := &Reconciler{CozyProxyContractImplemented: true} + run(t, c, r, ea) + old := onlyRendered(t, c, ea) + + pod := &corev1.Pod{} + if err := c.Get(context.TODO(), types.NamespacedName{Namespace: ns, Name: "virt-launcher-box"}, pod); err != nil { + t.Fatal(err) + } + pod.Annotations = map[string]string{vpcAnnotation: vpcName, vpcIPAnnotation: vpcIP} + if err := c.Update(context.TODO(), pod); err != nil { + t.Fatal(err) + } + got := run(t, c, r, ea) + if err := c.Get(context.TODO(), client.ObjectKeyFromObject(old), &corev1.Service{}); !apierrors.IsNotFound(err) { + t.Fatalf("the cozy-proxy Service must be withdrawn, got %v", err) + } + if n := len(ownedFloatingIPs(t, c, ea)); n != 0 { + t.Fatalf("no FloatingIP may wear the claim in the pass that withdraws the Service, got %d", n) + } + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonWithdrawalPending) + run(t, c, r, ea) + onlyFloatingIP(t, c, ea) +} + +// TestVPCLeftBehindFallsBackToService: a VM no longer in a VPC loses its +// FloatingIP and gets the cozy-proxy Service again. +func TestVPCLeftBehindFallsBackToService(t *testing.T) { + ea, objs := wholeIPVM(cozyv1alpha1.ExposureMethodWholeIP) + c := newCozyplaneClient(t, append(objs, existingFloatingIP(ea, vpcIP), + launcherPod("virt-launcher-box", "", "", nil), + endpointSlice("vm-instance-box-1", "vm-instance-box", true, "virt-launcher-box"))...) + r := &Reconciler{CozyProxyContractImplemented: true} + got := run(t, c, r, ea) + if n := len(ownedFloatingIPs(t, c, ea)); n != 0 { + t.Fatalf("FloatingIP must be withdrawn, %d left", n) + } + if n := len(renderedServices(t, c, ea)); n != 0 { + t.Fatalf("no Service may wear the claim in the pass that withdraws the FloatingIP, got %d", n) + } + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonWithdrawalPending) + run(t, c, r, ea) + onlyRendered(t, c, ea) +} + +// TestKubeOVNBackendKeepsCozyProxyService: on the kube-ovn flavour the VM +// joins a VPC through a secondary Multus NIC and keeps its pod-network NIC, +// so the pod carries no cozyplane annotation and the cozy-proxy Service, +// which maps to that NIC's address, stays the path. +func TestKubeOVNBackendKeepsCozyProxyService(t *testing.T) { + ea, objs := wholeIPVM(cozyv1alpha1.ExposureMethodWholeIP) + multus := map[string]string{"k8s.v1.cni.cncf.io/networks": `[{"name":"subnet-84dbec17","namespace":"tenant-foo"}]`} + c := newCozyplaneClient(t, append(objs, + launcherPod("virt-launcher-box", "", "", multus), + endpointSlice("vm-instance-box-1", "vm-instance-box", true, "virt-launcher-box"))...) + run(t, c, &Reconciler{CozyProxyContractImplemented: true}, ea) + svc := onlyRendered(t, c, ea) + if svc.Labels[ServiceProxyNameLabel] != ServiceProxyName || svc.Annotations[WholeIPAnnotation] != "true" { + t.Fatalf("expected the cozy-proxy whole-IP Service, got labels=%v annotations=%v", svc.Labels, svc.Annotations) + } + if n := len(ownedFloatingIPs(t, c, ea)); n != 0 { + t.Fatalf("no FloatingIP on a kube-ovn backend, got %d", n) + } +} + +func TestVPCRefusals(t *testing.T) { + tests := []struct { + name string + method cozyv1alpha1.ExposureMethod + pods []*corev1.Pod + served bool + withFIP bool + wantReason string + }{ + {name: "FloatingIP not served", method: cozyv1alpha1.ExposureMethodWholeIP, served: false, + pods: []*corev1.Pod{launcherPod("virt-launcher-box", vpcName, vpcIP, nil)}, wantReason: cozyv1alpha1.ReasonDatapathUnavailable}, + {name: "PortList", method: cozyv1alpha1.ExposureMethodPortList, served: true, withFIP: true, + pods: []*corev1.Pod{launcherPod("virt-launcher-box", vpcName, vpcIP, nil)}, wantReason: cozyv1alpha1.ReasonMethodUnsupportedInVPC}, + {name: "VPC in another namespace", method: cozyv1alpha1.ExposureMethodWholeIP, served: true, withFIP: true, + pods: []*corev1.Pod{launcherPod("virt-launcher-box", "tenant-parent/"+vpcName, vpcIP, nil)}, wantReason: cozyv1alpha1.ReasonVPCNotInNamespace}, + {name: "two VPC addresses", method: cozyv1alpha1.ExposureMethodWholeIP, served: true, withFIP: true, + pods: []*corev1.Pod{launcherPod("virt-launcher-a", vpcName, "10.10.0.4", nil), launcherPod("virt-launcher-b", vpcName, "10.10.0.5", nil)}, + wantReason: cozyv1alpha1.ReasonMultipleBackends}, + {name: "inside and outside a VPC", method: cozyv1alpha1.ExposureMethodWholeIP, served: true, withFIP: true, + pods: []*corev1.Pod{launcherPod("virt-launcher-a", vpcName, vpcIP, nil), launcherPod("virt-launcher-b", "", "", nil)}, + wantReason: cozyv1alpha1.ReasonMultipleBackends}, + {name: "VPC address not stamped yet", method: cozyv1alpha1.ExposureMethodWholeIP, served: true, + pods: []*corev1.Pod{launcherPod("virt-launcher-box", vpcName, "", nil)}, wantReason: cozyv1alpha1.ReasonWaitingForVPCAddress}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ea, objs := wholeIPVM(tt.method) + var names []string + for _, p := range tt.pods { + objs = append(objs, p) + names = append(names, p.Name) + } + objs = append(objs, endpointSlice("vm-instance-box-1", "vm-instance-box", true, names...)) + if tt.withFIP { + objs = append(objs, existingFloatingIP(ea, vpcIP)) + } + c := newClient(t, objs...) + if tt.served { + c = newCozyplaneClient(t, objs...) + } + got := run(t, c, &Reconciler{CozyProxyContractImplemented: true}, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, tt.wantReason) + if n := len(renderedServices(t, c, ea)); n != 0 { + t.Fatalf("no cozy-proxy Service may be rendered for a VPC backend, got %d", n) + } + if tt.served { + if n := len(ownedFloatingIPs(t, c, ea)); n != 0 { + t.Fatalf("no FloatingIP may stand on a refusal, got %d", n) + } + } + }) + } +} + +// TestVPCLiveMigrationKeepsOneBinding: during a live migration the source +// and target launcher pods share the VM's VPC address, which is one target, +// not two backends. +func TestVPCLiveMigrationKeepsOneBinding(t *testing.T) { + ea, objs := wholeIPVM(cozyv1alpha1.ExposureMethodWholeIP) + c := newCozyplaneClient(t, append(objs, + launcherPod("virt-launcher-src", vpcName, vpcIP, nil), + launcherPod("virt-launcher-dst", vpcName, vpcIP, nil), + endpointSlice("vm-instance-box-1", "vm-instance-box", true, "virt-launcher-src", "virt-launcher-dst"))...) + run(t, c, nil, ea) + fip := onlyFloatingIP(t, c, ea) + if v, _, _ := unstructured.NestedString(fip.Object, "spec", "target"); v != vpcIP { + t.Fatalf("target = %q", v) + } +} + +// TestVPCStoppedVMKeepsBinding: a stopped VM has no launcher pod, so nothing +// says where it is; the FloatingIP it already has stays instead of flipping +// to a cozy-proxy Service until the VM starts again. +func TestVPCStoppedVMKeepsBinding(t *testing.T) { + ea, objs := wholeIPVM(cozyv1alpha1.ExposureMethodWholeIP) + fip := existingFloatingIP(ea, vpcIP) + c := newCozyplaneClient(t, append(objs, fip)...) + got := run(t, c, &Reconciler{CozyProxyContractImplemented: true}, ea) + if n := len(renderedServices(t, c, ea)); n != 0 { + t.Fatalf("a stopped VPC VM must not get a cozy-proxy Service, got %d", n) + } + onlyFloatingIP(t, c, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonFloatingIPNotReady) +} + +// TestVPCTargetFollowsTheVM: a new VPC address re-points the FloatingIP in +// place. +func TestVPCTargetFollowsTheVM(t *testing.T) { + ea, objs := wholeIPVM(cozyv1alpha1.ExposureMethodWholeIP) + c := newCozyplaneClient(t, append(objs, existingFloatingIP(ea, "10.10.0.9"), + launcherPod("virt-launcher-box", vpcName, vpcIP, nil), + endpointSlice("vm-instance-box-1", "vm-instance-box", true, "virt-launcher-box"))...) + run(t, c, nil, ea) + fip := onlyFloatingIP(t, c, ea) + if fip.GetName() != "box-ip-fip01" { + t.Fatalf("the FloatingIP must be updated in place, got %q", fip.GetName()) + } + if v, _, _ := unstructured.NestedString(fip.Object, "spec", "target"); v != vpcIP { + t.Fatalf("target = %q, want %q", v, vpcIP) + } +} + +// TestVPCDetachWithdrawsFloatingIP: the endpoint going away withdraws the +// binding and keeps the claim, as on the Service path. +func TestVPCDetachWithdrawsFloatingIP(t *testing.T) { + ea, objs := wholeIPVM(cozyv1alpha1.ExposureMethodWholeIP) + var kept []client.Object + for _, o := range objs { + if _, isSvc := o.(*corev1.Service); !isSvc { + kept = append(kept, o) + } + } + c := newCozyplaneClient(t, append(kept, existingFloatingIP(ea, vpcIP))...) + got := run(t, c, nil, ea) + if n := len(ownedFloatingIPs(t, c, ea)); n != 0 { + t.Fatalf("FloatingIP must be withdrawn on detach, %d left", n) + } + if got.Status.Phase != cozyv1alpha1.EndpointAttachmentDetached { + t.Fatalf("phase = %s, want Detached", got.Status.Phase) + } +} + +// TestVPCFloatingIPNamesTheApiserverAccepts: cozyplane names the Service it +// owns after the FloatingIP plus "-", so the FloatingIP name must leave room +// for that inside a DNS-1035 label. +func TestVPCFloatingIPNamesTheApiserverAccepts(t *testing.T) { + long := strings.Repeat("a", 253) + lb := cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held", Method: cozyv1alpha1.ExposureMethodWholeIP} + ea := attachment(long, "ea-1", "VMInstance", "box", "vm-instance-box", lb) + _, objs := wholeIPVM(cozyv1alpha1.ExposureMethodWholeIP) + objs[len(objs)-1] = ea + c := newCozyplaneClient(t, append(objs, + launcherPod("virt-launcher-box", vpcName, vpcIP, nil), + endpointSlice("vm-instance-box-1", "vm-instance-box", true, "virt-launcher-box"))...) + run(t, c, nil, ea) + fip := onlyFloatingIP(t, c, ea) + if errs := apivalidation.NameIsDNS1035Label(fip.GetName()+"-", true); len(errs) > 0 { + t.Fatalf("cozyplane's Service generateName %q would be refused: %v", fip.GetName()+"-", errs) + } +} + +// TestTerminatingLauncherIsNotABackend: the source pod of a finished +// migration is terminating and no longer a binding target. +func TestTerminatingLauncherIsNotABackend(t *testing.T) { + ea, objs := wholeIPVM(cozyv1alpha1.ExposureMethodWholeIP) + slice := endpointSlice("vm-instance-box-1", "vm-instance-box", true, "virt-launcher-old", "virt-launcher-new") + slice.Endpoints[0].Conditions.Terminating = new(true) + c := newCozyplaneClient(t, append(objs, slice, + launcherPod("virt-launcher-old", vpcName, "10.10.0.9", nil), + launcherPod("virt-launcher-new", vpcName, vpcIP, nil))...) + run(t, c, nil, ea) + fip := onlyFloatingIP(t, c, ea) + if v, _, _ := unstructured.NestedString(fip.Object, "spec", "target"); v != vpcIP { + t.Fatalf("target = %q, want the non-terminating pod's %q", v, vpcIP) + } +} + +// TestNoBackendYetPublishesNothing is the race seen when an attachment is +// created before its VM's launcher pod: until a pod says whether the VM sits +// in a VPC, neither a cozy-proxy Service nor a FloatingIP is created, so +// the claim is never pinned to the wrong consumer. +func TestNoBackendYetPublishesNothing(t *testing.T) { + for _, tt := range []struct { + name string + pod *corev1.Pod + wantFIP bool + }{ + {name: "VM in a cozyplane VPC", pod: launcherPod("virt-launcher-box", vpcName, vpcIP, nil), wantFIP: true}, + {name: "VM on the pod network", pod: launcherPod("virt-launcher-box", "", "", nil)}, + } { + t.Run(tt.name, func(t *testing.T) { + ea, objs := wholeIPVM(cozyv1alpha1.ExposureMethodWholeIP) + c := newCozyplaneClient(t, objs...) + r := &Reconciler{CozyProxyContractImplemented: true} + + got := run(t, c, r, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonWaitingForBackend) + if n := len(renderedServices(t, c, ea)); n != 0 { + t.Fatalf("no Service may be rendered before a backend pod exists, got %d", n) + } + if n := len(ownedFloatingIPs(t, c, ea)); n != 0 { + t.Fatalf("no FloatingIP may be created before a backend pod exists, got %d", n) + } + if len(got.Status.Addresses) != 1 { + t.Fatalf("the claim's address must still be reported while waiting, got %v", got.Status.Addresses) + } + + for _, o := range []client.Object{tt.pod, endpointSlice("vm-instance-box-1", "vm-instance-box", false, tt.pod.Name)} { + if err := c.Create(context.TODO(), o); err != nil { + t.Fatal(err) + } + } + run(t, c, r, ea) + if tt.wantFIP { + onlyFloatingIP(t, c, ea) + if n := len(renderedServices(t, c, ea)); n != 0 { + t.Fatalf("a VPC VM must never get a cozy-proxy Service, got %d", n) + } + return + } + onlyRendered(t, c, ea) + if n := len(ownedFloatingIPs(t, c, ea)); n != 0 { + t.Fatalf("a pod-network VM gets no FloatingIP, got %d", n) + } + }) + } +} + +// TestPublishedServiceOutlivesItsPods: a VM on the pod network that stops +// keeps the Service it was published with; the wait applies only before +// anything is published. +func TestPublishedServiceOutlivesItsPods(t *testing.T) { + ea, objs := wholeIPVM(cozyv1alpha1.ExposureMethodWholeIP) + slice := endpointSlice("vm-instance-box-1", "vm-instance-box", true, "virt-launcher-box") + c := newCozyplaneClient(t, append(objs, slice)...) + r := &Reconciler{CozyProxyContractImplemented: true} + run(t, c, r, ea) + svc := onlyRendered(t, c, ea) + + if err := c.Delete(context.TODO(), slice); err != nil { + t.Fatal(err) + } + run(t, c, r, ea) + if kept := onlyRendered(t, c, ea); kept.Name != svc.Name { + t.Fatalf("the published Service must stay, got %q in place of %q", kept.Name, svc.Name) + } +} + +// TestRetargetWaitsForTheFloatingIPToObserveIt: re-pointing a Ready +// FloatingIP at a new target keeps its old status, so the attachment is not +// provisioned until the FloatingIP reports a status for the new generation. +func TestRetargetWaitsForTheFloatingIPToObserveIt(t *testing.T) { + ea, objs := wholeIPVM(cozyv1alpha1.ExposureMethodWholeIP) + fip := existingFloatingIP(ea, "10.10.0.9") + fip.SetGeneration(1) + fip.Object["status"] = map[string]interface{}{"phase": "Ready", "address": "203.0.113.7", "observedGeneration": int64(1)} + m := meta.NewDefaultRESTMapper(nil) + m.Add(floatingIPGVK, meta.RESTScopeNamespace) + c := fake.NewClientBuilder().WithScheme(newScheme(t)).WithRESTMapper(m). + WithStatusSubresource(&cozyv1alpha1.EndpointAttachment{}). + WithObjects(withBackendPods(append(objs, fip, + launcherPod("virt-launcher-box", vpcName, vpcIP, nil), + endpointSlice("vm-instance-box-1", "vm-instance-box", true, "virt-launcher-box")))...). + WithInterceptorFuncs(interceptor.Funcs{ + // cozyplane's registry bumps the generation on a spec change. + Update: func(ctx context.Context, cl client.WithWatch, o client.Object, opts ...client.UpdateOption) error { + if u, ok := o.(*unstructured.Unstructured); ok && u.GroupVersionKind().Kind == "FloatingIP" { + old := newFloatingIP() + if err := cl.Get(ctx, client.ObjectKeyFromObject(u), old); err != nil { + return err + } + if !equality.Semantic.DeepEqual(old.Object["spec"], u.Object["spec"]) { + u.SetGeneration(old.GetGeneration() + 1) + } + } + return cl.Update(ctx, o, opts...) + }, + }).Build() + + got := run(t, c, nil, ea) + live := onlyFloatingIP(t, c, ea) + if v, _, _ := unstructured.NestedString(live.Object, "spec", "target"); v != vpcIP || live.GetGeneration() != 2 { + t.Fatalf("premise: the FloatingIP must be re-pointed in place, target=%q generation=%d", v, live.GetGeneration()) + } + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonFloatingIPNotReady) + if msg := meta.FindStatusCondition(got.Status.Conditions, cozyv1alpha1.ConditionProvisioned).Message; !strings.Contains(msg, "generation 2") { + t.Fatalf("message must say the new generation is not yet observed, got %q", msg) + } + + live.Object["status"] = map[string]interface{}{"phase": "Ready", "address": "203.0.113.7", "observedGeneration": int64(2)} + if err := c.Update(context.TODO(), live); err != nil { + t.Fatal(err) + } + got = run(t, c, nil, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionTrue, cozyv1alpha1.ReasonProvisioned) +} diff --git a/internal/controller/endpointattachment/reconcile_edges_test.go b/internal/controller/endpointattachment/reconcile_edges_test.go new file mode 100644 index 000000000..58f7d0da3 --- /dev/null +++ b/internal/controller/endpointattachment/reconcile_edges_test.go @@ -0,0 +1,984 @@ +/* +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 endpointattachment + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/intstr" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + "sigs.k8s.io/controller-runtime/pkg/event" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/localsdn/v1alpha1" +) + +func newInterceptedClient(t *testing.T, funcs interceptor.Funcs, objs ...client.Object) client.Client { + t.Helper() + return fake.NewClientBuilder(). + WithScheme(newScheme(t)). + WithStatusSubresource(&cozyv1alpha1.EndpointAttachment{}). + WithObjects(withBackendPods(objs)...). + WithInterceptorFuncs(funcs). + Build() +} + +func dbObjects(ea *cozyv1alpha1.EndpointAttachment) []client.Object { + return []client.Object{ + helmRelease("postgres-mydb", "hr-1", "Postgres", "mydb"), + endpoint("postgres-mydb-ro", "Postgres", "mydb", map[string]string{"role": "replica"}, 5432), + claimObject("held", "public", "IPv4", true, "203.0.113.7"), + classObject("public", ""), + ea, + } +} + +func dbAttachment() *cozyv1alpha1.EndpointAttachment { + return attachment("ro-public", "ea-1", "Postgres", "mydb", "postgres-mydb-ro", cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held"}) +} + +func reconcileOnce(r *Reconciler, ea *cozyv1alpha1.EndpointAttachment) (ctrl.Result, error) { + return r.Reconcile(context.TODO(), ctrl.Request{NamespacedName: client.ObjectKeyFromObject(ea)}) +} + +func getAttachment(t *testing.T, c client.Client, ea *cozyv1alpha1.EndpointAttachment) *cozyv1alpha1.EndpointAttachment { + t.Helper() + got := &cozyv1alpha1.EndpointAttachment{} + if err := c.Get(context.TODO(), client.ObjectKeyFromObject(ea), got); err != nil { + t.Fatal(err) + } + return got +} + +// TestAttachedNeedsThisGeneration: when a new spec fails to render, the +// Provisioned=True left by the previous generation must not keep the +// attachment reading Attached. +func TestAttachedNeedsThisGeneration(t *testing.T) { + ea := dbAttachment() + fail := false + c := newInterceptedClient(t, interceptor.Funcs{ + Update: func(ctx context.Context, c client.WithWatch, o client.Object, opts ...client.UpdateOption) error { + if _, ok := o.(*corev1.Service); ok && fail { + return errors.New("apiserver unavailable") + } + return c.Update(ctx, o, opts...) + }, + }, dbObjects(ea)...) + r := &Reconciler{Client: c} + run(t, c, r, ea) + setIngress(t, c, onlyRendered(t, c, ea), "203.0.113.7") + if got := run(t, c, r, ea); got.Status.Phase != cozyv1alpha1.EndpointAttachmentAttached { + t.Fatalf("phase = %s, want Attached before the spec change", got.Status.Phase) + } + + live := getAttachment(t, c, ea) + live.Spec.LoadBalancer.Ports = []int32{5432} + live.Generation = 2 + if err := c.Update(context.TODO(), live); err != nil { + t.Fatal(err) + } + ep := &corev1.Service{} + if err := c.Get(context.TODO(), types.NamespacedName{Namespace: ns, Name: "postgres-mydb-ro"}, ep); err != nil { + t.Fatal(err) + } + ep.Spec.Selector = map[string]string{"role": "primary"} + if err := c.Update(context.TODO(), ep); err != nil { + t.Fatal(err) + } + fail = true + if _, err := reconcileOnce(r, ea); err == nil { + t.Fatal("a failed Service update must surface as an error") + } + got := getAttachment(t, c, ea) + if got.Status.Phase == cozyv1alpha1.EndpointAttachmentAttached { + t.Fatal("phase must not stay Attached while the new generation is unrendered") + } + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonRenderFailed) +} + +// TestClaimInUseWithdrawsOwnService: when the substrate records another +// Service as the claim's holder, this attachment's Service goes. +func TestClaimInUseWithdrawsOwnService(t *testing.T) { + ea := dbAttachment() + rival := &corev1.Service{ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: "rival-lb", UID: "svc-rival"}} + c := newClient(t, append(dbObjects(ea), rival, addressObject("203.0.113.7", nil))...) + run(t, c, nil, ea) + own := onlyRendered(t, c, ea) + + addr := addressObject("203.0.113.7", &types.NamespacedName{Namespace: ns, Name: rival.Name}) + live := addressObject("203.0.113.7", nil) + if err := c.Get(context.TODO(), client.ObjectKeyFromObject(live), live); err != nil { + t.Fatal(err) + } + live.Object["status"] = addr.Object["status"] + if err := c.Update(context.TODO(), live); err != nil { + t.Fatal(err) + } + got := run(t, c, nil, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonClaimInUse) + if err := c.Get(context.TODO(), client.ObjectKeyFromObject(own), &corev1.Service{}); err == nil { + t.Fatal("the Service that lost the claim must be withdrawn") + } + if got.Status.ServiceName != "" { + t.Fatalf("status.serviceName = %q after withdrawal", got.Status.ServiceName) + } +} + +// TestDatapathGateBeforeClaim: with the cozy-proxy declaration withdrawn, a +// delegated Service goes even while the claim cannot be found. +func TestDatapathGateBeforeClaim(t *testing.T) { + ea, objs := wholeIPVM(cozyv1alpha1.ExposureMethodWholeIP) + c := newClient(t, append(objs, endpointSlice("vm-instance-box-1", "vm-instance-box", true, "virt-launcher-box"))...) + run(t, c, &Reconciler{CozyProxyContractImplemented: true}, ea) + own := onlyRendered(t, c, ea) + + claim := newClaim() + if err := c.Get(context.TODO(), types.NamespacedName{Namespace: ns, Name: "held"}, claim); err != nil { + t.Fatal(err) + } + if err := c.Delete(context.TODO(), claim); err != nil { + t.Fatal(err) + } + got := run(t, c, &Reconciler{CozyProxyContractImplemented: false}, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonDatapathUnavailable) + if err := c.Get(context.TODO(), client.ObjectKeyFromObject(own), &corev1.Service{}); err == nil { + t.Fatal("the delegated Service must be withdrawn") + } +} + +// TestStaleCacheDoesNotDuplicateService: a Service the previous reconcile +// created but the cache has not seen is found through the API reader rather +// than created again. +func TestStaleCacheDoesNotDuplicateService(t *testing.T) { + ea := dbAttachment() + backing := newClient(t, dbObjects(ea)...) + c := interceptor.NewClient(backing.(client.WithWatch), interceptor.Funcs{ + List: func(ctx context.Context, cl client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + if _, ok := list.(*corev1.ServiceList); ok { + return nil + } + return cl.List(ctx, list, opts...) + }, + }) + r := &Reconciler{Client: c, Reader: backing} + run(t, backing, &Reconciler{Reader: backing}, ea) + run(t, c, r, ea) + if n := len(renderedServices(t, backing, ea)); n != 1 { + t.Fatalf("expected one Service despite the stale cache, got %d", n) + } +} + +// TestDuplicateServicesCollapse: should two owned Services exist anyway, the +// oldest stays and the other is withdrawn. +func TestDuplicateServicesCollapse(t *testing.T) { + ea := dbAttachment() + owned := func(name string, age time.Duration) *corev1.Service { + return &corev1.Service{ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: name, UID: types.UID("svc-" + name), + CreationTimestamp: metav1.NewTime(time.Now().Add(-age)), + OwnerReferences: []metav1.OwnerReference{controllerOwnerReference(ea)}}, + Spec: corev1.ServiceSpec{Type: corev1.ServiceTypeLoadBalancer}} + } + c := newClient(t, append(dbObjects(ea), owned("ro-public-old", time.Hour), owned("ro-public-new", time.Minute))...) + got := run(t, c, nil, ea) + svc := onlyRendered(t, c, ea) + if svc.Name != "ro-public-old" || got.Status.ServiceName != "ro-public-old" { + t.Fatalf("kept %q (status %q), want the oldest", svc.Name, got.Status.ServiceName) + } +} + +// TestSettledKeepsPollingWithoutWatches: without a claim watch nothing would +// enqueue the attachment on a claim change, so a settled reconcile polls. +func TestSettledKeepsPollingWithoutWatches(t *testing.T) { + for _, watched := range []bool{false, true} { + ea := dbAttachment() + c := newClient(t, dbObjects(ea)...) + r := &Reconciler{Client: c, claimWatched: watched} + run(t, c, r, ea) + setIngress(t, c, onlyRendered(t, c, ea), "203.0.113.7") + res, err := reconcileOnce(r, ea) + if err != nil { + t.Fatal(err) + } + expectCondition(t, getAttachment(t, c, ea), cozyv1alpha1.ConditionProvisioned, metav1.ConditionTrue, cozyv1alpha1.ReasonProvisioned) + if watched != (res.RequeueAfter == 0) { + t.Fatalf("claimWatched=%v: RequeueAfter = %s", watched, res.RequeueAfter) + } + } +} + +// TestSpecChangedDuringOwnershipPatch: the ownership patch returns the object +// as stored now; when that carries a newer spec, this reconcile stops instead +// of rendering from a mix of the two. +func TestSpecChangedDuringOwnershipPatch(t *testing.T) { + ea := dbAttachment() + c := newInterceptedClient(t, interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, o client.Object, p client.Patch, opts ...client.PatchOption) error { + if err := cl.Patch(ctx, o, p, opts...); err != nil { + return err + } + if got, ok := o.(*cozyv1alpha1.EndpointAttachment); ok { + got.Generation++ + } + return nil + }, + }, dbObjects(ea)...) + run(t, c, &Reconciler{Client: c}, ea) + if n := len(renderedServices(t, c, ea)); n != 0 { + t.Fatalf("nothing may be rendered from a spec that moved mid-reconcile, got %d", n) + } +} + +// TestFailedWithdrawalKeepsServiceName: a detach whose delete fails keeps +// naming the Service and says the withdrawal is pending. +func TestFailedWithdrawalKeepsServiceName(t *testing.T) { + ea := dbAttachment() + failDelete := false + c := newInterceptedClient(t, interceptor.Funcs{ + Delete: func(ctx context.Context, cl client.WithWatch, o client.Object, opts ...client.DeleteOption) error { + if svc, ok := o.(*corev1.Service); ok && failDelete && svc.Name != "postgres-mydb-ro" { + return errors.New("apiserver unavailable") + } + return cl.Delete(ctx, o, opts...) + }, + }, dbObjects(ea)...) + r := &Reconciler{Client: c} + run(t, c, r, ea) + own := onlyRendered(t, c, ea) + if err := c.Delete(context.TODO(), endpoint("postgres-mydb-ro", "Postgres", "mydb", nil)); err != nil { + t.Fatal(err) + } + failDelete = true + if _, err := reconcileOnce(r, ea); err == nil { + t.Fatal("a failed withdrawal must surface as an error") + } + got := getAttachment(t, c, ea) + if got.Status.ServiceName != own.Name { + t.Fatalf("status.serviceName = %q, want %q kept until the delete succeeds", got.Status.ServiceName, own.Name) + } + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonWithdrawalPending) + if c := meta.FindStatusCondition(got.Status.Conditions, cozyv1alpha1.ConditionProvisioned); !strings.Contains(c.Message, "pending") { + t.Fatalf("message must say the withdrawal is pending, got %q", c.Message) + } + if got.Status.Phase == cozyv1alpha1.EndpointAttachmentDetached { + t.Fatal("phase must not read Detached while the Service is still published") + } +} + +// TestRenderSettlesWithoutRewrites: once the stored Service matches, another +// reconcile sends no update, in either node-port mode and for the whole-IP +// sentinel port. +func TestRenderSettlesWithoutRewrites(t *testing.T) { + for _, nodePorts := range []bool{false, true} { + ea, objs := wholeIPVM(cozyv1alpha1.ExposureMethodWholeIP) + updates := 0 + c := newInterceptedClient(t, interceptor.Funcs{ + Update: func(ctx context.Context, cl client.WithWatch, o client.Object, opts ...client.UpdateOption) error { + if _, ok := o.(*corev1.Service); ok { + updates++ + } + return cl.Update(ctx, o, opts...) + }, + }, append(objs, endpointSlice("vm-instance-box-1", "vm-instance-box", true, "virt-launcher-box"))...) + r := &Reconciler{Client: c, CozyProxyContractImplemented: true, AllocateLoadBalancerNodePorts: nodePorts} + run(t, c, r, ea) + svc := onlyRendered(t, c, ea) + if svc.Spec.AllocateLoadBalancerNodePorts == nil || *svc.Spec.AllocateLoadBalancerNodePorts != nodePorts { + t.Fatalf("allocateLoadBalancerNodePorts = %v, want %v", svc.Spec.AllocateLoadBalancerNodePorts, nodePorts) + } + if svc.Spec.Ports[0].TargetPort != intstr.FromInt32(SentinelPort) { + t.Fatalf("sentinel targetPort = %v", svc.Spec.Ports[0].TargetPort) + } + updates = 0 + run(t, c, r, ea) + if updates != 0 { + t.Fatalf("nodePorts=%v: %d Service updates on an unchanged reconcile", nodePorts, updates) + } + } +} + +// TestPort65535IsNotAPlaceholder: a Service serving on 65535 is mirrored like +// any other; only the headless VM placeholder publishes nothing. +func TestPort65535IsNotAPlaceholder(t *testing.T) { + ea := attachment("app-ip", "ea-1", "Postgres", "mydb", "postgres-mydb-ro", cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held"}) + ep := endpoint("postgres-mydb-ro", "Postgres", "mydb", map[string]string{"role": "replica"}, SentinelPort) + ep.Spec.ClusterIP = "" + ep.Spec.Ports[0].TargetPort = intstr.FromInt32(8443) + objs := dbObjects(ea) + objs[1] = ep + c := newClient(t, objs...) + run(t, c, nil, ea) + svc := onlyRendered(t, c, ea) + if len(svc.Spec.Ports) != 1 || svc.Spec.Ports[0].Port != SentinelPort || svc.Spec.Ports[0].TargetPort != intstr.FromInt32(8443) { + t.Fatalf("ports = %+v, want the endpoint's mirrored", svc.Spec.Ports) + } +} + +// TestSelectorlessEndpointPublishesNothing: a Service with hand-managed +// endpoints has no selector to mirror, so nothing is rendered. +func TestSelectorlessEndpointPublishesNothing(t *testing.T) { + ea := dbAttachment() + objs := dbObjects(ea) + objs[1] = endpoint("postgres-mydb-ro", "Postgres", "mydb", nil, 5432) + c := newClient(t, objs...) + got := run(t, c, nil, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonNothingToPublish) + if n := len(renderedServices(t, c, ea)); n != 0 { + t.Fatalf("nothing may be rendered for a selectorless endpoint, got %d", n) + } +} + +// TestStoppedBindingIsKeptOnlyForItsEndpoint: retargeting an attachment +// whose VM is stopped withdraws the binding made for the old endpoint. +func TestStoppedBindingIsKeptOnlyForItsEndpoint(t *testing.T) { + ea, objs := wholeIPVM(cozyv1alpha1.ExposureMethodWholeIP) + fip := existingFloatingIP(ea, vpcIP) + fip.SetAnnotations(map[string]string{endpointAnnotation: "vm-instance-other"}) + c := newCozyplaneClient(t, append(objs, fip)...) + run(t, c, &Reconciler{CozyProxyContractImplemented: true}, ea) + if n := len(ownedFloatingIPs(t, c, ea)); n != 0 { + t.Fatalf("a binding for another endpoint must be withdrawn, %d left", n) + } +} + +// TestVPCAnnotationChangesEnqueue: a pod gaining or changing its VPC address +// enqueues the whole-IP attachments of its namespace, and unrelated pod +// changes do not. +func TestVPCAnnotationChangesEnqueue(t *testing.T) { + ea, objs := wholeIPVM(cozyv1alpha1.ExposureMethodWholeIP) + db := attachment("db-ip", "ea-2", "Postgres", "mydb", "postgres-mydb-ro", cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held"}) + c := newClient(t, append(objs, db)...) + r := &Reconciler{Client: c} + + p := vpcAnnotationsChanged() + before := launcherPod("virt-launcher-box", vpcName, "", nil) + after := launcherPod("virt-launcher-box", vpcName, vpcIP, nil) + if !p.Update(event.UpdateEvent{ObjectOld: before, ObjectNew: after}) { + t.Fatal("a newly stamped VPC address must enqueue") + } + if p.Update(event.UpdateEvent{ObjectOld: after, ObjectNew: after.DeepCopy()}) { + t.Fatal("an unchanged VPC address must not enqueue") + } + if p.Create(event.CreateEvent{Object: launcherPod("plain", "", "", nil)}) { + t.Fatal("a pod outside any VPC must not enqueue") + } + reqs := r.mapPod(context.TODO(), after) + if len(reqs) != 1 || reqs[0].Name != ea.Name { + t.Fatalf("enqueued %v, want only the whole-IP attachment %s", reqs, ea.Name) + } +} + +// TestAttachedNeedsThisGenerationOnEarlyFailure: a reconcile of a new spec +// that fails before it reaches the Provisioned step leaves the previous +// generation's Provisioned=True in place, which alone must not read Attached. +func TestAttachedNeedsThisGenerationOnEarlyFailure(t *testing.T) { + ea := dbAttachment() + fail := false + c := newInterceptedClient(t, interceptor.Funcs{ + List: func(ctx context.Context, cl client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + if _, ok := list.(*corev1.ServiceList); ok && fail { + return errors.New("apiserver unavailable") + } + return cl.List(ctx, list, opts...) + }, + }, dbObjects(ea)...) + r := &Reconciler{Client: c} + run(t, c, r, ea) + setIngress(t, c, onlyRendered(t, c, ea), "203.0.113.7") + run(t, c, r, ea) + + live := getAttachment(t, c, ea) + live.Spec.LoadBalancer.Ports = []int32{5432} + live.Generation = 2 + if err := c.Update(context.TODO(), live); err != nil { + t.Fatal(err) + } + fail = true + if _, err := reconcileOnce(r, ea); err == nil { + t.Fatal("the failed lookup must surface as an error") + } + if got := getAttachment(t, c, ea); got.Status.Phase == cozyv1alpha1.EndpointAttachmentAttached { + t.Fatal("a previous generation's Provisioned=True must not project Attached") + } +} + +// TestWithdrawalReachesServicesTheCacheMissed: a detach withdraws every +// owned Service the API holds, not only the one the cache showed. +func TestWithdrawalReachesServicesTheCacheMissed(t *testing.T) { + ea := dbAttachment() + owned := func(name string, age time.Duration) *corev1.Service { + return &corev1.Service{ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: name, UID: types.UID("svc-" + name), + CreationTimestamp: metav1.NewTime(time.Now().Add(-age)), + OwnerReferences: []metav1.OwnerReference{controllerOwnerReference(ea)}}} + } + objs := dbObjects(ea) + objs = append(objs[:1], objs[2:]...) // no endpoint Service: the attachment detaches + backing := newClient(t, append(objs, owned("ro-public-seen", time.Hour), owned("ro-public-unseen", time.Minute))...) + c := interceptor.NewClient(backing.(client.WithWatch), interceptor.Funcs{ + List: func(ctx context.Context, cl client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + if err := cl.List(ctx, list, opts...); err != nil { + return err + } + if sl, ok := list.(*corev1.ServiceList); ok { + var kept []corev1.Service + for _, svc := range sl.Items { + if svc.Name != "ro-public-unseen" { + kept = append(kept, svc) + } + } + sl.Items = kept + } + return nil + }, + }) + if _, err := reconcileOnce(&Reconciler{Client: c, Reader: backing}, ea); err != nil { + t.Fatal(err) + } + if n := len(renderedServices(t, backing, ea)); n != 0 { + t.Fatalf("every owned Service must be withdrawn, %d left", n) + } +} + +// TestSelectorLossWithdrawsBeforeTheClaim: an endpoint that loses its +// selector withdraws what was published even when the claim is gone too. +func TestSelectorLossWithdrawsBeforeTheClaim(t *testing.T) { + ea := dbAttachment() + c := newClient(t, dbObjects(ea)...) + run(t, c, nil, ea) + own := onlyRendered(t, c, ea) + + ep := &corev1.Service{} + if err := c.Get(context.TODO(), types.NamespacedName{Namespace: ns, Name: "postgres-mydb-ro"}, ep); err != nil { + t.Fatal(err) + } + ep.Spec.Selector = nil + if err := c.Update(context.TODO(), ep); err != nil { + t.Fatal(err) + } + claim := newClaim() + if err := c.Get(context.TODO(), types.NamespacedName{Namespace: ns, Name: "held"}, claim); err != nil { + t.Fatal(err) + } + if err := c.Delete(context.TODO(), claim); err != nil { + t.Fatal(err) + } + got := run(t, c, nil, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonNothingToPublish) + if err := c.Get(context.TODO(), client.ObjectKeyFromObject(own), &corev1.Service{}); err == nil { + t.Fatal("the Service mirroring the old selector must be withdrawn") + } +} + +// TestMissingClaimIsNotReportedHeld: a referenced claim that is gone is no +// longer named in status, and a later detach does not claim it holds an +// address. +func TestMissingClaimIsNotReportedHeld(t *testing.T) { + ea := dbAttachment() + c := newClient(t, dbObjects(ea)...) + run(t, c, nil, ea) + + claim := newClaim() + if err := c.Get(context.TODO(), types.NamespacedName{Namespace: ns, Name: "held"}, claim); err != nil { + t.Fatal(err) + } + if err := c.Delete(context.TODO(), claim); err != nil { + t.Fatal(err) + } + got := run(t, c, nil, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonClaimNotFound) + if got.Status.ClaimName != "" || len(got.Status.Addresses) != 0 { + t.Fatalf("a missing claim must not stay in status: %+v", got.Status) + } + + live := getAttachment(t, c, ea) + live.Status.ClaimName = "held" + if err := c.Status().Update(context.TODO(), live); err != nil { + t.Fatal(err) + } + if err := c.Delete(context.TODO(), endpoint("postgres-mydb-ro", "Postgres", "mydb", nil)); err != nil { + t.Fatal(err) + } + got = run(t, c, nil, ea) + if c := meta.FindStatusCondition(got.Status.Conditions, cozyv1alpha1.ConditionProvisioned); c != nil && strings.Contains(c.Message, "held by") { + t.Fatalf("a detach must not report a missing claim as holding the address: %q", c.Message) + } + if got.Status.ClaimName != "" { + t.Fatalf("status.claimName = %q for a claim that no longer exists", got.Status.ClaimName) + } +} + +// TestSwitchWaitsForAFinalizedService: a Service held by a finalizer stays +// listed after its delete is accepted, and no FloatingIP wears the claim +// until it is gone. +func TestSwitchWaitsForAFinalizedService(t *testing.T) { + ea, objs := wholeIPVM(cozyv1alpha1.ExposureMethodWholeIP) + c := newCozyplaneClient(t, append(objs, + launcherPod("virt-launcher-box", vpcName, vpcIP, nil), + endpointSlice("vm-instance-box-1", "vm-instance-box", true, "virt-launcher-box"), + &corev1.Service{ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: "box-ip-old", UID: "svc-old", + Finalizers: []string{"service.kubernetes.io/load-balancer-cleanup"}, + OwnerReferences: []metav1.OwnerReference{controllerOwnerReference(ea)}}})...) + r := &Reconciler{CozyProxyContractImplemented: true} + for i := 0; i < 2; i++ { + got := run(t, c, r, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonWithdrawalPending) + if n := len(ownedFloatingIPs(t, c, ea)); n != 0 { + t.Fatalf("pass %d: no FloatingIP while the old Service is still being removed, got %d", i, n) + } + } + old := &corev1.Service{} + if err := c.Get(context.TODO(), types.NamespacedName{Namespace: ns, Name: "box-ip-old"}, old); err != nil { + t.Fatal(err) + } + old.Finalizers = nil + if err := c.Update(context.TODO(), old); err != nil { + t.Fatal(err) + } + run(t, c, r, ea) + onlyFloatingIP(t, c, ea) +} + +// TestUnstampedBackendHoldsTheBinding: while one backend has no VPC address +// yet, nothing is bound or re-pointed, and a binding made for another +// endpoint is withdrawn. +func TestUnstampedBackendHoldsTheBinding(t *testing.T) { + t.Run("no binding yet", func(t *testing.T) { + ea, objs := wholeIPVM(cozyv1alpha1.ExposureMethodWholeIP) + c := newCozyplaneClient(t, append(objs, + launcherPod("virt-launcher-a", vpcName, vpcIP, nil), + launcherPod("virt-launcher-b", vpcName, "", nil), + endpointSlice("vm-instance-box-1", "vm-instance-box", true, "virt-launcher-a", "virt-launcher-b"))...) + got := run(t, c, nil, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonWaitingForVPCAddress) + if n := len(ownedFloatingIPs(t, c, ea)); n != 0 { + t.Fatalf("nothing may be bound while a backend is unstamped, got %d", n) + } + }) + t.Run("binding for this endpoint stays as it is", func(t *testing.T) { + ea, objs := wholeIPVM(cozyv1alpha1.ExposureMethodWholeIP) + fip := existingFloatingIP(ea, "10.10.0.9") + fip.SetAnnotations(map[string]string{endpointAnnotation: "vm-instance-box"}) + c := newCozyplaneClient(t, append(objs, fip, + launcherPod("virt-launcher-a", vpcName, vpcIP, nil), + launcherPod("virt-launcher-b", vpcName, "", nil), + endpointSlice("vm-instance-box-1", "vm-instance-box", true, "virt-launcher-a", "virt-launcher-b"))...) + run(t, c, nil, ea) + if v, _, _ := unstructured.NestedString(onlyFloatingIP(t, c, ea).Object, "spec", "target"); v != "10.10.0.9" { + t.Fatalf("target re-pointed to %q before every backend was stamped", v) + } + }) + t.Run("binding for another endpoint goes", func(t *testing.T) { + ea, objs := wholeIPVM(cozyv1alpha1.ExposureMethodWholeIP) + fip := existingFloatingIP(ea, vpcIP) + fip.SetAnnotations(map[string]string{endpointAnnotation: "vm-instance-other"}) + c := newCozyplaneClient(t, append(objs, fip, + launcherPod("virt-launcher-box", vpcName, "", nil), + endpointSlice("vm-instance-box-1", "vm-instance-box", true, "virt-launcher-box"))...) + got := run(t, c, nil, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonWaitingForVPCAddress) + if n := len(ownedFloatingIPs(t, c, ea)); n != 0 { + t.Fatalf("the old endpoint's binding must be withdrawn, %d left", n) + } + }) +} + +// TestOwnershipPatchRefusesAReplacedObject: the ownership patch carries the +// resource version it read, so it cannot land on a same-name replacement. +func TestOwnershipPatchRefusesAReplacedObject(t *testing.T) { + ea := dbAttachment() + c := newClient(t, dbObjects(ea)...) + stale := getAttachment(t, c, ea) + live := stale.DeepCopy() + live.Labels = map[string]string{"touched": "true"} + if err := c.Update(context.TODO(), live); err != nil { + t.Fatal(err) + } + r := &Reconciler{Client: c} + if _, err := r.ensureAttachmentOwnership(context.TODO(), stale, helmRelease("postgres-mydb", "hr-1", "Postgres", "mydb")); err == nil { + t.Fatal("a patch from a stale read must conflict") + } +} + +type failingMapper struct{ meta.RESTMapper } + +func (failingMapper) RESTMapping(schema.GroupKind, ...string) (*meta.RESTMapping, error) { + return nil, errors.New("the server is currently unable to handle the request") +} + +// TestOptionalKindDiscovery: a kind that is not served is no error, and a +// failed discovery is reported to the caller rather than ending setup. +func TestOptionalKindDiscovery(t *testing.T) { + m := meta.NewDefaultRESTMapper(nil) + m.Add(floatingIPGVK, meta.RESTScopeNamespace) + if served, err := kindServed(m, floatingIPGVK); !served || err != nil { + t.Fatalf("served kind: served=%v err=%v", served, err) + } + if served, err := kindServed(m, claimGVK); served || err != nil { + t.Fatalf("unserved kind: served=%v err=%v", served, err) + } + if served, err := kindServed(failingMapper{m}, floatingIPGVK); served || err == nil { + t.Fatalf("failed discovery: served=%v err=%v", served, err) + } +} + +// TestDetachedNeedsThisGeneration: a Detached left by an earlier generation +// must not describe a retargeted spec the controller has not evaluated. +func TestDetachedNeedsThisGeneration(t *testing.T) { + ea := dbAttachment() + objs := dbObjects(ea) + objs = append(objs[:1], objs[2:]...) + fail := false + c := newInterceptedClient(t, interceptor.Funcs{ + List: func(ctx context.Context, cl client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + if fail { + return errors.New("apiserver unavailable") + } + return cl.List(ctx, list, opts...) + }, + }, objs...) + r := &Reconciler{Client: c} + if got := run(t, c, r, ea); got.Status.Phase != cozyv1alpha1.EndpointAttachmentDetached && got.Status.Phase != cozyv1alpha1.EndpointAttachmentPending { + t.Fatalf("phase = %s", got.Status.Phase) + } + live := getAttachment(t, c, ea) + live.Status.Conditions = nil + if err := c.Status().Update(context.TODO(), live); err != nil { + t.Fatal(err) + } + ea2 := getAttachment(t, c, ea) + ea2.Status.Conditions = []metav1.Condition{ + {Type: cozyv1alpha1.ConditionResolved, Status: metav1.ConditionFalse, Reason: cozyv1alpha1.ReasonEndpointNotFound, ObservedGeneration: 1, LastTransitionTime: metav1.Now()}, + {Type: cozyv1alpha1.ConditionProvisioned, Status: metav1.ConditionFalse, Reason: cozyv1alpha1.ReasonEndpointDetached, ObservedGeneration: 1, LastTransitionTime: metav1.Now()}, + } + if err := c.Status().Update(context.TODO(), ea2); err != nil { + t.Fatal(err) + } + ea3 := getAttachment(t, c, ea) + ea3.Spec.Endpoint.ServiceName = "postgres-mydb-rw" + ea3.Generation = 2 + if err := c.Update(context.TODO(), ea3); err != nil { + t.Fatal(err) + } + fail = true + if _, err := reconcileOnce(r, ea); err == nil { + t.Fatal("the failed lookup must surface") + } + if got := getAttachment(t, c, ea); got.Status.Phase == cozyv1alpha1.EndpointAttachmentDetached { + t.Fatal("an earlier generation's Detached must not describe the retargeted spec") + } +} + +// TestChartDelegationWins: a delegated Service the attachment does not own, +// such as a vm-instance chart Service with external: true, takes the backend +// even when it appears after the attachment's own Service, because nothing +// would ever withdraw it. +func TestChartDelegationWins(t *testing.T) { + ea, objs := wholeIPVM(cozyv1alpha1.ExposureMethodWholeIP) + c := newClient(t, append(objs, endpointSlice("vm-instance-box-1", "vm-instance-box", true, "virt-launcher-box"))...) + r := &Reconciler{CozyProxyContractImplemented: true} + run(t, c, r, ea) + own := onlyRendered(t, c, ea) + + chart := &corev1.Service{ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: "vm-instance-box-external", UID: "svc-chart", + CreationTimestamp: metav1.NewTime(own.CreationTimestamp.Add(time.Hour)), + Labels: map[string]string{ServiceProxyNameLabel: ServiceProxyName}, + Annotations: map[string]string{WholeIPAnnotation: "false"}}, + Spec: corev1.ServiceSpec{Type: corev1.ServiceTypeLoadBalancer, Selector: map[string]string{"vm": "box"}, + Ports: []corev1.ServicePort{{Name: "port-22", Port: 22}}}} + for _, o := range []client.Object{chart, endpointSlice("vm-instance-box-external-1", chart.Name, true, "virt-launcher-box")} { + if err := c.Create(context.TODO(), o); err != nil { + t.Fatal(err) + } + } + got := run(t, c, r, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonBackendAlreadyDelegated) + if err := c.Get(context.TODO(), client.ObjectKeyFromObject(own), &corev1.Service{}); err == nil { + t.Fatal("the attachment's Service must yield the backend to the chart's") + } + if err := c.Get(context.TODO(), client.ObjectKeyFromObject(chart), &corev1.Service{}); err != nil { + t.Fatalf("the chart's Service must be left alone: %v", err) + } +} + +// TestDualClaimRefusedInVPC: a FloatingIP wears one address, so a Dual +// claim is refused on the VPC path rather than bound and left pending, and a +// binding made earlier is withdrawn. +func TestDualClaimRefusedInVPC(t *testing.T) { + for _, withFIP := range []bool{false, true} { + ea, objs := wholeIPVM(cozyv1alpha1.ExposureMethodWholeIP) + for i, o := range objs { + if u, ok := o.(*unstructured.Unstructured); ok && u.GetName() == "held" { + objs[i] = claimObject("held", "public", "Dual", true, "203.0.113.7", "2001:db8::7") + } + } + objs = append(objs, + launcherPod("virt-launcher-box", vpcName, vpcIP, nil), + endpointSlice("vm-instance-box-1", "vm-instance-box", true, "virt-launcher-box")) + if withFIP { + objs = append(objs, existingFloatingIP(ea, vpcIP)) + } + c := newCozyplaneClient(t, objs...) + got := run(t, c, nil, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonDualStackUnsupportedInVPC) + if n := len(ownedFloatingIPs(t, c, ea)); n != 0 { + t.Fatalf("withFIP=%v: no FloatingIP may stand for a Dual claim, got %d", withFIP, n) + } + if n := len(renderedServices(t, c, ea)); n != 0 { + t.Fatalf("withFIP=%v: no Service either, got %d", withFIP, n) + } + } +} + +// TestKCCMServiceIsNotAnEndpoint: a LoadBalancer Service the cloud-controller- +// manager of a tenant Kubernetes cluster creates carries the cluster's +// lineage and the tenant-resource mark, but belongs to a workload inside that +// cluster, so it is not attachable. +func TestKCCMServiceIsNotAnEndpoint(t *testing.T) { + ea := attachment("lb-ip", "ea-1", "Kubernetes", "mycluster", "a1b2c3d4", cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held"}) + kccm := endpoint("a1b2c3d4", "Kubernetes", "mycluster", map[string]string{"app": "web"}, 443) + kccm.Labels[kccmTenantServiceLabel] = "web-lb" + c := newClient(t, ea, kccm, + helmRelease("kubernetes-mycluster", "hr-1", "Kubernetes", "mycluster"), + claimObject("held", "public", "IPv4", true, "203.0.113.7"), classObject("public", "")) + got := run(t, c, nil, ea) + expectCondition(t, got, cozyv1alpha1.ConditionResolved, metav1.ConditionFalse, cozyv1alpha1.ReasonEndpointNotTenantFacing) + if n := len(renderedServices(t, c, ea)); n != 0 { + t.Fatalf("nothing may be rendered for a kccm Service, got %d", n) + } +} + +// TestUnrecordedBindingIsNotKept: a FloatingIP made before the endpoint was +// recorded on it cannot be told to belong to the current endpoint, so it is +// not kept for a stopped VM or across a retarget. +func TestUnrecordedBindingIsNotKept(t *testing.T) { + for _, tt := range []struct { + name string + pods []client.Object + }{ + {name: "stopped VM"}, + {name: "retarget onto an unstamped pod", pods: []client.Object{ + launcherPod("virt-launcher-box", vpcName, "", nil), + endpointSlice("vm-instance-box-1", "vm-instance-box", true, "virt-launcher-box"), + }}, + } { + t.Run(tt.name, func(t *testing.T) { + ea, objs := wholeIPVM(cozyv1alpha1.ExposureMethodWholeIP) + fip := existingFloatingIP(ea, vpcIP) + fip.SetAnnotations(nil) + c := newCozyplaneClient(t, append(append(objs, fip), tt.pods...)...) + run(t, c, &Reconciler{CozyProxyContractImplemented: true}, ea) + if n := len(ownedFloatingIPs(t, c, ea)); n != 0 { + t.Fatalf("an unrecorded binding must be withdrawn, %d left", n) + } + }) + } +} + +// TestServiceWaitsForTheFloatingIPsService: the switch from a FloatingIP back +// to a Service deletes the FloatingIP in the foreground, which keeps it +// listed until the Service it owns is gone, and renders nothing while it is +// listed, whether or not the substrate recorded that Service as the claim's +// holder. +func TestServiceWaitsForTheFloatingIPsService(t *testing.T) { + ea, objs := wholeIPVM(cozyv1alpha1.ExposureMethodWholeIP) + fip := existingFloatingIP(ea, vpcIP) + fip.SetFinalizers([]string{metav1.FinalizerDeleteDependents}) + fipSvc := &corev1.Service{ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: "box-ip-fip01-abcde", UID: "fip-svc", + Annotations: map[string]string{ClaimAnnotation: "held"}, + OwnerReferences: []metav1.OwnerReference{{APIVersion: "sdn.cozystack.io/v1alpha1", Kind: "FloatingIP", Name: fip.GetName(), UID: fip.GetUID(), Controller: new(true)}}}} + var policies []metav1.DeletionPropagation + m := meta.NewDefaultRESTMapper(nil) + m.Add(floatingIPGVK, meta.RESTScopeNamespace) + c := fake.NewClientBuilder().WithScheme(newScheme(t)).WithRESTMapper(m). + WithStatusSubresource(&cozyv1alpha1.EndpointAttachment{}). + WithObjects(withBackendPods(append(objs, fip, fipSvc, + launcherPod("virt-launcher-box", "", "", nil), + endpointSlice("vm-instance-box-1", "vm-instance-box", true, "virt-launcher-box")))...). + WithInterceptorFuncs(interceptor.Funcs{ + Delete: func(ctx context.Context, cl client.WithWatch, o client.Object, opts ...client.DeleteOption) error { + if u, ok := o.(*unstructured.Unstructured); ok && u.GroupVersionKind().Kind == "FloatingIP" { + do := &client.DeleteOptions{} + do.ApplyOptions(opts) + if do.PropagationPolicy != nil { + policies = append(policies, *do.PropagationPolicy) + } + } + return cl.Delete(ctx, o, opts...) + }, + }).Build() + r := &Reconciler{CozyProxyContractImplemented: true} + for i := 0; i < 2; i++ { + got := run(t, c, r, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonWithdrawalPending) + if n := len(renderedServices(t, c, ea)); n != 0 { + t.Fatalf("pass %d: no Service while the FloatingIP's own Service may still wear the claim, got %d", i, n) + } + } + if len(policies) == 0 || policies[0] != metav1.DeletePropagationForeground { + t.Fatalf("the FloatingIP must be deleted in the foreground, got %v", policies) + } + live := newFloatingIP() + if err := c.Get(context.TODO(), client.ObjectKeyFromObject(fip), live); err != nil { + t.Fatal(err) + } + live.SetFinalizers(nil) + if err := c.Update(context.TODO(), live); err != nil { + t.Fatal(err) + } + if err := c.Delete(context.TODO(), fipSvc); err != nil { + t.Fatal(err) + } + run(t, c, r, ea) + onlyRendered(t, c, ea) +} + +// TestCozyProxyRefusesNonIPv4: cozy-proxy programs IPv4 only, so a method +// attachment on its path with an IPv6 or Dual claim renders nothing, and a +// Service rendered earlier is withdrawn. The cozyplane FloatingIP path still +// serves IPv6, and a plain attachment with no method is not affected. +func TestCozyProxyRefusesNonIPv4(t *testing.T) { + claims := map[string][]string{"IPv6": {"2001:db8::7"}, "Dual": {"203.0.113.7", "2001:db8::7"}} + for _, method := range []cozyv1alpha1.ExposureMethod{cozyv1alpha1.ExposureMethodWholeIP, cozyv1alpha1.ExposureMethodPortList} { + for family, addrs := range claims { + t.Run(string(method)+"/"+family, func(t *testing.T) { + ea, objs := wholeIPVM(method) + for i, o := range objs { + if u, ok := o.(*unstructured.Unstructured); ok && u.GetName() == "held" { + objs[i] = claimObject("held", "public", family, true, addrs...) + } + } + c := newClient(t, append(objs, endpointSlice("vm-instance-box-1", "vm-instance-box", true, "virt-launcher-box"))...) + stale := &corev1.Service{ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: "box-ip-old", UID: "svc-old", + OwnerReferences: []metav1.OwnerReference{controllerOwnerReference(ea)}}, + Spec: corev1.ServiceSpec{Type: corev1.ServiceTypeLoadBalancer, Ports: []corev1.ServicePort{{Port: 22}}}} + if err := c.Create(context.TODO(), stale); err != nil { + t.Fatal(err) + } + got := run(t, c, &Reconciler{CozyProxyContractImplemented: true}, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonFamilyUnsupportedByDatapath) + if n := len(renderedServices(t, c, ea)); n != 0 { + t.Fatalf("no Service may stand for a %s claim on the cozy-proxy path, got %d", family, n) + } + }) + } + } + t.Run("cozyplane serves IPv6", func(t *testing.T) { + ea, objs := wholeIPVM(cozyv1alpha1.ExposureMethodWholeIP) + for i, o := range objs { + if u, ok := o.(*unstructured.Unstructured); ok && u.GetName() == "held" { + objs[i] = claimObject("held", "public", "IPv6", true, "2001:db8::7") + } + } + c := newCozyplaneClient(t, append(objs, + launcherPod("virt-launcher-box", vpcName, vpcIP, nil), + endpointSlice("vm-instance-box-1", "vm-instance-box", true, "virt-launcher-box"))...) + run(t, c, nil, ea) + onlyFloatingIP(t, c, ea) + }) + t.Run("no method is not affected", func(t *testing.T) { + ea := attachment("ro-public", "ea-1", "Postgres", "mydb", "postgres-mydb-ro", cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held"}) + c := newClient(t, helmRelease("postgres-mydb", "hr-1", "Postgres", "mydb"), ea, + endpoint("postgres-mydb-ro", "Postgres", "mydb", map[string]string{"role": "replica"}, 5432), + claimObject("held", "public", "IPv6", true, "2001:db8::7"), classObject("public", "")) + run(t, c, nil, ea) + onlyRendered(t, c, ea) + }) +} + +// TestNothingRendersBeforeTheClassIsAccepted: a consumer's loadBalancerClass +// is fixed at creation, and the class's provisioner reports it in status, so +// neither a Service nor a FloatingIP is created until the class is Accepted +// for its current generation. An empty status.loadBalancerClass before that +// means not reported yet, not the cluster default. +func TestNothingRendersBeforeTheClassIsAccepted(t *testing.T) { + notReported := pendingClassObject("public") + stale := classObject("public", "metallb.io/public") + stale.SetGeneration(2) + refused := classObject("public", "") + refused.Object["status"].(map[string]interface{})["conditions"] = []interface{}{map[string]interface{}{ + "type": "Accepted", "status": "False", "reason": "PoolRefused", "message": "IPAddressPool cozy-metallb/public auto-assigns", "observedGeneration": int64(1), + }} + for name, class := range map[string]*unstructured.Unstructured{"not reported": notReported, "stale generation": stale, "refused": refused} { + t.Run("service/"+name, func(t *testing.T) { + ea := attachment("ro-public", "ea-1", "Postgres", "mydb", "postgres-mydb-ro", cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held"}) + c := newClient(t, helmRelease("postgres-mydb", "hr-1", "Postgres", "mydb"), ea, + endpoint("postgres-mydb-ro", "Postgres", "mydb", map[string]string{"role": "replica"}, 5432), + claimObject("held", "public", "IPv4", true, "203.0.113.7"), class.DeepCopy()) + got := run(t, c, nil, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonClassNotAccepted) + if n := len(renderedServices(t, c, ea)); n != 0 { + t.Fatalf("no Service may be created before the class is accepted, got %d", n) + } + }) + t.Run("floatingip/"+name, func(t *testing.T) { + ea, objs := wholeIPVM(cozyv1alpha1.ExposureMethodWholeIP) + for i, o := range objs { + if u, ok := o.(*unstructured.Unstructured); ok && u.GroupVersionKind() == classGVK { + objs[i] = class.DeepCopy() + } + } + c := newCozyplaneClient(t, append(objs, + launcherPod("virt-launcher-box", vpcName, vpcIP, nil), + endpointSlice("vm-instance-box-1", "vm-instance-box", true, "virt-launcher-box"))...) + got := run(t, c, nil, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonClassNotAccepted) + if n := len(ownedFloatingIPs(t, c, ea)); n != 0 { + t.Fatalf("no FloatingIP may be created before the class is accepted, got %d", n) + } + }) + } +} + +// TestPublishedServiceSurvivesClassLosingAcceptance: a class whose +// provisioner withdraws acceptance later, such as a pool turned unusable, +// does not take a live address down with it. +func TestPublishedServiceSurvivesClassLosingAcceptance(t *testing.T) { + ea := attachment("ro-public", "ea-1", "Postgres", "mydb", "postgres-mydb-ro", cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held"}) + c := newClient(t, helmRelease("postgres-mydb", "hr-1", "Postgres", "mydb"), ea, + endpoint("postgres-mydb-ro", "Postgres", "mydb", map[string]string{"role": "replica"}, 5432), + claimObject("held", "public", "IPv4", true, "203.0.113.7"), classObject("public", "")) + run(t, c, nil, ea) + svc := onlyRendered(t, c, ea) + + class := &unstructured.Unstructured{} + class.SetGroupVersionKind(classGVK) + if err := c.Get(context.TODO(), client.ObjectKey{Name: "public"}, class); err != nil { + t.Fatal(err) + } + class.Object["status"].(map[string]interface{})["conditions"] = []interface{}{map[string]interface{}{ + "type": "Accepted", "status": "False", "reason": "PoolRefused", "observedGeneration": int64(1), + }} + if err := c.Update(context.TODO(), class); err != nil { + t.Fatal(err) + } + got := run(t, c, nil, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonClassNotAccepted) + if live := onlyRendered(t, c, ea); live.UID != svc.UID { + t.Fatal("the published Service must stay while the class is not accepted") + } +} diff --git a/internal/controller/endpointattachment/reconciler.go b/internal/controller/endpointattachment/reconciler.go new file mode 100644 index 000000000..625d9e101 --- /dev/null +++ b/internal/controller/endpointattachment/reconciler.go @@ -0,0 +1,879 @@ +/* +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 endpointattachment reconciles EndpointAttachment objects: it +// resolves one tenant-facing Service of a managed application, draws an +// address through the address substrate, and renders one additive +// LoadBalancer Service that mirrors the endpoint. It is engine-agnostic and +// knows nothing about TLS, hostnames or the CNI in use. +package endpointattachment + +import ( + "context" + "fmt" + "sort" + "strings" + "time" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + corev1 "k8s.io/api/core/v1" + discoveryv1 "k8s.io/api/discovery/v1" + "k8s.io/apimachinery/pkg/api/equality" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/tools/record" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/builder" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/event" + "sigs.k8s.io/controller-runtime/pkg/handler" + "sigs.k8s.io/controller-runtime/pkg/predicate" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/localsdn/v1alpha1" + appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1" + corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1" +) + +const ( + defaultApplicationGroup = "apps.cozystack.io" + + // kccmTenantServiceLabel is the label the kubevirt cloud-controller-manager + // of a tenant Kubernetes cluster writes on each LoadBalancer Service it + // creates in the cluster's namespace, naming the Service inside the tenant + // cluster it realises. Those Services carry the cluster's lineage and the + // tenant-resource mark, since the Kubernetes application definition selects + // Services by cluster label, so this label is what sets them apart. + kccmTenantServiceLabel = "cluster.x-k8s.io/tenant-service-name" + + indexEndpointService = ".spec.endpoint.serviceName" + indexClaimName = ".spec.loadBalancer.claimName" + indexApplication = ".spec.applicationRef" + + // requeueBackstop covers the states that wait on the address substrate + // when its kinds cannot be watched (CRDs absent at startup). + requeueBackstop = time.Minute + + // withdrawalRequeue paces the wait for a withdrawn consumer to disappear + // before its replacement is created; a Service with a finalizer stays + // listed for a while after its delete was accepted. + withdrawalRequeue = 5 * time.Second +) + +// Reconciler reconciles EndpointAttachment objects. +type Reconciler struct { + client.Client + Scheme *runtime.Scheme + Recorder record.EventRecorder + + // CozyProxyContractImplemented declares that a proxy answering to the + // cozy-proxy service-proxy-name is deployed on this cluster. It is a + // platform declaration, not a detection: without it a method-bearing + // attachment renders no Service at all, because every proxy skips a + // Service delegated to a name it does not claim while the load balancer + // still attracts the address, leaving a routable address that drops + // everything. + CozyProxyContractImplemented bool + + // AllocateLoadBalancerNodePorts follows the platform's LoadBalancer + // convention; false renders allocateLoadBalancerNodePorts: false. + AllocateLoadBalancerNodePorts bool + + // Reader reads past the cache, to recheck that no Service is rendered yet + // before creating one: the cache may not have seen a Service created by the + // previous reconcile. Nil falls back to the client. + Reader client.Reader + + // claimWatched and floatingIPWatched record whether SetupWithManager could + // register those watches; a kind served only after startup is picked up by + // the requeue backstop instead, including once the attachment is settled. + claimWatched bool + floatingIPWatched bool +} + +// settled is the result of a reconcile that reached its goal. Without a watch +// on a kind it depends on, nothing would enqueue the attachment on that kind's +// changes, so it keeps polling. +func (r *Reconciler) settled(watched bool) ctrl.Result { + if watched { + return ctrl.Result{} + } + return ctrl.Result{RequeueAfter: requeueBackstop} +} + +// Reconcile drives one attachment through resolve, claim, render and report. +func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + ea := &cozyv1alpha1.EndpointAttachment{} + if err := r.Get(ctx, req.NamespacedName, ea); err != nil { + return ctrl.Result{}, client.IgnoreNotFound(err) + } + if !ea.DeletionTimestamp.IsZero() { + return ctrl.Result{}, nil + } + origStatus := ea.Status.DeepCopy() + ea.Status.ObservedGeneration = ea.Generation + + res, rerr := r.reconcile(ctx, ea) + projectPhase(ea) + + if !equality.Semantic.DeepEqual(origStatus, &ea.Status) { + base := ea.DeepCopy() + base.Status = *origStatus + if err := r.Status().Patch(ctx, ea, client.MergeFrom(base)); err != nil { + if rerr == nil { + rerr = fmt.Errorf("update status: %w", err) + } + } + } + return res, rerr +} + +func (r *Reconciler) reconcile(ctx context.Context, ea *cozyv1alpha1.EndpointAttachment) (ctrl.Result, error) { + lb := ea.Spec.LoadBalancer + if lb == nil { + setUnresolved(ea, cozyv1alpha1.ReasonRenderFailed, "no mechanism member is set") + return ctrl.Result{}, r.withdrawAll(ctx, ea) + } + + hr, err := r.applicationRelease(ctx, ea) + if err != nil { + return ctrl.Result{}, err + } + if hr == nil { + setUnresolved(ea, cozyv1alpha1.ReasonApplicationNotFound, + fmt.Sprintf("no %s %s in namespace %s", ea.Spec.ApplicationRef.Kind, ea.Spec.ApplicationRef.Name, ea.Namespace)) + return r.detach(ctx, ea, cozyv1alpha1.ReasonApplicationNotFound) + } + if ref := helmReleaseOwner(ea); ref != nil && ref.UID != hr.UID { + setUnresolved(ea, cozyv1alpha1.ReasonApplicationIncarnationChange, + fmt.Sprintf("%s %s was recreated (HelmRelease %s now has UID %s, this attachment belongs to UID %s); it will be garbage-collected with the previous incarnation", + ea.Spec.ApplicationRef.Kind, ea.Spec.ApplicationRef.Name, hr.Name, hr.UID, ref.UID)) + return r.detach(ctx, ea, cozyv1alpha1.ReasonApplicationIncarnationChange) + } + if moved, err := r.ensureAttachmentOwnership(ctx, ea, hr); err != nil { + return ctrl.Result{}, err + } else if moved { + // The spec changed since this reconcile read it; the update event + // that brought the change reconciles it afresh. + return ctrl.Result{}, nil + } + + endpoint := &corev1.Service{} + if err := r.Get(ctx, types.NamespacedName{Namespace: ea.Namespace, Name: ea.Spec.Endpoint.ServiceName}, endpoint); err != nil { + if !apierrors.IsNotFound(err) { + return ctrl.Result{}, err + } + setUnresolved(ea, cozyv1alpha1.ReasonEndpointNotFound, + fmt.Sprintf("Service %s not found in namespace %s", ea.Spec.Endpoint.ServiceName, ea.Namespace)) + return r.detach(ctx, ea, cozyv1alpha1.ReasonEndpointNotFound) + } + if reason, msg := endpointDenied(ea, endpoint); reason != "" { + setUnresolved(ea, reason, msg) + return r.detach(ctx, ea, reason) + } + setResolved(ea, cozyv1alpha1.ReasonResolved, + fmt.Sprintf("Service %s is a tenant-facing endpoint of %s %s", endpoint.Name, ea.Spec.ApplicationRef.Kind, ea.Spec.ApplicationRef.Name)) + + own, err := r.ownedService(ctx, ea) + if err != nil { + return ctrl.Result{}, err + } + fip, fipServed, err := r.ownedFloatingIP(ctx, ea) + if err != nil { + return ctrl.Result{}, err + } + if len(endpoint.Spec.Selector) == 0 { + setUnprovisioned(ea, cozyv1alpha1.ReasonNothingToPublish, + fmt.Sprintf("Service %s has no selector: its endpoints are managed by hand, and a mirror carries the selector, not the endpoints", endpoint.Name)) + return ctrl.Result{}, r.withdrawAll(ctx, ea) + } + var vb vpcBackends + vpcPath := false + if lb.Method != "" { + if vb, err = r.resolveVPCBackends(ctx, ea, endpoint); err != nil { + return ctrl.Result{}, err + } + // A stopped VM has no backend pod to read; a binding it already has + // for this endpoint stays, rather than flipping to a cozy-proxy + // Service until it starts. + vpcPath = vb.InVPC || (vb.Pods == 0 && fip != nil && bindsEndpoint(fip, endpoint.Name)) + if !vpcPath && !r.CozyProxyContractImplemented { + setUnprovisioned(ea, cozyv1alpha1.ReasonDatapathUnavailable, + fmt.Sprintf("method %s needs a datapath implementing the %s Service contract, which this platform does not declare; no Service is rendered so the address is not attracted", lb.Method, ServiceProxyName)) + return ctrl.Result{}, r.withdrawAll(ctx, ea) + } + } + + claim, err := r.resolveClaim(ctx, ea) + if err != nil { + if !substrateInstalled(err) { + setUnprovisioned(ea, cozyv1alpha1.ReasonClaimPending, + "the address substrate (local.sdn.cozystack.io IPAddressClaim) is not installed on this cluster") + return ctrl.Result{RequeueAfter: requeueBackstop}, nil + } + return ctrl.Result{}, err + } + if claim == nil { + setUnprovisioned(ea, cozyv1alpha1.ReasonClaimNotFound, + fmt.Sprintf("IPAddressClaim %s not found in namespace %s", lb.ClaimName, ea.Namespace)) + ea.Status.ClaimName = "" + ea.Status.Addresses = nil + return ctrl.Result{RequeueAfter: requeueBackstop}, nil + } + view := parseClaim(claim) + ea.Status.ClaimName = view.Name + ea.Status.Addresses = nil + for _, a := range view.Addresses { + ea.Status.Addresses = append(ea.Status.Addresses, a.Address) + } + + if lb.ClaimName != "" && lb.Family != "" && view.Family != "" && view.Family != string(lb.Family) { + setUnprovisioned(ea, cozyv1alpha1.ReasonFamilyConflict, + fmt.Sprintf("attachment requests family %s but IPAddressClaim %s is %s", lb.Family, view.Name, view.Family)) + if err := r.withdrawFloatingIP(ctx, ea, fip); err != nil { + return ctrl.Result{}, err + } + return ctrl.Result{}, r.withdraw(ctx, ea, own) + } + if view.ClassName == "" { + setUnprovisioned(ea, cozyv1alpha1.ReasonClaimPending, + fmt.Sprintf("IPAddressClaim %s has not resolved its class yet (%s)", view.Name, view.WaitingReason)) + return ctrl.Result{RequeueAfter: requeueBackstop}, nil + } + class, err := r.classLoadBalancerClass(ctx, view.ClassName) + if err != nil { + if !substrateInstalled(err) { + setUnprovisioned(ea, cozyv1alpha1.ReasonClaimPending, + fmt.Sprintf("IPAddressClass %s of claim %s not found", view.ClassName, view.Name)) + return ctrl.Result{RequeueAfter: requeueBackstop}, nil + } + return ctrl.Result{}, err + } + // A consumer's loadBalancerClass cannot change after creation, so nothing + // is rendered before the provisioner reports it. What is already + // published stays: a class losing acceptance later must not drop a live + // address. + if !class.Accepted { + setUnprovisioned(ea, cozyv1alpha1.ReasonClassNotAccepted, + fmt.Sprintf("IPAddressClass %s is not accepted by its provisioner (%s); nothing new is rendered until it reports the loadBalancerClass its Services carry", view.ClassName, class.Why)) + return ctrl.Result{RequeueAfter: requeueBackstop}, nil + } + lbClass := class.LoadBalancerClass + if holder, err := r.foreignHolder(ctx, view, own, fip); err != nil { + return ctrl.Result{}, err + } else if holder != nil { + setUnprovisioned(ea, cozyv1alpha1.ReasonClaimInUse, + fmt.Sprintf("IPAddressClaim %s is already associated to Service %s; one claim serves one Service", view.Name, holder)) + // Two attachments can both render before the substrate records either + // association; the one that loses withdraws, so a single Service is + // left asking for the claim. + if err := r.withdrawFloatingIP(ctx, ea, fip); err != nil { + return ctrl.Result{}, err + } + if err := r.withdraw(ctx, ea, own); err != nil { + return ctrl.Result{}, err + } + return ctrl.Result{RequeueAfter: requeueBackstop}, nil + } + + // Whether a backend sits in a VPC decides between a cozy-proxy Service + // and a FloatingIP, and only a backend pod says so. Rendering a Service + // before one exists would pin the claim to the wrong consumer for a VM + // that turns out to be in a VPC, so a method attachment that has not + // published yet waits for one. Something already published stays. + if lb.Method != "" && !vpcPath && vb.Pods == 0 && own == nil { + setUnprovisioned(ea, cozyv1alpha1.ReasonWaitingForBackend, + fmt.Sprintf("Service %s has no backend pod yet, so nothing is published; the address stays held by IPAddressClaim %s", endpoint.Name, view.Name)) + if err := r.withdrawFloatingIP(ctx, ea, fip); err != nil { + return ctrl.Result{}, err + } + return ctrl.Result{RequeueAfter: requeueBackstop}, nil + } + // cozy-proxy programs IPv4 only, so an IPv6 address on its path would be + // attracted by the load balancer and forwarded nowhere. + if lb.Method != "" && !vpcPath && view.Family != "" && view.Family != string(cozyv1alpha1.AddressFamilyIPv4) { + setUnprovisioned(ea, cozyv1alpha1.ReasonFamilyUnsupportedByDatapath, + fmt.Sprintf("IPAddressClaim %s is %s, and the cozy-proxy datapath behind method %s maps IPv4 only; use an IPv4 claim", view.Name, view.Family, lb.Method)) + return ctrl.Result{}, r.withdrawAll(ctx, ea) + } + if vpcPath { + return r.reconcileVPCAttachment(ctx, ea, own, fip, fipServed, vb, view, lbClass, endpoint.Name) + } + // The claim has one consumer at a time: a Service is rendered only once + // the FloatingIP that wore the claim is gone. + if fip != nil { + if err := r.withdrawFloatingIP(ctx, ea, fip); err != nil { + return ctrl.Result{}, err + } + setUnprovisioned(ea, cozyv1alpha1.ReasonWithdrawalPending, + fmt.Sprintf("waiting for FloatingIP %s to be removed before IPAddressClaim %s gets a Service", fip.GetName(), view.Name)) + return ctrl.Result{RequeueAfter: withdrawalRequeue}, nil + } + + ports := mirroredPorts(endpoint, lb) + if len(ports) == 0 { + setUnprovisioned(ea, cozyv1alpha1.ReasonNothingToPublish, + fmt.Sprintf("Service %s has nothing to mirror (only the sentinel port %d or none of the requested ports); set ports or method", endpoint.Name, SentinelPort)) + return ctrl.Result{}, r.withdraw(ctx, ea, own) + } + + dark := false + if lb.Method != "" { + backends, err := r.backendPods(ctx, endpoint) + if err != nil { + return ctrl.Result{}, err + } + rival, err := r.delegatedRival(ctx, ea, own, backends) + if err != nil { + return ctrl.Result{}, err + } + if rival != nil { + setUnprovisioned(ea, cozyv1alpha1.ReasonBackendAlreadyDelegated, + fmt.Sprintf("backend %s of Service %s is already delegated to the datapath proxy by Service %s; the datapath maps one address per backend, so no Service is rendered", podNames(backends), endpoint.Name, rival.Name)) + return ctrl.Result{}, r.withdraw(ctx, ea, own) + } + if lb.Method == cozyv1alpha1.ExposureMethodWholeIP && len(backends) > 1 { + dark = true + } + } + + desired := desiredService(ea, renderInput{ + Endpoint: endpoint, + ClaimName: view.Name, + LoadBalancerClass: lbClass, + Dark: dark, + AllocateNodePorts: r.AllocateLoadBalancerNodePorts, + Family: view.Family, + }, ports) + if own == nil { + if err := r.Create(ctx, desired); err != nil { + setUnprovisioned(ea, cozyv1alpha1.ReasonRenderFailed, fmt.Sprintf("creating the Service failed: %v", err)) + return ctrl.Result{}, fmt.Errorf("create Service: %w", err) + } + own = desired + r.event(ea, corev1.EventTypeNormal, "Rendered", "rendered Service %s for endpoint %s", own.Name, endpoint.Name) + } else { + if !equalStringPtr(own.Spec.LoadBalancerClass, desired.Spec.LoadBalancerClass) { + setUnprovisioned(ea, cozyv1alpha1.ReasonRenderFailed, + fmt.Sprintf("Service %s carries loadBalancerClass %q but IPAddressClass %s fixes %q; the field is immutable, recreate the attachment", own.Name, derefString(own.Spec.LoadBalancerClass), view.ClassName, lbClass)) + ea.Status.ServiceName = own.Name + return ctrl.Result{}, nil + } + if primaryFamilyFixed(own, desired) { + setUnprovisioned(ea, cozyv1alpha1.ReasonRenderFailed, + fmt.Sprintf("Service %s has primary family %s but IPAddressClaim %s is %s; a Service's primary family is fixed at creation, recreate the attachment", own.Name, own.Spec.IPFamilies[0], view.Name, desired.Spec.IPFamilies[0])) + ea.Status.ServiceName = own.Name + return ctrl.Result{}, nil + } + if applyDesired(own, desired) { + if err := r.Update(ctx, own); err != nil { + setUnprovisioned(ea, cozyv1alpha1.ReasonRenderFailed, fmt.Sprintf("updating Service %s failed: %v", own.Name, err)) + return ctrl.Result{}, fmt.Errorf("update Service %s: %w", own.Name, err) + } + } + } + ea.Status.ServiceName = own.Name + + if dark { + setUnprovisioned(ea, cozyv1alpha1.ReasonMultipleBackends, + fmt.Sprintf("Service %s resolves to more than one ready backend; whole-IP NAT maps one address to one backend, so the address stays held by claim %s but nothing is served until exactly one backend remains", endpoint.Name, view.Name)) + return r.settled(r.claimWatched), nil + } + if !view.Bound { + setUnprovisioned(ea, cozyv1alpha1.ReasonClaimPending, + fmt.Sprintf("IPAddressClaim %s is not bound (%s)", view.Name, view.WaitingReason)) + return ctrl.Result{RequeueAfter: requeueBackstop}, nil + } + assigned := ingressAddresses(own) + if missing := missingAddresses(ea.Status.Addresses, assigned); len(ea.Status.Addresses) == 0 || len(missing) > 0 { + setUnprovisioned(ea, cozyv1alpha1.ReasonWaitingForAddress, + fmt.Sprintf("IPAddressClaim %s holds %s; waiting for Service %s to be assigned %s", view.Name, strings.Join(ea.Status.Addresses, ","), own.Name, strings.Join(missing, ","))) + return ctrl.Result{RequeueAfter: requeueBackstop}, nil + } + setProvisioned(ea, fmt.Sprintf("Service %s carries %s from IPAddressClaim %s", own.Name, strings.Join(ea.Status.Addresses, ","), view.Name)) + return r.settled(r.claimWatched), nil +} + +// applicationRelease finds the application's HelmRelease by the lineage +// labels the platform stamps on it. +func (r *Reconciler) applicationRelease(ctx context.Context, ea *cozyv1alpha1.EndpointAttachment) (*helmv2.HelmRelease, error) { + list := &helmv2.HelmReleaseList{} + if err := r.List(ctx, list, client.InNamespace(ea.Namespace), client.MatchingLabels(lineageLabels(ea.Spec.ApplicationRef))); err != nil { + return nil, err + } + if len(list.Items) == 0 { + return nil, nil + } + sort.Slice(list.Items, func(i, j int) bool { + return list.Items[i].CreationTimestamp.Before(&list.Items[j].CreationTimestamp) + }) + return &list.Items[0], nil +} + +func lineageLabels(ref cozyv1alpha1.EndpointApplicationReference) map[string]string { + group := ref.Group + if group == "" { + group = defaultApplicationGroup + } + return map[string]string{ + appsv1alpha1.ApplicationGroupLabel: group, + appsv1alpha1.ApplicationKindLabel: ref.Kind, + appsv1alpha1.ApplicationNameLabel: ref.Name, + } +} + +func helmReleaseOwner(ea *cozyv1alpha1.EndpointAttachment) *metav1.OwnerReference { + for i := range ea.OwnerReferences { + ref := &ea.OwnerReferences[i] + if ref.Kind == "HelmRelease" && strings.HasPrefix(ref.APIVersion, helmv2.GroupVersion.Group+"/") { + return ref + } + } + return nil +} + +// ensureAttachmentOwnership binds the attachment to this incarnation of the +// application (an owner reference to its HelmRelease, matched by UID) and +// stamps the lineage labels so tooling lists it with the application's other +// objects. The reference is set once and never rewritten. +func (r *Reconciler) ensureAttachmentOwnership(ctx context.Context, ea *cozyv1alpha1.EndpointAttachment, hr *helmv2.HelmRelease) (bool, error) { + patched := ea.DeepCopy() + changed := false + if helmReleaseOwner(patched) == nil { + patched.OwnerReferences = append(patched.OwnerReferences, metav1.OwnerReference{ + APIVersion: helmv2.GroupVersion.String(), + Kind: "HelmRelease", + Name: hr.Name, + UID: hr.UID, + }) + changed = true + } + if patched.Labels == nil { + patched.Labels = map[string]string{} + } + for k, v := range lineageLabels(patched.Spec.ApplicationRef) { + if patched.Labels[k] != v { + patched.Labels[k] = v + changed = true + } + } + if !changed { + return false, nil + } + // The patch is applied to a copy because the response carries the + // object as stored now, which may hold a newer spec than the one this + // reconcile has already read. + // The resource-version precondition keeps the patch from landing on a + // same-name replacement of the object this reconcile read; a conflict + // is retried from a fresh read. + if err := r.Patch(ctx, patched, client.MergeFromWithOptions(ea, client.MergeFromWithOptimisticLock{})); err != nil { + return false, fmt.Errorf("bind attachment to HelmRelease %s: %w", hr.Name, err) + } + if patched.Generation != ea.Generation { + return true, nil + } + ea.ObjectMeta = patched.ObjectMeta + return false, nil +} + +// endpointDenied applies the authorization seam: the Service must carry the +// lineage identity labels matching applicationRef on all three fields AND +// the tenant-facing marker. Lineage alone also covers operator-internal and +// headless Services; the marker is what the platform stamps on exactly the +// Services ApplicationDefinition.spec.services selects. +func endpointDenied(ea *cozyv1alpha1.EndpointAttachment, svc *corev1.Service) (reason, message string) { + if ref := metav1.GetControllerOf(svc); ref != nil && ref.Kind == attachmentGVK.Kind && strings.HasPrefix(ref.APIVersion, attachmentGVK.Group+"/") { + return cozyv1alpha1.ReasonEndpointNotTenantFacing, + fmt.Sprintf("Service %s is rendered by an EndpointAttachment and is not an application endpoint", svc.Name) + } + for k, want := range lineageLabels(ea.Spec.ApplicationRef) { + if got := svc.Labels[k]; got != want { + return cozyv1alpha1.ReasonEndpointLineageMismatch, + fmt.Sprintf("Service %s has %s=%q, attachment targets %q", svc.Name, k, got, want) + } + } + if svc.Labels[corev1alpha1.TenantResourceLabelKey] != corev1alpha1.TenantResourceLabelValue { + return cozyv1alpha1.ReasonEndpointNotTenantFacing, + fmt.Sprintf("Service %s is not marked tenant-facing (%s) by the platform; only Services the application definition declares as endpoints can be attached", svc.Name, corev1alpha1.TenantResourceLabelKey) + } + if _, ok := svc.Labels[kccmTenantServiceLabel]; ok { + return cozyv1alpha1.ReasonEndpointNotTenantFacing, + fmt.Sprintf("Service %s is a LoadBalancer the cloud-controller-manager of a tenant Kubernetes cluster created for a Service inside that cluster, not an endpoint of the application itself", svc.Name) + } + return "", "" +} + +// resolveClaim returns the claim the attachment consumes: the referenced +// one, or the one it minted (minting it on first sight). A nil claim with a +// nil error means the referenced claim does not exist. +func (r *Reconciler) resolveClaim(ctx context.Context, ea *cozyv1alpha1.EndpointAttachment) (*unstructured.Unstructured, error) { + if name := ea.Spec.LoadBalancer.ClaimName; name != "" { + u := newClaim() + if err := r.Get(ctx, types.NamespacedName{Namespace: ea.Namespace, Name: name}, u); err != nil { + if apierrors.IsNotFound(err) { + return nil, nil + } + return nil, err + } + return u, nil + } + u, err := r.mintedClaim(ctx, ea) + if err != nil || u != nil { + return u, err + } + u, err = r.mintClaim(ctx, ea) + if err != nil { + return nil, err + } + r.event(ea, corev1.EventTypeNormal, "ClaimMinted", "minted IPAddressClaim %s", u.GetName()) + return u, nil +} + +// foreignHolder reports a live Service, other than this attachment's own, +// that the claim's addresses are associated to. Such a claim is not fought +// over. +func (r *Reconciler) foreignHolder(ctx context.Context, view claimView, own *corev1.Service, fip *unstructured.Unstructured) (*types.NamespacedName, error) { + for _, a := range view.Addresses { + if a.Name == "" { + continue + } + holder, err := r.addressHolder(ctx, a.Name) + if err != nil { + if !substrateInstalled(err) { + return nil, nil + } + return nil, err + } + if holder == nil { + continue + } + if own != nil && holder.Namespace == own.Namespace && holder.Name == own.Name { + continue + } + live := &corev1.Service{} + if err := r.Get(ctx, *holder, live); err != nil { + if apierrors.IsNotFound(err) { + continue + } + return nil, err + } + // The FloatingIP this attachment owns wears the claim through a + // Service it owns in turn. + if fip != nil { + if ref := metav1.GetControllerOf(live); ref != nil && ref.UID == fip.GetUID() { + continue + } + } + return holder, nil + } + return nil, nil +} + +// detach is the endpoint-absent path: the rendered Service is torn down, +// the claim (minted or referenced) is kept so the address survives, and the +// Provisioned reason records that an address is held with nothing published. +func (r *Reconciler) detach(ctx context.Context, ea *cozyv1alpha1.EndpointAttachment, reason string) (ctrl.Result, error) { + own, err := r.ownedService(ctx, ea) + if err != nil { + return ctrl.Result{}, err + } + fip, _, err := r.ownedFloatingIP(ctx, ea) + if err != nil { + return ctrl.Result{}, err + } + if ea.Status.ClaimName != "" { + claim := newClaim() + if err := r.Get(ctx, types.NamespacedName{Namespace: ea.Namespace, Name: ea.Status.ClaimName}, claim); err != nil { + if !apierrors.IsNotFound(err) && substrateInstalled(err) { + return ctrl.Result{}, err + } + ea.Status.ClaimName = "" + ea.Status.Addresses = nil + } + } + held := own != nil || fip != nil || ea.Status.ClaimName != "" + werr := r.withdrawFloatingIP(ctx, ea, fip) + if werr == nil { + werr = r.withdraw(ctx, ea, own) + } + switch { + case werr != nil: + setUnprovisioned(ea, cozyv1alpha1.ReasonWithdrawalPending, + fmt.Sprintf("endpoint is absent; withdrawing what was published is pending (%v)", werr)) + case held && ea.Status.ClaimName != "": + setUnprovisioned(ea, cozyv1alpha1.ReasonEndpointDetached, + fmt.Sprintf("endpoint is absent; what was published is withdrawn and the address stays held by IPAddressClaim %s", ea.Status.ClaimName)) + case held: + setUnprovisioned(ea, cozyv1alpha1.ReasonEndpointDetached, "endpoint is absent; what was published is withdrawn") + default: + setUnprovisioned(ea, reason, "nothing rendered: the endpoint did not resolve") + } + return ctrl.Result{}, werr +} + +// withdrawAll withdraws everything published for the attachment. +func (r *Reconciler) withdrawAll(ctx context.Context, ea *cozyv1alpha1.EndpointAttachment) error { + own, err := r.ownedService(ctx, ea) + if err != nil { + return err + } + fip, _, err := r.ownedFloatingIP(ctx, ea) + if err != nil { + return err + } + if err := r.withdrawFloatingIP(ctx, ea, fip); err != nil { + return err + } + return r.withdraw(ctx, ea, own) +} + +// withdraw deletes the rendered Service, if any, and clears status.serviceName. +func (r *Reconciler) withdraw(ctx context.Context, ea *cozyv1alpha1.EndpointAttachment, own *corev1.Service) error { + if own == nil { + ea.Status.ServiceName = "" + return nil + } + if err := r.Delete(ctx, own); client.IgnoreNotFound(err) != nil { + return fmt.Errorf("withdraw Service %s: %w", own.Name, err) + } + // The cache may show one owned Service while the API holds another; + // a withdrawal is complete only when none is left. + if r.Reader != nil { + rest, err := r.listOwnedServices(ctx, r.Reader, ea) + if err != nil { + return err + } + for _, svc := range rest { + if svc.UID == own.UID || !svc.DeletionTimestamp.IsZero() { + continue + } + if err := r.Delete(ctx, svc); client.IgnoreNotFound(err) != nil { + return fmt.Errorf("withdraw Service %s: %w", svc.Name, err) + } + } + } + ea.Status.ServiceName = "" + r.event(ea, corev1.EventTypeNormal, "Withdrawn", "withdrew Service %s", own.Name) + return nil +} + +func (r *Reconciler) event(ea *cozyv1alpha1.EndpointAttachment, eventType, reason, format string, args ...interface{}) { + if r.Recorder == nil { + return + } + r.Recorder.Eventf(ea, eventType, reason, format, args...) +} + +func podNames(pods map[types.UID]string) string { + names := make([]string, 0, len(pods)) + for _, n := range pods { + names = append(names, n) + } + sort.Strings(names) + return strings.Join(names, ",") +} + +// missingAddresses returns the claim addresses the Service has not been +// assigned. A Dual claim binds a v4 and a v6 address, and the attachment is +// provisioned only once the Service carries both. +func missingAddresses(claimed, assigned []string) []string { + have := make(map[string]bool, len(assigned)) + for _, a := range assigned { + have[a] = true + } + var missing []string + for _, c := range claimed { + if !have[c] { + missing = append(missing, c) + } + } + return missing +} + +func derefString(s *string) string { + if s == nil { + return "" + } + return *s +} + +func applicationKey(ref cozyv1alpha1.EndpointApplicationReference) string { + l := lineageLabels(ref) + return l[appsv1alpha1.ApplicationGroupLabel] + "/" + l[appsv1alpha1.ApplicationKindLabel] + "/" + l[appsv1alpha1.ApplicationNameLabel] +} + +// SetupWithManager registers the controller, its field indices and the +// watches that make mirroring event-driven. The address-substrate kinds are +// watched when they are served at startup; otherwise the requeue backstop +// covers them. +func (r *Reconciler) SetupWithManager(mgr ctrl.Manager) error { + ctx := context.Background() + indexer := mgr.GetFieldIndexer() + if err := indexer.IndexField(ctx, &cozyv1alpha1.EndpointAttachment{}, indexEndpointService, func(o client.Object) []string { + return []string{o.(*cozyv1alpha1.EndpointAttachment).Spec.Endpoint.ServiceName} + }); err != nil { + return err + } + if err := indexer.IndexField(ctx, &cozyv1alpha1.EndpointAttachment{}, indexClaimName, func(o client.Object) []string { + ea := o.(*cozyv1alpha1.EndpointAttachment) + if ea.Spec.LoadBalancer == nil || ea.Spec.LoadBalancer.ClaimName == "" { + return nil + } + return []string{ea.Spec.LoadBalancer.ClaimName} + }); err != nil { + return err + } + if err := indexer.IndexField(ctx, &cozyv1alpha1.EndpointAttachment{}, indexApplication, func(o client.Object) []string { + return []string{applicationKey(o.(*cozyv1alpha1.EndpointAttachment).Spec.ApplicationRef)} + }); err != nil { + return err + } + + b := ctrl.NewControllerManagedBy(mgr). + Named("endpointattachment-controller"). + For(&cozyv1alpha1.EndpointAttachment{}). + Owns(&corev1.Service{}). + Watches(&corev1.Service{}, handler.EnqueueRequestsFromMapFunc(r.mapService)). + Watches(&discoveryv1.EndpointSlice{}, handler.EnqueueRequestsFromMapFunc(r.mapEndpointSlice)). + Watches(&helmv2.HelmRelease{}, handler.EnqueueRequestsFromMapFunc(r.mapHelmRelease)). + Watches(&corev1.Pod{}, handler.EnqueueRequestsFromMapFunc(r.mapPod), builder.WithPredicates(vpcAnnotationsChanged())) + + // Both kinds are optional, and the manager runs every other controller + // too: a discovery failure for either is logged and left to the requeue + // backstop rather than stopping the manager. + if served, err := kindServed(mgr.GetRESTMapper(), floatingIPGVK); served { + b = b.Owns(newFloatingIP()) + r.floatingIPWatched = true + } else if err != nil { + mgr.GetLogger().Error(err, "FloatingIP discovery failed; FloatingIP changes are picked up by periodic requeue", "kind", floatingIPGVK.String()) + } + if served, err := kindServed(mgr.GetRESTMapper(), claimGVK); served { + b = b.Owns(newClaim()). + Watches(newClaim(), handler.EnqueueRequestsFromMapFunc(r.mapClaim)) + r.claimWatched = true + } else if err != nil { + mgr.GetLogger().Error(err, "IPAddressClaim discovery failed; claim changes are picked up by periodic requeue", "kind", claimGVK.String()) + } else { + mgr.GetLogger().Info("address substrate not served; claim changes are picked up by periodic requeue", "kind", claimGVK.String()) + } + return b.Complete(r) +} + +func (r *Reconciler) attachmentsByIndex(ctx context.Context, namespace, index, value string) []reconcile.Request { + list := &cozyv1alpha1.EndpointAttachmentList{} + if err := r.List(ctx, list, client.InNamespace(namespace), client.MatchingFields{index: value}); err != nil { + return nil + } + out := make([]reconcile.Request, 0, len(list.Items)) + for _, ea := range list.Items { + out = append(out, reconcile.Request{NamespacedName: client.ObjectKeyFromObject(&ea)}) + } + return out +} + +// methodAttachments enqueues every attachment in the namespace that renders +// a delegated Service, since any delegated Service or endpoint change there +// can move the exclusivity verdict. +func (r *Reconciler) methodAttachments(ctx context.Context, namespace string) []reconcile.Request { + list := &cozyv1alpha1.EndpointAttachmentList{} + if err := r.List(ctx, list, client.InNamespace(namespace)); err != nil { + return nil + } + var out []reconcile.Request + for _, ea := range list.Items { + if ea.Spec.LoadBalancer != nil && ea.Spec.LoadBalancer.Method != "" { + out = append(out, reconcile.Request{NamespacedName: client.ObjectKeyFromObject(&ea)}) + } + } + return out +} + +func (r *Reconciler) mapService(ctx context.Context, o client.Object) []reconcile.Request { + svc, ok := o.(*corev1.Service) + if !ok { + return nil + } + reqs := r.attachmentsByIndex(ctx, svc.Namespace, indexEndpointService, svc.Name) + if svc.Labels[ServiceProxyNameLabel] == ServiceProxyName { + reqs = append(reqs, r.methodAttachments(ctx, svc.Namespace)...) + } + return reqs +} + +func (r *Reconciler) mapEndpointSlice(ctx context.Context, o client.Object) []reconcile.Request { + name := o.GetLabels()[discoveryv1.LabelServiceName] + if name == "" { + return nil + } + reqs := r.attachmentsByIndex(ctx, o.GetNamespace(), indexEndpointService, name) + return append(reqs, r.methodAttachments(ctx, o.GetNamespace())...) +} + +func (r *Reconciler) mapHelmRelease(ctx context.Context, o client.Object) []reconcile.Request { + l := o.GetLabels() + kind, name := l[appsv1alpha1.ApplicationKindLabel], l[appsv1alpha1.ApplicationNameLabel] + if kind == "" || name == "" { + return nil + } + key := applicationKey(cozyv1alpha1.EndpointApplicationReference{Group: l[appsv1alpha1.ApplicationGroupLabel], Kind: kind, Name: name}) + return r.attachmentsByIndex(ctx, o.GetNamespace(), indexApplication, key) +} + +// kindServed reports whether an optional kind can be watched. A kind that is +// not served is no error; a failed discovery is returned for the caller to +// log, and never stops setup. +func kindServed(m meta.RESTMapper, gvk schema.GroupVersionKind) (bool, error) { + if _, err := m.RESTMapping(gvk.GroupKind(), gvk.Version); err != nil { + if isNoKindMatch(err) { + return false, nil + } + return false, err + } + return true, nil +} + +// mapPod enqueues the whole-IP attachments in a pod's namespace when the VPC +// address cozyplane stamps on the pod appears or changes. The EndpointSlice +// does not change with it, so nothing else would carry the new target to the +// FloatingIP. +func (r *Reconciler) mapPod(ctx context.Context, o client.Object) []reconcile.Request { + return r.methodAttachments(ctx, o.GetNamespace()) +} + +func vpcAnnotationsChanged() predicate.Predicate { + carries := func(o client.Object) bool { + _, ok := o.GetAnnotations()[vpcAnnotation] + return ok + } + return predicate.Funcs{ + CreateFunc: func(e event.CreateEvent) bool { return carries(e.Object) }, + DeleteFunc: func(event.DeleteEvent) bool { return false }, + GenericFunc: func(event.GenericEvent) bool { return false }, + UpdateFunc: func(e event.UpdateEvent) bool { + oldA, newA := e.ObjectOld.GetAnnotations(), e.ObjectNew.GetAnnotations() + return oldA[vpcAnnotation] != newA[vpcAnnotation] || oldA[vpcIPAnnotation] != newA[vpcIPAnnotation] + }, + } +} + +func (r *Reconciler) mapClaim(ctx context.Context, o client.Object) []reconcile.Request { + return r.attachmentsByIndex(ctx, o.GetNamespace(), indexClaimName, o.GetName()) +} diff --git a/internal/controller/endpointattachment/reconciler_test.go b/internal/controller/endpointattachment/reconciler_test.go new file mode 100644 index 000000000..131175d21 --- /dev/null +++ b/internal/controller/endpointattachment/reconciler_test.go @@ -0,0 +1,1133 @@ +/* +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 endpointattachment + +import ( + "context" + "fmt" + "slices" + "strings" + "testing" + "time" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + corev1 "k8s.io/api/core/v1" + discoveryv1 "k8s.io/api/discovery/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + apimeta "k8s.io/apimachinery/pkg/api/meta" + apivalidation "k8s.io/apimachinery/pkg/api/validation" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/validation" + "k8s.io/apimachinery/pkg/util/validation/field" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/localsdn/v1alpha1" + appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1" + corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1" +) + +const ns = "tenant-foo" + +func newScheme(t *testing.T) *runtime.Scheme { + t.Helper() + s := runtime.NewScheme() + if err := clientgoscheme.AddToScheme(s); err != nil { + t.Fatalf("client-go scheme: %v", err) + } + if err := cozyv1alpha1.AddToScheme(s); err != nil { + t.Fatalf("cozystack scheme: %v", err) + } + if err := helmv2.AddToScheme(s); err != nil { + t.Fatalf("helm scheme: %v", err) + } + return s +} + +func newClient(t *testing.T, objs ...client.Object) client.Client { + t.Helper() + return fake.NewClientBuilder(). + WithScheme(newScheme(t)). + WithStatusSubresource(&cozyv1alpha1.EndpointAttachment{}). + WithObjects(withBackendPods(objs)...). + Build() +} + +// withBackendPods adds a pod, outside any VPC, for every pod an +// EndpointSlice fixture names and the test did not supply itself: the +// EndpointSlice controller only ever lists pods that exist. +func withBackendPods(objs []client.Object) []client.Object { + have := map[string]bool{} + for _, o := range objs { + if p, ok := o.(*corev1.Pod); ok { + have[p.Name] = true + } + } + out := append([]client.Object(nil), objs...) + for _, o := range objs { + s, ok := o.(*discoveryv1.EndpointSlice) + if !ok { + continue + } + for _, e := range s.Endpoints { + if e.TargetRef != nil && e.TargetRef.Kind == "Pod" && !have[e.TargetRef.Name] { + have[e.TargetRef.Name] = true + out = append(out, &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: e.TargetRef.Name, UID: e.TargetRef.UID}}) + } + } + } + return out +} + +func appLabels(kind, name string) map[string]string { + return map[string]string{ + appsv1alpha1.ApplicationGroupLabel: "apps.cozystack.io", + appsv1alpha1.ApplicationKindLabel: kind, + appsv1alpha1.ApplicationNameLabel: name, + } +} + +func helmRelease(name, uid, kind, app string) *helmv2.HelmRelease { + return &helmv2.HelmRelease{ObjectMeta: metav1.ObjectMeta{ + Namespace: ns, Name: name, UID: types.UID(uid), Labels: appLabels(kind, app), + }} +} + +// endpoint builds a Service the way the lineage webhook leaves a tenant-facing +// one: lineage labels plus the tenantresource marker. +func endpoint(name, kind, app string, selector map[string]string, ports ...int32) *corev1.Service { + labels := appLabels(kind, app) + labels[corev1alpha1.TenantResourceLabelKey] = corev1alpha1.TenantResourceLabelValue + svc := &corev1.Service{ + ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: name, UID: types.UID("svc-" + name), Labels: labels}, + Spec: corev1.ServiceSpec{Selector: selector}, + } + for _, p := range ports { + svc.Spec.Ports = append(svc.Spec.Ports, corev1.ServicePort{Name: "p", Port: p, Protocol: corev1.ProtocolTCP}) + } + // The vm-instance chart renders a not-yet-exposed VM Service headless, + // with the sentinel port as its only port. + if len(ports) == 1 && ports[0] == SentinelPort { + svc.Spec.ClusterIP = corev1.ClusterIPNone + } + return svc +} + +func attachment(name, uid, kind, app, service string, lb cozyv1alpha1.LoadBalancerAttachment) *cozyv1alpha1.EndpointAttachment { + return &cozyv1alpha1.EndpointAttachment{ + ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: name, UID: types.UID(uid), Generation: 1}, + Spec: cozyv1alpha1.EndpointAttachmentSpec{ + ApplicationRef: cozyv1alpha1.EndpointApplicationReference{Group: "apps.cozystack.io", Kind: kind, Name: app}, + Endpoint: cozyv1alpha1.EndpointReference{ServiceName: service}, + LoadBalancer: &lb, + }, + } +} + +func claimObject(name, className, family string, bound bool, addresses ...string) *unstructured.Unstructured { + u := newClaim() + u.SetNamespace(ns) + u.SetName(name) + spec := map[string]interface{}{} + if className != "" { + spec["className"] = className + } + if family != "" { + spec["family"] = family + } + u.Object["spec"] = spec + status := map[string]interface{}{"className": className, "phase": "Pending"} + if bound { + status["phase"] = "Bound" + var list []interface{} + for _, a := range addresses { + list = append(list, map[string]interface{}{"name": "ip-" + strings.ReplaceAll(a, ".", "-"), "address": a}) + } + status["addresses"] = list + } + u.Object["status"] = status + return u +} + +// classObject is an IPAddressClass its provisioner has accepted, reporting +// lbClass in status; an empty lbClass is the cluster default. +func classObject(name, lbClass string) *unstructured.Unstructured { + u := pendingClassObject(name) + u.Object["status"] = map[string]interface{}{ + "loadBalancerClass": lbClass, + "conditions": []interface{}{map[string]interface{}{ + "type": "Accepted", "status": "True", "reason": "Accepted", "observedGeneration": int64(1), + }}, + } + return u +} + +// pendingClassObject is an IPAddressClass its provisioner has not reported +// on yet. +func pendingClassObject(name string) *unstructured.Unstructured { + u := &unstructured.Unstructured{} + u.SetGroupVersionKind(classGVK) + u.SetName(name) + u.SetGeneration(1) + u.Object["spec"] = map[string]interface{}{"provisioner": "test"} + return u +} + +func addressObject(addr string, holder *types.NamespacedName) *unstructured.Unstructured { + u := &unstructured.Unstructured{} + u.SetGroupVersionKind(addressGVK) + u.SetName("ip-" + strings.ReplaceAll(addr, ".", "-")) + u.Object["spec"] = map[string]interface{}{"address": addr, "className": "public"} + status := map[string]interface{}{"phase": "Bound"} + if holder != nil { + status["associatedTo"] = map[string]interface{}{"kind": "Service", "namespace": holder.Namespace, "name": holder.Name} + } + u.Object["status"] = status + return u +} + +func endpointSlice(name, service string, ready bool, pods ...string) *discoveryv1.EndpointSlice { + s := &discoveryv1.EndpointSlice{ + ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: name, Labels: map[string]string{discoveryv1.LabelServiceName: service}}, + AddressType: discoveryv1.AddressTypeIPv4, + } + for _, p := range pods { + s.Endpoints = append(s.Endpoints, discoveryv1.Endpoint{ + Addresses: []string{"10.0.0.1"}, + Conditions: discoveryv1.EndpointConditions{Ready: new(ready)}, + TargetRef: &corev1.ObjectReference{Kind: "Pod", Name: p, UID: types.UID("pod-" + p)}, + }) + } + return s +} + +func run(t *testing.T, c client.Client, r *Reconciler, ea *cozyv1alpha1.EndpointAttachment) *cozyv1alpha1.EndpointAttachment { + t.Helper() + if r == nil { + r = &Reconciler{} + } + r.Client = c + if _, err := r.Reconcile(context.TODO(), ctrl.Request{NamespacedName: client.ObjectKeyFromObject(ea)}); err != nil { + t.Fatalf("reconcile: %v", err) + } + got := &cozyv1alpha1.EndpointAttachment{} + if err := c.Get(context.TODO(), client.ObjectKeyFromObject(ea), got); err != nil { + t.Fatalf("get attachment: %v", err) + } + return got +} + +func renderedServices(t *testing.T, c client.Client, ea *cozyv1alpha1.EndpointAttachment) []corev1.Service { + t.Helper() + list := &corev1.ServiceList{} + if err := c.List(context.TODO(), list, client.InNamespace(ns)); err != nil { + t.Fatalf("list services: %v", err) + } + var out []corev1.Service + for _, s := range list.Items { + if isControlledBy(&s, ea) { + out = append(out, s) + } + } + return out +} + +func onlyRendered(t *testing.T, c client.Client, ea *cozyv1alpha1.EndpointAttachment) *corev1.Service { + t.Helper() + got := renderedServices(t, c, ea) + if len(got) != 1 { + t.Fatalf("expected exactly one rendered Service, got %d", len(got)) + } + return &got[0] +} + +func expectCondition(t *testing.T, ea *cozyv1alpha1.EndpointAttachment, condType string, status metav1.ConditionStatus, reason string) { + t.Helper() + c := apimeta.FindStatusCondition(ea.Status.Conditions, condType) + if c == nil { + t.Fatalf("condition %s missing; status: %+v", condType, ea.Status) + } + if c.Status != status || c.Reason != reason { + t.Fatalf("condition %s = %s/%s (%s), want %s/%s", condType, c.Status, c.Reason, c.Message, status, reason) + } +} + +func setIngress(t *testing.T, c client.Client, svc *corev1.Service, ips ...string) { + t.Helper() + live := &corev1.Service{} + if err := c.Get(context.TODO(), client.ObjectKeyFromObject(svc), live); err != nil { + t.Fatalf("get service: %v", err) + } + live.Status.LoadBalancer.Ingress = nil + for _, ip := range ips { + live.Status.LoadBalancer.Ingress = append(live.Status.LoadBalancer.Ingress, corev1.LoadBalancerIngress{IP: ip}) + } + if err := c.Status().Update(context.TODO(), live); err != nil { + t.Fatalf("set ingress: %v", err) + } +} + +// TestResolveDenyMatrix pins the authorization seam: both label families are +// required on the endpoint Service, and each failure carries its own reason. +func TestResolveDenyMatrix(t *testing.T) { + tests := []struct { + name string + mutate func(*corev1.Service) + noService bool + noRelease bool + wantStatus metav1.ConditionStatus + wantReason string + }{ + {name: "both families present", wantStatus: metav1.ConditionTrue, wantReason: cozyv1alpha1.ReasonResolved}, + {name: "kind label mismatches", mutate: func(s *corev1.Service) { s.Labels[appsv1alpha1.ApplicationKindLabel] = "MariaDB" }, + wantStatus: metav1.ConditionFalse, wantReason: cozyv1alpha1.ReasonEndpointLineageMismatch}, + {name: "name label mismatches", mutate: func(s *corev1.Service) { s.Labels[appsv1alpha1.ApplicationNameLabel] = "other" }, + wantStatus: metav1.ConditionFalse, wantReason: cozyv1alpha1.ReasonEndpointLineageMismatch}, + {name: "group label mismatches", mutate: func(s *corev1.Service) { s.Labels[appsv1alpha1.ApplicationGroupLabel] = "foreign.example.com" }, + wantStatus: metav1.ConditionFalse, wantReason: cozyv1alpha1.ReasonEndpointLineageMismatch}, + {name: "lineage without marker", mutate: func(s *corev1.Service) { delete(s.Labels, corev1alpha1.TenantResourceLabelKey) }, + wantStatus: metav1.ConditionFalse, wantReason: cozyv1alpha1.ReasonEndpointNotTenantFacing}, + {name: "marker false", mutate: func(s *corev1.Service) { s.Labels[corev1alpha1.TenantResourceLabelKey] = "false" }, + wantStatus: metav1.ConditionFalse, wantReason: cozyv1alpha1.ReasonEndpointNotTenantFacing}, + {name: "service missing", noService: true, wantStatus: metav1.ConditionFalse, wantReason: cozyv1alpha1.ReasonEndpointNotFound}, + {name: "application missing", noRelease: true, wantStatus: metav1.ConditionFalse, wantReason: cozyv1alpha1.ReasonApplicationNotFound}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ea := attachment("ro-public", "ea-1", "Postgres", "mydb", "postgres-mydb-ro", cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held"}) + objs := []client.Object{ea} + if !tt.noRelease { + objs = append(objs, helmRelease("postgres-mydb", "hr-1", "Postgres", "mydb")) + } + if !tt.noService { + svc := endpoint("postgres-mydb-ro", "Postgres", "mydb", map[string]string{"role": "replica"}, 5432) + if tt.mutate != nil { + tt.mutate(svc) + } + objs = append(objs, svc) + } + c := newClient(t, objs...) + got := run(t, c, nil, ea) + expectCondition(t, got, cozyv1alpha1.ConditionResolved, tt.wantStatus, tt.wantReason) + if tt.wantStatus == metav1.ConditionFalse && len(renderedServices(t, c, got)) != 0 { + t.Fatal("nothing may be rendered for an unresolved endpoint") + } + }) + } +} + +// TestRenderMirrorsEndpoint walks the resolve → claim → render → report +// pipeline for the flagship database case with a referenced claim. +func TestRenderMirrorsEndpoint(t *testing.T) { + ep := endpoint("postgres-mydb-ro", "Postgres", "mydb", map[string]string{"cnpg.io/cluster": "postgres-mydb", "role": "replica"}, 5432, 9187) + ea := attachment("ro-public", "ea-1", "Postgres", "mydb", "postgres-mydb-ro", cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held", Ports: []int32{5432}}) + c := newClient(t, + helmRelease("postgres-mydb", "hr-1", "Postgres", "mydb"), ep, ea, + claimObject("held", "public", "IPv4", true, "203.0.113.7"), + classObject("public", "metallb.io/public"), + addressObject("203.0.113.7", nil), + ) + + got := run(t, c, nil, ea) + expectCondition(t, got, cozyv1alpha1.ConditionResolved, metav1.ConditionTrue, cozyv1alpha1.ReasonResolved) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonWaitingForAddress) + if got.Status.Phase != cozyv1alpha1.EndpointAttachmentPending { + t.Fatalf("phase = %s, want Pending", got.Status.Phase) + } + if got.Status.ClaimName != "held" || len(got.Status.Addresses) != 1 || got.Status.Addresses[0] != "203.0.113.7" { + t.Fatalf("status did not mirror the claim: %+v", got.Status) + } + + svc := onlyRendered(t, c, ea) + if !strings.HasPrefix(svc.Name, "ro-public-") || svc.Name == "ro-public-" { + t.Fatalf("Service must be generateName'd from the attachment, got %q", svc.Name) + } + if got.Status.ServiceName != svc.Name { + t.Fatalf("status.serviceName = %q, want %q", got.Status.ServiceName, svc.Name) + } + if svc.Annotations[ClaimAnnotation] != "held" { + t.Fatalf("claim annotation = %q", svc.Annotations[ClaimAnnotation]) + } + if svc.Spec.LoadBalancerClass == nil || *svc.Spec.LoadBalancerClass != "metallb.io/public" { + t.Fatalf("loadBalancerClass must be read from the class before creation, got %v", svc.Spec.LoadBalancerClass) + } + if svc.Spec.Type != corev1.ServiceTypeLoadBalancer || svc.Spec.ExternalTrafficPolicy != corev1.ServiceExternalTrafficPolicyLocal { + t.Fatalf("unexpected type/policy: %s/%s", svc.Spec.Type, svc.Spec.ExternalTrafficPolicy) + } + if svc.Spec.AllocateLoadBalancerNodePorts == nil || *svc.Spec.AllocateLoadBalancerNodePorts { + t.Fatal("node ports must be disabled by default") + } + if !equalStringMaps(svc.Spec.Selector, ep.Spec.Selector) { + t.Fatalf("selector not mirrored: %v", svc.Spec.Selector) + } + if len(svc.Spec.Ports) != 1 || svc.Spec.Ports[0].Port != 5432 { + t.Fatalf("ports must be the endpoint's filtered by spec.ports, got %v", svc.Spec.Ports) + } + if _, ok := svc.Labels[ServiceProxyNameLabel]; ok { + t.Fatal("a plain attachment must not be delegated to the datapath proxy") + } + for _, k := range []string{appsv1alpha1.ApplicationKindLabel, corev1alpha1.TenantResourceLabelKey} { + if _, ok := svc.Labels[k]; ok { + t.Fatalf("rendered Service must not copy the endpoint's %s label", k) + } + } + if ref := metav1.GetControllerOf(svc); ref == nil || ref.UID != ea.UID { + t.Fatalf("Service must be controller-owned by the attachment, got %+v", svc.OwnerReferences) + } + + // The address lands on the Service: Provisioned flips, phase Attached. + setIngress(t, c, svc, "203.0.113.7") + got = run(t, c, nil, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionTrue, cozyv1alpha1.ReasonProvisioned) + if got.Status.Phase != cozyv1alpha1.EndpointAttachmentAttached { + t.Fatalf("phase = %s, want Attached", got.Status.Phase) + } + if hr := helmReleaseOwner(got); hr == nil || hr.UID != "hr-1" { + t.Fatalf("attachment must be owned by the application's HelmRelease, got %+v", got.OwnerReferences) + } + if got.Labels[appsv1alpha1.ApplicationNameLabel] != "mydb" { + t.Fatalf("lineage labels must be stamped on the attachment, got %v", got.Labels) + } + + // The operator relabels; the mirror follows on the next reconcile. + live := &corev1.Service{} + if err := c.Get(context.TODO(), client.ObjectKeyFromObject(ep), live); err != nil { + t.Fatal(err) + } + live.Spec.Selector = map[string]string{"cnpg.io/cluster": "postgres-mydb", "role": "primary"} + if err := c.Update(context.TODO(), live); err != nil { + t.Fatal(err) + } + run(t, c, nil, ea) + svc = onlyRendered(t, c, ea) + if svc.Spec.Selector["role"] != "primary" { + t.Fatalf("selector drift not mirrored: %v", svc.Spec.Selector) + } + if svc.Name != got.Status.ServiceName { + t.Fatal("re-mirroring must update the Service in place, not replace it") + } +} + +// TestMintedClaim covers the className path: a claim is minted under the +// attachment's control and the Service waits for the class to resolve. +func TestMintedClaim(t *testing.T) { + ep := endpoint("postgres-mydb-rw", "Postgres", "mydb", map[string]string{"role": "primary"}, 5432) + ea := attachment("rw-public", "ea-1", "Postgres", "mydb", "postgres-mydb-rw", cozyv1alpha1.LoadBalancerAttachment{Family: cozyv1alpha1.AddressFamilyIPv4}) + c := newClient(t, helmRelease("postgres-mydb", "hr-1", "Postgres", "mydb"), ep, ea, classObject("public", "")) + + got := run(t, c, nil, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonClaimPending) + claims := &unstructured.UnstructuredList{} + claims.SetGroupVersionKind(claimListGVK) + if err := c.List(context.TODO(), claims, client.InNamespace(ns)); err != nil { + t.Fatal(err) + } + if len(claims.Items) != 1 { + t.Fatalf("expected one minted claim, got %d", len(claims.Items)) + } + minted := claims.Items[0] + if !isControlledBy(&minted, ea) { + t.Fatalf("minted claim must be controller-owned by the attachment: %+v", minted.GetOwnerReferences()) + } + if !strings.HasPrefix(minted.GetName(), "rw-public-") { + t.Fatalf("minted claim name %q", minted.GetName()) + } + if fam, _, _ := unstructured.NestedString(minted.Object, "spec", "family"); fam != "IPv4" { + t.Fatalf("family not passed through: %q", fam) + } + if _, has, _ := unstructured.NestedString(minted.Object, "spec", "className"); has { + t.Fatal("no className means the default class; none must be written") + } + if got.Status.ClaimName != minted.GetName() { + t.Fatalf("status.claimName = %q", got.Status.ClaimName) + } + if len(renderedServices(t, c, ea)) != 0 { + t.Fatal("no Service may exist before the claim's class fixes loadBalancerClass") + } + + // Reconcile again: the minted claim is rediscovered, not re-minted. + run(t, c, nil, ea) + if err := c.List(context.TODO(), claims, client.InNamespace(ns)); err != nil { + t.Fatal(err) + } + if len(claims.Items) != 1 { + t.Fatalf("claim re-minted: %d claims", len(claims.Items)) + } + + // The substrate resolves the default class and binds. + live := claims.Items[0] + live.Object["status"] = map[string]interface{}{ + "className": "public", "phase": "Bound", + "addresses": []interface{}{map[string]interface{}{"name": "ip-a", "address": "203.0.113.9"}}, + } + if err := c.Update(context.TODO(), &live); err != nil { + t.Fatal(err) + } + got = run(t, c, nil, ea) + svc := onlyRendered(t, c, ea) + if svc.Spec.LoadBalancerClass != nil { + t.Fatalf("an empty class loadBalancerClass must stay empty on the Service, got %q", *svc.Spec.LoadBalancerClass) + } + if svc.Annotations[ClaimAnnotation] != minted.GetName() { + t.Fatalf("claim annotation = %q", svc.Annotations[ClaimAnnotation]) + } + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonWaitingForAddress) +} + +// TestIdentityLabelledButUnownedServiceIsIgnored is the identity proof: a +// Service carrying the ownership label but no controller reference to the +// attachment is neither adopted nor updated; the controller renders its own. +func TestIdentityLabelledButUnownedServiceIsIgnored(t *testing.T) { + ep := endpoint("postgres-mydb-ro", "Postgres", "mydb", map[string]string{"role": "replica"}, 5432) + ea := attachment("ro-public", "ea-1", "Postgres", "mydb", "postgres-mydb-ro", cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held"}) + impostor := &corev1.Service{ + ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: "ro-public-fake", UID: "svc-fake", + Labels: map[string]string{OwnerLabel: ea.Name}, + Annotations: map[string]string{"tenant": "wrote-this"}}, + Spec: corev1.ServiceSpec{Type: corev1.ServiceTypeClusterIP, Selector: map[string]string{"app": "evil"}, + Ports: []corev1.ServicePort{{Port: 80}}}, + } + strayOwner := &corev1.Service{ + ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: "ro-public-stale", UID: "svc-stale", + Labels: map[string]string{OwnerLabel: ea.Name}, + OwnerReferences: []metav1.OwnerReference{{ + APIVersion: cozyv1alpha1.GroupVersion.String(), Kind: "EndpointAttachment", + Name: ea.Name, UID: "ea-previous-incarnation", Controller: new(true), + }}}, + Spec: corev1.ServiceSpec{Type: corev1.ServiceTypeLoadBalancer, Selector: map[string]string{"app": "stale"}, + Ports: []corev1.ServicePort{{Port: 5432}}}, + } + c := newClient(t, helmRelease("postgres-mydb", "hr-1", "Postgres", "mydb"), ep, ea, impostor, strayOwner, + claimObject("held", "public", "IPv4", true, "203.0.113.7"), classObject("public", ""), addressObject("203.0.113.7", nil)) + + run(t, c, nil, ea) + + own := onlyRendered(t, c, ea) + if own.Name == impostor.Name || own.Name == strayOwner.Name { + t.Fatalf("controller adopted %q instead of rendering its own Service", own.Name) + } + for _, name := range []string{impostor.Name, strayOwner.Name} { + live := &corev1.Service{} + if err := c.Get(context.TODO(), types.NamespacedName{Namespace: ns, Name: name}, live); err != nil { + t.Fatalf("%s must be left alone, got %v", name, err) + } + if live.Spec.Selector["app"] == "" || live.Annotations[ClaimAnnotation] != "" { + t.Fatalf("%s was modified: %+v", name, live.Spec) + } + } +} + +// TestIdentitySameNameRecreatedApplication: the attachment is bound to one +// application incarnation by UID. A same-name successor is not re-adopted; +// the attachment reports the change, withdraws, and waits for GC. +func TestIdentitySameNameRecreatedApplication(t *testing.T) { + ep := endpoint("postgres-mydb-ro", "Postgres", "mydb", map[string]string{"role": "replica"}, 5432) + ea := attachment("ro-public", "ea-1", "Postgres", "mydb", "postgres-mydb-ro", cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held"}) + c := newClient(t, helmRelease("postgres-mydb", "hr-old", "Postgres", "mydb"), ep, ea, + claimObject("held", "public", "IPv4", true, "203.0.113.7"), classObject("public", ""), addressObject("203.0.113.7", nil)) + got := run(t, c, nil, ea) + if helmReleaseOwner(got).UID != "hr-old" { + t.Fatalf("owner = %+v", got.OwnerReferences) + } + rendered := onlyRendered(t, c, ea) + + // The application is deleted and recreated under the same name. + old := &helmv2.HelmRelease{} + if err := c.Get(context.TODO(), types.NamespacedName{Namespace: ns, Name: "postgres-mydb"}, old); err != nil { + t.Fatal(err) + } + if err := c.Delete(context.TODO(), old); err != nil { + t.Fatal(err) + } + if err := c.Create(context.TODO(), helmRelease("postgres-mydb", "hr-new", "Postgres", "mydb")); err != nil { + t.Fatal(err) + } + + got = run(t, c, nil, ea) + expectCondition(t, got, cozyv1alpha1.ConditionResolved, metav1.ConditionFalse, cozyv1alpha1.ReasonApplicationIncarnationChange) + if helmReleaseOwner(got).UID != "hr-old" { + t.Fatalf("owner reference must never be rewritten to the successor, got %+v", got.OwnerReferences) + } + if err := c.Get(context.TODO(), client.ObjectKeyFromObject(rendered), &corev1.Service{}); !apierrors.IsNotFound(err) { + t.Fatalf("rendered Service must be withdrawn from the successor, got %v", err) + } + if got.Status.Phase != cozyv1alpha1.EndpointAttachmentDetached { + t.Fatalf("phase = %s, want Detached", got.Status.Phase) + } +} + +// TestHoldAndMove is the proposal's contract in one test: a reserved claim +// is attached, the attachment goes away, the claim is untouched and still +// holds its address, and a second attachment on a different application's +// endpoint serves the same address. +func TestHoldAndMove(t *testing.T) { + epA := endpoint("postgres-a-rw", "Postgres", "a", map[string]string{"cluster": "a"}, 5432) + epB := endpoint("mariadb-b-primary", "MariaDB", "b", map[string]string{"cluster": "b"}, 3306) + ea1 := attachment("a-public", "ea-1", "Postgres", "a", "postgres-a-rw", cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held"}) + c := newClient(t, + helmRelease("postgres-a", "hr-a", "Postgres", "a"), helmRelease("mariadb-b", "hr-b", "MariaDB", "b"), + epA, epB, ea1, + claimObject("held", "public", "IPv4", true, "203.0.113.7"), classObject("public", ""), addressObject("203.0.113.7", nil)) + + run(t, c, nil, ea1) + s1 := onlyRendered(t, c, ea1) + setIngress(t, c, s1, "203.0.113.7") + got := run(t, c, nil, ea1) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionTrue, cozyv1alpha1.ReasonProvisioned) + + // The substrate associates the address to S1. A second attachment on the + // same claim is refused, not fought over. + addr := addressObject("203.0.113.7", &types.NamespacedName{Namespace: ns, Name: s1.Name}) + live := &unstructured.Unstructured{} + live.SetGroupVersionKind(addressGVK) + if err := c.Get(context.TODO(), client.ObjectKeyFromObject(addr), live); err != nil { + t.Fatal(err) + } + live.Object["status"] = addr.Object["status"] + if err := c.Update(context.TODO(), live); err != nil { + t.Fatal(err) + } + ea2 := attachment("b-public", "ea-2", "MariaDB", "b", "mariadb-b-primary", cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held"}) + if err := c.Create(context.TODO(), ea2); err != nil { + t.Fatal(err) + } + got2 := run(t, c, nil, ea2) + expectCondition(t, got2, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonClaimInUse) + if len(renderedServices(t, c, ea2)) != 0 { + t.Fatal("a claim worn by another Service must not be contended") + } + + // Detach: the first attachment is deleted (its Service goes with it by + // GC, simulated here). The claim was never owned or written. + if err := c.Delete(context.TODO(), got); err != nil { + t.Fatal(err) + } + if err := c.Delete(context.TODO(), s1); err != nil { + t.Fatal(err) + } + held := newClaim() + if err := c.Get(context.TODO(), types.NamespacedName{Namespace: ns, Name: "held"}, held); err != nil { + t.Fatalf("referenced claim must survive detachment: %v", err) + } + if len(held.GetOwnerReferences()) != 0 { + t.Fatalf("referenced claim must never be owned: %+v", held.GetOwnerReferences()) + } + if v := parseClaim(held); !v.Bound || v.Addresses[0].Address != "203.0.113.7" { + t.Fatalf("claim must still hold its address: %+v", v) + } + + // Move: the holder is gone, so the association record is stale and the + // second attachment takes the address to a different application. + got2 = run(t, c, nil, ea2) + s2 := onlyRendered(t, c, ea2) + if s2.Annotations[ClaimAnnotation] != "held" || !equalStringMaps(s2.Spec.Selector, epB.Spec.Selector) { + t.Fatalf("second attachment must consume the same claim on the new target: %+v", s2) + } + setIngress(t, c, s2, "203.0.113.7") + got2 = run(t, c, nil, ea2) + expectCondition(t, got2, cozyv1alpha1.ConditionProvisioned, metav1.ConditionTrue, cozyv1alpha1.ReasonProvisioned) + if got2.Status.Addresses[0] != "203.0.113.7" { + t.Fatalf("same address must serve the new target, got %v", got2.Status.Addresses) + } +} + +// TestDetachKeepsAddress: an endpoint that disappears (a scale-down) turns +// the attachment Detached, withdraws the Service, keeps the claim, and the +// same claim is reused when the endpoint returns. +func TestDetachKeepsAddress(t *testing.T) { + ep := endpoint("mariadb-x-secondary", "MariaDB", "x", map[string]string{"role": "secondary"}, 3306) + ea := attachment("sec", "ea-1", "MariaDB", "x", "mariadb-x-secondary", cozyv1alpha1.LoadBalancerAttachment{ClassName: "public"}) + c := newClient(t, helmRelease("mariadb-x", "hr-1", "MariaDB", "x"), ep, ea, classObject("public", "")) + got := run(t, c, nil, ea) + minted := got.Status.ClaimName + claim := newClaim() + if err := c.Get(context.TODO(), types.NamespacedName{Namespace: ns, Name: minted}, claim); err != nil { + t.Fatal(err) + } + claim.Object["status"] = map[string]interface{}{"className": "public", "phase": "Bound", + "addresses": []interface{}{map[string]interface{}{"name": "ip-x", "address": "203.0.113.20"}}} + if err := c.Update(context.TODO(), claim); err != nil { + t.Fatal(err) + } + run(t, c, nil, ea) + svc := onlyRendered(t, c, ea) + + if err := c.Delete(context.TODO(), ep); err != nil { + t.Fatal(err) + } + got = run(t, c, nil, ea) + if got.Status.Phase != cozyv1alpha1.EndpointAttachmentDetached { + t.Fatalf("phase = %s, want Detached (%+v)", got.Status.Phase, got.Status.Conditions) + } + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonEndpointDetached) + if err := c.Get(context.TODO(), client.ObjectKeyFromObject(svc), &corev1.Service{}); !apierrors.IsNotFound(err) { + t.Fatalf("Service must be torn down on detach, got %v", err) + } + if err := c.Get(context.TODO(), types.NamespacedName{Namespace: ns, Name: minted}, newClaim()); err != nil { + t.Fatalf("minted claim must be kept across a detach: %v", err) + } + if got.Status.ClaimName != minted || got.Status.ServiceName != "" { + t.Fatalf("status after detach: %+v", got.Status) + } + + if err := c.Create(context.TODO(), endpoint("mariadb-x-secondary", "MariaDB", "x", map[string]string{"role": "secondary"}, 3306)); err != nil { + t.Fatal(err) + } + got = run(t, c, nil, ea) + again := onlyRendered(t, c, ea) + if again.Annotations[ClaimAnnotation] != minted { + t.Fatalf("reattachment must reuse the held claim, got %q", again.Annotations[ClaimAnnotation]) + } + if got.Status.Phase != cozyv1alpha1.EndpointAttachmentPending { + t.Fatalf("phase = %s, want Pending until the address lands", got.Status.Phase) + } +} + +func TestSentinelEndpointNeedsPortsOrMethod(t *testing.T) { + vm := endpoint("vm-instance-box", "VMInstance", "box", map[string]string{"vm": "box"}, SentinelPort) + ea := attachment("box-ip", "ea-1", "VMInstance", "box", "vm-instance-box", cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held"}) + c := newClient(t, helmRelease("vm-instance-box", "hr-1", "VMInstance", "box"), vm, ea, + claimObject("held", "public", "IPv4", true, "203.0.113.7"), classObject("public", ""), addressObject("203.0.113.7", nil)) + got := run(t, c, nil, ea) + expectCondition(t, got, cozyv1alpha1.ConditionResolved, metav1.ConditionTrue, cozyv1alpha1.ReasonResolved) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonNothingToPublish) + if len(renderedServices(t, c, ea)) != 0 { + t.Fatal("nothing must be rendered from a sentinel-only endpoint") + } +} + +// TestMethodModes renders the two VM datapath modes and pins the capability +// gate: without the platform's declaration no Service exists at all. +func TestMethodModes(t *testing.T) { + vmObjects := func(lb cozyv1alpha1.LoadBalancerAttachment) (*cozyv1alpha1.EndpointAttachment, client.Client) { + vm := endpoint("vm-instance-box", "VMInstance", "box", map[string]string{"vm": "box"}, SentinelPort) + ea := attachment("box-ip", "ea-1", "VMInstance", "box", "vm-instance-box", lb) + return ea, newClient(t, helmRelease("vm-instance-box", "hr-1", "VMInstance", "box"), vm, ea, + endpointSlice("vm-instance-box-1", "vm-instance-box", true, "virt-launcher-box"), + claimObject("held", "public", "IPv4", true, "203.0.113.7"), classObject("public", ""), addressObject("203.0.113.7", nil)) + } + + t.Run("gated off renders nothing", func(t *testing.T) { + ea, c := vmObjects(cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held", Method: cozyv1alpha1.ExposureMethodPortList, Ports: []int32{22}}) + got := run(t, c, &Reconciler{CozyProxyContractImplemented: false}, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonDatapathUnavailable) + if len(renderedServices(t, c, ea)) != 0 { + t.Fatal("an address nothing can serve must not be attracted") + } + }) + + t.Run("PortList", func(t *testing.T) { + ea, c := vmObjects(cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held", Method: cozyv1alpha1.ExposureMethodPortList, Ports: []int32{443, 22}, AllowICMP: new(false)}) + run(t, c, &Reconciler{CozyProxyContractImplemented: true}, ea) + svc := onlyRendered(t, c, ea) + if svc.Labels[ServiceProxyNameLabel] != ServiceProxyName { + t.Fatalf("labels = %v", svc.Labels) + } + if svc.Annotations[WholeIPAnnotation] != "false" || svc.Annotations[AllowICMPAnnotation] != "false" { + t.Fatalf("annotations = %v", svc.Annotations) + } + if len(svc.Spec.Ports) != 2 || svc.Spec.Ports[0].Port != 22 || svc.Spec.Ports[0].TargetPort.IntValue() != 22 || + svc.Spec.Ports[0].Name != "port-22" || svc.Spec.Ports[1].Port != 443 { + t.Fatalf("ports = %+v", svc.Spec.Ports) + } + if !equalStringMaps(svc.Spec.Selector, map[string]string{"vm": "box"}) { + t.Fatalf("selector = %v", svc.Spec.Selector) + } + }) + + t.Run("WholeIP", func(t *testing.T) { + ea, c := vmObjects(cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held", Method: cozyv1alpha1.ExposureMethodWholeIP}) + got := run(t, c, &Reconciler{CozyProxyContractImplemented: true}, ea) + svc := onlyRendered(t, c, ea) + if svc.Annotations[WholeIPAnnotation] != "true" { + t.Fatalf("annotations = %v", svc.Annotations) + } + if _, ok := svc.Annotations[AllowICMPAnnotation]; ok { + t.Fatal("allowICMP is a PortList knob") + } + if len(svc.Spec.Ports) != 1 || svc.Spec.Ports[0].Port != SentinelPort { + t.Fatalf("whole-IP without ports renders the sentinel port, got %+v", svc.Spec.Ports) + } + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonWaitingForAddress) + }) + + t.Run("WholeIP with ports", func(t *testing.T) { + ea, c := vmObjects(cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held", Method: cozyv1alpha1.ExposureMethodWholeIP, Ports: []int32{80}}) + run(t, c, &Reconciler{CozyProxyContractImplemented: true}, ea) + svc := onlyRendered(t, c, ea) + if len(svc.Spec.Ports) != 1 || svc.Spec.Ports[0].Port != 80 || svc.Spec.Ports[0].Name != "port-80" { + t.Fatalf("ports = %+v", svc.Spec.Ports) + } + }) +} + +// TestWholeIPMultipleBackendsHeldDark: 1:1 NAT has no meaning against two +// backends. The address is neither released nor coin-flipped: the Service +// keeps its identity and its claim but selects nothing until one backend +// remains. +func TestWholeIPMultipleBackendsHeldDark(t *testing.T) { + vm := endpoint("vm-instance-box", "VMInstance", "box", map[string]string{"vm": "box"}, SentinelPort) + ea := attachment("box-ip", "ea-1", "VMInstance", "box", "vm-instance-box", cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held", Method: cozyv1alpha1.ExposureMethodWholeIP}) + slice := endpointSlice("vm-instance-box-1", "vm-instance-box", true, "virt-launcher-src", "virt-launcher-dst") + c := newClient(t, helmRelease("vm-instance-box", "hr-1", "VMInstance", "box"), vm, ea, slice, + claimObject("held", "public", "IPv4", true, "203.0.113.7"), classObject("public", ""), addressObject("203.0.113.7", nil)) + r := &Reconciler{CozyProxyContractImplemented: true} + + got := run(t, c, r, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonMultipleBackends) + dark := onlyRendered(t, c, ea) + if dark.Spec.Selector["vm"] != "" { + t.Fatalf("a whole-IP Service with two backends must not select them, got %v", dark.Spec.Selector) + } + if dark.Annotations[ClaimAnnotation] != "held" || dark.Annotations[WholeIPAnnotation] != "true" { + t.Fatalf("the address must stay held on the same Service: %v", dark.Annotations) + } + setIngress(t, c, dark, "203.0.113.7") + got = run(t, c, r, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonMultipleBackends) + + // The migration completes: one backend remains, the mirror is restored on + // the same Service. + live := &discoveryv1.EndpointSlice{} + if err := c.Get(context.TODO(), client.ObjectKeyFromObject(slice), live); err != nil { + t.Fatal(err) + } + live.Endpoints = live.Endpoints[1:] + if err := c.Update(context.TODO(), live); err != nil { + t.Fatal(err) + } + got = run(t, c, r, ea) + lit := onlyRendered(t, c, ea) + if lit.Name != dark.Name || lit.Spec.Selector["vm"] != "box" { + t.Fatalf("Service identity must survive the handover: %s %v", lit.Name, lit.Spec.Selector) + } + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionTrue, cozyv1alpha1.ReasonProvisioned) +} + +// TestBackendExclusivity keys the one-delegation-per-backend rule on the pod, +// in either mode, counting chart-rendered Services as well as attachments. +// The older delegation wins and the newer one renders no Service. +func TestBackendExclusivity(t *testing.T) { + legacy := &corev1.Service{ + ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: "vm-instance-box", UID: "svc-legacy", + CreationTimestamp: metav1.NewTime(time.Now().Add(-time.Hour)), + Labels: func() map[string]string { + l := appLabels("VMInstance", "box") + l[corev1alpha1.TenantResourceLabelKey] = corev1alpha1.TenantResourceLabelValue + l[ServiceProxyNameLabel] = ServiceProxyName + return l + }(), + Annotations: map[string]string{WholeIPAnnotation: "false", AllowICMPAnnotation: "true"}}, + Spec: corev1.ServiceSpec{Type: corev1.ServiceTypeLoadBalancer, Selector: map[string]string{"vm": "box"}, + Ports: []corev1.ServicePort{{Name: "port-22", Port: 22}}}, + } + ea := attachment("box-ip", "ea-1", "VMInstance", "box", "vm-instance-box", cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held", Method: cozyv1alpha1.ExposureMethodWholeIP}) + c := newClient(t, helmRelease("vm-instance-box", "hr-1", "VMInstance", "box"), legacy, ea, + endpointSlice("vm-instance-box-1", "vm-instance-box", true, "virt-launcher-box"), + claimObject("held", "public", "IPv4", true, "203.0.113.7"), classObject("public", ""), addressObject("203.0.113.7", nil)) + r := &Reconciler{CozyProxyContractImplemented: true} + + got := run(t, c, r, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonBackendAlreadyDelegated) + if len(renderedServices(t, c, ea)) != 0 { + t.Fatal("the losing delegation must not present a Service the datapath would steal the slot for") + } + + // The legacy exposure is switched off: the slot frees and the attachment + // renders. + if err := c.Delete(context.TODO(), legacy); err != nil { + t.Fatal(err) + } + if err := c.Create(context.TODO(), endpoint("vm-instance-box", "VMInstance", "box", map[string]string{"vm": "box"}, SentinelPort)); err != nil { + t.Fatal(err) + } + run(t, c, r, ea) + own := onlyRendered(t, c, ea) + + // A second whole-IP attachment on the same VM loses to the first, with + // the distinct reason; the first keeps its Service. + if err := c.Create(context.TODO(), endpointSlice(own.Name+"-1", own.Name, true, "virt-launcher-box")); err != nil { + t.Fatal(err) + } + ea2 := attachment("box-ip-2", "ea-2", "VMInstance", "box", "vm-instance-box", cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held2", Method: cozyv1alpha1.ExposureMethodWholeIP}) + if err := c.Create(context.TODO(), ea2); err != nil { + t.Fatal(err) + } + if err := c.Create(context.TODO(), claimObject("held2", "public", "IPv4", true, "203.0.113.8")); err != nil { + t.Fatal(err) + } + got2 := run(t, c, r, ea2) + expectCondition(t, got2, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonBackendAlreadyDelegated) + if len(renderedServices(t, c, ea2)) != 0 { + t.Fatal("second whole-IP attachment must render nothing") + } + if len(renderedServices(t, c, ea)) != 1 { + t.Fatal("the winner keeps its Service") + } +} + +// TestSubstrateAbsent: without the claim kind served, the attachment +// resolves, reports that it is waiting on the substrate, and renders nothing. +func TestSubstrateAbsent(t *testing.T) { + ep := endpoint("postgres-mydb-ro", "Postgres", "mydb", map[string]string{"role": "replica"}, 5432) + ea := attachment("ro-public", "ea-1", "Postgres", "mydb", "postgres-mydb-ro", cozyv1alpha1.LoadBalancerAttachment{}) + noKind := &apimeta.NoKindMatchError{GroupKind: claimGVK.GroupKind(), SearchedVersions: []string{"v1alpha1"}} + c := fake.NewClientBuilder().WithScheme(newScheme(t)). + WithStatusSubresource(&cozyv1alpha1.EndpointAttachment{}). + WithObjects(helmRelease("postgres-mydb", "hr-1", "Postgres", "mydb"), ep, ea). + WithInterceptorFuncs(interceptor.Funcs{ + List: func(ctx context.Context, c client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + if _, ok := list.(*unstructured.UnstructuredList); ok { + return noKind + } + return c.List(ctx, list, opts...) + }, + }).Build() + got := run(t, c, nil, ea) + expectCondition(t, got, cozyv1alpha1.ConditionResolved, metav1.ConditionTrue, cozyv1alpha1.ReasonResolved) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonClaimPending) + if len(renderedServices(t, c, ea)) != 0 { + t.Fatal("no Service without a claim to consume") + } +} + +func TestFamilyConflictWithReferencedClaim(t *testing.T) { + ep := endpoint("postgres-mydb-ro", "Postgres", "mydb", map[string]string{"role": "replica"}, 5432) + ea := attachment("ro-public", "ea-1", "Postgres", "mydb", "postgres-mydb-ro", cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held", Family: cozyv1alpha1.AddressFamilyIPv6}) + c := newClient(t, helmRelease("postgres-mydb", "hr-1", "Postgres", "mydb"), ep, ea, + claimObject("held", "public", "IPv4", true, "203.0.113.7"), classObject("public", "")) + got := run(t, c, nil, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonFamilyConflict) + if len(renderedServices(t, c, ea)) != 0 { + t.Fatal("nothing is rendered against the wrong family") + } +} + +// TestDualClaimNeedsEveryAddress: a Dual claim binds a v4 and a v6 address, +// and a Service carrying only one of them is not provisioned. +func TestDualClaimNeedsEveryAddress(t *testing.T) { + ep := endpoint("postgres-mydb-rw", "Postgres", "mydb", map[string]string{"role": "primary"}, 5432) + ea := attachment("rw-dual", "ea-1", "Postgres", "mydb", "postgres-mydb-rw", + cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held", Family: cozyv1alpha1.AddressFamilyDual}) + c := newClient(t, helmRelease("postgres-mydb", "hr-1", "Postgres", "mydb"), ep, ea, + claimObject("held", "public", "Dual", true, "192.0.2.10", "2001:db8::10"), classObject("public", "")) + + run(t, c, nil, ea) + svc := onlyRendered(t, c, ea) + + setIngress(t, c, svc, "192.0.2.10") + got := run(t, c, nil, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonWaitingForAddress) + if msg := apimeta.FindStatusCondition(got.Status.Conditions, cozyv1alpha1.ConditionProvisioned).Message; !strings.Contains(msg, "2001:db8::10") { + t.Fatalf("message must name the address still missing, got %q", msg) + } + if got.Status.Phase != cozyv1alpha1.EndpointAttachmentPending { + t.Fatalf("phase = %s, want Pending while one family is unassigned", got.Status.Phase) + } + + setIngress(t, c, svc, "192.0.2.10", "2001:db8::10") + got = run(t, c, nil, ea) + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionTrue, cozyv1alpha1.ReasonProvisioned) + if got.Status.Phase != cozyv1alpha1.EndpointAttachmentAttached { + t.Fatalf("phase = %s, want Attached", got.Status.Phase) + } +} + +// TestNamesTheApiserverAccepts: an attachment name may be any DNS-1123 +// subdomain up to 253 characters, dots and a leading digit included. Every +// child the controller creates for it must still carry a name, a +// generateName and an ownership label value the apiserver accepts, on both +// address-selection paths. +func TestNamesTheApiserverAccepts(t *testing.T) { + names := []string{ + strings.Repeat("a", 70) + ".replicas-public", + "1st.replicas", + strings.Repeat("b", 253), + } + for _, name := range names { + for _, path := range []string{"minted", "referenced"} { + t.Run(fmt.Sprintf("%s/%d-chars", path, len(name)), func(t *testing.T) { + if errs := validation.IsDNS1123Subdomain(name); len(errs) > 0 { + t.Fatalf("fixture name is not a valid attachment name: %v", errs) + } + lb := cozyv1alpha1.LoadBalancerAttachment{ClassName: "public"} + objs := []client.Object{ + helmRelease("postgres-mydb", "hr-1", "Postgres", "mydb"), + endpoint("postgres-mydb-ro", "Postgres", "mydb", map[string]string{"role": "replica"}, 5432), + classObject("public", ""), + } + if path == "referenced" { + lb = cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held"} + objs = append(objs, claimObject("held", "public", "IPv4", true, "203.0.113.7")) + } + ea := attachment(name, "ea-1", "Postgres", "mydb", "postgres-mydb-ro", lb) + c := newClient(t, append(objs, ea)...) + run(t, c, nil, ea) + + svc := onlyRendered(t, c, ea) + if errs := apivalidation.NameIsDNS1035Label(svc.GenerateName, true); len(errs) > 0 { + t.Errorf("Service generateName %q would be refused: %v", svc.GenerateName, errs) + } + if errs := validation.IsDNS1035Label(svc.Name); len(errs) > 0 { + t.Errorf("Service name %q would be refused: %v", svc.Name, errs) + } + if errs := validation.IsValidLabelValue(svc.Labels[OwnerLabel]); len(errs) > 0 { + t.Errorf("Service ownership label %q would be refused: %v", svc.Labels[OwnerLabel], errs) + } + if path != "minted" { + return + } + claim, err := (&Reconciler{Client: c}).mintedClaim(context.TODO(), ea) + if err != nil || claim == nil { + t.Fatalf("minted claim not found: %v", err) + } + if errs := apivalidation.NameIsDNSSubdomain(claim.GetGenerateName(), true); len(errs) > 0 { + t.Errorf("claim generateName %q would be refused: %v", claim.GetGenerateName(), errs) + } + if errs := validation.IsValidLabelValue(claim.GetLabels()[OwnerLabel]); len(errs) > 0 { + t.Errorf("claim ownership label %q would be refused: %v", claim.GetLabels()[OwnerLabel], errs) + } + }) + } + } +} + +// TestOwnerLabelValueKeepsLongNamesApart: two long names sharing their first +// 63 characters must not label alike, or the diagnostic selector would mix +// their children. +func TestOwnerLabelValueKeepsLongNamesApart(t *testing.T) { + a := strings.Repeat("x", 63) + "-one" + b := strings.Repeat("x", 63) + "-two" + if ownerLabelValue(a) == ownerLabelValue(b) { + t.Fatalf("%q and %q label alike: %q", a, b, ownerLabelValue(a)) + } + if short := "mydb-replicas"; ownerLabelValue(short) != short { + t.Fatalf("a name that fits must label as itself, got %q", ownerLabelValue(short)) + } +} + +// TestServiceFamiliesFollowTheClaim: the rendered Service asks for the +// claim's families, so the load balancer can assign an address of a family +// other than the cluster's primary one, and both addresses of a Dual claim. +func TestServiceFamiliesFollowTheClaim(t *testing.T) { + for _, tt := range []struct { + family string + address []string + policy corev1.IPFamilyPolicy + families []corev1.IPFamily + }{ + {"IPv4", []string{"203.0.113.7"}, corev1.IPFamilyPolicySingleStack, []corev1.IPFamily{corev1.IPv4Protocol}}, + {"", []string{"203.0.113.7"}, corev1.IPFamilyPolicySingleStack, []corev1.IPFamily{corev1.IPv4Protocol}}, + {"IPv6", []string{"2001:db8::7"}, corev1.IPFamilyPolicySingleStack, []corev1.IPFamily{corev1.IPv6Protocol}}, + {"Dual", []string{"203.0.113.7", "2001:db8::7"}, corev1.IPFamilyPolicyRequireDualStack, []corev1.IPFamily{corev1.IPv4Protocol, corev1.IPv6Protocol}}, + } { + t.Run("family="+tt.family, func(t *testing.T) { + ea := attachment("ro-public", "ea-1", "Postgres", "mydb", "postgres-mydb-ro", cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held"}) + c := newClient(t, helmRelease("postgres-mydb", "hr-1", "Postgres", "mydb"), ea, + endpoint("postgres-mydb-ro", "Postgres", "mydb", map[string]string{"role": "replica"}, 5432), + claimObject("held", "public", tt.family, true, tt.address...), classObject("public", "")) + run(t, c, nil, ea) + svc := onlyRendered(t, c, ea) + if svc.Spec.IPFamilyPolicy == nil || *svc.Spec.IPFamilyPolicy != tt.policy || !slices.Equal(svc.Spec.IPFamilies, tt.families) { + t.Fatalf("Service families = %v/%v, want %s/%v", svc.Spec.IPFamilyPolicy, svc.Spec.IPFamilies, tt.policy, tt.families) + } + }) + } +} + +// TestServiceFamiliesReconciled: a Service rendered without the claim's +// families, as before they were set, is brought to them when its primary +// family already matches, and reported, not rewritten, when it does not, +// because the apiserver never changes a Service's primary family. +func TestServiceFamiliesReconciled(t *testing.T) { + for _, tt := range []struct { + name, family string + address []string + live []corev1.IPFamily + wantReason string + wantFamilies []corev1.IPFamily + }{ + {name: "unset becomes the claim's", family: "IPv4", address: []string{"203.0.113.7"}, + wantFamilies: []corev1.IPFamily{corev1.IPv4Protocol}}, + {name: "single stack gains the second family", family: "Dual", address: []string{"203.0.113.7", "2001:db8::7"}, + live: []corev1.IPFamily{corev1.IPv4Protocol}, wantFamilies: []corev1.IPFamily{corev1.IPv4Protocol, corev1.IPv6Protocol}}, + {name: "primary family mismatch", family: "IPv6", address: []string{"2001:db8::7"}, + live: []corev1.IPFamily{corev1.IPv4Protocol}, wantReason: cozyv1alpha1.ReasonRenderFailed, wantFamilies: []corev1.IPFamily{corev1.IPv4Protocol}}, + } { + t.Run(tt.name, func(t *testing.T) { + ea := attachment("ro-public", "ea-1", "Postgres", "mydb", "postgres-mydb-ro", cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held"}) + c := newClient(t, helmRelease("postgres-mydb", "hr-1", "Postgres", "mydb"), ea, + endpoint("postgres-mydb-ro", "Postgres", "mydb", map[string]string{"role": "replica"}, 5432), + claimObject("held", "public", tt.family, true, tt.address...), classObject("public", "")) + run(t, c, nil, ea) + svc := onlyRendered(t, c, ea) + svc.Spec.IPFamilyPolicy = nil + svc.Spec.IPFamilies = tt.live + if err := c.Update(context.TODO(), svc); err != nil { + t.Fatal(err) + } + got := run(t, c, nil, ea) + if tt.wantReason != "" { + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, tt.wantReason) + } + svc = onlyRendered(t, c, ea) + if !slices.Equal(svc.Spec.IPFamilies, tt.wantFamilies) { + t.Fatalf("Service families = %v, want %v", svc.Spec.IPFamilies, tt.wantFamilies) + } + }) + } +} + +// TestRefusedDualStackCreateIsRenderFailed: on a cluster without a +// dual-stack service range the apiserver refuses a RequireDualStack Service, +// and the attachment says so instead of waiting for an address. +func TestRefusedDualStackCreateIsRenderFailed(t *testing.T) { + ea := attachment("rw-dual", "ea-1", "Postgres", "mydb", "postgres-mydb-rw", cozyv1alpha1.LoadBalancerAttachment{ClaimName: "held"}) + c := fake.NewClientBuilder().WithScheme(newScheme(t)). + WithStatusSubresource(&cozyv1alpha1.EndpointAttachment{}). + WithObjects(helmRelease("postgres-mydb", "hr-1", "Postgres", "mydb"), ea, + endpoint("postgres-mydb-rw", "Postgres", "mydb", map[string]string{"role": "primary"}, 5432), + claimObject("held", "public", "Dual", true, "203.0.113.7", "2001:db8::7"), classObject("public", "")). + WithInterceptorFuncs(interceptor.Funcs{ + Create: func(ctx context.Context, cl client.WithWatch, o client.Object, opts ...client.CreateOption) error { + if svc, ok := o.(*corev1.Service); ok && svc.Spec.IPFamilyPolicy != nil && *svc.Spec.IPFamilyPolicy == corev1.IPFamilyPolicyRequireDualStack { + return apierrors.NewInvalid(schema.GroupKind{Kind: "Service"}, svc.GenerateName, + field.ErrorList{field.Invalid(field.NewPath("spec", "ipFamilyPolicy"), "RequireDualStack", "this cluster is not configured for dual-stack services")}) + } + return cl.Create(ctx, o, opts...) + }, + }).Build() + r := &Reconciler{Client: c} + if _, err := r.Reconcile(context.TODO(), ctrl.Request{NamespacedName: client.ObjectKeyFromObject(ea)}); err == nil { + t.Fatal("a refused create must be returned for a retry") + } + got := &cozyv1alpha1.EndpointAttachment{} + if err := c.Get(context.TODO(), client.ObjectKeyFromObject(ea), got); err != nil { + t.Fatal(err) + } + expectCondition(t, got, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, cozyv1alpha1.ReasonRenderFailed) + if msg := apimeta.FindStatusCondition(got.Status.Conditions, cozyv1alpha1.ConditionProvisioned).Message; !strings.Contains(msg, "dual-stack") { + t.Fatalf("message must carry the apiserver's reason, got %q", msg) + } +} diff --git a/internal/controller/endpointattachment/render.go b/internal/controller/endpointattachment/render.go new file mode 100644 index 000000000..a56b3f51d --- /dev/null +++ b/internal/controller/endpointattachment/render.go @@ -0,0 +1,454 @@ +/* +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 endpointattachment + +import ( + "context" + "fmt" + "slices" + "sort" + "strings" + + corev1 "k8s.io/api/core/v1" + discoveryv1 "k8s.io/api/discovery/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/intstr" + "sigs.k8s.io/controller-runtime/pkg/client" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/localsdn/v1alpha1" +) + +// The datapath-delegation contract. The rendered Service is one fixed +// interface with two implementors (cozy-proxy today, cozyplane's proxy +// later); both match these strings literally, so they are rendered exactly +// and nothing is added beside them. +const ( + ServiceProxyNameLabel = "service.kubernetes.io/service-proxy-name" + ServiceProxyName = "cozy-proxy" + WholeIPAnnotation = "networking.cozystack.io/wholeIP" + AllowICMPAnnotation = "networking.cozystack.io/allowICMP" + + // SentinelPort is the placeholder port a whole-IP Service carries when + // no port list is given, and the one port a not-yet-exposed VM Service + // has, which makes it "nothing to mirror". + SentinelPort int32 = 65535 + + // OwnerLabel indexes objects this controller renders for an attachment. + // It is a diagnostic; identity is the controller owner reference. + OwnerLabel = "cozystack.io/endpoint-attachment" + + // darkSelectorKey is a label no pod carries. A Service whose selector is + // this label alone keeps its identity and its address while serving + // nothing, which is what a whole-IP attachment does while its endpoint + // resolves to more than one backend. + darkSelectorKey = "internal.cozystack.io/endpoint-attachment-dark" +) + +// renderInput is everything the desired Service depends on. +type renderInput struct { + Endpoint *corev1.Service + ClaimName string + LoadBalancerClass string + Dark bool + AllocateNodePorts bool + // Family is the claim's spec.family; empty reads as IPv4, the + // substrate's default. + Family string +} + +// serviceFamilies maps a claim family onto the Service's family fields. Left +// unset, the apiserver gives the Service the cluster's primary family, and +// the load balancer then cannot assign an address of the other one. +func serviceFamilies(family string) (corev1.IPFamilyPolicy, []corev1.IPFamily) { + switch family { + case string(cozyv1alpha1.AddressFamilyIPv6): + return corev1.IPFamilyPolicySingleStack, []corev1.IPFamily{corev1.IPv6Protocol} + case string(cozyv1alpha1.AddressFamilyDual): + return corev1.IPFamilyPolicyRequireDualStack, []corev1.IPFamily{corev1.IPv4Protocol, corev1.IPv6Protocol} + default: + return corev1.IPFamilyPolicySingleStack, []corev1.IPFamily{corev1.IPv4Protocol} + } +} + +// primaryFamilyFixed reports a live Service whose primary family differs from +// the desired one: the apiserver never changes ipFamilies[0] after creation. +func primaryFamilyFixed(live, desired *corev1.Service) bool { + return len(live.Spec.IPFamilies) > 0 && len(desired.Spec.IPFamilies) > 0 && + live.Spec.IPFamilies[0] != desired.Spec.IPFamilies[0] +} + +// mirroredPorts derives the rendered Service's ports from the endpoint's and +// the member's port list. A nil result with a nil error means nothing +// meaningful is publishable. +func mirroredPorts(endpoint *corev1.Service, lb *cozyv1alpha1.LoadBalancerAttachment) []corev1.ServicePort { + sentinelOnly := isSentinelOnly(endpoint) + if len(lb.Ports) == 0 { + if sentinelOnly { + if lb.Method == cozyv1alpha1.ExposureMethodWholeIP { + // The target is spelled out because the apiserver defaults it to + // the port, and a desired value left at zero would differ from + // the stored one on every reconcile. + return []corev1.ServicePort{{Port: SentinelPort, TargetPort: intstr.FromInt32(SentinelPort)}} + } + return nil + } + return copyPorts(endpoint.Spec.Ports) + } + wanted := make([]int32, len(lb.Ports)) + copy(wanted, lb.Ports) + sort.Slice(wanted, func(i, j int) bool { return wanted[i] < wanted[j] }) + if sentinelOnly { + out := make([]corev1.ServicePort, 0, len(wanted)) + for _, p := range wanted { + out = append(out, corev1.ServicePort{ + Name: fmt.Sprintf("port-%d", p), + Protocol: corev1.ProtocolTCP, + Port: p, + TargetPort: intstr.FromInt32(p), + }) + } + return out + } + set := map[int32]bool{} + for _, p := range wanted { + set[p] = true + } + var out []corev1.ServicePort + for _, p := range copyPorts(endpoint.Spec.Ports) { + if set[p.Port] { + out = append(out, p) + } + } + return out +} + +// isSentinelOnly reports an endpoint that publishes nothing: no ports, or the +// placeholder a not-yet-exposed VM Service has, which is headless with the one +// sentinel port. A Service that serves on port 65535 is not a placeholder. +func isSentinelOnly(svc *corev1.Service) bool { + if len(svc.Spec.Ports) == 0 { + return true + } + return svc.Spec.ClusterIP == corev1.ClusterIPNone && len(svc.Spec.Ports) == 1 && svc.Spec.Ports[0].Port == SentinelPort +} + +func copyPorts(in []corev1.ServicePort) []corev1.ServicePort { + out := make([]corev1.ServicePort, 0, len(in)) + for _, p := range in { + out = append(out, corev1.ServicePort{ + Name: p.Name, + Protocol: p.Protocol, + AppProtocol: p.AppProtocol, + Port: p.Port, + TargetPort: p.TargetPort, + }) + } + return out +} + +// desiredService builds the additive LoadBalancer Service for an attachment. +func desiredService(ea *cozyv1alpha1.EndpointAttachment, in renderInput, ports []corev1.ServicePort) *corev1.Service { + lb := ea.Spec.LoadBalancer + svc := &corev1.Service{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: ea.Namespace, + GenerateName: childGenerateName(ea.Name), + Labels: map[string]string{OwnerLabel: ownerLabelValue(ea.Name)}, + Annotations: map[string]string{ClaimAnnotation: in.ClaimName}, + OwnerReferences: []metav1.OwnerReference{ + controllerOwnerReference(ea), + }, + }, + Spec: corev1.ServiceSpec{ + Type: corev1.ServiceTypeLoadBalancer, + ExternalTrafficPolicy: corev1.ServiceExternalTrafficPolicyLocal, + Ports: ports, + Selector: copyMap(in.Endpoint.Spec.Selector), + }, + } + if in.LoadBalancerClass != "" { + svc.Spec.LoadBalancerClass = new(in.LoadBalancerClass) + } + // Set in both modes: the apiserver stores true when the field is left + // unset, which a nil desired value would then differ from on every + // reconcile. + svc.Spec.AllocateLoadBalancerNodePorts = new(in.AllocateNodePorts) + policy, families := serviceFamilies(in.Family) + svc.Spec.IPFamilyPolicy = &policy + svc.Spec.IPFamilies = families + if in.Dark { + svc.Spec.Selector = map[string]string{darkSelectorKey: string(ea.UID)} + } + if lb.Method != "" { + svc.Labels[ServiceProxyNameLabel] = ServiceProxyName + switch lb.Method { + case cozyv1alpha1.ExposureMethodWholeIP: + svc.Annotations[WholeIPAnnotation] = "true" + case cozyv1alpha1.ExposureMethodPortList: + svc.Annotations[WholeIPAnnotation] = "false" + allow := lb.AllowICMP == nil || *lb.AllowICMP + svc.Annotations[AllowICMPAnnotation] = fmt.Sprintf("%t", allow) + } + } + return svc +} + +// applyDesired copies the fields this controller owns onto a live Service, +// leaving everything else (other controllers' annotations, node ports, +// cluster IPs, the immutable loadBalancerClass) untouched. It reports whether +// anything changed. +func applyDesired(live, desired *corev1.Service) bool { + changed := false + if live.Labels == nil { + live.Labels = map[string]string{} + } + if live.Annotations == nil { + live.Annotations = map[string]string{} + } + for _, k := range []string{OwnerLabel, ServiceProxyNameLabel} { + if v, ok := desired.Labels[k]; ok { + if live.Labels[k] != v { + live.Labels[k] = v + changed = true + } + } else if _, ok := live.Labels[k]; ok { + delete(live.Labels, k) + changed = true + } + } + for _, k := range []string{ClaimAnnotation, WholeIPAnnotation, AllowICMPAnnotation} { + if v, ok := desired.Annotations[k]; ok { + if live.Annotations[k] != v { + live.Annotations[k] = v + changed = true + } + } else if _, ok := live.Annotations[k]; ok { + delete(live.Annotations, k) + changed = true + } + } + if live.Spec.Type != desired.Spec.Type { + live.Spec.Type = desired.Spec.Type + changed = true + } + if live.Spec.ExternalTrafficPolicy != desired.Spec.ExternalTrafficPolicy { + live.Spec.ExternalTrafficPolicy = desired.Spec.ExternalTrafficPolicy + changed = true + } + if !equalStringMaps(live.Spec.Selector, desired.Spec.Selector) { + live.Spec.Selector = copyMap(desired.Spec.Selector) + changed = true + } + if !equalPorts(live.Spec.Ports, desired.Spec.Ports) { + live.Spec.Ports = mergeNodePorts(live.Spec.Ports, desired.Spec.Ports) + changed = true + } + if !equalBoolPtr(live.Spec.AllocateLoadBalancerNodePorts, desired.Spec.AllocateLoadBalancerNodePorts) { + live.Spec.AllocateLoadBalancerNodePorts = desired.Spec.AllocateLoadBalancerNodePorts + changed = true + } + if live.Spec.IPFamilyPolicy == nil || *live.Spec.IPFamilyPolicy != *desired.Spec.IPFamilyPolicy { + live.Spec.IPFamilyPolicy = desired.Spec.IPFamilyPolicy + changed = true + } + if !slices.Equal(live.Spec.IPFamilies, desired.Spec.IPFamilies) { + live.Spec.IPFamilies = slices.Clone(desired.Spec.IPFamilies) + changed = true + } + return changed +} + +// mergeNodePorts keeps the node ports the apiserver already allocated for +// ports that survive the update, so a mirror refresh does not reallocate them. +func mergeNodePorts(live, desired []corev1.ServicePort) []corev1.ServicePort { + byPort := map[string]int32{} + for _, p := range live { + byPort[portKey(p)] = p.NodePort + } + out := copyPorts(desired) + for i := range out { + out[i].NodePort = byPort[portKey(out[i])] + } + return out +} + +func portKey(p corev1.ServicePort) string { + proto := p.Protocol + if proto == "" { + proto = corev1.ProtocolTCP + } + return fmt.Sprintf("%s/%d", proto, p.Port) +} + +func equalPorts(a, b []corev1.ServicePort) bool { + if len(a) != len(b) { + return false + } + for i := range a { + pa, pb := a[i], b[i] + if pa.Name != pb.Name || pa.Port != pb.Port || pa.TargetPort != pb.TargetPort || + normProto(pa.Protocol) != normProto(pb.Protocol) || !equalStringPtr(pa.AppProtocol, pb.AppProtocol) { + return false + } + } + return true +} + +func normProto(p corev1.Protocol) corev1.Protocol { + if p == "" { + return corev1.ProtocolTCP + } + return p +} + +// ownedService finds the Service rendered for an attachment. Identity is the +// controller owner reference: a Service carrying the ownership label but +// controlled by anything else is not this attachment's and is never adopted. +// +// Finding none in the cache is rechecked against the API before the caller +// creates one, since a Service the previous reconcile created may not have +// reached the cache yet. Should two exist anyway, the oldest is kept and the +// rest are withdrawn, so detaching cannot leave one published. +func (r *Reconciler) ownedService(ctx context.Context, ea *cozyv1alpha1.EndpointAttachment) (*corev1.Service, error) { + owned, err := r.listOwnedServices(ctx, r.Client, ea) + if err != nil { + return nil, err + } + if len(owned) == 0 && r.Reader != nil { + if owned, err = r.listOwnedServices(ctx, r.Reader, ea); err != nil { + return nil, err + } + } + if len(owned) == 0 { + return nil, nil + } + sort.Slice(owned, func(i, j int) bool { return older(owned[i], owned[j]) }) + for _, extra := range owned[1:] { + if err := r.Delete(ctx, extra); client.IgnoreNotFound(err) != nil { + return nil, fmt.Errorf("withdraw duplicate Service %s: %w", extra.Name, err) + } + r.event(ea, corev1.EventTypeNormal, "Withdrawn", "withdrew duplicate Service %s", extra.Name) + } + return owned[0], nil +} + +func (r *Reconciler) listOwnedServices(ctx context.Context, reader client.Reader, ea *cozyv1alpha1.EndpointAttachment) ([]*corev1.Service, error) { + list := &corev1.ServiceList{} + if err := reader.List(ctx, list, client.InNamespace(ea.Namespace)); err != nil { + return nil, err + } + var owned []*corev1.Service + for i := range list.Items { + if isControlledBy(&list.Items[i], ea) { + owned = append(owned, &list.Items[i]) + } + } + return owned, nil +} + +// backendPods returns the pods an endpoint Service currently routes to, +// counting only ready endpoints so that a terminating replica or a not-yet- +// ready surge pod does not count as a second backend. +func (r *Reconciler) backendPods(ctx context.Context, svc *corev1.Service) (map[types.UID]string, error) { + slices := &discoveryv1.EndpointSliceList{} + if err := r.List(ctx, slices, client.InNamespace(svc.Namespace), + client.MatchingLabels{discoveryv1.LabelServiceName: svc.Name}); err != nil { + return nil, err + } + pods := map[types.UID]string{} + for _, s := range slices.Items { + for _, e := range s.Endpoints { + if e.Conditions.Ready != nil && !*e.Conditions.Ready { + continue + } + if e.TargetRef == nil || e.TargetRef.Kind != "Pod" { + continue + } + pods[e.TargetRef.UID] = e.TargetRef.Name + } + } + return pods, nil +} + +// delegatedRival finds another Service delegated to the datapath proxy that +// selects any of the same backend pods. The physical unit of exclusivity is +// the backend pod, and it covers both render modes: cozy-proxy's egress map +// is keyed by pod and holds one service IP, and a second delegated Service on +// the same pod evicts the first from both directions. +// +// A delegation no EndpointAttachment renders, such as a vm-instance Service +// with external: true, always wins: nothing would ever withdraw it, so an +// attachment that kept its own Service would share the slot for good. Between +// attachments the oldest delegation wins, ties broken by name, so that two +// reconcilers never fight over the slot. A rival is reported only when it +// would win against this attachment's own Service (or when that Service does +// not exist yet). +func (r *Reconciler) delegatedRival(ctx context.Context, ea *cozyv1alpha1.EndpointAttachment, own *corev1.Service, backends map[types.UID]string) (*corev1.Service, error) { + if len(backends) == 0 { + return nil, nil + } + list := &corev1.ServiceList{} + if err := r.List(ctx, list, client.InNamespace(ea.Namespace), + client.MatchingLabels{ServiceProxyNameLabel: ServiceProxyName}); err != nil { + return nil, err + } + var rivals []*corev1.Service + for i := range list.Items { + other := &list.Items[i] + if own != nil && other.UID == own.UID { + continue + } + theirs, err := r.backendPods(ctx, other) + if err != nil { + return nil, err + } + for uid := range theirs { + if _, shared := backends[uid]; shared { + rivals = append(rivals, other) + break + } + } + } + if len(rivals) == 0 { + return nil, nil + } + sort.Slice(rivals, func(i, j int) bool { return older(rivals[i], rivals[j]) }) + for _, rival := range rivals { + if !renderedByAttachment(rival) { + return rival, nil + } + } + if own != nil && older(own, rivals[0]) { + return nil, nil + } + return rivals[0], nil +} + +// renderedByAttachment reports whether an EndpointAttachment controls the +// Service, and so would withdraw it on losing the slot. +func renderedByAttachment(svc *corev1.Service) bool { + ref := metav1.GetControllerOf(svc) + return ref != nil && ref.Kind == attachmentGVK.Kind && strings.HasPrefix(ref.APIVersion, attachmentGVK.Group+"/") +} + +func older(a, b *corev1.Service) bool { + if !a.CreationTimestamp.Equal(&b.CreationTimestamp) { + return a.CreationTimestamp.Before(&b.CreationTimestamp) + } + return a.Name < b.Name +} diff --git a/internal/controller/endpointattachment/status.go b/internal/controller/endpointattachment/status.go new file mode 100644 index 000000000..b32202fb9 --- /dev/null +++ b/internal/controller/endpointattachment/status.go @@ -0,0 +1,89 @@ +/* +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 endpointattachment + +import ( + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/localsdn/v1alpha1" +) + +// provisionedMessageSuffix is appended to every Provisioned=True message so +// that a green attachment is not read as a reachability guarantee: the CNI's +// own policy objects (VPC gateways, SecurityGroups, NetworkPolicies) still +// gate the path, and this controller cannot see them. +const provisionedMessageSuffix = "; the address is bound and the Service carries it, end-to-end reachability additionally depends on the CNI's own policy objects" + +func setCondition(ea *cozyv1alpha1.EndpointAttachment, condType string, status metav1.ConditionStatus, reason, message string) { + meta.SetStatusCondition(&ea.Status.Conditions, metav1.Condition{ + Type: condType, + Status: status, + Reason: reason, + Message: message, + ObservedGeneration: ea.Generation, + }) +} + +func setResolved(ea *cozyv1alpha1.EndpointAttachment, reason, message string) { + setCondition(ea, cozyv1alpha1.ConditionResolved, metav1.ConditionTrue, reason, message) +} + +func setUnresolved(ea *cozyv1alpha1.EndpointAttachment, reason, message string) { + setCondition(ea, cozyv1alpha1.ConditionResolved, metav1.ConditionFalse, reason, message) +} + +func setProvisioned(ea *cozyv1alpha1.EndpointAttachment, message string) { + setCondition(ea, cozyv1alpha1.ConditionProvisioned, metav1.ConditionTrue, cozyv1alpha1.ReasonProvisioned, message+provisionedMessageSuffix) +} + +func setUnprovisioned(ea *cozyv1alpha1.EndpointAttachment, reason, message string) { + setCondition(ea, cozyv1alpha1.ConditionProvisioned, metav1.ConditionFalse, reason, message) +} + +// projectPhase derives status.phase from the conditions. It is never stored +// independently: Detached is "the endpoint went away after an address was +// held", which the Provisioned reason records. +func projectPhase(ea *cozyv1alpha1.EndpointAttachment) { + resolved := currentAndTrue(ea, cozyv1alpha1.ConditionResolved) + provisioned := currentAndTrue(ea, cozyv1alpha1.ConditionProvisioned) + switch { + case resolved && provisioned: + ea.Status.Phase = cozyv1alpha1.EndpointAttachmentAttached + case !resolved && currentReason(ea, cozyv1alpha1.ConditionProvisioned) == cozyv1alpha1.ReasonEndpointDetached: + ea.Status.Phase = cozyv1alpha1.EndpointAttachmentDetached + default: + ea.Status.Phase = cozyv1alpha1.EndpointAttachmentPending + } +} + +// currentAndTrue requires the condition to describe this generation: a +// Provisioned=True left over from a spec the controller has not yet rendered +// must not make the attachment read as Attached. +func currentAndTrue(ea *cozyv1alpha1.EndpointAttachment, condType string) bool { + c := meta.FindStatusCondition(ea.Status.Conditions, condType) + return c != nil && c.Status == metav1.ConditionTrue && c.ObservedGeneration == ea.Generation +} + +// currentReason is the condition's reason when it describes this generation, +// and empty otherwise. +func currentReason(ea *cozyv1alpha1.EndpointAttachment, condType string) string { + if c := meta.FindStatusCondition(ea.Status.Conditions, condType); c != nil && c.ObservedGeneration == ea.Generation { + return c.Reason + } + return "" +} diff --git a/internal/controller/endpointattachment/substrate.go b/internal/controller/endpointattachment/substrate.go new file mode 100644 index 000000000..2c81504f5 --- /dev/null +++ b/internal/controller/endpointattachment/substrate.go @@ -0,0 +1,232 @@ +/* +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 endpointattachment + +import ( + "context" + "fmt" + "strings" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/localsdn/v1alpha1" +) + +// The address substrate (community #35) is consumed through one annotation +// and two Service fields, and read as unstructured so that this controller +// carries no module or CRD dependency on it. Everything below the annotation +// belongs to the substrate's per-class drivers. +const ( + // ClaimAnnotation names, on a LoadBalancer Service, the IPAddressClaim in + // the Service's own namespace whose address the Service consumes. + ClaimAnnotation = "local.sdn.cozystack.io/ip-address-claim" + + claimPhaseBound = "Bound" +) + +var ( + substrateGroupVersion = schema.GroupVersion{Group: "local.sdn.cozystack.io", Version: "v1alpha1"} + claimGVK = substrateGroupVersion.WithKind("IPAddressClaim") + claimListGVK = substrateGroupVersion.WithKind("IPAddressClaimList") + classGVK = substrateGroupVersion.WithKind("IPAddressClass") + addressGVK = substrateGroupVersion.WithKind("IPAddress") +) + +// claimView is the slice of an IPAddressClaim this controller reads. +type claimView struct { + Name string + Family string + ClassName string // spec.className, or status.className once the default class is resolved + Bound bool + Addresses []boundAddress + WaitingReason string // why the claim is not bound, as the substrate reports it +} + +type boundAddress struct { + Name string // the cluster-scoped IPAddress object + Address string +} + +func newClaim() *unstructured.Unstructured { + u := &unstructured.Unstructured{} + u.SetGroupVersionKind(claimGVK) + return u +} + +func parseClaim(u *unstructured.Unstructured) claimView { + v := claimView{Name: u.GetName()} + v.Family, _, _ = unstructured.NestedString(u.Object, "spec", "family") + v.ClassName, _, _ = unstructured.NestedString(u.Object, "spec", "className") + if v.ClassName == "" { + v.ClassName, _, _ = unstructured.NestedString(u.Object, "status", "className") + } + phase, _, _ := unstructured.NestedString(u.Object, "status", "phase") + v.Bound = phase == claimPhaseBound + addrs, _, _ := unstructured.NestedSlice(u.Object, "status", "addresses") + for _, a := range addrs { + m, ok := a.(map[string]interface{}) + if !ok { + continue + } + name, _ := m["name"].(string) + address, _ := m["address"].(string) + if address != "" { + v.Addresses = append(v.Addresses, boundAddress{Name: name, Address: address}) + } + } + if !v.Bound { + v.WaitingReason = phase + conds, _, _ := unstructured.NestedSlice(u.Object, "status", "conditions") + for _, c := range conds { + m, ok := c.(map[string]interface{}) + if !ok { + continue + } + if status, _ := m["status"].(string); status == string(metav1.ConditionTrue) { + continue + } + if reason, _ := m["reason"].(string); reason != "" { + v.WaitingReason = reason + } + if msg, _ := m["message"].(string); msg != "" { + v.WaitingReason += ": " + msg + } + break + } + } + return v +} + +// mintedClaim finds the claim this attachment owns, by controller owner +// reference. The claim is minted with generateName, so nothing but the owner +// reference identifies it. +func (r *Reconciler) mintedClaim(ctx context.Context, ea *cozyv1alpha1.EndpointAttachment) (*unstructured.Unstructured, error) { + list := &unstructured.UnstructuredList{} + list.SetGroupVersionKind(claimListGVK) + if err := r.List(ctx, list, client.InNamespace(ea.Namespace)); err != nil { + return nil, err + } + for i := range list.Items { + if isControlledBy(&list.Items[i], ea) { + return &list.Items[i], nil + } + } + return nil, nil +} + +func (r *Reconciler) mintClaim(ctx context.Context, ea *cozyv1alpha1.EndpointAttachment) (*unstructured.Unstructured, error) { + lb := ea.Spec.LoadBalancer + u := newClaim() + u.SetNamespace(ea.Namespace) + u.SetGenerateName(childGenerateName(ea.Name)) + u.SetLabels(map[string]string{OwnerLabel: ownerLabelValue(ea.Name)}) + spec := map[string]interface{}{} + if lb.ClassName != "" { + spec["className"] = lb.ClassName + } + if lb.Family != "" { + spec["family"] = string(lb.Family) + } + u.Object["spec"] = spec + u.SetOwnerReferences([]metav1.OwnerReference{controllerOwnerReference(ea)}) + if err := r.Create(ctx, u); err != nil { + return nil, fmt.Errorf("mint IPAddressClaim: %w", err) + } + return u, nil +} + +// classConditionAccepted is the condition an IPAddressClass's provisioner +// sets on it once it serves the class. +const classConditionAccepted = "Accepted" + +// classAcceptance is what an IPAddressClass's provisioner reports about it. +type classAcceptance struct { + // LoadBalancerClass is what a Service consuming a claim of the class + // carries; empty means the cluster default. Meaningful only when Accepted. + LoadBalancerClass string + Accepted bool + // Why says why the class is not accepted yet. + Why string +} + +// classLoadBalancerClass reads the loadBalancerClass an IPAddressClass's +// provisioner reports in status. It counts only while the Accepted condition +// is True for the class's current generation: before that, an empty value +// means not reported yet, not the cluster default. +func (r *Reconciler) classLoadBalancerClass(ctx context.Context, className string) (classAcceptance, error) { + u := &unstructured.Unstructured{} + u.SetGroupVersionKind(classGVK) + if err := r.Get(ctx, types.NamespacedName{Name: className}, u); err != nil { + return classAcceptance{}, err + } + conds, _, _ := unstructured.NestedSlice(u.Object, "status", "conditions") + for _, c := range conds { + m, ok := c.(map[string]interface{}) + if !ok || m["type"] != classConditionAccepted { + continue + } + observed, _, _ := unstructured.NestedInt64(m, "observedGeneration") + status, _ := m["status"].(string) + switch { + case observed != u.GetGeneration(): + return classAcceptance{Why: fmt.Sprintf("its provisioner has not yet observed generation %d", u.GetGeneration())}, nil + case status != string(metav1.ConditionTrue): + reason, _ := m["reason"].(string) + msg, _ := m["message"].(string) + return classAcceptance{Why: strings.TrimSpace(fmt.Sprintf("Accepted=%s %s: %s", status, reason, msg))}, nil + } + lbClass, _, _ := unstructured.NestedString(u.Object, "status", "loadBalancerClass") + return classAcceptance{LoadBalancerClass: lbClass, Accepted: true}, nil + } + return classAcceptance{Why: "its provisioner has not reported on it yet"}, nil +} + +// addressHolder returns the Service an IPAddress is currently announced on, +// or nil when the address is reserved but inert. The substrate records this +// as status.associatedTo on the cluster-scoped IPAddress. +func (r *Reconciler) addressHolder(ctx context.Context, addressName string) (*types.NamespacedName, error) { + u := &unstructured.Unstructured{} + u.SetGroupVersionKind(addressGVK) + if err := r.Get(ctx, types.NamespacedName{Name: addressName}, u); err != nil { + return nil, client.IgnoreNotFound(err) + } + assoc, found, _ := unstructured.NestedMap(u.Object, "status", "associatedTo") + if !found { + return nil, nil + } + kind, _ := assoc["kind"].(string) + if kind != "" && kind != "Service" { + return nil, nil + } + ns, _ := assoc["namespace"].(string) + name, _ := assoc["name"].(string) + if name == "" { + return nil, nil + } + return &types.NamespacedName{Namespace: ns, Name: name}, nil +} + +// substrateInstalled reports whether the claim kind is served, so that the +// reconciler can tell "waiting for the substrate" from an API error. +func substrateInstalled(err error) bool { + return !apierrors.IsNotFound(err) && !isNoKindMatch(err) +} diff --git a/internal/controller/endpointattachment/util.go b/internal/controller/endpointattachment/util.go new file mode 100644 index 000000000..2439a2ff7 --- /dev/null +++ b/internal/controller/endpointattachment/util.go @@ -0,0 +1,130 @@ +/* +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 endpointattachment + +import ( + "crypto/sha256" + "encoding/hex" + "strings" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/validation" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/localsdn/v1alpha1" +) + +var attachmentGVK = cozyv1alpha1.GroupVersion.WithKind("EndpointAttachment") + +func controllerOwnerReference(ea *cozyv1alpha1.EndpointAttachment) metav1.OwnerReference { + return *metav1.NewControllerRef(ea, attachmentGVK) +} + +// ownerLabelValue bounds the attachment name to a label value. A custom +// resource name may run to 253 characters and a label value to 63; past that +// the name is truncated and suffixed with a hash of the whole name, so two +// long names that share a prefix still label apart. +func ownerLabelValue(name string) string { + if len(name) <= validation.LabelValueMaxLength { + return name + } + sum := sha256.Sum256([]byte(name)) + suffix := hex.EncodeToString(sum[:4]) + prefix := strings.TrimRight(name[:validation.LabelValueMaxLength-len(suffix)-1], "-.") + return prefix + "-" + suffix +} + +// maxGenerateNamePrefix is the longest base the apiserver keeps before +// appending its five random characters to a generateName. +const maxGenerateNamePrefix = validation.DNS1035LabelMaxLength - 5 + +// childGenerateName derives the generateName prefix of the objects rendered +// for an attachment. A Service name is a DNS-1035 label, so the prefix may +// hold neither the dots nor the leading digit an attachment name allows, and +// the apiserver validates the prefix itself, so it must fit the label length. +func childGenerateName(name string) string { + prefix := strings.ReplaceAll(name, ".", "-") + if prefix[0] >= '0' && prefix[0] <= '9' { + prefix = "ea-" + prefix + } + if len(prefix) > maxGenerateNamePrefix-1 { + prefix = prefix[:maxGenerateNamePrefix-1] + } + return prefix + "-" +} + +// isControlledBy reports whether obj's controller owner reference points at +// this attachment's UID. Labels are never consulted: they are mutable and +// can collide, the UID cannot. +func isControlledBy(obj metav1.Object, ea *cozyv1alpha1.EndpointAttachment) bool { + ref := metav1.GetControllerOf(obj) + return ref != nil && ref.UID == ea.UID +} + +func isNoKindMatch(err error) bool { + return meta.IsNoMatchError(err) +} + +func copyMap(in map[string]string) map[string]string { + if in == nil { + return nil + } + out := make(map[string]string, len(in)) + for k, v := range in { + out[k] = v + } + return out +} + +func equalStringMaps(a, b map[string]string) bool { + if len(a) != len(b) { + return false + } + for k, v := range a { + if bv, ok := b[k]; !ok || bv != v { + return false + } + } + return true +} + +func equalBoolPtr(a, b *bool) bool { + if a == nil || b == nil { + return a == nil && b == nil + } + return *a == *b +} + +func equalStringPtr(a, b *string) bool { + if a == nil || b == nil { + return a == nil && b == nil + } + return *a == *b +} + +// ingressAddresses lists the addresses a LoadBalancer Service has been +// assigned. +func ingressAddresses(svc *corev1.Service) []string { + var out []string + for _, i := range svc.Status.LoadBalancer.Ingress { + if i.IP != "" { + out = append(out, i.IP) + } + } + return out +} diff --git a/packages/core/platform/templates/bundles/system.yaml b/packages/core/platform/templates/bundles/system.yaml index 78d06a3ec..f747210cc 100644 --- a/packages/core/platform/templates/bundles/system.yaml +++ b/packages/core/platform/templates/bundles/system.yaml @@ -252,10 +252,30 @@ platform-level key, so `telemetry.disabled: true` plus the installer flag silences both. Without this, an operator who followed the documented opt-out kept sending cozy_application_count. */ -}} +{{- $controllerValues := dict -}} {{- if .Values.telemetry.disabled -}} -{{- $controllerValues := dict "cozystackController" (dict "disableTelemetry" true) -}} -{{- $_ := set $cozystackEngineComponents "cozystack-controller" (dict "values" $controllerValues) -}} +{{- $_ := set $controllerValues "disableTelemetry" true -}} {{- end -}} +{{- /* EndpointAttachment's method: WholeIP|PortList modes render the Service + contract cozy-proxy implements. A proxy skips a Service delegated to a + name it does not claim while the load balancer still attracts the + address, so the controller renders those modes only where the platform + declares an implementor deployed. This chart is what deploys cozy-proxy, + so the declaration is derived here rather than detected in the + controller: it renders the include cozystack.platform.system.common-packages + emits the cozy-proxy Package with, on the variants that call that helper, + so it cannot drift from the emission. Node ports follow cozy-lib's + convention: only Hetzner RobotLB forwards through them. */ -}} +{{- $disabledPackages := default (list) .Values.bundles.disabledPackages -}} +{{- $enabledPackages := default (list) .Values.bundles.enabledPackages -}} +{{- $commonPackagesVariant := has .Values.bundles.system.variant (list "isp-full" "isp-slim" "isp-full-generic" "isp-slim-generic") -}} +{{- $cozyProxyPackage := include "cozystack.platform.package.full.default" (list "cozystack.cozy-proxy" $) | trim -}} +{{- $cozyProxyDeployed := and $commonPackagesVariant (ne $cozyProxyPackage "") -}} +{{- $robotLBDeployed := and (has "cozystack.hetzner-robotlb" $enabledPackages) (not (has "cozystack.hetzner-robotlb" $disabledPackages)) -}} +{{- $_ := set $controllerValues "endpointAttachments" (dict + "cozyProxyContractImplemented" $cozyProxyDeployed + "allocateLoadBalancerNodePorts" $robotLBDeployed) -}} +{{- $_ := set $cozystackEngineComponents "cozystack-controller" (dict "values" (dict "cozystackController" $controllerValues)) -}} {{- $keycloakTruststores := .Values.authentication.oidc.keycloakTruststores -}} {{- $hasKeycloakTruststores := and (not (kindIs "invalid" $keycloakTruststores)) (or (not (kindIs "slice" $keycloakTruststores)) (not (empty $keycloakTruststores))) -}} {{- $keycloakComponents := dict -}} diff --git a/packages/core/platform/tests/bundles_endpoint_attachment_datapath_test.yaml b/packages/core/platform/tests/bundles_endpoint_attachment_datapath_test.yaml new file mode 100644 index 000000000..29e5176af --- /dev/null +++ b/packages/core/platform/tests/bundles_endpoint_attachment_datapath_test.yaml @@ -0,0 +1,209 @@ +suite: EndpointAttachment datapath capability wiring +templates: + - templates/bundles/system.yaml +release: + name: cozystack + namespace: cozy-system +tests: + # The controller renders method: WholeIP|PortList Services only where the + # platform declares a cozy-proxy-contract implementor deployed. This chart + # is the deployer, so the declaration must track exactly the condition under + # which it emits the cozy-proxy Package: a declaration that is true where no + # proxy runs leaves a routable address that drops everything, and one that + # is false where a proxy runs refuses every VM attachment. + - it: declares the contract on isp-full, where cozy-proxy is deployed + set: + bundles: + system: + enabled: true + variant: isp-full + documentSelector: + path: metadata.name + value: cozystack.cozystack-engine + asserts: + - equal: + path: spec.components.cozystack-controller.values.cozystackController.endpointAttachments.cozyProxyContractImplemented + value: true + - equal: + path: spec.components.cozystack-controller.values.cozystackController.endpointAttachments.allocateLoadBalancerNodePorts + value: false + + - it: declares the contract on isp-full-generic beside the cozystack-api override + set: + bundles: + system: + enabled: true + variant: isp-full-generic + documentSelector: + path: metadata.name + value: cozystack.cozystack-engine + asserts: + - equal: + path: spec.components.cozystack-controller.values.cozystackController.endpointAttachments.cozyProxyContractImplemented + value: true + - equal: + path: spec.components.cozystack-api.values.cozystackAPI.nodeSelector["node-role.kubernetes.io/control-plane"] + value: "true" + + - it: withdraws the declaration when cozy-proxy is disabled + set: + bundles: + system: + enabled: true + variant: isp-full + disabledPackages: + - cozystack.cozy-proxy + documentSelector: + path: metadata.name + value: cozystack.cozystack-engine + asserts: + - equal: + path: spec.components.cozystack-controller.values.cozystackController.endpointAttachments.cozyProxyContractImplemented + value: false + + - it: withdraws the declaration on isp-hosted, which deploys no cozy-proxy + set: + bundles: + system: + enabled: true + variant: isp-hosted + documentSelector: + path: metadata.name + value: cozystack.cozystack-engine + asserts: + - equal: + path: spec.components.cozystack-controller.values.cozystackController.endpointAttachments.cozyProxyContractImplemented + value: false + + - it: allocates node ports when Hetzner RobotLB is enabled + set: + bundles: + system: + enabled: true + variant: isp-full + enabledPackages: + - cozystack.hetzner-robotlb + documentSelector: + path: metadata.name + value: cozystack.cozystack-engine + asserts: + - equal: + path: spec.components.cozystack-controller.values.cozystackController.endpointAttachments.allocateLoadBalancerNodePorts + value: true + + - it: keeps the telemetry opt-out beside the declaration + set: + bundles: + system: + enabled: true + variant: isp-full + telemetry: + disabled: true + documentSelector: + path: metadata.name + value: cozystack.cozystack-engine + asserts: + - equal: + path: spec.components.cozystack-controller.values.cozystackController.disableTelemetry + value: true + - equal: + path: spec.components.cozystack-controller.values.cozystackController.endpointAttachments.cozyProxyContractImplemented + value: true + + # The slim variants emit cozy-proxy only on explicit opt-in, so the + # declaration follows that opt-in rather than the variant name. + - it: withdraws the declaration on isp-slim without opt-in + set: + bundles: + system: + enabled: true + variant: isp-slim + documentSelector: + path: metadata.name + value: cozystack.cozystack-engine + asserts: + - equal: + path: spec.components.cozystack-controller.values.cozystackController.endpointAttachments.cozyProxyContractImplemented + value: false + + - it: declares the contract on isp-slim when cozy-proxy is opted in + set: + bundles: + system: + enabled: true + variant: isp-slim + enabledPackages: + - cozystack.cozy-proxy + documentSelector: + path: metadata.name + value: cozystack.cozystack-engine + asserts: + - equal: + path: spec.components.cozystack-controller.values.cozystackController.endpointAttachments.cozyProxyContractImplemented + value: true + + - it: emits the cozy-proxy Package on isp-slim when opted in + set: + bundles: + system: + enabled: true + variant: isp-slim + enabledPackages: + - cozystack.cozy-proxy + documentSelector: + path: metadata.name + value: cozystack.cozy-proxy + asserts: + - equal: + path: kind + value: Package + + - it: declares the contract on isp-slim-generic when cozy-proxy is opted in + set: + bundles: + system: + enabled: true + variant: isp-slim-generic + enabledPackages: + - cozystack.cozy-proxy + documentSelector: + path: metadata.name + value: cozystack.cozystack-engine + asserts: + - equal: + path: spec.components.cozystack-controller.values.cozystackController.endpointAttachments.cozyProxyContractImplemented + value: true + + - it: withdraws the declaration on isp-slim when cozy-proxy is opted in and disabled + set: + bundles: + system: + enabled: true + variant: isp-slim + enabledPackages: + - cozystack.cozy-proxy + disabledPackages: + - cozystack.cozy-proxy + documentSelector: + path: metadata.name + value: cozystack.cozystack-engine + asserts: + - equal: + path: spec.components.cozystack-controller.values.cozystackController.endpointAttachments.cozyProxyContractImplemented + value: false + + - it: withdraws the declaration on isp-hosted-slim, which emits no cozy-proxy even when opted in + set: + bundles: + system: + enabled: true + variant: isp-hosted-slim + enabledPackages: + - cozystack.cozy-proxy + documentSelector: + path: metadata.name + value: cozystack.cozystack-engine + asserts: + - equal: + path: spec.components.cozystack-controller.values.cozystackController.endpointAttachments.cozyProxyContractImplemented + value: false diff --git a/packages/core/platform/tests/bundles_telemetry_optout_test.yaml b/packages/core/platform/tests/bundles_telemetry_optout_test.yaml index 484ec77a0..1fa9dfe38 100644 --- a/packages/core/platform/tests/bundles_telemetry_optout_test.yaml +++ b/packages/core/platform/tests/bundles_telemetry_optout_test.yaml @@ -28,7 +28,7 @@ tests: path: spec.components.cozystack-controller.values.cozystackController.disableTelemetry value: true - - it: leaves the controller untouched by default, so telemetry stays opt-out (isp-full) + - it: leaves the telemetry flag unset by default, so telemetry stays opt-out (isp-full) set: bundles: system: @@ -39,7 +39,7 @@ tests: value: cozystack.cozystack-engine asserts: - notExists: - path: spec.components + path: spec.components.cozystack-controller.values.cozystackController.disableTelemetry - it: threads the flag on the oidc variant too (isp-full) set: diff --git a/packages/system/cozystack-basics/templates/clusterroles.yaml b/packages/system/cozystack-basics/templates/clusterroles.yaml index 15d381eb7..1c7ecb688 100644 --- a/packages/system/cozystack-basics/templates/clusterroles.yaml +++ b/packages/system/cozystack-basics/templates/clusterroles.yaml @@ -36,6 +36,9 @@ rules: - apiGroups: ["sdn.cozystack.io"] resources: ["securitygroups"] verbs: ['*'] +- apiGroups: ["local.sdn.cozystack.io"] + resources: ["endpointattachments"] + verbs: ['*'] - apiGroups: - cozystack.io resources: @@ -145,6 +148,11 @@ rules: - workloadmonitors - workloads verbs: ["get", "list", "watch"] +- apiGroups: + - local.sdn.cozystack.io + resources: + - endpointattachments + verbs: ["get", "list", "watch"] - apiGroups: - core.cozystack.io resources: @@ -329,6 +337,14 @@ rules: - credentials/revoke verbs: - create +- apiGroups: ["local.sdn.cozystack.io"] + resources: + - endpointattachments + verbs: + - create + - update + - patch + - delete --- # == super admin cluster role == # Aggregates admin + all roles labeled for super-admin access diff --git a/packages/system/cozystack-controller/definitions/local.sdn.cozystack.io_endpointattachments.yaml b/packages/system/cozystack-controller/definitions/local.sdn.cozystack.io_endpointattachments.yaml new file mode 100644 index 000000000..4c83884f2 --- /dev/null +++ b/packages/system/cozystack-controller/definitions/local.sdn.cozystack.io_endpointattachments.yaml @@ -0,0 +1,272 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.16.4 + name: endpointattachments.local.sdn.cozystack.io +spec: + group: local.sdn.cozystack.io + names: + kind: EndpointAttachment + listKind: EndpointAttachmentList + plural: endpointattachments + singular: endpointattachment + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .spec.applicationRef.name + name: Application + type: string + - jsonPath: .spec.endpoint.serviceName + name: Endpoint + type: string + - jsonPath: .status.phase + name: Phase + type: string + - jsonPath: .status.addresses + name: Addresses + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + EndpointAttachment attaches an external address to one tenant-facing + endpoint of one managed application. + 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: |- + EndpointAttachmentSpec defines the desired state of EndpointAttachment. + + The mechanism is a union with loadBalancer as its only member today. A + future member is added by extending the list in the exactly-one rule. + properties: + applicationRef: + description: ApplicationRef names the application in this namespace. + Immutable. + properties: + group: + default: apps.cozystack.io + description: Group of the application's API. + type: string + kind: + description: Kind of the application, e.g. Postgres. + minLength: 1 + type: string + name: + description: Name of the application instance in this namespace. + minLength: 1 + type: string + required: + - kind + - name + type: object + x-kubernetes-validations: + - message: applicationRef is immutable + rule: self == oldSelf + endpoint: + description: |- + Endpoint selects which tenant-facing Service of the application to + attach the address to. + properties: + serviceName: + description: |- + ServiceName is a tenant-facing Service of the application, in the + attachment's namespace. + minLength: 1 + type: string + required: + - serviceName + type: object + loadBalancer: + description: |- + LoadBalancer attaches a dedicated address through an additive + LoadBalancer Service. + properties: + allowICMP: + description: AllowICMP lets ICMP through in PortList mode. + type: boolean + claimName: + description: |- + ClaimName binds a pre-reserved IPAddressClaim in this namespace instead + of minting one. The claim outlives the attachment. + type: string + className: + description: |- + ClassName mints a fresh IPAddressClaim from this IPAddressClass. Empty + with no claimName mints from the default class. + type: string + family: + description: |- + Family is passed to a minted claim and validated against a referenced + one. + enum: + - IPv4 + - IPv6 + - Dual + type: string + method: + description: |- + Method selects a VM datapath mode. WholeIP renders 1:1 NAT of every + port to a single backend; PortList renders the listed ports. + enum: + - WholeIP + - PortList + type: string + ports: + description: |- + Ports is a subset of the endpoint's ports to publish. It is the only + port source when the endpoint has nothing meaningful to mirror (a VM's + sentinel-port Service). + items: + format: int32 + maximum: 65535 + minimum: 1 + type: integer + maxItems: 256 + type: array + x-kubernetes-list-type: set + type: object + x-kubernetes-validations: + - message: className and claimName are mutually exclusive + rule: '!(has(self.className) && has(self.claimName))' + - message: className is immutable + rule: has(self.className) == has(oldSelf.className) && (!has(self.className) + || self.className == oldSelf.className) + - message: claimName is immutable + rule: has(self.claimName) == has(oldSelf.claimName) && (!has(self.claimName) + || self.claimName == oldSelf.claimName) + - message: family is immutable + rule: has(self.family) == has(oldSelf.family) && (!has(self.family) + || self.family == oldSelf.family) + - message: allowICMP applies to method PortList only + rule: '!has(self.allowICMP) || (has(self.method) && self.method + == ''PortList'')' + - message: method PortList requires ports + rule: '!(has(self.method) && self.method == ''PortList'') || (has(self.ports) + && size(self.ports) > 0)' + required: + - applicationRef + - endpoint + type: object + x-kubernetes-validations: + - message: exactly one mechanism member must be set + rule: '[has(self.loadBalancer)].filter(m, m).size() == 1' + - message: the mechanism member is immutable + rule: has(self.loadBalancer) == has(oldSelf.loadBalancer) + status: + description: EndpointAttachmentStatus defines the observed state of EndpointAttachment. + properties: + addresses: + description: Addresses mirrors the claim's bound addresses. + items: + type: string + type: array + claimName: + description: |- + ClaimName is the IPAddressClaim the rendered Service consumes, minted + or referenced. + type: string + conditions: + description: Conditions follow metav1.Condition semantics. + 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 + observedGeneration: + description: ObservedGeneration is the spec generation the status + reflects. + format: int64 + type: integer + phase: + description: Phase summarises the conditions. + enum: + - Pending + - Attached + - Detached + type: string + serviceName: + description: ServiceName is the rendered LoadBalancer Service. + type: string + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/packages/system/cozystack-controller/templates/deployment.yaml b/packages/system/cozystack-controller/templates/deployment.yaml index 298a84b44..aac25d9fb 100644 --- a/packages/system/cozystack-controller/templates/deployment.yaml +++ b/packages/system/cozystack-controller/templates/deployment.yaml @@ -31,6 +31,12 @@ spec: {{- with .Values.cozystackController.seaweedfsMetricsEndpoint }} - --seaweedfs-metrics-endpoint={{ . }} {{- end }} + {{- if .Values.cozystackController.endpointAttachments.cozyProxyContractImplemented }} + - --cozy-proxy-contract-implemented + {{- end }} + {{- if .Values.cozystackController.endpointAttachments.allocateLoadBalancerNodePorts }} + - --endpoint-attachment-allocate-node-ports + {{- end }} {{- with .Values.cozystackController.resources }} resources: {{- toYaml . | nindent 10 }} diff --git a/packages/system/cozystack-controller/templates/rbac.yaml b/packages/system/cozystack-controller/templates/rbac.yaml index da8f71f49..a9f7b646d 100644 --- a/packages/system/cozystack-controller/templates/rbac.yaml +++ b/packages/system/cozystack-controller/templates/rbac.yaml @@ -19,6 +19,31 @@ rules: - apiGroups: ["gateway.networking.k8s.io"] resources: ["gatewayclasses"] verbs: ["get", "list", "watch"] +# EndpointAttachmentReconciler renders one additive LoadBalancer Service per +# attachment and withdraws it; it identifies its own Services by controller +# owner reference and never writes an application's Services. +- apiGroups: [""] + resources: ["services"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] +# EndpointAttachment is the one local.sdn.cozystack.io kind this controller +# serves. The other kinds in the group belong to the address substrate: the +# reconciler mints an IPAddressClaim per className attachment (owned by the +# attachment, so garbage-collected with it) and reads classes and addresses +# to set loadBalancerClass and detect a claim another Service already wears. +# Those are read as unstructured; the grant is harmless where the substrate +# is not installed. +- apiGroups: ["local.sdn.cozystack.io"] + resources: ["endpointattachments", "endpointattachments/status"] + verbs: ['*'] +- apiGroups: ["local.sdn.cozystack.io"] + resources: ["ipaddressclaims"] + verbs: ["get", "list", "watch", "create", "delete"] +# EndpointAttachmentReconciler binds a whole-IP backend inside a cozyplane VPC +# through a FloatingIP it owns, created, re-pointed and withdrawn with the +# attachment. The kind exists only where cozyplane serves it. +- apiGroups: ["sdn.cozystack.io"] + resources: ["floatingips"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] # TenantGatewayReconciler renders the per-tenant Issuer and the # wildcard / per-listener Certificates the Gateway listeners reference. - apiGroups: ["cert-manager.io"] diff --git a/packages/system/cozystack-controller/tests/rbac_floatingip_test.yaml b/packages/system/cozystack-controller/tests/rbac_floatingip_test.yaml new file mode 100644 index 000000000..a67253378 --- /dev/null +++ b/packages/system/cozystack-controller/tests/rbac_floatingip_test.yaml @@ -0,0 +1,23 @@ +suite: cozystack-controller ClusterRole grants FloatingIP writes +templates: + - templates/rbac.yaml + +release: + name: cozystack-controller + namespace: cozy-system + +# The EndpointAttachment reconciler creates, re-points and withdraws the +# cozyplane FloatingIPs it owns, which the read-only catch-all rule does not +# allow. +tests: + - it: grants the ClusterRole write access to cozyplane FloatingIPs + documentSelector: + path: kind + value: ClusterRole + asserts: + - contains: + path: rules + content: + apiGroups: ["sdn.cozystack.io"] + resources: ["floatingips"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] diff --git a/packages/system/cozystack-controller/values.yaml b/packages/system/cozystack-controller/values.yaml index 4c98be23a..7ce6d5d6b 100644 --- a/packages/system/cozystack-controller/values.yaml +++ b/packages/system/cozystack-controller/values.yaml @@ -15,3 +15,16 @@ cozystackController: # Empty by default: no resources block is rendered, so requests and limits are # opt-in. Idle usage (measured) is ~69Mi — keep a limit above that. resources: {} + # EndpointAttachment rendering. + endpointAttachments: + # Declares that a service proxy answering to the cozy-proxy + # service-proxy-name is deployed, so attachments may render + # method: WholeIP|PortList Services. The platform sets it wherever it + # deploys cozy-proxy. Left false, such attachments render no Service + # and report DatapathContractUnavailable instead of attracting an + # address nothing would serve. + cozyProxyContractImplemented: false + # Allocate node ports on rendered LoadBalancer Services. Off unless the + # load balancer forwards through node ports (Hetzner RobotLB), matching + # the cozy-lib convention the charts follow. + allocateLoadBalancerNodePorts: false