diff --git a/config/galactic-edge/controller-rbac.yaml b/config/galactic-edge/controller-rbac.yaml index 5de7d8192..3e7326b16 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 49935b997..c861e428d 100644 --- a/docs/edge/provider-contract.md +++ b/docs/edge/provider-contract.md @@ -281,9 +281,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 @@ -301,7 +301,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: @@ -314,7 +314,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, until the Lease's `spec.renewTime` plus its `spec.leaseDurationSeconds` (the cell's lease duration when unset) less the maximum skew. 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, 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, 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/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/admit_test.go b/internal/edge/listener/admit_test.go index 84c822348..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" ) @@ -279,6 +280,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 @@ -295,6 +298,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) { @@ -305,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 a114cf99b..45fc3c406 100644 --- a/internal/edge/listener/backends.go +++ b/internal/edge/listener/backends.go @@ -32,9 +32,24 @@ 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 + // 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 +// 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. @@ -106,7 +121,26 @@ 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 + 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 + } + 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) } 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 86a80dc8b..c6a7ea664 100644 --- a/internal/edge/listener/ingress.go +++ b/internal/edge/listener/ingress.go @@ -27,6 +27,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" ) @@ -402,8 +403,9 @@ func (r *IngressReconciler) reclaimConflict(ctx context.Context, key client.Obje } // 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 { @@ -426,6 +428,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/isolation_envtest_test.go b/internal/edge/listener/isolation_envtest_test.go new file mode 100644 index 000000000..9322874b2 --- /dev/null +++ b/internal/edge/listener/isolation_envtest_test.go @@ -0,0 +1,141 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +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. +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 + }) +} + +// 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 +// 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/listener_envtest_test.go b/internal/edge/listener/listener_envtest_test.go index 93cd27afd..5033d438f 100644 --- a/internal/edge/listener/listener_envtest_test.go +++ b/internal/edge/listener/listener_envtest_test.go @@ -34,7 +34,7 @@ func TestListenerAdmission(t *testing.T) { f.newProvider("unapproved", PublicListener) f.setApproved("unapproved", false) f.start(f.listenerConfig()) - vpc := f.readyVPC(providerName) + vpc := f.readyVPC() accepted, programmed := galacticv1alpha1.EdgeListenerAccepted, galacticv1alpha1.EdgeListenerProgrammed expectRefused := func(name, reason string) { t.Helper() @@ -160,8 +160,10 @@ func TestListenerAdmission(t *testing.T) { func TestListenerBackends(t *testing.T) { f := startAPI(t) programmed := galacticv1alpha1.EdgeListenerProgrammed - vpc, svc := f.acceptedListener("public") + vpc, svc := f.acceptedListener() 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) @@ -223,7 +225,8 @@ func TestListenerLeaseExpiry(t *testing.T) { cfg := f.listenerConfig() cfg.LeaseDuration = 8 * time.Second f.start(cfg) - vpc := f.readyVPC(providerName) + vpc := f.readyVPC() + f.vrf(vpc, nodeA, "router-a", 5) svc := f.newService(ingressSvc, vpc, []string{SocketAccess, PublicListener}, nil) f.newListener("public", ingressSvc, vip6, vip4) a := f.newBackend("a", svc, vpc, nodeA, 1) @@ -259,7 +262,11 @@ func TestListenerLeaseExpiry(t *testing.T) { func TestListenerBackendInstance(t *testing.T) { f := startAPI(t) programmed := galacticv1alpha1.EdgeListenerProgrammed - vpc, svc := f.acceptedListener("public") + vpc, svc := f.acceptedListener() + // Both nodes can publish a backend, so only the instance checks stand + // between these attachments and serving. + f.vrf(vpc, nodeA, "router-a", 5) + f.vrf(vpc, "edge-3", "router-c", 7) a := f.newBackend("a", svc, vpc, nodeA, 1) f.expectCondition("public", programmed, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonBackendsReady) diff --git a/internal/edge/listener/listener_fixture_envtest_test.go b/internal/edge/listener/listener_fixture_envtest_test.go index 6132fbf26..c694eef53 100644 --- a/internal/edge/listener/listener_fixture_envtest_test.go +++ b/internal/edge/listener/listener_fixture_envtest_test.go @@ -49,12 +49,12 @@ func (f *fixture) listenerConfig() Config { return cfg } -// readyVPC waits for provider's ingress gVPC to have its identifier. -func (f *fixture) readyVPC(name string) *cloudv1alpha1.VPC { +// readyVPC waits for providerName's ingress gVPC to have its identifier. +func (f *fixture) readyVPC() *cloudv1alpha1.VPC { f.t.Helper() var vpc *cloudv1alpha1.VPC - eventually(f.t, "ingress gVPC "+IngressVPCName(name), func() bool { - vpc = f.ingressVPC(name) + eventually(f.t, "ingress gVPC "+IngressVPCName(providerName), func() bool { + vpc = f.ingressVPC(providerName) return vpc != nil && vpc.Status.VPC != "" }) return vpc @@ -327,16 +327,16 @@ func (f *fixture) gateway(node string) { }) } -// acceptedListener starts the controllers and creates an accepted listener -// named name against an ingress service, returning the ingress gVPC and the +// acceptedListener starts the controllers and creates the accepted listener +// "public" against an ingress service, returning the ingress gVPC and the // service. -func (f *fixture) acceptedListener(name string) (*cloudv1alpha1.VPC, *galacticv1alpha1.EdgeService) { +func (f *fixture) acceptedListener() (*cloudv1alpha1.VPC, *galacticv1alpha1.EdgeService) { f.t.Helper() f.start(f.listenerConfig()) - vpc := f.readyVPC(providerName) + vpc := f.readyVPC() svc := f.newService(ingressSvc, vpc, []string{SocketAccess, PublicListener}, nil) - f.newListener(name, ingressSvc, vip6, vip4) - f.expectCondition(name, galacticv1alpha1.EdgeListenerAccepted, metav1.ConditionTrue, + f.newListener("public", ingressSvc, vip6, vip4) + f.expectCondition("public", galacticv1alpha1.EdgeListenerAccepted, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonAccepted) return vpc, svc } diff --git a/internal/edge/listener/publish.go b/internal/edge/listener/publish.go new file mode 100644 index 000000000..8081926a5 --- /dev/null +++ b/internal/edge/listener/publish.go @@ -0,0 +1,233 @@ +// 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, l, 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 +// 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, string, error) { + addr, err := netip.ParseAddr(att.Status.Address) + 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)} + 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, fmt.Sprintf("BGPVRFInstance %s does not exist yet", key.Name), 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, fmt.Sprintf("BGPVRFInstance %s names no router or export route target", key.Name), 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 +} + +// 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 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(key.Namespace, key.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. 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): + 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 + case !listenersAdvertisement(&cur, l): + return nil + } + 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. 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 + 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 ownedBy(&list.Items[i], key) && 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..10da04917 --- /dev/null +++ b/internal/edge/listener/publish_envtest_test.go @@ -0,0 +1,204 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +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" + + 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() + 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() + 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 }) +} + +// 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() + 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 fe9cfaf79..abcfef8dc 100644 --- a/internal/edge/listener/reconciler.go +++ b/internal/edge/listener/reconciler.go @@ -8,12 +8,15 @@ import ( "context" "fmt" "net/netip" + "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" @@ -28,7 +31,8 @@ const deadlineRetry = time.Second // defaultLeaseDuration is the foundation's lease duration, timing.Params'. const defaultLeaseDuration = 15 * 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 @@ -36,15 +40,18 @@ const defaultLeaseDuration = 15 * time.Second // prefixes, and nothing else serves them on its ports. Its backends are the // attachments made against its EdgeService; one serves while the listener // is accepted and the attachment is programmed, ready, holding its -// instance's lease unexpired and not past its drain deadline, unless its node runs a -// gateway, which cannot deliver to its own node. +// instance's lease unexpired and not past its drain deadline, unless its +// node runs a 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 @@ -60,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() @@ -84,8 +98,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 @@ -95,6 +112,15 @@ 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 + } if err := r.setStatus(ctx, &l, d); err != nil { return ctrl.Result{}, err } @@ -151,17 +177,30 @@ 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 := 0, 0 + serving, local, unpublished := 0, 0, 0 + var causes []string for i := range backends { switch b := &backends[i]; { case b.serving: serving++ case accepted && b.eligible && b.local: 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 { @@ -171,12 +210,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 cannot be published (%s)", unpublished, why) + } 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("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" } diff --git a/internal/edge/listener/setup.go b/internal/edge/listener/setup.go index 93cd27887..c096e0b4c 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" @@ -28,6 +29,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" "go.datum.net/galactic/internal/edge/provider" edgeroute "go.datum.net/galactic/internal/edge/route" ) @@ -113,6 +115,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) @@ -132,11 +135,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 @@ -147,11 +150,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. @@ -168,6 +181,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) } @@ -329,5 +343,20 @@ func (r *Reconciler) setup(mgr ctrl.Manager) error { Watches(&coordinationv1.Lease{}, byInstance, builder.WithPredicates(edgeroute.InstanceLeases, r.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")