Files
cozystack/internal/controller/endpointattachment/substrate.go
T
Timofei Larkin 9f00135618 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 <lllamnyp@gmail.com>
2026-11-27 08:33:56 +01:00

233 lines
8.2 KiB
Go

/*
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)
}