From 9dbe55a52a8ed33861bb57db4a442a0c094080c1 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Sat, 28 Nov 2026 17:33:56 -0500 Subject: [PATCH 1/5] feat(edge): Publish the /128 of each serving listener attachment Core now writes a BGPAdvertisement in galactic-system for the address of each serving listener backend, so the gateways can resolve the backend's uSID. It has the shape of an edge route's: the router, VRF ID and first export route target of the ingress gVPC's BGPVRFInstance on the backend's node, End.DT46, and the EVPN family. It is named from the attachment's UID and annotated with the listener and attachment. It is labelled with the new galactic.datumapis.com/edge-listener label, not edge-route, so galactic-router advertises it with no forwarding gate, as the listener has none; router GC finds no netns annotation on it and never reclaims it. Tests pin both. Two more labels, a hash of the listener's namespace and name and the gVPC's identifier, let core select a listener's advertisements, and keep an ingress gVPC with a /128 in it from being reclaimed. A backend serves only once its advertisement can be built: until its gVPC's VRF on its node names a router and an export route target it is not serving, and Programmed is not BackendsReady while no backend is. Core withdraws the advertisement, on UID and resourceVersion preconditions, once the backend stops serving (Ready cleared, drain deadline passed, lease released), its attachment goes or its listener is gone. Refs #1509 --- config/galactic-edge/controller-rbac.yaml | 4 +- docs/edge/provider-contract.md | 10 +- internal/crdnames/crdnames.go | 45 ++++ internal/crdnames/crdnames_test.go | 22 ++ internal/edge/listener/backends.go | 19 +- internal/edge/listener/doc.go | 5 +- internal/edge/listener/ingress.go | 14 +- .../edge/listener/listener_envtest_test.go | 2 + internal/edge/listener/publish.go | 192 ++++++++++++++++++ .../edge/listener/publish_envtest_test.go | 173 ++++++++++++++++ internal/edge/listener/reconciler.go | 32 ++- internal/edge/listener/setup.go | 40 +++- internal/gc/gc_test.go | 16 ++ internal/reconcile/edgegate_test.go | 12 +- 14 files changed, 557 insertions(+), 29 deletions(-) create mode 100644 internal/edge/listener/publish.go create mode 100644 internal/edge/listener/publish_envtest_test.go diff --git a/config/galactic-edge/controller-rbac.yaml b/config/galactic-edge/controller-rbac.yaml index 28b3e0252..983972077 100644 --- a/config/galactic-edge/controller-rbac.yaml +++ b/config/galactic-edge/controller-rbac.yaml @@ -130,8 +130,8 @@ subjects: name: galactic-controller namespace: galactic-system --- -# Route publication: one BGPAdvertisement per accepted route, written only -# where the cell's BGP objects live. +# Publication: one BGPAdvertisement per accepted route and per serving +# listener attachment, written only where the cell's BGP objects live. apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: diff --git a/docs/edge/provider-contract.md b/docs/edge/provider-contract.md index 4f2ed65af..d50585d7d 100644 --- a/docs/edge/provider-contract.md +++ b/docs/edge/provider-contract.md @@ -280,9 +280,9 @@ The advertisement names that node's router, the VRF's ID and export route target `galactic-router` advertises an edge route's advertisement only while the forwarding gate it names is open on its node: the named host link is the edge link of the named address and holds an unexpired gate for exactly the prefix. It reads the gate from the pinned map whenever it builds its desired state, and polls it every 250 ms so a deadline passing withdraws the prefix with no API event. Without the pinned map it advertises none, and opens the map again at most every second until it can read it. An advertisement it leaves out is reported `Advertised` False with reason `GateClosed`. Publication never widens what the gate allows: a prefix whose gate closes is withdrawn locally even if core is cut off and still publishes it. -An attachment's own address is not published. Workloads of the gVPC on the attachment's node reach the address, and every prefix whose gate is open on the attachment's link, through local entries `galactic-edge` keeps in the uSID datapath (see [Shared, written by existing components](#shared-written-by-existing-components)). The entry for a prefix stays while its route is accepted on the node and not released, whether or not the gate is open, so a closed gate drops that traffic on the node instead of sending it to the gVPC's egress shards. Workloads on other nodes reach only published prefixes. A provider that must be reachable at its address from other nodes claims an `EdgeRoute` for the address's `/128`, which the conflict check allows for the holder's own address. That route is gated and published like any other, and adds no host route, since the link's own route already carries the address. +An attachment's own address is not published, except a serving listener attachment's (see [Public listener](#public-listener)). Workloads of the gVPC on the attachment's node reach the address, and every prefix whose gate is open on the attachment's link, through local entries `galactic-edge` keeps in the uSID datapath (see [Shared, written by existing components](#shared-written-by-existing-components)). The entry for a prefix stays while its route is accepted on the node and not released, whether or not the gate is open, so a closed gate drops that traffic on the node instead of sending it to the gVPC's egress shards. Workloads on other nodes reach only published prefixes. A provider that must be reachable at its address from other nodes claims an `EdgeRoute` for the address's `/128`, which the conflict check allows for the holder's own address. That route is gated and published like any other, and adds no host route, since the link's own route already carries the address. -Core's write access to `BGPAdvertisement` is a Role in `galactic-system`. Kubernetes RBAC cannot scope it by label, so the Role covers every advertisement there, though core reads and writes only those labeled `galactic.datumapis.com/edge-route`. +Core's write access to `BGPAdvertisement` is a Role in `galactic-system`. Kubernetes RBAC cannot scope it by label, so the Role covers every advertisement there, though core reads and writes only those labeled `galactic.datumapis.com/edge-route` or `galactic.datumapis.com/edge-listener`. ### Reaping @@ -300,7 +300,7 @@ A drain stops new routes and attachments for its scope at once. Forwarding conti ### Public listener -Core (`internal/edge/listener`) keeps one ingress gVPC per approved provider that lists `PublicListener/v1`: the VPC `edge-ingress-` in `galactic-system`, labelled `galactic.datumapis.com/edge-ingress`. Its `/64` comes from `galactic-controller --edge-ingress-prefix`, and its fabric identifier, `status.vpc`, from the provider's `--edge-ingress-identity`. A provider without an identity gets no gVPC, and core records an `IngressIdentityMissing` Event on its `EdgeProvider`. Neither the `/64` nor the identifier moves once recorded: a changed identity is reported as `Ready` False with reason `IdentityMismatch` on the VPC and is not applied. Core deletes the gVPC once its provider may no longer hold a listener, no `EdgeService` references it and no `NetworkService` names its identifier. A provider the prefix has no free `/64` for is retried every minute. A VPC of that name with a controller, such as one NSO adopted for a `NetworkContext` of the same name, is not core's, and core neither trusts nor writes it. +Core (`internal/edge/listener`) keeps one ingress gVPC per approved provider that lists `PublicListener/v1`: the VPC `edge-ingress-` in `galactic-system`, labelled `galactic.datumapis.com/edge-ingress`. Its `/64` comes from `galactic-controller --edge-ingress-prefix`, and its fabric identifier, `status.vpc`, from the provider's `--edge-ingress-identity`. A provider without an identity gets no gVPC, and core records an `IngressIdentityMissing` Event on its `EdgeProvider`. Neither the `/64` nor the identifier moves once recorded: a changed identity is reported as `Ready` False with reason `IdentityMismatch` on the VPC and is not applied. Core deletes the gVPC once its provider may no longer hold a listener, no `EdgeService` references it, no `NetworkService` names its identifier and no listener `/128` is published in it. A provider the prefix has no free `/64` for is retried every minute. A VPC of that name with a controller, such as one NSO adopted for a `NetworkContext` of the same name, is not core's, and core neither trusts nor writes it. Core accepts an `EdgeListener` only while all of these hold, and otherwise sets `Accepted` False with the reason of the first that fails: @@ -313,7 +313,9 @@ Core accepts an `EdgeListener` only while all of these hold, and otherwise sets A listener refused at its current generation holds neither its service nor its addresses against a newer one, but its `NetworkService`s claim their addresses against newer listeners until they are gone. A newer listener's `NetworkService`s never claim against an older one, so an older listener that becomes admissible takes its addresses back, and the newer one refuses itself and withdraws. -The listener's backends, in `status.backends`, are the attachments made against its `EdgeService`. One is serving while the listener is accepted and the attachment is `Allocated`, `Programmed` and `Ready`, with its node, gVPC, address and host link reported; is `Admitted`, or `Draining` before its `status.drainDeadline`; and its instance is its pod's, on its node, holding its lease. A backend on a node that a `NetworkGateway` in `galactic-system` targets is never serving, since a gateway cannot deliver to its own node. `Programmed` is True with `BackendsReady` while any backend serves, and otherwise False with `LocalBackendsExcluded` when an eligible backend is excluded that way, or `NoBackends`. +The listener's backends, in `status.backends`, are the attachments made against its `EdgeService`. One is serving while the listener is accepted and the attachment is `Allocated`, `Programmed` and `Ready`, with its node, gVPC, address and host link reported; is `Admitted`, or `Draining` before its `status.drainDeadline`; its instance is its pod's, on its node, holding its lease; and its `/128` can be published (see below). A backend on a node that a `NetworkGateway` in `galactic-system` targets is never serving, since a gateway cannot deliver to its own node. `Programmed` is True with `BackendsReady` while any backend serves, and otherwise False with `LocalBackendsExcluded` when an eligible backend is excluded that way, or `NoBackends`. + +Core publishes the `/128` of each serving backend's address as a `BGPAdvertisement` in `galactic-system`, named `edge-listener-`, so the gateways can resolve the backend's uSID. It has the shape of a route's: the router, VRF ID and first export route target of the gVPC's `BGPVRFInstance` on the backend's node, `End.DT46`, and the EVPN address family. It is labelled `galactic.datumapis.com/edge-listener` with the listener's UID, `galactic.datumapis.com/edge-listener-key` with a hash of the listener's namespace and name, and `galactic.datumapis.com/edge-listener-vpc` with the gVPC's identifier, instead of `galactic.datumapis.com/edge-route`, so `galactic-router` advertises it without a forwarding gate, and router GC, finding no netns annotation on it, never reclaims it. A backend whose `BGPVRFInstance` does not exist or names no router or export route target is not serving until it does, and `Programmed` is not `BackendsReady` while no backend is published. Core withdraws the advertisement, on a precondition of the version read, as soon as the backend stops serving, its attachment goes or its listener is gone. ### Restart and replacement diff --git a/internal/crdnames/crdnames.go b/internal/crdnames/crdnames.go index 5b12cdeb5..0000305b2 100644 --- a/internal/crdnames/crdnames.go +++ b/internal/crdnames/crdnames.go @@ -127,6 +127,51 @@ func EdgeAdvertisementName(routeUID string) string { return "edge-" + routeUID } +// Labels and annotations of the BGPAdvertisement galactic-controller +// publishes for the /128 of one serving Galactic Edge listener attachment +// (EdgeListenerAdvertisementName). It carries no LabelEdgeRoute, so +// galactic-router advertises it as it does any other advertisement, with no +// forwarding gate, and router GC, finding no netns annotation on it, never +// reclaims it: galactic-controller withdraws it. +const ( + // LabelEdgeListener is the listener's metadata.uid. Its presence marks + // the advertisement as a listener attachment's. + LabelEdgeListener = "galactic.datumapis.com/edge-listener" + // LabelEdgeListenerAttachment is the attachment's metadata.uid. + LabelEdgeListenerAttachment = "galactic.datumapis.com/edge-listener-attachment" + // LabelEdgeListenerKey is EdgeListenerKey of the listener's namespace + // and name, which selects every advertisement of a listener by name, + // whichever object of that name it was published for. + LabelEdgeListenerKey = "galactic.datumapis.com/edge-listener-key" + // LabelEdgeListenerVPC is the base62 identifier of the gVPC the + // advertisement is published in. + LabelEdgeListenerVPC = "galactic.datumapis.com/edge-listener-vpc" + // AnnotationEdgeListener is the listener's namespace and name. + AnnotationEdgeListener = "galactic.datumapis.com/edge-listener" + // AnnotationEdgeListenerAttachment is the attachment's namespace and + // name. + AnnotationEdgeListenerAttachment = "galactic.datumapis.com/edge-listener-attachment" +) + +// edgeListenerKeyLen is how many hex characters of a SHA-256 EdgeListenerKey +// keeps. +const edgeListenerKeyLen = 32 + +// EdgeListenerKey returns the value of LabelEdgeListenerKey for the listener +// namespace/name: a hash, since a listener's name may be longer than a label +// value. A reader checks AnnotationEdgeListener as well. +func EdgeListenerKey(namespace, name string) string { + sum := sha256.Sum256([]byte(namespace + "/" + name)) + return hex.EncodeToString(sum[:])[:edgeListenerKeyLen] +} + +// EdgeListenerAdvertisementName returns the name of the BGPAdvertisement of +// the /128 of the listener attachment with metadata.uid attachmentUID. An +// attachment serves at most one listener, so it has at most one. +func EdgeListenerAdvertisementName(attachmentUID string) string { + return "edge-listener-" + attachmentUID +} + // containerIDLen is how many characters of a container ID appear in an // annotation key. Kubernetes limits the name part of an annotation key to 63 // bytes, and the longest prefix here is 22 bytes, leaving 41 for the suffix. diff --git a/internal/crdnames/crdnames_test.go b/internal/crdnames/crdnames_test.go index 7dc9b6411..dc88622c4 100644 --- a/internal/crdnames/crdnames_test.go +++ b/internal/crdnames/crdnames_test.go @@ -306,6 +306,28 @@ func TestVPCSegmentSharedByBothNames(t *testing.T) { } } +// TestEdgeListenerAdvertisementName: a listener attachment's advertisement +// is a valid object name, never a route's, and is not labelled as a route's, +// which galactic-router would advertise only behind a forwarding gate. +func TestEdgeListenerAdvertisementName(t *testing.T) { + const uid = "0f3c9a1e-6b2d-4e8f-9a7c-1d2e3f4a5b6c" + got := EdgeListenerAdvertisementName(uid) + assertValidObjectName(t, "EdgeListenerAdvertisementName", got) + if got == EdgeAdvertisementName(uid) { + t.Errorf("a listener attachment's advertisement shares the name %q of a route's", got) + } + if LabelEdgeListener == LabelEdgeRoute || LabelEdgeListenerAttachment == LabelEdgeRoute { + t.Error("a listener attachment's advertisement carries the edge route label") + } + key := EdgeListenerKey("galactic-system", strings.Repeat("a", 253)) + if errs := validation.IsValidLabelValue(key); len(errs) > 0 { + t.Errorf("EdgeListenerKey = %q is not a label value: %v", key, errs) + } + if key == EdgeListenerKey("galactic-system", strings.Repeat("a", 252)) { + t.Error("EdgeListenerKey collides for distinct listeners") + } +} + func assertValidObjectName(t *testing.T, who, name string) { t.Helper() if errs := validation.IsDNS1123Subdomain(name); len(errs) > 0 { diff --git a/internal/edge/listener/backends.go b/internal/edge/listener/backends.go index 8bccbea45..837e80423 100644 --- a/internal/edge/listener/backends.go +++ b/internal/edge/listener/backends.go @@ -32,11 +32,20 @@ type backend struct { // local is whether the attachment is on a node that advertises the // listener's addresses. local bool + // adv is the advertisement of its /128, nil while its gVPC's VRF on its + // node names no router or export route target. + adv *bgpv1alpha1.BGPAdvertisement // serving is whether it receives new flows: the listener is accepted, - // and it is eligible and not local. + // it is eligible and not local, and its /128 can be published. serving bool } +// unpublished reports whether b would serve but for its /128, which cannot be +// published yet. +func (b *backend) unpublished(accepted bool) bool { + return accepted && b.eligible && !b.local && !b.serving +} + // status is the backend as the listener's status reports it. func (b *backend) status() galacticv1alpha1.EdgeListenerBackend { return galacticv1alpha1.EdgeListenerBackend{ @@ -103,7 +112,13 @@ func (r *Reconciler) backends(ctx context.Context, l *galacticv1alpha1.EdgeListe next = deadline } b.local = gateways[att.Status.NodeName] - b.serving = b.eligible && !b.local && vpc != "" && att.Status.VPC == vpc + if b.eligible && !b.local && vpc != "" && att.Status.VPC == vpc { + adv, err := r.desiredAdvertisement(ctx, l, att) + if err != nil { + return nil, time.Time{}, err + } + b.adv, b.serving = adv, adv != nil + } out = append(out, b) } return out, next, nil diff --git a/internal/edge/listener/doc.go b/internal/edge/listener/doc.go index 5d31786a5..c461380eb 100644 --- a/internal/edge/listener/doc.go +++ b/internal/edge/listener/doc.go @@ -5,6 +5,7 @@ // Package listener is core's half of the Galactic Edge public listener, run // by galactic-controller --role=cell --edge. It keeps one ingress gVPC per // provider that may hold a listener, in the gateway namespace, with a fabric -// identity and a /64 the operator configures. It admits each EdgeListener -// and reports which of its listener attachments serve. +// identity and a /64 the operator configures. It admits each EdgeListener, +// reports which of its listener attachments serve, and publishes the /128 +// of each serving attachment. package listener diff --git a/internal/edge/listener/ingress.go b/internal/edge/listener/ingress.go index 6760282c5..4730b7f44 100644 --- a/internal/edge/listener/ingress.go +++ b/internal/edge/listener/ingress.go @@ -25,6 +25,7 @@ import ( bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" "go.datum.net/galactic/internal/cloud/identifier" + "go.datum.net/galactic/internal/crdnames" "go.datum.net/galactic/internal/edge/admission" ) @@ -310,8 +311,9 @@ func (r *IngressReconciler) reclaim(ctx context.Context, vpc *cloudv1alpha1.VPC, } // holder returns what still uses vpc, or "" when nothing does: an -// EdgeService in its namespace that grants it, or a NetworkService, in any -// namespace, whose vpcRef is its fabric identifier. +// EdgeService in its namespace that grants it, a NetworkService, in any +// namespace, whose vpcRef is its fabric identifier, or a listener /128 +// advertisement published in it. func (r *IngressReconciler) holder(ctx context.Context, vpc *cloudv1alpha1.VPC) (string, error) { var services galacticv1alpha1.EdgeServiceList if err := r.APIReader.List(ctx, &services, client.InNamespace(vpc.Namespace)); err != nil { @@ -334,6 +336,14 @@ func (r *IngressReconciler) holder(ctx context.Context, vpc *cloudv1alpha1.VPC) return "NetworkService " + netsvcs.Items[i].Namespace + "/" + netsvcs.Items[i].Name, nil } } + var advs bgpv1alpha1.BGPAdvertisementList + if err := r.APIReader.List(ctx, &advs, client.InNamespace(r.Namespace), + client.MatchingLabels{crdnames.LabelEdgeListenerVPC: vpc.Status.VPC}); err != nil { + return "", fmt.Errorf("list listener advertisements: %w", err) + } + if len(advs.Items) > 0 { + return "BGPAdvertisement " + advs.Items[0].Namespace + "/" + advs.Items[0].Name, nil + } return "", nil } diff --git a/internal/edge/listener/listener_envtest_test.go b/internal/edge/listener/listener_envtest_test.go index cb715efd8..8fc02bc96 100644 --- a/internal/edge/listener/listener_envtest_test.go +++ b/internal/edge/listener/listener_envtest_test.go @@ -124,6 +124,8 @@ func TestListenerBackends(t *testing.T) { programmed := galacticv1alpha1.EdgeListenerProgrammed vpc, svc := f.acceptedListener("public") f.expectCondition("public", programmed, metav1.ConditionFalse, galacticv1alpha1.EdgeListenerReasonNoBackends) + // A backend serves only once its address can be published. + f.vrf(vpc, nodeA, "router-a", 5) a := f.newBackend("a", svc, vpc, nodeA, 1) f.expectCondition("public", programmed, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonBackendsReady) diff --git a/internal/edge/listener/publish.go b/internal/edge/listener/publish.go new file mode 100644 index 000000000..16b7eb0ce --- /dev/null +++ b/internal/edge/listener/publish.go @@ -0,0 +1,192 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package listener + +import ( + "context" + "fmt" + "maps" + "net/netip" + + "k8s.io/apimachinery/pkg/api/equality" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/log" + + bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" + galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" + "go.datum.net/galactic/internal/crdnames" +) + +// publish keeps one BGPAdvertisement of the /128 of each of l's serving +// backends, in the gVPC's VRF on the backend's node, so the gateways can +// resolve the backend's uSID, and withdraws every other advertisement of l. +// A backend serves only once its advertisement can be built (see backends). +func (r *Reconciler) publish(ctx context.Context, l *galacticv1alpha1.EdgeListener, backends []backend) error { + keep := map[string]bool{} + for i := range backends { + b := &backends[i] + if !b.serving || b.adv == nil { + continue + } + if err := r.applyAdvertisement(ctx, b.adv); err != nil { + return err + } + keep[b.adv.Name] = true + } + return r.withdrawIf(ctx, client.ObjectKeyFromObject(l), func(adv *bgpv1alpha1.BGPAdvertisement) bool { + return !keep[adv.Name] + }) +} + +// desiredAdvertisement returns the advertisement of att's /128 for l, or nil +// when att's VRF on its node is not ready to publish into. The VRF is read +// from the cache, which its watch keeps. +func (r *Reconciler) desiredAdvertisement(ctx context.Context, l *galacticv1alpha1.EdgeListener, + att *galacticv1alpha1.EdgeAttachment) (*bgpv1alpha1.BGPAdvertisement, error) { + addr, err := netip.ParseAddr(att.Status.Address) + if err != nil || !addr.Is6() || addr.Is4In6() { + return nil, nil + } + key := client.ObjectKey{Namespace: r.Namespace, + Name: crdnames.BGPVRFInstanceName(att.Status.VPC, att.Status.NodeName)} + var vrf bgpv1alpha1.BGPVRFInstance + switch err := r.Client.Get(ctx, key, &vrf); { + case apierrors.IsNotFound(err): + log.FromContext(ctx).V(1).Info("VRF not ready for a listener attachment", "vrf", key.Name, + "attachment", att.Name) + return nil, nil + case err != nil: + return nil, err + case vrf.Spec.RouterRef == nil || vrf.Spec.RouterRef.Name == "" || len(vrf.Spec.ExportRouteTargets) == 0: + log.FromContext(ctx).V(1).Info("VRF names no router or export route target", "vrf", key.Name, + "attachment", att.Name) + return nil, nil + } + vrfID := vrf.Spec.VRFID + function := bgpv1alpha1.SRv6FunctionEndDT46 + return &bgpv1alpha1.BGPAdvertisement{ + ObjectMeta: metav1.ObjectMeta{ + Name: crdnames.EdgeListenerAdvertisementName(string(att.UID)), Namespace: r.Namespace, + Labels: map[string]string{ + crdnames.LabelEdgeListener: string(l.UID), + crdnames.LabelEdgeListenerAttachment: string(att.UID), + crdnames.LabelEdgeListenerKey: crdnames.EdgeListenerKey(l.Namespace, l.Name), + crdnames.LabelEdgeListenerVPC: att.Status.VPC, + }, + Annotations: map[string]string{ + crdnames.AnnotationEdgeListener: l.Namespace + "/" + l.Name, + crdnames.AnnotationEdgeListenerAttachment: att.Namespace + "/" + att.Name, + }, + }, + Spec: bgpv1alpha1.BGPAdvertisementSpec{ + RouterRef: bgpv1alpha1.RouterRef{Name: vrf.Spec.RouterRef.Name}, + AddressFamily: bgpv1alpha1.AddressFamily{AFI: bgpv1alpha1.AFIL2VPN, SAFI: bgpv1alpha1.SAFIEVPN}, + Prefixes: []bgpv1alpha1.Prefix{bgpv1alpha1.Prefix(netip.PrefixFrom(addr, 128).String())}, + Communities: []bgpv1alpha1.Community{bgpv1alpha1.Community(vrf.Spec.ExportRouteTargets[0].Value)}, + VRFID: &vrfID, + Function: &function, + }, + }, nil +} + +// applyAdvertisement creates want or updates the advertisement of its name +// to it. +func (r *Reconciler) applyAdvertisement(ctx context.Context, want *bgpv1alpha1.BGPAdvertisement) error { + var cur bgpv1alpha1.BGPAdvertisement + switch err := r.APIReader.Get(ctx, client.ObjectKeyFromObject(want), &cur); { + case apierrors.IsNotFound(err): + if err := r.Client.Create(ctx, want); err != nil && !apierrors.IsAlreadyExists(err) { + return fmt.Errorf("publish BGPAdvertisement %s: %w", want.Name, err) + } + return nil + case err != nil: + return err + } + if equality.Semantic.DeepEqual(cur.Spec, want.Spec) && subset(want.Labels, cur.Labels) && + subset(want.Annotations, cur.Annotations) { + return nil + } + cur.Spec = want.Spec + if cur.Labels == nil { + cur.Labels = map[string]string{} + } + if cur.Annotations == nil { + cur.Annotations = map[string]string{} + } + maps.Copy(cur.Labels, want.Labels) + maps.Copy(cur.Annotations, want.Annotations) + if err := r.Client.Update(ctx, &cur); err != nil { + return fmt.Errorf("publish BGPAdvertisement %s: %w", want.Name, err) + } + return nil +} + +func subset(want, have map[string]string) bool { + for k, v := range want { + if have[k] != v { + return false + } + } + return true +} + +// withdrawGone withdraws the advertisements of the listener named key, which +// was found gone, except those of a listener recreated under its name since: +// that listener's own pass decides them. +func (r *Reconciler) withdrawGone(ctx context.Context, key client.ObjectKey) error { + var l galacticv1alpha1.EdgeListener + err := r.APIReader.Get(ctx, key, &l) + if err != nil && !apierrors.IsNotFound(err) { + return err + } + return r.withdrawIf(ctx, key, func(adv *bgpv1alpha1.BGPAdvertisement) bool { + return err != nil || adv.Labels[crdnames.LabelEdgeListener] != string(l.UID) + }) +} + +// listenerAdvertisements reads the advertisements of the listener named key, +// selected by LabelEdgeListenerKey and checked against +// AnnotationEdgeListener. +func (r *Reconciler) listenerAdvertisements(ctx context.Context, key client.ObjectKey, +) ([]bgpv1alpha1.BGPAdvertisement, error) { + var list bgpv1alpha1.BGPAdvertisementList + if err := r.APIReader.List(ctx, &list, client.InNamespace(r.Namespace), + client.MatchingLabels{crdnames.LabelEdgeListenerKey: crdnames.EdgeListenerKey(key.Namespace, key.Name)}, + ); err != nil { + return nil, fmt.Errorf("list advertisements of EdgeListener %s: %w", key, err) + } + out := list.Items[:0] + for i := range list.Items { + if list.Items[i].Annotations[crdnames.AnnotationEdgeListener] == key.String() { + out = append(out, list.Items[i]) + } + } + return out, nil +} + +// withdrawIf deletes the advertisements of the listener named key that +// remove selects, each on a precondition of the version read, so an +// advertisement rewritten since is decided again rather than deleted. +func (r *Reconciler) withdrawIf(ctx context.Context, key client.ObjectKey, + remove func(*bgpv1alpha1.BGPAdvertisement) bool) error { + list, err := r.listenerAdvertisements(ctx, key) + if err != nil { + return err + } + for i := range list { + adv := &list[i] + if !remove(adv) { + continue + } + uid, rv := adv.UID, adv.ResourceVersion + err := r.Client.Delete(ctx, adv, client.Preconditions{UID: &uid, ResourceVersion: &rv}) + if err != nil && !apierrors.IsNotFound(err) && !apierrors.IsConflict(err) { + return fmt.Errorf("withdraw BGPAdvertisement %s: %w", adv.Name, err) + } + } + return nil +} diff --git a/internal/edge/listener/publish_envtest_test.go b/internal/edge/listener/publish_envtest_test.go new file mode 100644 index 000000000..167b31068 --- /dev/null +++ b/internal/edge/listener/publish_envtest_test.go @@ -0,0 +1,173 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package listener + +import ( + "context" + "testing" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + + cloudv1alpha1 "go.datum.net/galactic/api/cloud/v1alpha1" + bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" + galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" + "go.datum.net/galactic/internal/crdnames" +) + +// routeTarget is the export route target of every fixture VRF. +const routeTarget = "64496:171" + +// vrf creates vpc's BGPVRFInstance on node, as the node agent does. +func (f *fixture) vrf(vpc *cloudv1alpha1.VPC, node, router string, vrfID int32) { + f.t.Helper() + rt := []bgpv1alpha1.RouteTarget{{Value: routeTarget}} + f.create(&bgpv1alpha1.BGPVRFInstance{ + ObjectMeta: metav1.ObjectMeta{Name: crdnames.BGPVRFInstanceName(vpc.Status.VPC, node), Namespace: gatewayNS}, + Spec: bgpv1alpha1.BGPVRFInstanceSpec{ + RouterTarget: bgpv1alpha1.RouterTarget{RouterRef: &bgpv1alpha1.RouterRef{Name: router}}, + VRFID: vrfID, ImportRouteTargets: rt, ExportRouteTargets: rt, + }, + }) +} + +// advertisement reads b's /128 advertisement, or nil. +func (f *fixture) advertisement(b *listenerBackend) *bgpv1alpha1.BGPAdvertisement { + f.t.Helper() + var adv bgpv1alpha1.BGPAdvertisement + if !f.get(client.ObjectKey{Namespace: gatewayNS, Name: crdnames.EdgeListenerAdvertisementName(string(b.att.UID))}, + &adv) { + return nil + } + return &adv +} + +func (f *fixture) expectPublished(b *listenerBackend, published bool) { + f.t.Helper() + what := "the /128 of " + b.att.Name + " to be withdrawn" + if published { + what = "the /128 of " + b.att.Name + " to be published" + } + eventually(f.t, what, func() bool { return (f.advertisement(b) != nil) == published }) +} + +// TestListenerPublication checks that core publishes the /128 of each +// serving backend into the ingress gVPC's VRF on the backend's node, with no +// edge route label, and withdraws it when the provider clears Ready, when +// the drain deadline passes and when the listener is deleted; that a backend +// whose VRF is missing does not serve, and leaves the listener not +// Programmed, until its VRF exists; and that an advertisement of a listener +// that is gone is withdrawn. +func TestListenerPublication(t *testing.T) { + f := startAPI(t) + ctx := context.Background() + programmed := galacticv1alpha1.EdgeListenerProgrammed + vpc, svc := f.acceptedListener("public") + a := f.newBackend("a", svc, vpc, nodeA, 1) + eventually(t, "the backend to be listed", func() bool { _, ok := f.serving()[a.att.Name]; return ok }) + f.expectCondition("public", programmed, metav1.ConditionFalse, galacticv1alpha1.EdgeListenerReasonNoBackends) + never(t, "served or published a backend whose VRF is missing", func() bool { + return f.serving()[a.att.Name] || f.advertisement(a) != nil + }) + f.vrf(vpc, nodeA, "router-a", 5) + f.expectPublished(a, true) + f.expectCondition("public", programmed, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonBackendsReady) + + l := f.listener("public") + adv := f.advertisement(a) + s := adv.Spec + if s.RouterRef.Name != "router-a" || s.VRFID == nil || *s.VRFID != 5 || s.Function == nil || + *s.Function != bgpv1alpha1.SRv6FunctionEndDT46 || s.AddressFamily.AFI != bgpv1alpha1.AFIL2VPN || + s.AddressFamily.SAFI != bgpv1alpha1.SAFIEVPN || len(s.Prefixes) != 1 || + string(s.Prefixes[0]) != a.att.Status.Address+"/128" || len(s.Communities) != 1 || + string(s.Communities[0]) != routeTarget { + t.Errorf("advertisement spec = %+v", s) + } + if _, gated := adv.Labels[crdnames.LabelEdgeRoute]; gated || + adv.Labels[crdnames.LabelEdgeListener] != string(l.UID) || + adv.Labels[crdnames.LabelEdgeListenerAttachment] != string(a.att.UID) || + adv.Labels[crdnames.LabelEdgeListenerKey] != crdnames.EdgeListenerKey(gatewayNS, "public") || + adv.Labels[crdnames.LabelEdgeListenerVPC] != vpc.Status.VPC || + adv.Annotations[crdnames.AnnotationEdgeListener] != gatewayNS+"/public" || + adv.Annotations[crdnames.AnnotationEdgeListenerAttachment] != providerNS+"/"+a.att.Name { + t.Errorf("advertisement labels %v, annotations %v", adv.Labels, adv.Annotations) + } + + // The provider clears Ready, then sets it again. + f.setReady(a, metav1.ConditionFalse) + f.expectPublished(a, false) + f.setReady(a, metav1.ConditionTrue) + f.expectPublished(a, true) + + // A second backend whose VRF does not exist yet serves only once it + // does. + b := f.newBackend("b", svc, vpc, nodeB, 2) + eventually(t, "the second backend to be listed", func() bool { _, ok := f.serving()[b.att.Name]; return ok }) + never(t, "served or published into a missing VRF", func() bool { + return f.serving()[b.att.Name] || f.advertisement(b) != nil + }) + f.vrf(vpc, nodeB, "router-b", 7) + f.expectPublished(b, true) + eventually(t, "the second backend to serve", func() bool { return f.serving()[b.att.Name] }) + + // A draining backend is withdrawn once its drain deadline passes. + deadline := time.Now().Add(6 * time.Second).Truncate(time.Second) + f.startDrain(a, deadline) + never(t, "withdrew before the drain deadline", func() bool { return f.advertisement(a) == nil }) + f.expectPublished(a, false) + if time.Now().Before(deadline) { + t.Errorf("withdrawn before the drain deadline %s", deadline) + } + + // An advertisement of a listener that is gone is withdrawn. + stale := f.advertisement(b).DeepCopy() + stale.ObjectMeta = metav1.ObjectMeta{Name: "edge-listener-stale", Namespace: gatewayNS, + Labels: map[string]string{crdnames.LabelEdgeListener: "uid-gone", + crdnames.LabelEdgeListenerKey: crdnames.EdgeListenerKey(gatewayNS, "gone")}, + Annotations: map[string]string{crdnames.AnnotationEdgeListener: gatewayNS + "/gone"}} + stale.Status = bgpv1alpha1.BGPAdvertisementStatus{} + f.create(stale) + eventually(t, "the gone listener's advertisement to be withdrawn", func() bool { + var adv bgpv1alpha1.BGPAdvertisement + return !f.get(client.ObjectKeyFromObject(stale), &adv) + }) + + // Deleting the listener withdraws every /128. + if err := f.admin.Delete(ctx, f.listener("public")); err != nil { + t.Fatal(err) + } + f.expectPublished(b, false) +} + +// TestIngressVPCHeldByAdvertisement checks that a listener /128 published in +// an ingress gVPC holds it from being reclaimed. +func TestIngressVPCHeldByAdvertisement(t *testing.T) { + f := startAPI(t) + ctx := context.Background() + f.start(f.config()) + vpc := f.readyVPC(providerName) + function := bgpv1alpha1.SRv6FunctionEndDT46 + adv := &bgpv1alpha1.BGPAdvertisement{ + ObjectMeta: metav1.ObjectMeta{Name: "edge-listener-held", Namespace: gatewayNS, + Labels: map[string]string{crdnames.LabelEdgeListener: "uid-held", + crdnames.LabelEdgeListenerVPC: vpc.Status.VPC}}, + Spec: bgpv1alpha1.BGPAdvertisementSpec{ + RouterRef: bgpv1alpha1.RouterRef{Name: "router-a"}, + AddressFamily: bgpv1alpha1.AddressFamily{AFI: bgpv1alpha1.AFIL2VPN, SAFI: bgpv1alpha1.SAFIEVPN}, + Prefixes: []bgpv1alpha1.Prefix{"fd00:e1::101/128"}, + Function: &function, + }, + } + f.create(adv) + f.setApproved(providerName, false) + never(t, "reclaimed a gVPC a listener /128 is published in", func() bool { + return f.ingressVPC(providerName) == nil + }) + if err := f.admin.Delete(ctx, adv); err != nil { + t.Fatal(err) + } + eventually(t, "the unused gVPC to be reclaimed", func() bool { return f.ingressVPC(providerName) == nil }) +} diff --git a/internal/edge/listener/reconciler.go b/internal/edge/listener/reconciler.go index 38ce0b172..b2c833bb5 100644 --- a/internal/edge/listener/reconciler.go +++ b/internal/edge/listener/reconciler.go @@ -25,7 +25,8 @@ import ( // waits for has just passed. const deadlineRetry = time.Second -// Reconciler admits EdgeListeners and reports their backends. +// Reconciler admits EdgeListeners, reports their backends and publishes the +// /128 of each serving backend. // // A listener is Accepted when its provider may hold a listener, its // EdgeService grants the provider SocketAccess and PublicListener on the @@ -34,14 +35,17 @@ const deadlineRetry = time.Second // attachments made against its EdgeService; one serves while the listener // is accepted and the attachment is programmed, ready, holding its // instance's lease and not past its drain deadline, unless its node runs a -// gateway, which cannot deliver to its own node. +// gateway, which cannot deliver to its own node. Each serving backend's +// address is advertised into the gVPC's VRF on its node, and withdrawn once +// it stops serving or its listener is gone. type Reconciler struct { // Client reads listeners, attachments, instances, leases, services and // gateways from the cache, and writes status. Client client.Client - // APIReader reads providers and EdgeServices uncached. + // APIReader reads providers, EdgeServices and advertisements uncached. APIReader client.Reader - // Namespace is the gateway namespace, where NetworkGateways live. + // Namespace is the gateway namespace, where NetworkGateways and the + // cell's BGP objects live. Namespace string // VPCs finds each provider's ingress gVPC. VPCs IngressVPCs @@ -77,8 +81,11 @@ type decision struct { // Reconcile implements reconcile.Reconciler for EdgeListeners. func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { var l galacticv1alpha1.EdgeListener - if err := r.Client.Get(ctx, req.NamespacedName, &l); err != nil { - return ctrl.Result{}, client.IgnoreNotFound(err) + switch err := r.Client.Get(ctx, req.NamespacedName, &l); { + case apierrors.IsNotFound(err): + return ctrl.Result{}, r.withdrawGone(ctx, req.NamespacedName) + case err != nil: + return ctrl.Result{}, err } if !l.DeletionTimestamp.IsZero() { return ctrl.Result{}, nil @@ -88,6 +95,9 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu if err != nil { return ctrl.Result{}, err } + if err := r.publish(ctx, &l, d.backends); err != nil { + return ctrl.Result{}, err + } if err := r.setStatus(ctx, &l, d); err != nil { return ctrl.Result{}, err } @@ -146,13 +156,15 @@ func (r *Reconciler) decide(ctx context.Context, l *galacticv1alpha1.EdgeListene // programmed is l's Programmed condition from its backends. func programmed(l *galacticv1alpha1.EdgeListener, accepted bool, backends []backend) metav1.Condition { - serving, local := 0, 0 + serving, local, unpublished := 0, 0, 0 for i := range backends { switch b := &backends[i]; { case b.serving: serving++ case accepted && b.eligible && b.local: local++ + case b.unpublished(accepted): + unpublished++ } } c := metav1.Condition{Type: galacticv1alpha1.EdgeListenerProgrammed, Status: metav1.ConditionFalse, @@ -164,12 +176,18 @@ func programmed(l *galacticv1alpha1.EdgeListener, accepted bool, backends []back if local > 0 { c.Message += fmt.Sprintf("; %d on gateway nodes are excluded", local) } + if unpublished > 0 { + c.Message += fmt.Sprintf("; %d await a VRF to publish into", unpublished) + } case !accepted: c.Message = "the listener is not accepted" case local > 0: c.Reason = galacticv1alpha1.EdgeListenerReasonLocalBackendsExcluded c.Message = fmt.Sprintf("every eligible listener attachment, %d, is on a gateway node, which cannot "+ "deliver to its own node", local) + case unpublished > 0: + c.Message = fmt.Sprintf("every eligible listener attachment, %d, awaits its gVPC's BGPVRFInstance on its "+ + "node naming a router and an export route target, so its address cannot be published", unpublished) default: c.Message = "no listener attachment is programmed, ready and holding its instance's lease" } diff --git a/internal/edge/listener/setup.go b/internal/edge/listener/setup.go index 14279bd09..4ed85a067 100644 --- a/internal/edge/listener/setup.go +++ b/internal/edge/listener/setup.go @@ -9,6 +9,7 @@ import ( "errors" "fmt" "net/netip" + "strings" "time" coordinationv1 "k8s.io/api/coordination/v1" @@ -26,6 +27,7 @@ import ( cloudv1alpha1 "go.datum.net/galactic/api/cloud/v1alpha1" bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" + "go.datum.net/galactic/internal/crdnames" edgeroute "go.datum.net/galactic/internal/edge/route" ) @@ -95,11 +97,11 @@ func (r *IngressReconciler) setup(mgr ctrl.Manager) error { } return []reconcile.Request{{NamespacedName: client.ObjectKey{Name: p}}} }) - // A NetworkService naming an ingress gVPC's identifier holds it from - // being reclaimed, so its events reach the gVPC's provider. - byNetworkService := handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, o client.Object) []reconcile.Request { - s, ok := o.(*bgpv1alpha1.NetworkService) - if !ok || s.Spec.VPCRef == "" { + // A NetworkService naming an ingress gVPC's identifier, or a listener + // /128 published in it, holds it from being reclaimed, so its events + // reach the gVPC's provider. + byIdentifier := func(ctx context.Context, id string) []reconcile.Request { + if id == "" { return nil } var vpcs cloudv1alpha1.VPCList @@ -110,11 +112,21 @@ func (r *IngressReconciler) setup(mgr ctrl.Manager) error { } var out []reconcile.Request for i := range vpcs.Items { - if p := vpcs.Items[i].Annotations[AnnotationIngressProvider]; p != "" && vpcs.Items[i].Status.VPC == s.Spec.VPCRef { + if p := vpcs.Items[i].Annotations[AnnotationIngressProvider]; p != "" && vpcs.Items[i].Status.VPC == id { out = append(out, reconcile.Request{NamespacedName: client.ObjectKey{Name: p}}) } } return out + } + byNetworkService := handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, o client.Object) []reconcile.Request { + s, ok := o.(*bgpv1alpha1.NetworkService) + if !ok { + return nil + } + return byIdentifier(ctx, s.Spec.VPCRef) + }) + byAdvertisement := handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, o client.Object) []reconcile.Request { + return byIdentifier(ctx, o.GetLabels()[crdnames.LabelEdgeListenerVPC]) }) // An EdgeService in the gateway namespace holds its provider's ingress // gVPC from being reclaimed. @@ -131,6 +143,7 @@ func (r *IngressReconciler) setup(mgr ctrl.Manager) error { Watches(&cloudv1alpha1.VPC{}, toProvider). Watches(&galacticv1alpha1.EdgeService{}, byServiceProvider). Watches(&bgpv1alpha1.NetworkService{}, byNetworkService). + Watches(&bgpv1alpha1.BGPAdvertisement{}, byAdvertisement). Complete(r) } @@ -279,5 +292,20 @@ func (r *Reconciler) setup(mgr ctrl.Manager) error { Watches(&coordinationv1.Lease{}, byInstance, builder.WithPredicates(edgeroute.InstanceLeases, leaseHolding)). // A gateway node cannot deliver to a backend on itself. Watches(&bgpv1alpha1.NetworkGateway{}, all, builder.WithPredicates(predicate.GenerationChangedPredicate{})). + // An advertisement's listener, from its annotation, withdraws it + // once it may no longer publish it. + Watches(&bgpv1alpha1.BGPAdvertisement{}, handler.EnqueueRequestsFromMapFunc( + func(_ context.Context, o client.Object) []reconcile.Request { + if _, ok := o.GetLabels()[crdnames.LabelEdgeListener]; !ok { + return nil + } + ns, n, ok := strings.Cut(o.GetAnnotations()[crdnames.AnnotationEdgeListener], "/") + if !ok { + return nil + } + return []reconcile.Request{{NamespacedName: client.ObjectKey{Namespace: ns, Name: n}}} + })). + // A VPC's VRF on a node is what a backend there is published into. + Watches(&bgpv1alpha1.BGPVRFInstance{}, all, builder.WithPredicates(specOrDeletion)). Complete(r) } diff --git a/internal/gc/gc_test.go b/internal/gc/gc_test.go index 9750d1e28..ade0973d8 100644 --- a/internal/gc/gc_test.go +++ b/internal/gc/gc_test.go @@ -53,6 +53,22 @@ func TestCollectNetNSPaths(t *testing.T) { }, want: map[string]string{}, }, + { + // galactic-controller withdraws a listener attachment's /128; + // with no netns annotation, GC never judges it orphaned. + name: "edge listener advertisement", + adv: &bgpv1alpha1.BGPAdvertisement{ + ObjectMeta: metav1.ObjectMeta{ + Name: crdnames.EdgeListenerAdvertisementName("uid-attachment"), + Labels: map[string]string{crdnames.LabelEdgeListener: "uid-listener"}, + Annotations: map[string]string{ + crdnames.AnnotationEdgeListener: "galactic-system/public", + crdnames.AnnotationEdgeListenerAttachment: "edge/ea-a", + }, + }, + }, + want: map[string]string{}, + }, { name: "single netns annotation", adv: &bgpv1alpha1.BGPAdvertisement{ diff --git a/internal/reconcile/edgegate_test.go b/internal/reconcile/edgegate_test.go index 834370f82..9cca6f179 100644 --- a/internal/reconcile/edgegate_test.go +++ b/internal/reconcile/edgegate_test.go @@ -24,7 +24,8 @@ func (g gateSet) Open(adv *bgpv1alpha1.BGPAdvertisement) bool { return g[adv.Nam // TestBuildDesiredRouter_EdgeGate: a Galactic Edge route's advertisement is // in the desired router only while its gate is open on the node, and never -// without a gate to check; every other advertisement is unaffected. +// without a gate to check; every other advertisement, a listener +// attachment's /128 included, is unaffected. func TestBuildDesiredRouter_EdgeGate(t *testing.T) { const node = "node-a" router := &bgpv1alpha1.BGPRouter{ @@ -48,8 +49,11 @@ func TestBuildDesiredRouter_EdgeGate(t *testing.T) { } return a } + listener := adv("listener", false) + listener.Labels = map[string]string{crdnames.LabelEdgeListener: "uid-listener", + crdnames.LabelEdgeListenerAttachment: "uid-attachment"} c := fake.NewClientBuilder().WithScheme(newTestScheme(t)). - WithObjects(adv("workload", false), adv("open", true), adv("closed", true)). + WithObjects(adv("workload", false), adv("open", true), adv("closed", true), listener). WithIndex(&bgpv1alpha1.BGPAdvertisement{}, routerRefIndexer, func(obj client.Object) []string { return []string{obj.(*bgpv1alpha1.BGPAdvertisement).Spec.RouterRef.Name} }). @@ -61,8 +65,8 @@ func TestBuildDesiredRouter_EdgeGate(t *testing.T) { gate EdgeGate want []string }{ - {"no gate", nil, []string{"workload"}}, - {"gate", gateSet{"open": true}, []string{"open", "workload"}}, + {"no gate", nil, []string{"listener", "workload"}}, + {"gate", gateSet{"open": true}, []string{"listener", "open", "workload"}}, } { t.Run(tc.name, func(t *testing.T) { r := New(c, node, "2001:db8::1") From fde3e45a8e9a68039020a2791299a13efeb45a01 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Sat, 28 Nov 2026 23:09:52 -0500 Subject: [PATCH 2/5] fix(edge): Name why a listener backend's /128 cannot be published Programmed's message blamed the VRF for every eligible backend that was not published, including one whose attachment address is not a plain IPv6 address. desiredAdvertisement now returns the cause: the address, a missing BGPVRFInstance, or one that names no router or export route target. A backend in another gVPC than the listener's says so too. Programmed's message names the first few backends and their causes. Withdrawing a deleting listener's /128s needs no change: the finalizer deletes its NetworkServices, waits until they are gone, and only then withdraws its /128s, and a listener removed without its finalizer keeps them while any of its NetworkServices exists. Refs #1509 --- docs/edge/provider-contract.md | 2 +- internal/edge/listener/admit_test.go | 9 ++++++ internal/edge/listener/backends.go | 13 ++++++-- internal/edge/listener/publish.go | 20 ++++++------ .../edge/listener/publish_envtest_test.go | 31 +++++++++++++++++++ internal/edge/listener/reconciler.go | 18 +++++++++-- 6 files changed, 77 insertions(+), 16 deletions(-) diff --git a/docs/edge/provider-contract.md b/docs/edge/provider-contract.md index afa280afb..93f1e8df1 100644 --- a/docs/edge/provider-contract.md +++ b/docs/edge/provider-contract.md @@ -316,7 +316,7 @@ A listener refused at its current generation holds neither its service nor its a The listener's backends, in `status.backends`, are the attachments made against its `EdgeService`. One is serving while the listener is accepted and the attachment is `Allocated`, `Programmed` and `Ready`, with its node, gVPC, address and host link reported; is `Admitted`, or `Draining` before its `status.drainDeadline`; its instance is its pod's, on its node, holding its lease; and its `/128` can be published (see below). A backend on a node that a `NetworkGateway` in `galactic-system` targets is never serving, since a gateway cannot deliver to its own node. `Programmed` is True with `BackendsReady` while any backend serves, and otherwise False with `LocalBackendsExcluded` when an eligible backend is excluded that way, or `NoBackends`. -Core publishes the `/128` of each serving backend's address as a `BGPAdvertisement` in `galactic-system`, named `edge-listener-`, so the gateways can resolve the backend's uSID. It has the shape of a route's: the router, VRF ID and first export route target of the gVPC's `BGPVRFInstance` on the backend's node, `End.DT46`, and the EVPN address family. It is labelled `galactic.datumapis.com/edge-listener` with the listener's UID, `galactic.datumapis.com/edge-listener-key` with a hash of the listener's namespace and name, and `galactic.datumapis.com/edge-listener-vpc` with the gVPC's identifier, instead of `galactic.datumapis.com/edge-route`, so `galactic-router` advertises it without a forwarding gate, and router GC, finding no netns annotation on it, never reclaims it. A backend whose `BGPVRFInstance` does not exist or names no router or export route target is not serving until it does, and `Programmed` is not `BackendsReady` while no backend is published. Core withdraws the advertisement, on a precondition of the version read, as soon as the backend stops serving, its attachment goes or its listener is gone. +Core publishes the `/128` of each serving backend's address as a `BGPAdvertisement` in `galactic-system`, named `edge-listener-`, so the gateways can resolve the backend's uSID. It has the shape of a route's: the router, VRF ID and first export route target of the gVPC's `BGPVRFInstance` on the backend's node, `End.DT46`, and the EVPN address family. It is labelled `galactic.datumapis.com/edge-listener` with the listener's UID, `galactic.datumapis.com/edge-listener-key` with a hash of the listener's namespace and name, and `galactic.datumapis.com/edge-listener-vpc` with the gVPC's identifier, instead of `galactic.datumapis.com/edge-route`, so `galactic-router` advertises it without a forwarding gate, and router GC, finding no netns annotation on it, never reclaims it. A backend whose `BGPVRFInstance` does not exist or names no router or export route target is not serving until it does, and neither is one whose address is not a plain IPv6 address. `Programmed` is not `BackendsReady` while no backend is published, and its message names why each such backend cannot be. Core withdraws the advertisement, on a precondition of the version read, as soon as the backend stops serving, its attachment goes or its listener is gone. ### Restart and replacement diff --git a/internal/edge/listener/admit_test.go b/internal/edge/listener/admit_test.go index 6c71c2407..21cbdc8b2 100644 --- a/internal/edge/listener/admit_test.go +++ b/internal/edge/listener/admit_test.go @@ -7,6 +7,7 @@ package listener import ( "net/netip" "slices" + "strings" "testing" "time" @@ -261,6 +262,8 @@ func TestProgrammed(t *testing.T) { b := func(eligible, local, serving bool) backend { return backend{att: eligibleAttachment(), eligible: eligible, local: local, serving: serving} } + unpublishable := b(true, false, false) + unpublishable.unpublishable = `its address "192.0.2.50" is not a plain IPv6 address` tests := []struct { name string accepted bool @@ -277,6 +280,12 @@ func TestProgrammed(t *testing.T) { galacticv1alpha1.EdgeListenerReasonNoBackends}, {"NotAccepted", false, []backend{b(true, true, false)}, metav1.ConditionFalse, galacticv1alpha1.EdgeListenerReasonNoBackends}, + {"Unpublishable", true, []backend{unpublishable}, metav1.ConditionFalse, + galacticv1alpha1.EdgeListenerReasonNoBackends}, + } + if c := programmed(&l, true, []backend{unpublishable}); !strings.Contains(c.Message, "plain IPv6") || + strings.Contains(c.Message, "BGPVRFInstance") { + t.Errorf("Programmed message for an unpublishable address = %q, want its cause and no VRF", c.Message) } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/internal/edge/listener/backends.go b/internal/edge/listener/backends.go index 837e80423..58c8f27c1 100644 --- a/internal/edge/listener/backends.go +++ b/internal/edge/listener/backends.go @@ -38,6 +38,9 @@ type backend struct { // serving is whether it receives new flows: the listener is accepted, // it is eligible and not local, and its /128 can be published. serving bool + // unpublishable is why its /128 cannot be published, when it would + // serve but for that. + unpublishable string } // unpublished reports whether b would serve but for its /128, which cannot be @@ -112,12 +115,16 @@ func (r *Reconciler) backends(ctx context.Context, l *galacticv1alpha1.EdgeListe next = deadline } b.local = gateways[att.Status.NodeName] - if b.eligible && !b.local && vpc != "" && att.Status.VPC == vpc { - adv, err := r.desiredAdvertisement(ctx, l, att) + switch { + case !b.eligible || b.local || vpc == "": + case att.Status.VPC != vpc: + b.unpublishable = fmt.Sprintf("it is in gVPC %s, not the listener's %s", att.Status.VPC, vpc) + default: + adv, why, err := r.desiredAdvertisement(ctx, l, att) if err != nil { return nil, time.Time{}, err } - b.adv, b.serving = adv, adv != nil + b.adv, b.serving, b.unpublishable = adv, adv != nil, why } out = append(out, b) } diff --git a/internal/edge/listener/publish.go b/internal/edge/listener/publish.go index 16b7eb0ce..5bf2ae580 100644 --- a/internal/edge/listener/publish.go +++ b/internal/edge/listener/publish.go @@ -43,13 +43,15 @@ func (r *Reconciler) publish(ctx context.Context, l *galacticv1alpha1.EdgeListen } // desiredAdvertisement returns the advertisement of att's /128 for l, or nil -// when att's VRF on its node is not ready to publish into. The VRF is read -// from the cache, which its watch keeps. +// and why it cannot be published: att's address is not a plain IPv6 +// address, or its VRF on its node does not exist or names no router or +// export route target. The VRF is read from the cache, which its watch +// keeps. func (r *Reconciler) desiredAdvertisement(ctx context.Context, l *galacticv1alpha1.EdgeListener, - att *galacticv1alpha1.EdgeAttachment) (*bgpv1alpha1.BGPAdvertisement, error) { + att *galacticv1alpha1.EdgeAttachment) (*bgpv1alpha1.BGPAdvertisement, string, error) { addr, err := netip.ParseAddr(att.Status.Address) - if err != nil || !addr.Is6() || addr.Is4In6() { - return nil, nil + if err != nil || !addr.Is6() || addr.Is4In6() || addr.Zone() != "" { + return nil, fmt.Sprintf("its address %q is not a plain IPv6 address", att.Status.Address), nil } key := client.ObjectKey{Namespace: r.Namespace, Name: crdnames.BGPVRFInstanceName(att.Status.VPC, att.Status.NodeName)} @@ -58,13 +60,13 @@ func (r *Reconciler) desiredAdvertisement(ctx context.Context, l *galacticv1alph case apierrors.IsNotFound(err): log.FromContext(ctx).V(1).Info("VRF not ready for a listener attachment", "vrf", key.Name, "attachment", att.Name) - return nil, nil + return nil, fmt.Sprintf("BGPVRFInstance %s does not exist yet", key.Name), nil case err != nil: - return nil, err + return nil, "", err case vrf.Spec.RouterRef == nil || vrf.Spec.RouterRef.Name == "" || len(vrf.Spec.ExportRouteTargets) == 0: log.FromContext(ctx).V(1).Info("VRF names no router or export route target", "vrf", key.Name, "attachment", att.Name) - return nil, nil + return nil, fmt.Sprintf("BGPVRFInstance %s names no router or export route target", key.Name), nil } vrfID := vrf.Spec.VRFID function := bgpv1alpha1.SRv6FunctionEndDT46 @@ -90,7 +92,7 @@ func (r *Reconciler) desiredAdvertisement(ctx context.Context, l *galacticv1alph VRFID: &vrfID, Function: &function, }, - }, nil + }, "", nil } // applyAdvertisement creates want or updates the advertisement of its name diff --git a/internal/edge/listener/publish_envtest_test.go b/internal/edge/listener/publish_envtest_test.go index 167b31068..d7938fe7a 100644 --- a/internal/edge/listener/publish_envtest_test.go +++ b/internal/edge/listener/publish_envtest_test.go @@ -6,9 +6,11 @@ package listener import ( "context" + "strings" "testing" "time" + "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" @@ -171,3 +173,32 @@ func TestIngressVPCHeldByAdvertisement(t *testing.T) { } eventually(t, "the unused gVPC to be reclaimed", func() bool { return f.ingressVPC(providerName) == nil }) } + +// TestListenerUnpublishable checks that Programmed names why a backend's +// /128 cannot be published: its VRF when the VRF is missing, and its +// address, not the VRF, when the address is not a plain IPv6 address. +func TestListenerUnpublishable(t *testing.T) { + f := startAPI(t) + programmed := galacticv1alpha1.EdgeListenerProgrammed + vpc, svc := f.acceptedListener("public") + a := f.newBackend("a", svc, vpc, nodeA, 1) + message := func() string { + c := meta.FindStatusCondition(f.listener("public").Status.Conditions, programmed) + if c == nil { + return "" + } + return c.Message + } + eventually(t, "Programmed to name the missing VRF", func() bool { + return strings.Contains(message(), "BGPVRFInstance") && strings.Contains(message(), "does not exist") + }) + f.vrf(vpc, nodeA, "router-a", 5) + f.expectPublished(a, true) + f.attachmentStatus(a, func(s *galacticv1alpha1.EdgeAttachmentStatus) { s.Address = "192.0.2.50" }) + f.expectPublished(a, false) + f.expectCondition("public", programmed, metav1.ConditionFalse, galacticv1alpha1.EdgeListenerReasonNoBackends) + eventually(t, "Programmed to name the address", func() bool { + m := message() + return strings.Contains(m, "plain IPv6") && !strings.Contains(m, "BGPVRFInstance") + }) +} diff --git a/internal/edge/listener/reconciler.go b/internal/edge/listener/reconciler.go index b2c833bb5..8e2a8d602 100644 --- a/internal/edge/listener/reconciler.go +++ b/internal/edge/listener/reconciler.go @@ -8,6 +8,7 @@ import ( "context" "fmt" "net/netip" + "strings" "time" "k8s.io/apimachinery/pkg/api/equality" @@ -154,9 +155,13 @@ func (r *Reconciler) decide(ctx context.Context, l *galacticv1alpha1.EdgeListene return d, nil } +// maxCauses is how many unpublishable backends Programmed's message names. +const maxCauses = 3 + // programmed is l's Programmed condition from its backends. func programmed(l *galacticv1alpha1.EdgeListener, accepted bool, backends []backend) metav1.Condition { serving, local, unpublished := 0, 0, 0 + var causes []string for i := range backends { switch b := &backends[i]; { case b.serving: @@ -165,8 +170,15 @@ func programmed(l *galacticv1alpha1.EdgeListener, accepted bool, backends []back local++ case b.unpublished(accepted): unpublished++ + if len(causes) < maxCauses { + causes = append(causes, b.att.Namespace+"/"+b.att.Name+": "+b.unpublishable) + } } } + why := strings.Join(causes, "; ") + if unpublished > len(causes) { + why += fmt.Sprintf("; and %d more", unpublished-len(causes)) + } c := metav1.Condition{Type: galacticv1alpha1.EdgeListenerProgrammed, Status: metav1.ConditionFalse, Reason: galacticv1alpha1.EdgeListenerReasonNoBackends, ObservedGeneration: l.Generation} switch { @@ -177,7 +189,7 @@ func programmed(l *galacticv1alpha1.EdgeListener, accepted bool, backends []back c.Message += fmt.Sprintf("; %d on gateway nodes are excluded", local) } if unpublished > 0 { - c.Message += fmt.Sprintf("; %d await a VRF to publish into", unpublished) + c.Message += fmt.Sprintf("; %d cannot be published (%s)", unpublished, why) } case !accepted: c.Message = "the listener is not accepted" @@ -186,8 +198,8 @@ func programmed(l *galacticv1alpha1.EdgeListener, accepted bool, backends []back c.Message = fmt.Sprintf("every eligible listener attachment, %d, is on a gateway node, which cannot "+ "deliver to its own node", local) case unpublished > 0: - c.Message = fmt.Sprintf("every eligible listener attachment, %d, awaits its gVPC's BGPVRFInstance on its "+ - "node naming a router and an export route target, so its address cannot be published", unpublished) + c.Message = fmt.Sprintf("the address of every eligible listener attachment, %d, cannot be published: %s", + unpublished, why) default: c.Message = "no listener attachment is programmed, ready and holding its instance's lease" } From 5bd7af8926084fe40100f862857150c300a7a80b Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Sun, 29 Nov 2026 08:30:05 -0500 Subject: [PATCH 3/5] test(edge): Pin that a backend in another gVPC never serves A listener attachment whose status.vpc is another gVPC than the listener's ingress gVPC must never serve or be published. The new envtest gives both gVPCs a VRF on the node, so only that check stands between the attachment and publication, moves a published backend into the other gVPC, and asserts it is withdrawn, is not serving, is not published again over a window, and that Programmed names the gVPC. Deleting the check makes the test fail with the /128 still published. Refs #1509 --- .../edge/listener/isolation_envtest_test.go | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 internal/edge/listener/isolation_envtest_test.go diff --git a/internal/edge/listener/isolation_envtest_test.go b/internal/edge/listener/isolation_envtest_test.go new file mode 100644 index 000000000..1d1a5036c --- /dev/null +++ b/internal/edge/listener/isolation_envtest_test.go @@ -0,0 +1,56 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package listener + +import ( + "strings" + "testing" + + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + cloudv1alpha1 "go.datum.net/galactic/api/cloud/v1alpha1" + galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" + "go.datum.net/galactic/internal/cloud/identifier" +) + +// programmedMessage reads the listener "public"'s Programmed message. +func (f *fixture) programmedMessage() string { + f.t.Helper() + c := meta.FindStatusCondition(f.listener("public").Status.Conditions, galacticv1alpha1.EdgeListenerProgrammed) + if c == nil { + return "" + } + return c.Message +} + +// TestListenerOtherGVPC checks that an attachment against the listener's +// EdgeService that is in another gVPC than the listener's ingress gVPC +// never serves and is never published, even where its own gVPC has a VRF +// it could be published into, and that Programmed names the cause. +func TestListenerOtherGVPC(t *testing.T) { + f := startAPI(t) + vpc, svc := f.acceptedListener() + other, err := identifier.VPCBase62(ingressIdentity + 9) + if err != nil { + t.Fatal(err) + } + // Both gVPCs have a VRF on the node, so only the gVPC check stands + // between the attachment and publication. + f.vrf(vpc, nodeA, "router-a", 5) + f.vrf(&cloudv1alpha1.VPC{Status: cloudv1alpha1.VPCStatus{VPC: other}}, nodeA, "router-a", 6) + a := f.newBackend("a", svc, vpc, nodeA, 1) + f.expectPublished(a, true) + f.attachmentStatus(a, func(s *galacticv1alpha1.EdgeAttachmentStatus) { s.VPC = other }) + f.expectPublished(a, false) + f.expectCondition("public", galacticv1alpha1.EdgeListenerProgrammed, metav1.ConditionFalse, + galacticv1alpha1.EdgeListenerReasonNoBackends) + eventually(t, "Programmed to name the other gVPC", func() bool { + return strings.Contains(f.programmedMessage(), "is in gVPC "+other) + }) + never(t, "served or published an attachment in another gVPC", func() bool { + return f.serving()[a.att.Name] || f.advertisement(a) != nil + }) +} From 77b95bb31b9a2777466f1d5cff05598b0c8a6d24 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Sun, 29 Nov 2026 08:30:14 -0500 Subject: [PATCH 4/5] fix(edge): Never adopt another object's listener advertisement name applyAdvertisement updated whatever object sat at a backend's advertisement name, edge-listener-, without checking it was a listener's. Core now updates an object there only if it carries galactic.datumapis.com/edge-listener and the listener's galactic.datumapis.com/edge-listener-key. Otherwise the backend does not serve, Programmed names the object, and core records a BGPAdvertisementNameTaken Event on the listener, as it does for a NetworkService name another object holds. Refs #1509 --- docs/edge/provider-contract.md | 2 +- internal/edge/listener/admit_test.go | 26 ++++++++++ internal/edge/listener/backends.go | 12 +++++ .../edge/listener/isolation_envtest_test.go | 51 +++++++++++++++++++ internal/edge/listener/publish.go | 35 +++++++++++-- internal/edge/listener/reconciler.go | 15 ++++++ internal/edge/listener/setup.go | 1 + 7 files changed, 138 insertions(+), 4 deletions(-) diff --git a/docs/edge/provider-contract.md b/docs/edge/provider-contract.md index 97a193617..e8546bb27 100644 --- a/docs/edge/provider-contract.md +++ b/docs/edge/provider-contract.md @@ -316,7 +316,7 @@ A listener refused at its current generation holds neither its service nor its a The listener's backends, in `status.backends`, are the attachments made against its `EdgeService`. One is serving while the listener is accepted and the attachment is `Allocated`, `Programmed` and `Ready`, with its node, gVPC, address and host link reported; is `Admitted`, or `Draining` before its `status.drainDeadline`; its instance is its pod's, on its node, holding its lease, until the Lease's `spec.renewTime` plus its `spec.leaseDurationSeconds` (the cell's lease duration when unset) less the maximum skew; and its `/128` can be published (see below). A backend on a node that a `NetworkGateway` in `galactic-system` targets is never serving, since a gateway cannot deliver to its own node. `Programmed` is True with `BackendsReady` while any backend serves, and otherwise False with `LocalBackendsExcluded` when an eligible backend is excluded that way, or `NoBackends`. -Core publishes the `/128` of each serving backend's address as a `BGPAdvertisement` in `galactic-system`, named `edge-listener-`, so the gateways can resolve the backend's uSID. It has the shape of a route's: the router, VRF ID and first export route target of the gVPC's `BGPVRFInstance` on the backend's node, `End.DT46`, and the EVPN address family. It is labelled `galactic.datumapis.com/edge-listener` with the listener's UID, `galactic.datumapis.com/edge-listener-key` with a hash of the listener's namespace and name, and `galactic.datumapis.com/edge-listener-vpc` with the gVPC's identifier, instead of `galactic.datumapis.com/edge-route`, so `galactic-router` advertises it without a forwarding gate, and router GC, finding no netns annotation on it, never reclaims it. A backend whose `BGPVRFInstance` does not exist or names no router or export route target is not serving until it does, and neither is one whose address is not a plain IPv6 address. `Programmed` is not `BackendsReady` while no backend is published, and its message names why each such backend cannot be. Core withdraws the advertisement, on a precondition of the version read, as soon as the backend stops serving, its attachment goes or its listener is gone. +Core publishes the `/128` of each serving backend's address as a `BGPAdvertisement` in `galactic-system`, named `edge-listener-`, so the gateways can resolve the backend's uSID. It has the shape of a route's: the router, VRF ID and first export route target of the gVPC's `BGPVRFInstance` on the backend's node, `End.DT46`, and the EVPN address family. It is labelled `galactic.datumapis.com/edge-listener` with the listener's UID, `galactic.datumapis.com/edge-listener-key` with a hash of the listener's namespace and name, and `galactic.datumapis.com/edge-listener-vpc` with the gVPC's identifier, instead of `galactic.datumapis.com/edge-route`, so `galactic-router` advertises it without a forwarding gate, and router GC, finding no netns annotation on it, never reclaims it. A backend whose `BGPVRFInstance` does not exist or names no router or export route target is not serving until it does, and neither is one whose address is not a plain IPv6 address. `Programmed` is not `BackendsReady` while no backend is published, and its message names why each such backend cannot be. A backend in another gVPC than the listener's ingress gVPC never serves. An object at a backend's advertisement name that lacks `galactic.datumapis.com/edge-listener` or the listener's `galactic.datumapis.com/edge-listener-key` is never updated or adopted: the backend does not serve, `Programmed` names it, and core records a `BGPAdvertisementNameTaken` Event. Core withdraws the advertisement, on a precondition of the version read, as soon as the backend stops serving, its attachment goes or its listener is gone. ### Restart and replacement diff --git a/internal/edge/listener/admit_test.go b/internal/edge/listener/admit_test.go index d82066fc1..d4b29bbbf 100644 --- a/internal/edge/listener/admit_test.go +++ b/internal/edge/listener/admit_test.go @@ -17,6 +17,7 @@ import ( bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" + "go.datum.net/galactic/internal/crdnames" "go.datum.net/galactic/internal/edge/admission" ) @@ -313,3 +314,28 @@ func TestProgrammed(t *testing.T) { }) } } + +// TestListenersAdvertisement: only an advertisement carrying the listener +// label and the listener's key is the listener's to update. +func TestListenersAdvertisement(t *testing.T) { + l := listenerAt("public", 1, vip6) + key := crdnames.EdgeListenerKey(gatewayNS, "public") + for _, tt := range []struct { + name string + labels map[string]string + want bool + }{ + {"Unlabelled", nil, false}, + {"KeyOnly", map[string]string{crdnames.LabelEdgeListenerKey: key}, false}, + {"OtherListener", map[string]string{crdnames.LabelEdgeListener: "uid", + crdnames.LabelEdgeListenerKey: crdnames.EdgeListenerKey(gatewayNS, "other")}, false}, + {"Ours", map[string]string{crdnames.LabelEdgeListener: "uid", crdnames.LabelEdgeListenerKey: key}, true}, + } { + t.Run(tt.name, func(t *testing.T) { + adv := &bgpv1alpha1.BGPAdvertisement{ObjectMeta: metav1.ObjectMeta{Labels: tt.labels}} + if got := listenersAdvertisement(adv, &l); got != tt.want { + t.Errorf("listenersAdvertisement = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/internal/edge/listener/backends.go b/internal/edge/listener/backends.go index ab54786e4..45fc3c406 100644 --- a/internal/edge/listener/backends.go +++ b/internal/edge/listener/backends.go @@ -41,6 +41,9 @@ type backend struct { // unpublishable is why its /128 cannot be published, when it would // serve but for that. unpublishable string + // advertisementTaken is whether that is because another object holds + // its advertisement's name. + advertisementTaken bool } // unpublished reports whether b would serve but for its /128, which cannot be @@ -127,6 +130,15 @@ func (r *Reconciler) backends(ctx context.Context, l *galacticv1alpha1.EdgeListe if err != nil { return nil, time.Time{}, err } + if adv != nil { + taken, err := r.advertisementTaken(ctx, l, adv.Name) + if err != nil { + return nil, time.Time{}, err + } + if taken != "" { + adv, why, b.advertisementTaken = nil, taken, true + } + } b.adv, b.serving, b.unpublishable = adv, adv != nil, why } out = append(out, b) diff --git a/internal/edge/listener/isolation_envtest_test.go b/internal/edge/listener/isolation_envtest_test.go index 1d1a5036c..c7f92d7c3 100644 --- a/internal/edge/listener/isolation_envtest_test.go +++ b/internal/edge/listener/isolation_envtest_test.go @@ -5,15 +5,20 @@ package listener import ( + "context" "strings" "testing" + eventsv1 "k8s.io/api/events/v1" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" cloudv1alpha1 "go.datum.net/galactic/api/cloud/v1alpha1" + bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" "go.datum.net/galactic/internal/cloud/identifier" + "go.datum.net/galactic/internal/crdnames" ) // programmedMessage reads the listener "public"'s Programmed message. @@ -54,3 +59,49 @@ func TestListenerOtherGVPC(t *testing.T) { return f.serving()[a.att.Name] || f.advertisement(a) != nil }) } + +// TestListenerAdvertisementNameTaken checks that core neither updates nor +// adopts an object at a backend's advertisement name that is not one of the +// listener's, does not count that backend as serving, names it in +// Programmed and records an Event. +func TestListenerAdvertisementNameTaken(t *testing.T) { + f := startAPI(t) + ctx := context.Background() + vpc, svc := f.acceptedListener() + a := f.newBackend("a", svc, vpc, nodeA, 1) + function := bgpv1alpha1.SRv6FunctionEndDT46 + foreign := &bgpv1alpha1.BGPAdvertisement{ + ObjectMeta: metav1.ObjectMeta{Name: crdnames.EdgeListenerAdvertisementName(string(a.att.UID)), + Namespace: gatewayNS}, + Spec: bgpv1alpha1.BGPAdvertisementSpec{ + RouterRef: bgpv1alpha1.RouterRef{Name: "router-z"}, + AddressFamily: bgpv1alpha1.AddressFamily{AFI: bgpv1alpha1.AFIL2VPN, SAFI: bgpv1alpha1.SAFIEVPN}, + Prefixes: []bgpv1alpha1.Prefix{"fd00:e1::999/128"}, + Function: &function, + }, + } + f.create(foreign) + f.vrf(vpc, nodeA, "router-a", 5) + eventually(t, "Programmed to name the advertisement", func() bool { + return strings.Contains(f.programmedMessage(), "is not this listener's") + }) + never(t, "served the backend or wrote the foreign advertisement", func() bool { + var cur bgpv1alpha1.BGPAdvertisement + f.get(client.ObjectKeyFromObject(foreign), &cur) + return f.serving()[a.att.Name] || cur.ResourceVersion != foreign.ResourceVersion + }) + f.expectCondition("public", galacticv1alpha1.EdgeListenerProgrammed, metav1.ConditionFalse, + galacticv1alpha1.EdgeListenerReasonNoBackends) + eventually(t, "a BGPAdvertisementNameTaken Event", func() bool { + var list eventsv1.EventList + if err := f.admin.List(ctx, &list, client.InNamespace(gatewayNS)); err != nil { + t.Fatal(err) + } + for _, e := range list.Items { + if e.Reason == ReasonAdvertisementNameTaken && e.Regarding.Name == "public" { + return true + } + } + return false + }) +} diff --git a/internal/edge/listener/publish.go b/internal/edge/listener/publish.go index 5bf2ae580..f074e82f4 100644 --- a/internal/edge/listener/publish.go +++ b/internal/edge/listener/publish.go @@ -32,7 +32,7 @@ func (r *Reconciler) publish(ctx context.Context, l *galacticv1alpha1.EdgeListen if !b.serving || b.adv == nil { continue } - if err := r.applyAdvertisement(ctx, b.adv); err != nil { + if err := r.applyAdvertisement(ctx, l, b.adv); err != nil { return err } keep[b.adv.Name] = true @@ -95,9 +95,36 @@ func (r *Reconciler) desiredAdvertisement(ctx context.Context, l *galacticv1alph }, "", nil } +// listenersAdvertisement reports whether adv is a listener attachment's +// advertisement of the listener l's name: it carries LabelEdgeListener and +// l's LabelEdgeListenerKey. Only such an advertisement is l's to update. +func listenersAdvertisement(adv *bgpv1alpha1.BGPAdvertisement, l *galacticv1alpha1.EdgeListener) bool { + _, ok := adv.Labels[crdnames.LabelEdgeListener] + return ok && adv.Labels[crdnames.LabelEdgeListenerKey] == crdnames.EdgeListenerKey(l.Namespace, l.Name) +} + +// advertisementTaken returns why the advertisement name belongs to another +// object, or "" when no object holds it or it is l's +// (listenersAdvertisement). It reads from the cache. +func (r *Reconciler) advertisementTaken(ctx context.Context, l *galacticv1alpha1.EdgeListener, name string, +) (string, error) { + var cur bgpv1alpha1.BGPAdvertisement + switch err := r.Client.Get(ctx, client.ObjectKey{Namespace: r.Namespace, Name: name}, &cur); { + case apierrors.IsNotFound(err): + return "", nil + case err != nil: + return "", err + case listenersAdvertisement(&cur, l): + return "", nil + } + return fmt.Sprintf("BGPAdvertisement %s/%s exists and is not this listener's", r.Namespace, name), nil +} + // applyAdvertisement creates want or updates the advertisement of its name -// to it. -func (r *Reconciler) applyAdvertisement(ctx context.Context, want *bgpv1alpha1.BGPAdvertisement) error { +// to it. One of that name that is not l's (listenersAdvertisement) is left +// alone. +func (r *Reconciler) applyAdvertisement(ctx context.Context, l *galacticv1alpha1.EdgeListener, + want *bgpv1alpha1.BGPAdvertisement) error { var cur bgpv1alpha1.BGPAdvertisement switch err := r.APIReader.Get(ctx, client.ObjectKeyFromObject(want), &cur); { case apierrors.IsNotFound(err): @@ -107,6 +134,8 @@ func (r *Reconciler) applyAdvertisement(ctx context.Context, want *bgpv1alpha1.B return nil case err != nil: return err + case !listenersAdvertisement(&cur, l): + return nil } if equality.Semantic.DeepEqual(cur.Spec, want.Spec) && subset(want.Labels, cur.Labels) && subset(want.Annotations, cur.Annotations) { diff --git a/internal/edge/listener/reconciler.go b/internal/edge/listener/reconciler.go index 0d671d763..abcfef8dc 100644 --- a/internal/edge/listener/reconciler.go +++ b/internal/edge/listener/reconciler.go @@ -11,10 +11,12 @@ import ( "strings" "time" + 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" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/tools/events" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" @@ -65,8 +67,15 @@ type Reconciler struct { LeaseDuration time.Duration // Now is the wall clock. Nil means time.Now. Now func() time.Time + // Events records backends whose advertisement name another object + // holds; nil records none. + Events events.EventRecorder } +// ReasonAdvertisementNameTaken is the reason of the Event core records on a +// listener whose backend's /128 advertisement name another object holds. +const ReasonAdvertisementNameTaken = "BGPAdvertisementNameTaken" + func (r *Reconciler) now() time.Time { if r.Now != nil { return r.Now() @@ -103,6 +112,12 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu if err != nil { return ctrl.Result{}, err } + for i := range d.backends { + if b := &d.backends[i]; b.advertisementTaken && r.Events != nil { + r.Events.Eventf(&l, nil, corev1.EventTypeWarning, ReasonAdvertisementNameTaken, "PublishAddress", + "%s: %s, so its address is not published", b.att.Namespace+"/"+b.att.Name, b.unpublishable) + } + } if err := r.publish(ctx, &l, d.backends); err != nil { return ctrl.Result{}, err } diff --git a/internal/edge/listener/setup.go b/internal/edge/listener/setup.go index f8da5bec5..8466d6370 100644 --- a/internal/edge/listener/setup.go +++ b/internal/edge/listener/setup.go @@ -113,6 +113,7 @@ func Setup(mgr ctrl.Manager, cfg Config) error { Client: mgr.GetClient(), APIReader: mgr.GetAPIReader(), Namespace: cfg.Namespace, VPCs: VPCLookup{Reader: mgr.GetAPIReader(), Namespace: cfg.Namespace}, VIPPrefixes: cfg.VIPPrefixes, MaxSkew: cfg.MaxSkew, Now: cfg.Now, LeaseDuration: cfg.LeaseDuration, + Events: cfg.Events, } if err := listeners.setup(mgr); err != nil { return fmt.Errorf("set up EdgeListener reconciler: %w", err) From 9ee7a0bf8058d762757324f0a637cea21f2b1a8b Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Sun, 29 Nov 2026 11:43:37 -0500 Subject: [PATCH 5/5] fix(edge): Withdraw only listener advertisements core would update Core refused to update an advertisement without the edge-listener label, but still selected it for withdrawal by listener key and annotation, so removing that label made core delete the object as unwanted. Withdrawal now uses the same ownership check as updates: the edge-listener label and the listener's key label. --- docs/edge/provider-contract.md | 2 +- .../edge/listener/isolation_envtest_test.go | 34 +++++++++++++++++++ internal/edge/listener/publish.go | 18 +++++++--- 3 files changed, 49 insertions(+), 5 deletions(-) diff --git a/docs/edge/provider-contract.md b/docs/edge/provider-contract.md index e8546bb27..c861e428d 100644 --- a/docs/edge/provider-contract.md +++ b/docs/edge/provider-contract.md @@ -316,7 +316,7 @@ A listener refused at its current generation holds neither its service nor its a The listener's backends, in `status.backends`, are the attachments made against its `EdgeService`. One is serving while the listener is accepted and the attachment is `Allocated`, `Programmed` and `Ready`, with its node, gVPC, address and host link reported; is `Admitted`, or `Draining` before its `status.drainDeadline`; its instance is its pod's, on its node, holding its lease, until the Lease's `spec.renewTime` plus its `spec.leaseDurationSeconds` (the cell's lease duration when unset) less the maximum skew; and its `/128` can be published (see below). A backend on a node that a `NetworkGateway` in `galactic-system` targets is never serving, since a gateway cannot deliver to its own node. `Programmed` is True with `BackendsReady` while any backend serves, and otherwise False with `LocalBackendsExcluded` when an eligible backend is excluded that way, or `NoBackends`. -Core publishes the `/128` of each serving backend's address as a `BGPAdvertisement` in `galactic-system`, named `edge-listener-`, so the gateways can resolve the backend's uSID. It has the shape of a route's: the router, VRF ID and first export route target of the gVPC's `BGPVRFInstance` on the backend's node, `End.DT46`, and the EVPN address family. It is labelled `galactic.datumapis.com/edge-listener` with the listener's UID, `galactic.datumapis.com/edge-listener-key` with a hash of the listener's namespace and name, and `galactic.datumapis.com/edge-listener-vpc` with the gVPC's identifier, instead of `galactic.datumapis.com/edge-route`, so `galactic-router` advertises it without a forwarding gate, and router GC, finding no netns annotation on it, never reclaims it. A backend whose `BGPVRFInstance` does not exist or names no router or export route target is not serving until it does, and neither is one whose address is not a plain IPv6 address. `Programmed` is not `BackendsReady` while no backend is published, and its message names why each such backend cannot be. A backend in another gVPC than the listener's ingress gVPC never serves. An object at a backend's advertisement name that lacks `galactic.datumapis.com/edge-listener` or the listener's `galactic.datumapis.com/edge-listener-key` is never updated or adopted: the backend does not serve, `Programmed` names it, and core records a `BGPAdvertisementNameTaken` Event. Core withdraws the advertisement, on a precondition of the version read, as soon as the backend stops serving, its attachment goes or its listener is gone. +Core publishes the `/128` of each serving backend's address as a `BGPAdvertisement` in `galactic-system`, named `edge-listener-`, so the gateways can resolve the backend's uSID. It has the shape of a route's: the router, VRF ID and first export route target of the gVPC's `BGPVRFInstance` on the backend's node, `End.DT46`, and the EVPN address family. It is labelled `galactic.datumapis.com/edge-listener` with the listener's UID, `galactic.datumapis.com/edge-listener-key` with a hash of the listener's namespace and name, and `galactic.datumapis.com/edge-listener-vpc` with the gVPC's identifier, instead of `galactic.datumapis.com/edge-route`, so `galactic-router` advertises it without a forwarding gate, and router GC, finding no netns annotation on it, never reclaims it. A backend whose `BGPVRFInstance` does not exist or names no router or export route target is not serving until it does, and neither is one whose address is not a plain IPv6 address. `Programmed` is not `BackendsReady` while no backend is published, and its message names why each such backend cannot be. A backend in another gVPC than the listener's ingress gVPC never serves. An object at a backend's advertisement name that lacks `galactic.datumapis.com/edge-listener` or the listener's `galactic.datumapis.com/edge-listener-key` is never updated, adopted or withdrawn: the backend does not serve, `Programmed` names it, and core records a `BGPAdvertisementNameTaken` Event. Core withdraws the advertisement, on a precondition of the version read, as soon as the backend stops serving, its attachment goes or its listener is gone. ### Restart and replacement diff --git a/internal/edge/listener/isolation_envtest_test.go b/internal/edge/listener/isolation_envtest_test.go index c7f92d7c3..9322874b2 100644 --- a/internal/edge/listener/isolation_envtest_test.go +++ b/internal/edge/listener/isolation_envtest_test.go @@ -60,6 +60,40 @@ func TestListenerOtherGVPC(t *testing.T) { }) } +// TestListenerUnlabelledAdvertisementKept checks that core withdraws only +// an advertisement it would update: one of the listener's whose +// LabelEdgeListener is removed is neither withdrawn when its backend stops +// serving nor when the listener is deleted. +func TestListenerUnlabelledAdvertisementKept(t *testing.T) { + f := startAPI(t) + ctx := context.Background() + vpc, svc := f.acceptedListener() + f.vrf(vpc, nodeA, "router-a", 5) + a := f.newBackend("a", svc, vpc, nodeA, 1) + f.expectPublished(a, true) + adv := f.advertisement(a) + delete(adv.Labels, crdnames.LabelEdgeListener) + if err := f.admin.Update(ctx, adv); err != nil { + t.Fatal(err) + } + unchanged := func() bool { + cur := f.advertisement(a) + return cur != nil && cur.ResourceVersion == adv.ResourceVersion + } + + // The backend stops serving, which withdraws an advertisement core owns. + f.setReady(a, metav1.ConditionFalse) + f.expectCondition("public", galacticv1alpha1.EdgeListenerProgrammed, metav1.ConditionFalse, + galacticv1alpha1.EdgeListenerReasonNoBackends) + never(t, "withdrew or rewrote an advertisement core does not own", func() bool { return !unchanged() }) + + if err := f.admin.Delete(ctx, f.listener("public")); err != nil { + t.Fatal(err) + } + eventually(t, "the listener to be gone", func() bool { return f.listener("public") == nil }) + never(t, "withdrew an advertisement core does not own with its listener", func() bool { return !unchanged() }) +} + // TestListenerAdvertisementNameTaken checks that core neither updates nor // adopts an object at a backend's advertisement name that is not one of the // listener's, does not count that backend as serving, names it in diff --git a/internal/edge/listener/publish.go b/internal/edge/listener/publish.go index f074e82f4..8081926a5 100644 --- a/internal/edge/listener/publish.go +++ b/internal/edge/listener/publish.go @@ -97,10 +97,18 @@ func (r *Reconciler) desiredAdvertisement(ctx context.Context, l *galacticv1alph // listenersAdvertisement reports whether adv is a listener attachment's // advertisement of the listener l's name: it carries LabelEdgeListener and -// l's LabelEdgeListenerKey. Only such an advertisement is l's to update. +// l's LabelEdgeListenerKey. Only such an advertisement is l's to update or +// withdraw. func listenersAdvertisement(adv *bgpv1alpha1.BGPAdvertisement, l *galacticv1alpha1.EdgeListener) bool { + return ownedBy(adv, client.ObjectKeyFromObject(l)) +} + +// ownedBy reports whether adv is a listener attachment's advertisement of +// the listener named key: it carries LabelEdgeListener and key's +// LabelEdgeListenerKey. +func ownedBy(adv *bgpv1alpha1.BGPAdvertisement, key client.ObjectKey) bool { _, ok := adv.Labels[crdnames.LabelEdgeListener] - return ok && adv.Labels[crdnames.LabelEdgeListenerKey] == crdnames.EdgeListenerKey(l.Namespace, l.Name) + return ok && adv.Labels[crdnames.LabelEdgeListenerKey] == crdnames.EdgeListenerKey(key.Namespace, key.Name) } // advertisementTaken returns why the advertisement name belongs to another @@ -181,7 +189,9 @@ func (r *Reconciler) withdrawGone(ctx context.Context, key client.ObjectKey) err // listenerAdvertisements reads the advertisements of the listener named key, // selected by LabelEdgeListenerKey and checked against -// AnnotationEdgeListener. +// AnnotationEdgeListener. Only those core would update (ownedBy) are +// returned, so an advertisement it refuses to update is never withdrawn +// either. func (r *Reconciler) listenerAdvertisements(ctx context.Context, key client.ObjectKey, ) ([]bgpv1alpha1.BGPAdvertisement, error) { var list bgpv1alpha1.BGPAdvertisementList @@ -192,7 +202,7 @@ func (r *Reconciler) listenerAdvertisements(ctx context.Context, key client.Obje } out := list.Items[:0] for i := range list.Items { - if list.Items[i].Annotations[crdnames.AnnotationEdgeListener] == key.String() { + if ownedBy(&list.Items[i], key) && list.Items[i].Annotations[crdnames.AnnotationEdgeListener] == key.String() { out = append(out, list.Items[i]) } }