From 1261b5237f28c6cee1427f095b2163a63de82e41 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Sun, 29 Nov 2026 17:04:33 -0500 Subject: [PATCH 1/2] feat(edge): Report each listener backend's UID and host link Gateways are to serve a listener service from the backends in its EdgeListener's status. Their health gate matches a published decision on the backend's attachment UID, and the router probes a backend through its host-side link. Neither was in the status, so gateways would have had to read every provider namespace's EdgeAttachments. Core now copies the attachment's metadata.uid and status.hostLink into each status.backends entry. Both fields are optional and additive. --- api/v1alpha1/edgelistener_types.go | 12 ++++++++++++ config/crd/galactic.datumapis.com_edgelisteners.yaml | 12 ++++++++++++ docs/api/galactic.md | 2 ++ internal/edge/listener/backends.go | 4 ++-- 4 files changed, 28 insertions(+), 2 deletions(-) diff --git a/api/v1alpha1/edgelistener_types.go b/api/v1alpha1/edgelistener_types.go index f8b4a5e21..8b5ed22c8 100644 --- a/api/v1alpha1/edgelistener_types.go +++ b/api/v1alpha1/edgelistener_types.go @@ -180,6 +180,12 @@ type EdgeListenerBackend struct { // +kubebuilder:validation:MaxLength=317 Attachment string `json:"attachment"` + // UID is the EdgeAttachment's metadata.uid. A gateway health decision + // must name it to apply to this backend. + // +optional + // +kubebuilder:validation:MaxLength=36 + UID string `json:"uid,omitempty"` + // Node is the attachment's node. // +optional // +kubebuilder:validation:MaxLength=253 @@ -190,6 +196,12 @@ type EdgeListenerBackend struct { // +kubebuilder:validation:MaxLength=39 Address string `json:"address,omitempty"` + // HostLink is the host end of the attachment's link, which the gateway + // health check probes through. + // +optional + // +kubebuilder:validation:MaxLength=15 + HostLink string `json:"hostLink,omitempty"` + // Serving is whether the attachment receives new flows: it is // programmed, its instance lease is valid and its provider reports Ready. // +optional diff --git a/config/crd/galactic.datumapis.com_edgelisteners.yaml b/config/crd/galactic.datumapis.com_edgelisteners.yaml index 3c2561baf..7f8fd0299 100644 --- a/config/crd/galactic.datumapis.com_edgelisteners.yaml +++ b/config/crd/galactic.datumapis.com_edgelisteners.yaml @@ -214,6 +214,12 @@ spec: description: Attachment is the EdgeAttachment's namespace and name. maxLength: 317 type: string + hostLink: + description: |- + HostLink is the host end of the attachment's link, which the gateway + health check probes through. + maxLength: 15 + type: string node: description: Node is the attachment's node. maxLength: 253 @@ -223,6 +229,12 @@ spec: Serving is whether the attachment receives new flows: it is programmed, its instance lease is valid and its provider reports Ready. type: boolean + uid: + description: |- + UID is the EdgeAttachment's metadata.uid. A gateway health decision + must name it to apply to this backend. + maxLength: 36 + type: string required: - attachment type: object diff --git a/docs/api/galactic.md b/docs/api/galactic.md index 9d998d9b2..234865e9e 100644 --- a/docs/api/galactic.md +++ b/docs/api/galactic.md @@ -328,8 +328,10 @@ _Appears in:_ | Field | Description | Default | Validation | | --- | --- | --- | --- | | `attachment` _string_ | Attachment is the EdgeAttachment's namespace and name. | | MaxLength: 317
| +| `uid` _string_ | UID is the EdgeAttachment's metadata.uid. A gateway health decision
must name it to apply to this backend. | | MaxLength: 36
| | `node` _string_ | Node is the attachment's node. | | MaxLength: 253
| | `address` _string_ | Address is the attachment's IPv6 address in the ingress gVPC. | | MaxLength: 39
| +| `hostLink` _string_ | HostLink is the host end of the attachment's link, which the gateway
health check probes through. | | MaxLength: 15
| | `serving` _boolean_ | Serving is whether the attachment receives new flows: it is
programmed, its instance lease is valid and its provider reports Ready. | | | diff --git a/internal/edge/listener/backends.go b/internal/edge/listener/backends.go index 45fc3c406..c01404991 100644 --- a/internal/edge/listener/backends.go +++ b/internal/edge/listener/backends.go @@ -55,8 +55,8 @@ func (b *backend) unpublished(accepted bool) bool { // status is the backend as the listener's status reports it. func (b *backend) status() galacticv1alpha1.EdgeListenerBackend { return galacticv1alpha1.EdgeListenerBackend{ - Attachment: b.att.Namespace + "/" + b.att.Name, Node: b.att.Status.NodeName, - Address: b.att.Status.Address, Serving: b.serving, + Attachment: b.att.Namespace + "/" + b.att.Name, UID: string(b.att.UID), Node: b.att.Status.NodeName, + Address: b.att.Status.Address, HostLink: b.att.Status.HostLink, Serving: b.serving, } } From 8d0ce9bc53958016f2803ef34b66f74b77772921 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Sun, 29 Nov 2026 17:04:55 -0500 Subject: [PATCH 2/2] feat(gateway): Serve listener services from their serving backends A NetworkService that names an EdgeListener had no backends: gateways and routers reported the listener pending, so its VIPs were never loaded or advertised. Gateways and galactic-router now take such a service's backends from the listener's status.backends entries that core reports serving. Core already decides readiness, lease, drain deadline and local-delivery exclusion, so neither re-checks EdgeAttachments. Each serving backend gets a Maglev slot on every gateway and a veth ServiceVIPBinding on its node. The router probes it through its host link and publishes the decision under the attachment's UID, so the existing health gate, failure policy and withdrawal paths apply unchanged. Gateways and routers watch EdgeListener status only where the API server serves the kind; elsewhere a listener service stays pending and every other service is unaffected. Their ClusterRoles grant read access to edgelisteners, and the gateway's RBAC preflight checks it when the kind is served. --- api/network/v1alpha1/networkservice_types.go | 5 +- cmd/galactic-gateway/main.go | 17 +- cmd/galactic-gateway/preflight_test.go | 35 +- cmd/galactic-gateway/rbac_test.go | 12 +- cmd/galactic-gateway/root.go | 12 +- cmd/galactic-router/main.go | 6 + ...alactic.datumapis.com_networkservices.yaml | 5 +- config/galactic-gateway/rbac.yaml | 8 + config/galactic-router/rbac.yaml | 7 + docs/api/network-gateway.md | 2 +- docs/designs/edge-public-listener.md | 2 +- docs/edge/provider-contract.md | 6 +- .../controller/backendhealth_controller.go | 95 +++-- internal/controller/listenerbackends.go | 232 +++++++++++ internal/controller/listenerbackends_test.go | 390 ++++++++++++++++++ .../controller/networkgateway_controller.go | 55 ++- .../networkgateway_controller_test.go | 14 +- .../controller/networkgateway_health_test.go | 8 +- .../controller/networkgateway_ipv4_test.go | 24 +- .../networkservice_binding_controller.go | 42 +- .../networkservice_controller_test.go | 4 + internal/controller/rulebackends.go | 70 ++-- internal/controller/rulebackends_test.go | 39 +- internal/controller/servicescope_test.go | 6 +- 24 files changed, 940 insertions(+), 156 deletions(-) create mode 100644 internal/controller/listenerbackends.go create mode 100644 internal/controller/listenerbackends_test.go diff --git a/api/network/v1alpha1/networkservice_types.go b/api/network/v1alpha1/networkservice_types.go index 0c2cfeaa7..ce046a1f8 100644 --- a/api/network/v1alpha1/networkservice_types.go +++ b/api/network/v1alpha1/networkservice_types.go @@ -249,8 +249,9 @@ type NetworkServiceSpec struct { // whose listener attachments are the service's backends, in place of // BackendSelector. Core sets it on the services it writes for a // listener, one per listener port. It is allowed only in the gateway - // namespace. Until gateways resolve listener backends, a service that - // sets it has no backends and its VIPs are not advertised. + // namespace. Its backends are the listener's status.backends that core + // reports serving; gateways and backend nodes never select them from + // VPCAttachments. // +optional EdgeListenerRef *NetworkServiceEdgeListenerReference `json:"edgeListenerRef,omitempty"` diff --git a/cmd/galactic-gateway/main.go b/cmd/galactic-gateway/main.go index 3cec22295..5e402c01c 100644 --- a/cmd/galactic-gateway/main.go +++ b/cmd/galactic-gateway/main.go @@ -24,6 +24,8 @@ import ( authorizationv1 "k8s.io/api/authorization/v1" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" + + galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" ) const ( @@ -42,6 +44,7 @@ const ( cloudAPIVersion = "v1alpha1" resourceVPCAttachments = "vpcattachments" resourceVPCs = "vpcs" + resourceEdgeListeners = "edgelisteners" ) // verbList and verbWatch are the verbs an informer needs on each type it @@ -74,7 +77,9 @@ type watchedResource struct{ group, version, kind, resource string } // is a real requirement here. VPCs are watched only with projectServices on. // ServiceVIPBindings are watched whatever the IPv4 VIP and backend health // switches say, since a shared address or port range rule reads them too. -func watchedResources(projectServices bool) []watchedResource { +// EdgeListeners are watched only when the API server serves them (listeners), +// as the gateway controller registers that watch only then. +func watchedResources(projectServices, listeners bool) []watchedResource { resources := []watchedResource{ {group: networkAPIGroup, version: networkAPIVersion, kind: "NetworkGateway", resource: resourceNetworkGateways}, {group: networkAPIGroup, version: networkAPIVersion, kind: "NetworkService", resource: resourceNetworkServices}, @@ -92,6 +97,12 @@ func watchedResources(projectServices bool) []watchedResource { resources = append(resources, watchedResource{group: cloudAPIGroup, version: cloudAPIVersion, kind: "VPC", resource: resourceVPCs}) } + if listeners { + resources = append(resources, watchedResource{ + group: galacticv1alpha1.GroupVersion.Group, version: galacticv1alpha1.GroupVersion.Version, + kind: "EdgeListener", resource: resourceEdgeListeners, + }) + } return resources } @@ -101,11 +112,11 @@ func watchedResources(projectServices bool) []watchedResource { // startup with the resources it names. A review that cannot be made is logged // and skipped, since the manager's own cache sync reports a real outage, but // once ctx ends startup fails rather than passing a check it never finished. -func checkWatchPermissions(ctx context.Context, c client.Client, projectServices bool) error { +func checkWatchPermissions(ctx context.Context, c client.Client, projectServices, listeners bool) error { logger := ctrl.Log.WithName("rbac-preflight") var denied []string - for _, r := range watchedResources(projectServices) { + for _, r := range watchedResources(projectServices, listeners) { var missing []string for _, verb := range informerVerbs { review := &authorizationv1.SelfSubjectAccessReview{ diff --git a/cmd/galactic-gateway/preflight_test.go b/cmd/galactic-gateway/preflight_test.go index fb5d3ab87..a5279d9de 100644 --- a/cmd/galactic-gateway/preflight_test.go +++ b/cmd/galactic-gateway/preflight_test.go @@ -7,6 +7,7 @@ package main import ( "context" "fmt" + "net/http" "os" "path/filepath" "slices" @@ -16,6 +17,7 @@ import ( "time" rbacv1 "k8s.io/api/rbac/v1" + apimeta "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" utilruntime "k8s.io/apimachinery/pkg/util/runtime" @@ -34,6 +36,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/controller" ) @@ -100,13 +103,23 @@ func (c *recordingCache) recorded() []schema.GroupVersionKind { // watchedKinds starts a manager with the field index and controllers // setupControllers registers, configured by projectServices, ipv4VIPs and -// backendHealth, and returns every kind they watch. -func watchedKinds(t *testing.T, projectServices, ipv4VIPs, backendHealth bool) []schema.GroupVersionKind { +// backendHealth, and returns every kind they watch. listeners is whether the +// manager's discovery serves EdgeListener. +func watchedKinds(t *testing.T, projectServices, ipv4VIPs, backendHealth, listeners bool) []schema.GroupVersionKind { t.Helper() scheme := runtime.NewScheme() utilruntime.Must(clientgoscheme.AddToScheme(scheme)) utilruntime.Must(bgpv1alpha1.AddToScheme(scheme)) utilruntime.Must(cloudv1alpha1.AddToScheme(scheme)) + utilruntime.Must(galacticv1alpha1.AddToScheme(scheme)) + // Discovery is static, so it needs no API server either. + mapper := apimeta.NewDefaultRESTMapper(nil) + for gvk := range scheme.AllKnownTypes() { + if gvk.Group == galacticv1alpha1.GroupVersion.Group && gvk.Kind == "EdgeListener" && !listeners { + continue + } + mapper.Add(gvk, apimeta.RESTScopeNamespace) + } rc := &recordingCache{ FakeInformers: &informertest.FakeInformers{Scheme: scheme}, kinds: map[schema.GroupVersionKind]bool{}, @@ -118,6 +131,7 @@ func watchedKinds(t *testing.T, projectServices, ipv4VIPs, backendHealth bool) [ HealthProbeBindAddress: "0", Metrics: metricsserver.Options{BindAddress: "0"}, NewCache: func(*rest.Config, cache.Options) (cache.Cache, error) { return rc, nil }, + MapperProvider: func(*rest.Config, *http.Client) (apimeta.RESTMapper, error) { return mapper, nil }, Controller: config.Controller{SkipNameValidation: ptr.To(true)}, }) if err != nil { @@ -171,19 +185,20 @@ func watchedKinds(t *testing.T, projectServices, ipv4VIPs, backendHealth bool) [ // watch a type checkWatchPermissions does not check, or the other way round, // so a new watch cannot ship without its pre-flight entry. func TestWatchedResourcesMatchControllers(t *testing.T) { - for _, tc := range []struct{ projectServices, ipv4VIPs, backendHealth bool }{ + for _, tc := range []struct{ projectServices, ipv4VIPs, backendHealth, listeners bool }{ {}, {ipv4VIPs: true}, {backendHealth: true}, - {projectServices: true, ipv4VIPs: true, backendHealth: true}, + {listeners: true}, + {projectServices: true, ipv4VIPs: true, backendHealth: true, listeners: true}, } { - t.Run(fmt.Sprintf("projectServices=%t,ipv4VIPs=%t,backendHealth=%t", - tc.projectServices, tc.ipv4VIPs, tc.backendHealth), func(t *testing.T) { + t.Run(fmt.Sprintf("projectServices=%t,ipv4VIPs=%t,backendHealth=%t,listeners=%t", + tc.projectServices, tc.ipv4VIPs, tc.backendHealth, tc.listeners), func(t *testing.T) { want := map[schema.GroupVersionKind]watchedResource{} - for _, r := range watchedResources(tc.projectServices) { + for _, r := range watchedResources(tc.projectServices, tc.listeners) { want[schema.GroupVersionKind{Group: r.group, Version: r.version, Kind: r.kind}] = r } - got := watchedKinds(t, tc.projectServices, tc.ipv4VIPs, tc.backendHealth) + got := watchedKinds(t, tc.projectServices, tc.ipv4VIPs, tc.backendHealth, tc.listeners) for _, gvk := range got { if _, ok := want[gvk]; !ok { t.Errorf("a controller watches %s, which watchedResources leaves out", gvk) @@ -202,7 +217,7 @@ func TestWatchedResourcesMatchControllers(t *testing.T) { // other than its kind's CRD does, which would review access to the wrong // resource. func TestWatchedResourceNames(t *testing.T) { - for _, r := range watchedResources(true) { + for _, r := range watchedResources(true, true) { data, err := os.ReadFile(filepath.Join("..", "..", "config", "crd", r.group+"_"+r.resource+".yaml")) if err != nil { t.Errorf("%s: no CRD for resource %q: %v", r.kind, r.resource, err) @@ -255,7 +270,7 @@ func TestShippedRoleGrantsWatches(t *testing.T) { slices.Contains(rule.Verbs, verb) }) } - for _, r := range watchedResources(true) { + for _, r := range watchedResources(true, true) { for _, verb := range informerVerbs { if !grants(r.group, r.resource, verb) { t.Errorf("config/galactic-gateway/rbac.yaml does not grant %s on %s.%s", verb, r.resource, r.group) diff --git a/cmd/galactic-gateway/rbac_test.go b/cmd/galactic-gateway/rbac_test.go index 4ea70366a..a13055af9 100644 --- a/cmd/galactic-gateway/rbac_test.go +++ b/cmd/galactic-gateway/rbac_test.go @@ -129,7 +129,7 @@ func TestCheckWatchPermissions(t *testing.T) { denyVPCs := func(_, resource string) bool { return resource != resourceVPCs } c, asked := accessReviewClient(t, denyVPCs, nil) - if err := checkWatchPermissions(ctx, c, false); err != nil { + if err := checkWatchPermissions(ctx, c, false, false); err != nil { t.Fatalf("project services off: %v, want nil", err) } for _, a := range *asked { @@ -139,13 +139,13 @@ func TestCheckWatchPermissions(t *testing.T) { } c, _ = accessReviewClient(t, denyVPCs, nil) - err := checkWatchPermissions(ctx, c, true) + err := checkWatchPermissions(ctx, c, true, false) if err == nil || !strings.Contains(err.Error(), resourceVPCs) { t.Fatalf("project services on without VPC access: %v, want an error naming %s", err, resourceVPCs) } c, _ = accessReviewClient(t, allowAll, nil) - if err := checkWatchPermissions(ctx, c, true); err != nil { + if err := checkWatchPermissions(ctx, c, true, false); err != nil { t.Fatalf("all granted: %v, want nil", err) } @@ -153,20 +153,20 @@ func TestCheckWatchPermissions(t *testing.T) { return verb != verbList || resource != resourceNetworkServiceAddresses } c, _ = accessReviewClient(t, denyAddressList, nil) - err = checkWatchPermissions(ctx, c, false) + err = checkWatchPermissions(ctx, c, false, false) if err == nil || !strings.Contains(err.Error(), verbList+" on "+resourceNetworkServiceAddresses) { t.Fatalf("list denied on %s: %v, want an error naming it", resourceNetworkServiceAddresses, err) } c, _ = accessReviewClient(t, allowAll, errors.New("unavailable")) - if err := checkWatchPermissions(ctx, c, true); err != nil { + if err := checkWatchPermissions(ctx, c, true, false); err != nil { t.Fatalf("reviews that cannot be made: %v, want nil", err) } ended, cancel := context.WithCancel(ctx) cancel() c, _ = accessReviewClient(t, allowAll, context.Canceled) - if err := checkWatchPermissions(ended, c, true); err == nil { + if err := checkWatchPermissions(ended, c, true, false); err == nil { t.Fatal("reviews cut off by the context ending: nil, want an error") } } diff --git a/cmd/galactic-gateway/root.go b/cmd/galactic-gateway/root.go index 0f61b65a9..5a775ff7f 100644 --- a/cmd/galactic-gateway/root.go +++ b/cmd/galactic-gateway/root.go @@ -24,8 +24,10 @@ 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/config" "go.datum.net/galactic/internal/controller" + "go.datum.net/galactic/internal/edge/listener" "go.datum.net/galactic/internal/gateway" "go.datum.net/galactic/internal/logging" "go.datum.net/galactic/internal/metadata" @@ -54,6 +56,7 @@ func runCmd(cfg *config.GatewayConfig) error { utilruntime.Must(clientgoscheme.AddToScheme(scheme)) utilruntime.Must(bgpv1alpha1.AddToScheme(scheme)) utilruntime.Must(cloudv1alpha1.AddToScheme(scheme)) + utilruntime.Must(galacticv1alpha1.AddToScheme(scheme)) mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{ Scheme: scheme, @@ -101,9 +104,14 @@ func runCmd(cfg *config.GatewayConfig) error { grpcSrv.GracefulStop() }() - // Pre-flight RBAC check: a watch the role denies fails startup. + // Pre-flight RBAC check: a watch the role denies fails startup. The + // EdgeListener watch exists only where the API server serves the kind. + listenersServed, err := listener.ListenerAPIServed(mgr.GetRESTMapper()) + if err != nil { + return err + } rbacCtx, cancelRBAC := context.WithTimeout(ctx, 30*time.Second) - err = checkWatchPermissions(rbacCtx, mgr.GetClient(), cfg.ProjectServices) + err = checkWatchPermissions(rbacCtx, mgr.GetClient(), cfg.ProjectServices, listenersServed) cancelRBAC() if err != nil { return err diff --git a/cmd/galactic-router/main.go b/cmd/galactic-router/main.go index 51aea9928..70d47af80 100644 --- a/cmd/galactic-router/main.go +++ b/cmd/galactic-router/main.go @@ -78,6 +78,12 @@ func checkWatchPermissions(mgr ctrl.Manager, trafficPolicy bool) { {group: bgpAPIGroup, version: bgpAPIVersion, resource: resourceProducerReports}, {group: bgpAPIGroup, version: bgpAPIVersion, resource: resourceServiceRoutePolicy}, {group: "galactic.datumapis.com", version: "v1alpha1", resource: resourceVPCAttachments}, + // Watched only where the API server serves EdgeListener, but checked + // everywhere: this pre-flight only logs, and the ClusterRole grants it. + { + group: galacticv1alpha1.GroupVersion.Group, version: galacticv1alpha1.GroupVersion.Version, + resource: "edgelisteners", + }, {version: "v1", resource: resourceSecrets}, {version: "v1", resource: resourceNodes}, } diff --git a/config/crd/galactic.datumapis.com_networkservices.yaml b/config/crd/galactic.datumapis.com_networkservices.yaml index 7ffcd5e94..d35ad54f7 100644 --- a/config/crd/galactic.datumapis.com_networkservices.yaml +++ b/config/crd/galactic.datumapis.com_networkservices.yaml @@ -263,8 +263,9 @@ spec: whose listener attachments are the service's backends, in place of BackendSelector. Core sets it on the services it writes for a listener, one per listener port. It is allowed only in the gateway - namespace. Until gateways resolve listener backends, a service that - sets it has no backends and its VIPs are not advertised. + namespace. Its backends are the listener's status.backends that core + reports serving; gateways and backend nodes never select them from + VPCAttachments. properties: name: description: Name is the EdgeListener's name. diff --git a/config/galactic-gateway/rbac.yaml b/config/galactic-gateway/rbac.yaml index 0073cfe88..8c20cd9d3 100644 --- a/config/galactic-gateway/rbac.yaml +++ b/config/galactic-gateway/rbac.yaml @@ -72,6 +72,14 @@ rules: resources: - vpcattachments verbs: ["get", "list", "watch"] + # A listener NetworkService's backends are its EdgeListener's serving + # backends, read from the listener's status and watched so a backend that + # stops serving leaves the Maglev table. A gateway skips the watch when + # the API server does not serve EdgeListener. + - apiGroups: ["galactic.datumapis.com"] + resources: + - edgelisteners + verbs: ["get", "list", "watch"] # With GALACTIC_GATEWAY_PROJECT_SERVICES on, a NetworkService in a project # namespace is accepted only when a VPC in that namespace carries its # vpcRef, so the gateway reads VPCs and re-checks its services when one diff --git a/config/galactic-router/rbac.yaml b/config/galactic-router/rbac.yaml index 0da3f02b8..501aa7d20 100644 --- a/config/galactic-router/rbac.yaml +++ b/config/galactic-router/rbac.yaml @@ -68,6 +68,13 @@ rules: - vpcs - vpcattachments verbs: ["get", "list", "watch"] + # A listener NetworkService's backends, their bindings and their health + # probes come from its EdgeListener's status. The router skips the watch + # when the API server does not serve EdgeListener. + - apiGroups: ["galactic.datumapis.com"] + resources: + - edgelisteners + verbs: ["get", "list", "watch"] # GC keeps a VPC's VRF and BGPVRFInstance while an edge attachment on # this node uses it (internal/edge/maintenance), read uncached. - apiGroups: ["galactic.datumapis.com"] diff --git a/docs/api/network-gateway.md b/docs/api/network-gateway.md index a0d772a7b..f57dda84b 100644 --- a/docs/api/network-gateway.md +++ b/docs/api/network-gateway.md @@ -663,7 +663,7 @@ _Appears in:_ | `portRange` _[PortRange](#portrange)_ | PortRange replaces Port for an inclusive IPv6 UDP interval. Backend ports
are preserved; BackendPort must be omitted. | | | | `addressGroup` _[NetworkServiceAddressGroup](#networkserviceaddressgroup)_ | AddressGroup binds this listener to a complete, authoritative address inventory. | | | | `backendSelector` _[LabelSelector](https://kubernetes.io/docs/reference/generated/kubernetes-api/v/#labelselector-v1-meta)_ | BackendSelector selects the VPCAttachments (galactic.datumapis.com/v1alpha1)
that serve this service, matched against each VPCAttachment object's own
labels: in any namespace for a service in a gateway namespace, and only
in its own namespace for a service in a project namespace. Only
attachments whose status.vpc equals VPCRef are candidates, whatever their
labels, so a selector cannot reach into another tenant's VPC. Each selected attachment contributes the
IPv6 addresses in its spec.interface.addresses as backends, on
BackendPort, for both VIPs: its node translates the IPv4 VIP's flows to
and from IPv6, and its IPv4 addresses are never backends. An attachment
with no status.node, or no IPv6 address, is not a backend until it has
both. An empty selector is rejected rather than read as "every
attachment in the VPC". Exactly one of BackendSelector and
EdgeListenerRef is required. | | | -| `edgeListenerRef` _[NetworkServiceEdgeListenerReference](#networkserviceedgelistenerreference)_ | EdgeListenerRef names the EdgeListener, in the service's namespace,
whose listener attachments are the service's backends, in place of
BackendSelector. Core sets it on the services it writes for a
listener, one per listener port. It is allowed only in the gateway
namespace. Until gateways resolve listener backends, a service that
sets it has no backends and its VIPs are not advertised. | | | +| `edgeListenerRef` _[NetworkServiceEdgeListenerReference](#networkserviceedgelistenerreference)_ | EdgeListenerRef names the EdgeListener, in the service's namespace,
whose listener attachments are the service's backends, in place of
BackendSelector. Core sets it on the services it writes for a
listener, one per listener port. It is allowed only in the gateway
namespace. Its backends are the listener's status.backends that core
reports serving; gateways and backend nodes never select them from
VPCAttachments. | | | | `backendPort` _integer_ | BackendPort is the destination port on every selected backend, 1-65535.
Like Port, it is required for tcp, udp and sctp and must be unset for
esp, gre and icmp. Zero means unset and is omitted when encoding, and an
explicit 0 is refused. | | Maximum: 65535
Minimum: 1
| | `sessionAffinity` _[NetworkServiceSessionAffinity](#networkservicesessionaffinity)_ | SessionAffinity selects which connections from one client share a
backend: None, the default, balances each connection on its own;
ClientIP pins a client address to one backend; ClientIPAndProtocol pins
a client address and protocol to one. Two services pin a client to the
same backend only if both set the same affinity and select the same
backend addresses. A change takes effect on every gateway node without a
restart, and rehashes every connection of the service, so most open
connections reach a different backend afterwards. | None | Enum: [None ClientIP ClientIPAndProtocol]
| | `healthCheck` _[NetworkServiceHealthCheck](#networkservicehealthcheck)_ | HealthCheck turns on health checks for the service's backends. Each
backend's own node opens a TCP connection to it on the health check
port, from the link-local address of the backend's host-side interface,
and publishes a decision in status.health of the backend's
ServiceVIPBindings. The gateway nodes take a backend whose decision is
Unhealthy out of the service's Maglev table, and keep every backend
when all of them are Unhealthy by default. FailClosed instead requires
fresh Healthy results for the current configuration and withdraws a VIP
with no healthy backends. Unset, no backend is probed and every
one stays in the table.
Where interface traffic policy is enforced, the backend's policy must
allow TCP from fe80::/10 to the health check port on the Private path,
and the replies back. | | | diff --git a/docs/designs/edge-public-listener.md b/docs/designs/edge-public-listener.md index 89f5eee91..eda169c8c 100644 --- a/docs/designs/edge-public-listener.md +++ b/docs/designs/edge-public-listener.md @@ -1,6 +1,6 @@ # Galactic Edge public listener -Status: proposed, with its open decisions settled. The Phase 0 lab proof is done (see [Phase 0 results](#phase-0-results)), and Phase 1, the API, is implemented: `EdgeListener`, the `PublicListener` capability and `NetworkService.spec.edgeListenerRef` exist. Phase 2, core, is implemented: the ingress gVPC, listener admission and status, `/128` publication and the `NetworkService` writer. Phase 3's unmatched-egress drop is implemented. Gateways do not resolve listener backends yet (Phase 4), so nothing serves a listener. It extends the [Galactic Edge Foundation](galactic-edge.md) and reuses the [XDP/DSR gateway](../gateway/architecture.md). The [provider contract](../edge/provider-contract.md) remains the reference for behavior that exists today. +Status: proposed, with its open decisions settled. The Phase 0 lab proof is done (see [Phase 0 results](#phase-0-results)), and Phase 1, the API, is implemented: `EdgeListener`, the `PublicListener` capability and `NetworkService.spec.edgeListenerRef` exist. Phase 2, core, is implemented: the ingress gVPC, listener admission and status, `/128` publication and the `NetworkService` writer. Phase 3's unmatched-egress drop is implemented. Phase 4's backend resolution is implemented: gateways and `galactic-router` serve a listener from the backends core reports serving. Its lab failover tests are not done yet. It extends the [Galactic Edge Foundation](galactic-edge.md) and reuses the [XDP/DSR gateway](../gateway/architecture.md). The [provider contract](../edge/provider-contract.md) remains the reference for behavior that exists today. This design follows the [Datum enhancement template](https://github.com/datum-cloud/enhancements/blob/main/enhancements/template/README.md). diff --git a/docs/edge/provider-contract.md b/docs/edge/provider-contract.md index e942f8db5..1ef37d1ae 100644 --- a/docs/edge/provider-contract.md +++ b/docs/edge/provider-contract.md @@ -76,7 +76,7 @@ A field not listed is read-only to everyone but the control plane that owns the | `BGPAdvertisement` for an `EdgeRoute` | Core | One per route in `galactic-system`, named `edge-`, labeled with the route's UID and accepted epoch. No owner reference: the route is in another namespace. See [Publication](#publication). | | `EdgeListener.spec` | Platform authority | `providerRef` and `serviceRef` are immutable. No provider ServiceAccount may write it: the `galactic-edge-provider-listener` policy refuses every provider write, and the `galactic-edge-listener-authority` ClusterRole, bound by the operator, grants the authority access. | | `EdgeListener.status` | Core | `Accepted` and `Programmed` conditions and the listener's backends. No provider ServiceAccount may write it. | -| `NetworkService` with `edgeListenerRef` | Core | One per listener port, in `galactic-system` only. No provider ServiceAccount may write any `NetworkService`. Until gateways resolve listener backends, such a service has none and its VIPs are not advertised. | +| `NetworkService` with `edgeListenerRef` | Core | One per listener port, in `galactic-system` only. No provider ServiceAccount may write any `NetworkService`. Its backends are the listener's serving backends (see below). | | Deletion of dead `EdgeInstance`s and `EdgeRoute`s | Core | See [Reaping](#reaping). | `admission.Writer` knows two writers, core and provider (`internal/edge/admission/admission.go:169`). `galactic-controller` and `galactic-edge` both count as core there, so `MaySetCondition` separates core from providers, not one core process from the other. The split between them in this table is enforced by RBAC and admission policies that limit `galactic-edge`'s ServiceAccount to `Programmed`, `Released`, device names and `closedEpoch`. @@ -315,12 +315,14 @@ 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`; 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`. +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`. Each backend also reports its attachment's `uid` and `hostLink`. 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. While a listener is accepted, core writes one `NetworkService` per port in `galactic-system`, named `--` (a listener name with a dot, or one too long for a 63-character name, is shortened and given a hash suffix) and controlled by the listener. Each carries the listener's addresses as `vipAddresses`, the port's `protocol`, `port` and `backendPort`, the listener's `sessionAffinity`, `edgeListenerRef` naming the listener, `vpcRef` set to the ingress gVPC's `status.vpc`, and a `healthCheck` with the listener's `failurePolicy` probing `healthPort`, or the first `tcp` port's `backendPort`. Core deletes the service of a port the listener no longer lists, and every service of a listener that is no longer accepted. A `NetworkService` of one of those names that the listener does not control is left alone: core names it in the listener's `Programmed` message and records a `NetworkServiceNameTaken` Event. +The gateways and `galactic-router` take a listener service's backends from its listener's `status.backends` and never from `VPCAttachment`s. Each backend core reports `serving`, with its `uid`, node, host link and a plain IPv6 address, gets a Maglev slot on every gateway node and a `veth` `ServiceVIPBinding` on its own node, on the service's `backendPort`. A backend that stops serving leaves new selection on the next gateway reconcile, which the listener's status update triggers, and its binding goes. A `Draining` backend therefore keeps receiving new flows until its `status.drainDeadline`, and one that loses its lease stops when core's requeue at the lease's expiry less the maximum skew writes the status. The router probes each backend's `healthPort` through its host link and publishes the decision under the attachment's UID, and the service's `failurePolicy`, `ServiceVIPBinding` and advertisement rules apply as for any other service: a service with no serving backend is withdrawn from every gateway, and under `FailClosed` so is one with no healthy backend. A gateway or router whose API server does not serve `EdgeListener` serves no listener service. Each checks this once at startup, so one started before the CRD was installed serves listener services only after a restart. A backend that core reports serving without its `uid` or `hostLink`, as a core older than the gateways does, is never served, so roll out core first. + The gateway holds each `NetworkService` with its `galactic.datum.net/networkservice-teardown` finalizer until it has deleted the service's advertisements, but each gateway node keeps serving the service for its drain delay (5 s) after that, and the withdrawal takes time to converge in BGP. So core keeps a refused or deleted listener's backend `/128`s until its services are gone and then for `galactic-controller --edge-listener-withdraw-delay` (default 30 s, which must exceed the gateway drain delay), so a VIP is never advertised toward a backend that can no longer be resolved. Core records the instant it first saw the services gone in the listener's `galactic.datumapis.com/edge-listener-services-gone` annotation, so a restart of core does not shorten the hold. During the hold it keeps only the `/128`s of backends that would still serve: an attachment that goes, moves to another gVPC or address, or stops being eligible or holding its lease, loses its `/128` at once. A deleted listener is held by core's `galactic.datumapis.com/edge-listener` finalizer: core deletes its services, waits until they are gone and the delay has passed, withdraws its `/128`s, and only then removes the finalizer. If the finalizer is removed by hand, the garbage collector deletes the services through their owner references, and core withdraws the `/128`s once they are gone. ### Restart and replacement diff --git a/internal/controller/backendhealth_controller.go b/internal/controller/backendhealth_controller.go index 87c01c932..6ff5acd16 100644 --- a/internal/controller/backendhealth_controller.go +++ b/internal/controller/backendhealth_controller.go @@ -28,6 +28,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/healthprobe" ) @@ -44,7 +45,8 @@ type BackendProber interface { // ServiceVIPBindings. // // For each generated binding on its node it finds the VPCAttachment holding -// the binding's backend address, probes that backend through Prober, and +// the binding's backend address, or for a listener service the EdgeListener +// backend holding it, probes that backend through Prober, and // writes the decision to the binding's status.health. Every binding of one // backend shares one probe loop and carries the same decision. status.health // is written only when the decision changes, with a merge patch of that field @@ -68,6 +70,18 @@ type BackendHealthReconciler struct { Prober BackendProber events chan event.GenericEvent + + // listenersServed is whether the API server serves EdgeListener, set by + // SetupWithManager. While it is false no listener backend is probed. + listenersServed bool +} + +// probeBackend is the backend a binding's address belongs to, as a probe +// needs it: the UID a published decision names, and the host-side interface +// the probe leaves through. +type probeBackend struct { + uid types.UID + iface string } // Reconcile converges one binding's probe and status.health. @@ -102,11 +116,11 @@ func (r *BackendHealthReconciler) Reconcile(ctx context.Context, req ctrl.Reques return ctrl.Result{}, r.publish(ctx, binding, nil) } - attachment, err := r.backendAttachment(ctx, rule.Spec.VPCRef, binding.Spec.BackendAddress) + backend, err := r.backendFor(ctx, rule, binding.Spec.BackendAddress) if err != nil { return ctrl.Result{}, err } - if attachment == nil { + if backend == nil { // No attachment on this node holds the address any more, so the // binding writer is about to delete the binding. A decision already // published names the old attachment, which readers check. @@ -114,7 +128,7 @@ func (r *BackendHealthReconciler) Reconcile(ctx context.Context, req ctrl.Reques return ctrl.Result{}, nil } - target, err := healthTarget(rule, attachment, binding) + target, err := healthTarget(rule, backend.iface, binding) if err != nil { // Only an address the API server already validated reaches here, so // this is not worth a retry. @@ -122,8 +136,8 @@ func (r *BackendHealthReconciler) Reconcile(ctx context.Context, req ctrl.Reques r.Prober.Release(owner) return ctrl.Result{}, nil } - id := healthTargetID(attachment.UID, target) - seed := seedDecision(binding.Status.Health, attachment.UID, target.Port) + id := healthTargetID(backend.uid, target) + seed := seedDecision(binding.Status.Health, backend.uid, target.Port) if rule.Spec.HealthCheck.FailurePolicy == bgpv1alpha1.NetworkServiceHealthFailClosed { id = fmt.Sprintf("%s|%s|%d", id, rule.UID, rule.Generation) seed = nil @@ -139,7 +153,7 @@ func (r *BackendHealthReconciler) Reconcile(ctx context.Context, req ctrl.Reques State: bgpv1alpha1.BackendHealthState(decision.State), Reason: decision.Reason, Message: truncateMessage(decision.Message), - AttachmentUID: attachment.UID, + AttachmentUID: backend.uid, Port: int32(target.Port), LastTransitionTime: metav1.NewTime(decision.Since.Truncate(time.Second)), }) @@ -154,22 +168,34 @@ func (r *BackendHealthReconciler) ownsBinding(binding *bgpv1alpha1.ServiceVIPBin binding.Spec.TargetRef.Name == r.NodeName } -// backendAttachment returns the VPCAttachment on this node in vpc that holds -// address, or nil when none does. -func (r *BackendHealthReconciler) backendAttachment( - ctx context.Context, vpc, address string, -) (*cloudv1alpha1.VPCAttachment, error) { +// backendFor returns the backend on this node that holds address for rule, +// or nil when none does: the VPCAttachment in rule's VPC holding it or, for a +// rule naming an EdgeListener, that listener's serving backend holding it. +func (r *BackendHealthReconciler) backendFor( + ctx context.Context, rule *bgpv1alpha1.NetworkService, address string, +) (*probeBackend, error) { addr, err := netip.ParseAddr(address) if err != nil { return nil, nil //nolint:nilerr // an unparsable address belongs to no attachment } - attachments, err := listVPCAttachmentsInVPC(ctx, r.Client, vpc) + if rule.Spec.EdgeListenerRef != nil { + listeners, err := listListenerBackends(ctx, r.Client, rule.Namespace, r.listenersServed) + if err != nil { + return nil, err + } + lb := listenerBackendOnNode(rule, listeners, r.NodeName, addr) + if lb == nil { + return nil, nil + } + return &probeBackend{uid: types.UID(lb.UID), iface: lb.HostLink}, nil + } + attachments, err := listVPCAttachmentsInVPC(ctx, r.Client, rule.Spec.VPCRef) if err != nil { return nil, err } for _, a := range attachments { if a.Status.Node == r.NodeName && slices.Contains(attachmentIPv6Addresses(a), addr) { - return a, nil + return &probeBackend{uid: a.UID, iface: a.Status.HostInterface}, nil } } return nil, nil @@ -226,11 +252,12 @@ func ruleHealthCheckPort(rule *bgpv1alpha1.NetworkService) int32 { return rule.Spec.BackendPort } -// healthTarget returns the probe target for binding's backend, held by -// attachment, under rule's healthCheck. Fields the API server defaults are -// read as their defaults if a client left them zero anyway. +// healthTarget returns the probe target for binding's backend, reached +// through the host-side interface iface, under rule's healthCheck. Fields the +// API server defaults are read as their defaults if a client left them zero +// anyway. func healthTarget( - rule *bgpv1alpha1.NetworkService, attachment *cloudv1alpha1.VPCAttachment, binding *bgpv1alpha1.ServiceVIPBinding, + rule *bgpv1alpha1.NetworkService, iface string, binding *bgpv1alpha1.ServiceVIPBinding, ) (healthprobe.Target, error) { addr, err := netip.ParseAddr(binding.Spec.BackendAddress) if err != nil { @@ -249,7 +276,7 @@ func healthTarget( } return healthprobe.Target{ Refresh: failClosedHealth(rule), - Interface: attachment.Status.HostInterface, + Interface: iface, Addr: addr, Port: uint16(port), Config: healthprobe.Config{ @@ -304,7 +331,12 @@ func (r *BackendHealthReconciler) SetupWithManager(mgr ctrl.Manager) error { r.Prober = healthprobe.NewProber(ctx, dial, func(owner string) { r.enqueue(ctx, owner) }) } - return ctrl.NewControllerManagedBy(mgr). + served, err := edgeListenerServed(mgr.GetRESTMapper()) + if err != nil { + return err + } + r.listenersServed = served + b := ctrl.NewControllerManagedBy(mgr). For(&bgpv1alpha1.ServiceVIPBinding{}, builder.WithPredicates(predicate.NewPredicateFuncs(r.isNodeBinding))). // A rule gaining, losing or changing its healthCheck changes what its // bindings on this node probe. @@ -323,9 +355,26 @@ func (r *BackendHealthReconciler) SetupWithManager(mgr ctrl.Manager) error { builder.WithPredicates(attachmentProbeTargetChanged()), ). // A probe loop's decision changed. - WatchesRawSource(source.Channel(r.events, &handler.EnqueueRequestForObject{})). - Named("backend-health"). - Complete(r) + WatchesRawSource(source.Channel(r.events, &handler.EnqueueRequestForObject{})) + if served { + // A listener backend appearing, going, changing its UID or host + // link, or starting or stopping serving changes what the bindings of + // the services naming the listener probe. + b = b.Watches(&galacticv1alpha1.EdgeListener{}, handler.EnqueueRequestsFromMapFunc( + func(ctx context.Context, obj client.Object) []ctrlreconcile.Request { + rules := listenerRuleRequests(ctx, r.Client, obj) + reqs := make([]ctrlreconcile.Request, 0, len(rules)) + for _, req := range rules { + reqs = append(reqs, r.ruleBindingRequests(ctx, &bgpv1alpha1.NetworkService{ + ObjectMeta: metav1.ObjectMeta{Namespace: req.Namespace, Name: req.Name}, + })...) + } + return reqs + }), + builder.WithPredicates(edgeListenerBackendsChanged()), + ) + } + return b.Named("backend-health").Complete(r) } // enqueue asks for a reconcile of the binding named owner, "namespace/name". diff --git a/internal/controller/listenerbackends.go b/internal/controller/listenerbackends.go new file mode 100644 index 000000000..c6da8309d --- /dev/null +++ b/internal/controller/listenerbackends.go @@ -0,0 +1,232 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package controller + +import ( + "context" + "fmt" + "net/netip" + "strings" + + "k8s.io/apimachinery/pkg/api/equality" + apimeta "k8s.io/apimachinery/pkg/api/meta" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/event" + "sigs.k8s.io/controller-runtime/pkg/predicate" + ctrlreconcile "sigs.k8s.io/controller-runtime/pkg/reconcile" + + bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" + galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" + "go.datum.net/galactic/internal/edge/listener" +) + +// listenerBackends maps each EdgeListener, by namespace and name, to the +// backends its status reports. Core decides which of them serve: an +// attachment that is programmed, ready, holding its instance lease, not past +// its drain deadline and not on a gateway node (see +// docs/edge/provider-contract.md). Gateways and routers take that decision as +// it is and never re-check the attachments. +// +// A nil map is a cluster that does not serve EdgeListener: every listener +// service is then pending. +type listenerBackends map[types.NamespacedName][]galacticv1alpha1.EdgeListenerBackend + +// edgeListenerServed reports whether mapper serves the EdgeListener kind. A +// controller registers its EdgeListener watch, and reads listeners, only +// when it does, so a gateway or router rolled out before the CRD keeps +// serving every other service. +func edgeListenerServed(mapper apimeta.RESTMapper) (bool, error) { + return listener.ListenerAPIServed(mapper) +} + +// listListenerBackends lists the EdgeListeners in namespace, the gateway +// namespace, the only one whose NetworkServices may name a listener. It +// returns nil without listing when served is false. +func listListenerBackends( + ctx context.Context, c client.Reader, namespace string, served bool, +) (listenerBackends, error) { + if !served { + return nil, nil + } + var list galacticv1alpha1.EdgeListenerList + if err := c.List(ctx, &list, client.InNamespace(namespace), client.UnsafeDisableDeepCopy); err != nil { + return nil, fmt.Errorf("list EdgeListeners in %s: %w", namespace, err) + } + out := make(listenerBackends, len(list.Items)) + for i := range list.Items { + l := &list.Items[i] + out[types.NamespacedName{Namespace: l.Namespace, Name: l.Name}] = l.Status.Backends + } + return out, nil +} + +// listenerCandidateBackends returns the backends of rule, which names an +// EdgeListener, on port: one per serving backend of that listener. A serving +// backend the datapath cannot use is pending as "namespace/name: reason". A +// backend core does not report serving is left out without a reason, unless +// no backend serves, when the listener is pending. +// +// A listener backend is a SocketAccess attachment, a veth into the provider +// pod's VRF, so its binding's egress kind is veth. Only a gateway-namespace +// service may name a listener; core writes them there, and admission keeps +// project namespaces from setting edgeListenerRef. +func listenerCandidateBackends( + rule *bgpv1alpha1.NetworkService, listeners listenerBackends, objNS string, port uint16, +) (backends []ruleBackend, pending []string) { + key := types.NamespacedName{Namespace: rule.Namespace, Name: rule.Spec.EdgeListenerRef.Name} + if ruleIsTenant(rule, objNS) { + return nil, []string{key.String() + ": only a NetworkService in " + objNS + " may name an EdgeListener"} + } + if listeners == nil { + return nil, []string{key.String() + ": the EdgeListener API is not served"} + } + status, ok := listeners[key] + if !ok { + return nil, []string{key.String() + ": EdgeListener not found"} + } + if len(status) == 0 { + return nil, []string{key.String() + ": the EdgeListener reports no backends"} + } + notServing := 0 + for i := range status { + lb := &status[i] + if !lb.Serving { + // Core reports why in the listener's status. A draining or + // unready backend is routine, so it is not pending here. + notServing++ + continue + } + b, why := listenerBackend(lb, port) + if why != "" { + pending = append(pending, lb.Attachment+": "+why) + continue + } + backends = append(backends, b) + } + if len(backends) == 0 && notServing > 0 { + pending = append(pending, fmt.Sprintf("%s: none of the EdgeListener's %d backends is serving", + key, len(status))) + } + return backends, pending +} + +// listenerBackend converts lb into a ruleBackend on port, or returns why it +// is not one: core does not report it serving, or reports it without the +// identity, node or plain IPv6 address the datapath needs. +func listenerBackend(lb *galacticv1alpha1.EdgeListenerBackend, port uint16) (ruleBackend, string) { + ns, name, ok := strings.Cut(lb.Attachment, "/") + switch { + case !lb.Serving: + return ruleBackend{}, "not serving" + case !ok || ns == "" || name == "": + return ruleBackend{}, "attachment is not namespace/name" + case lb.UID == "": + return ruleBackend{}, "no attachment UID reported yet" + case lb.Node == "": + return ruleBackend{}, "no node reported" + case lb.HostLink == "": + return ruleBackend{}, "no host link reported yet" + } + addr, err := netip.ParseAddr(lb.Address) + if err != nil || !familyIPv6.has(addr) || addr.Zone() != "" { + return ruleBackend{}, fmt.Sprintf("address %q is not a plain IPv6 address", lb.Address) + } + return ruleBackend{ + attachment: types.NamespacedName{Namespace: ns, Name: name}, + uid: types.UID(lb.UID), + node: lb.Node, + addr: addr, + port: port, + egressKind: bgpv1alpha1.ServiceVIPBindingEgressKindVeth, + }, "" +} + +// listenerBackendOnNode returns the serving backend of the listener rule +// names that is on node and holds addr, or nil when none is. +func listenerBackendOnNode( + rule *bgpv1alpha1.NetworkService, listeners listenerBackends, node string, addr netip.Addr, +) *galacticv1alpha1.EdgeListenerBackend { + key := types.NamespacedName{Namespace: rule.Namespace, Name: rule.Spec.EdgeListenerRef.Name} + for i, lb := range listeners[key] { + if lb.Node != node { + continue + } + if b, why := listenerBackend(&lb, 0); why == "" && b.addr == addr { + return &listeners[key][i] + } + } + return nil +} + +// edgeListenerBackendsChanged passes EdgeListener events that can change a +// listener service's backends: every create, delete and generic event, and +// an update only when status.backends changed. Condition and generation +// updates are dropped. +func edgeListenerBackendsChanged() predicate.Predicate { + return predicate.Funcs{ + UpdateFunc: func(e event.UpdateEvent) bool { + oldL, okOld := e.ObjectOld.(*galacticv1alpha1.EdgeListener) + newL, okNew := e.ObjectNew.(*galacticv1alpha1.EdgeListener) + if !okOld || !okNew { + return true + } + return !equality.Semantic.DeepEqual(oldL.Status.Backends, newL.Status.Backends) + }, + } +} + +// rulesNamingListener returns the NetworkServices in l's namespace whose +// edgeListenerRef names l. +func rulesNamingListener( + ctx context.Context, c client.Reader, l client.Object, +) ([]bgpv1alpha1.NetworkService, error) { + var list bgpv1alpha1.NetworkServiceList + if err := c.List(ctx, &list, client.InNamespace(l.GetNamespace())); err != nil { + return nil, err + } + var out []bgpv1alpha1.NetworkService + for i := range list.Items { + if ref := list.Items[i].Spec.EdgeListenerRef; ref != nil && ref.Name == l.GetName() { + out = append(out, list.Items[i]) + } + } + return out, nil +} + +// listenerRuleRequests returns a request for each NetworkService naming l. +func listenerRuleRequests(ctx context.Context, c client.Reader, l client.Object) []ctrlreconcile.Request { + rules, err := rulesNamingListener(ctx, c, l) + if err != nil { + return nil + } + out := make([]ctrlreconcile.Request, 0, len(rules)) + for i := range rules { + out = append(out, ctrlreconcile.Request{NamespacedName: client.ObjectKeyFromObject(&rules[i])}) + } + return out +} + +// listenerVPCRuleRequests returns a request for every NetworkService in the +// VPC of each service naming l. Rules in one VPC compete for backend claims +// (ruleBackendOwners), so a listener backend starting or stopping serving can +// give a backend to, or take one from, a rule that does not name l. +func listenerVPCRuleRequests(ctx context.Context, c client.Client, l client.Object) []ctrlreconcile.Request { + rules, err := rulesNamingListener(ctx, c, l) + if err != nil { + return nil + } + seen := map[string]bool{} + var out []ctrlreconcile.Request + for i := range rules { + vpc := rules[i].Spec.VPCRef + if seen[vpc] { + continue + } + seen[vpc] = true + out = append(out, vpcRulesRequests(ctx, c, vpc)...) + } + return out +} diff --git a/internal/controller/listenerbackends_test.go b/internal/controller/listenerbackends_test.go new file mode 100644 index 000000000..eaa517174 --- /dev/null +++ b/internal/controller/listenerbackends_test.go @@ -0,0 +1,390 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package controller + +import ( + "context" + "net/netip" + "slices" + "strings" + "testing" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/event" + + 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/healthprobe" +) + +const ( + testListenerName = "masque-public" + testEdgeNodeA = "edge-a" + // testListenerUIDA is servingListenerBackend("a", ...)'s UID. + testListenerUIDA = "uid-a" +) + +// newListenerRule returns a gateway-namespace rule in testVPCRef that names +// testListenerName in place of a BackendSelector, as core writes it. +func newListenerRule(name string, vips ...string) *bgpv1alpha1.NetworkService { + rule := newTestRule(name, testVPCRef, vips...) + rule.Spec.BackendSelector = metav1.LabelSelector{} + rule.Spec.EdgeListenerRef = &bgpv1alpha1.NetworkServiceEdgeListenerReference{Name: testListenerName} + return rule +} + +// servingListenerBackend returns a serving backend of testListenerName on +// node holding addr, with every field core reports. +func servingListenerBackend(name, node, addr string) galacticv1alpha1.EdgeListenerBackend { + return galacticv1alpha1.EdgeListenerBackend{ + Attachment: "provider/" + name, UID: "uid-" + name, Node: node, Address: addr, + HostLink: "eh-" + name, Serving: true, + } +} + +// testListeners returns listeners holding backends under testListenerName in +// testNamespace. +func testListeners(backends ...galacticv1alpha1.EdgeListenerBackend) listenerBackends { + return listenerBackends{{Namespace: testNamespace, Name: testListenerName}: backends} +} + +// TestSelectRuleBackends_EdgeListener covers a listener service: its +// backends are exactly the listener's serving backends, on the rule's +// backendPort with egress kind veth and the attachment's UID, sorted by +// address. A serving backend reported without its UID, host link, node or a +// plain IPv6 address is pending; one core does not report serving is left out +// quietly. An attachment in the rule's VPC is never selected. +func TestSelectRuleBackends_EdgeListener(t *testing.T) { + rule := newListenerRule(testRuleName, testVIP) + attachment := newBackendAttachment(testVPCRef, "fd00:10::99") + + notServing := servingListenerBackend("draining", "edge-b", "fd00:20::3") + notServing.Serving = false + noUID := servingListenerBackend("no-uid", "edge-b", "fd00:20::4") + noUID.UID = "" + noLink := servingListenerBackend("no-link", "edge-b", "fd00:20::5") + noLink.HostLink = "" + mapped := servingListenerBackend("mapped", "edge-b", "::ffff:192.0.2.1") + listeners := testListeners( + servingListenerBackend("b", "edge-b", "fd00:20::2"), + servingListenerBackend("a", testEdgeNodeA, "fd00:20::1"), + notServing, noUID, noLink, mapped, + ) + + sel, err := selectRuleBackends(rule, []*cloudv1alpha1.VPCAttachment{attachment}, listeners, nil, familyIPv6, + testNamespace) + if err != nil { + t.Fatalf("selectRuleBackends: %v", err) + } + if len(sel.backends) != 2 { + t.Fatalf("backends = %+v, want the two serving backends", sel.backends) + } + want := []ruleBackend{ + {attachment: types.NamespacedName{Namespace: "provider", Name: "a"}, uid: testListenerUIDA, node: testEdgeNodeA, + addr: netip.MustParseAddr("fd00:20::1"), port: testBackendPort, + egressKind: bgpv1alpha1.ServiceVIPBindingEgressKindVeth}, + {attachment: types.NamespacedName{Namespace: "provider", Name: "b"}, uid: "uid-b", node: "edge-b", + addr: netip.MustParseAddr("fd00:20::2"), port: testBackendPort, + egressKind: bgpv1alpha1.ServiceVIPBindingEgressKindVeth}, + } + for i := range want { + if sel.backends[i] != want[i] { + t.Errorf("backends[%d] = %+v, want %+v", i, sel.backends[i], want[i]) + } + } + joined := strings.Join(sel.pending, "\n") + if strings.Contains(joined, "provider/draining") { + t.Errorf("pending = %v names a backend core does not report serving, want it left out", sel.pending) + } + for _, w := range []string{ + "provider/no-uid: no attachment UID", + "provider/no-link: no host link", + `provider/mapped: address "::ffff:192.0.2.1" is not a plain IPv6 address`, + } { + if !strings.Contains(joined, w) { + t.Errorf("pending = %v, want %q", sel.pending, w) + } + } + if strings.Contains(joined, attachment.Name) { + t.Errorf("pending = %v names a VPCAttachment, want listener backends only", sel.pending) + } +} + +// TestSelectRuleBackends_EdgeListenerUnavailable covers a listener service +// with nothing to resolve: the API is not served, the listener does not +// exist, it reports no backends, or the service is not in the gateway +// namespace. Each selects nothing and says why. +func TestSelectRuleBackends_EdgeListenerUnavailable(t *testing.T) { + tenant := newListenerRule(testRuleName, testVIP) + tenant.Namespace = "project-a" + for _, tc := range []struct { + name string + rule *bgpv1alpha1.NetworkService + listeners listenerBackends + want string + }{ + {"not served", newListenerRule(testRuleName, testVIP), nil, "API is not served"}, + {"not found", newListenerRule(testRuleName, testVIP), listenerBackends{}, "EdgeListener not found"}, + {"no backends", newListenerRule(testRuleName, testVIP), testListeners(), "reports no backends"}, + {"none serving", newListenerRule(testRuleName, testVIP), testListeners(stoppedListenerBackend()), + "none of the EdgeListener's 1 backends is serving"}, + {"tenant", tenant, testListeners(servingListenerBackend("a", testEdgeNodeA, "fd00:20::1")), + "only a NetworkService in " + testNamespace}, + } { + t.Run(tc.name, func(t *testing.T) { + sel, err := selectRuleBackends(tc.rule, nil, tc.listeners, nil, familyIPv6, testNamespace) + if err != nil { + t.Fatalf("selectRuleBackends: %v", err) + } + if len(sel.backends) != 0 { + t.Errorf("backends = %+v, want none", sel.backends) + } + if len(sel.pending) != 1 || !strings.Contains(sel.pending[0], tc.want) { + t.Errorf("pending = %v, want %q", sel.pending, tc.want) + } + }) + } +} + +// TestRuleBackendOwners_EdgeListener covers backend ownership for listener +// services: each listener backend is claimed by the oldest service naming it, +// so the gateway and the backend's node agree on one owner. +func TestRuleBackendOwners_EdgeListener(t *testing.T) { + older := newListenerRule("older", testVIP) + older.CreationTimestamp = metav1.Unix(100, 0) + newer := newListenerRule("newer", "2001:db8:5::6") + newer.CreationTimestamp = metav1.Unix(200, 0) + listeners := testListeners(servingListenerBackend("a", testEdgeNodeA, "fd00:20::1")) + + owners := ruleBackendOwners([]bgpv1alpha1.NetworkService{*newer, *older}, nil, listeners, testNamespace) + sel, err := selectRuleBackends(newer, nil, listeners, owners, familyIPv6, testNamespace) + if err != nil { + t.Fatalf("selectRuleBackends: %v", err) + } + if len(sel.backends) != 0 || len(sel.claimed) != 1 || sel.claimed[0].owner.Name != "older" { + t.Errorf("backends = %+v, claimed = %+v, want the backend claimed by older", sel.backends, sel.claimed) + } +} + +// TestBuildDesiredRule_EdgeListener covers the gateway's whole build of a +// listener service: its serving backend resolves to its node's uSID, the +// same way an attachment's does. +func TestBuildDesiredRule_EdgeListener(t *testing.T) { + backendRouter, backendAdv, backendVRF := newBackendFixtures("vpc-1") + idx := &backendSIDIndex{ + routers: map[string]*bgpv1alpha1.BGPRouter{backendRouter.Name: backendRouter}, + advs: []*bgpv1alpha1.BGPAdvertisement{backendAdv}, + vrfInstances: map[string]*bgpv1alpha1.BGPVRFInstance{backendVRF.Name: backendVRF}, + } + listeners := testListeners(servingListenerBackend("a", testComputeNodeName, testBackendAddr)) + + dr, unresolved, _, _, err := buildDesiredRule(newListenerRule(testRuleName, testVIP), nil, listeners, + idx, nil, false, nil, healthGate{}, testNamespace) + if err != nil { + t.Fatalf("buildDesiredRule: %v", err) + } + if len(unresolved) != 0 { + t.Errorf("unresolved = %v, want none", unresolved) + } + if len(dr.Backends) != 1 || dr.Backends[0].Address != netip.MustParseAddr(testBackendAddr) { + t.Fatalf("backends = %+v, want %s", dr.Backends, testBackendAddr) + } + + // The same listener with its backend no longer serving leaves the rule + // with no backend, so it fails to build and its VIPs are not served. + listeners = testListeners(galacticv1alpha1.EdgeListenerBackend{ + Attachment: "provider/a", UID: testListenerUIDA, Node: testComputeNodeName, Address: testBackendAddr, + HostLink: "eh-a", + }) + if _, _, _, _, err := buildDesiredRule(newListenerRule(testRuleName, testVIP), nil, listeners, + idx, nil, false, nil, healthGate{}, testNamespace); err == nil { + t.Error("buildDesiredRule with no serving backend succeeded, want an error") + } +} + +// TestListenerBackendOnNode covers the health prober's lookup: only a +// serving backend on the node holding the address is found. +func TestListenerBackendOnNode(t *testing.T) { + rule := newListenerRule(testRuleName, testVIP) + stopped := servingListenerBackend("stopped", testEdgeNodeA, "fd00:20::2") + stopped.Serving = false + listeners := testListeners( + servingListenerBackend("a", testEdgeNodeA, "fd00:20::1"), + servingListenerBackend("b", "edge-b", "fd00:20::3"), + stopped, + ) + for _, tc := range []struct { + node, addr, want string + }{ + {testEdgeNodeA, "fd00:20::1", testListenerUIDA}, + {testEdgeNodeA, "fd00:20::3", ""}, + {testEdgeNodeA, "fd00:20::2", ""}, + {"edge-b", "fd00:20::3", "uid-b"}, + } { + got := listenerBackendOnNode(rule, listeners, tc.node, netip.MustParseAddr(tc.addr)) + switch { + case tc.want == "" && got != nil: + t.Errorf("node %s addr %s = %+v, want none", tc.node, tc.addr, got) + case tc.want != "" && (got == nil || got.UID != tc.want): + t.Errorf("node %s addr %s = %+v, want UID %s", tc.node, tc.addr, got, tc.want) + } + } +} + +// TestEdgeListenerBackendsChanged covers the watch predicate: only a change +// to status.backends passes an update. +func TestEdgeListenerBackendsChanged(t *testing.T) { + base := &galacticv1alpha1.EdgeListener{Status: galacticv1alpha1.EdgeListenerStatus{ + Backends: []galacticv1alpha1.EdgeListenerBackend{servingListenerBackend("a", testEdgeNodeA, "fd00:20::1")}, + }} + conditions := base.DeepCopy() + conditions.Status.Conditions = []metav1.Condition{{Type: "Programmed", Status: metav1.ConditionTrue}} + conditions.Status.ObservedGeneration = 2 + stopped := base.DeepCopy() + stopped.Status.Backends[0].Serving = false + + p := edgeListenerBackendsChanged() + if p.Update(event.UpdateEvent{ObjectOld: base, ObjectNew: conditions}) { + t.Error("a condition-only update passed, want it dropped") + } + if !p.Update(event.UpdateEvent{ObjectOld: base, ObjectNew: stopped}) { + t.Error("a backend that stopped serving was dropped, want it passed") + } + if !p.Create(event.CreateEvent{Object: base}) || !p.Delete(event.DeleteEvent{Object: base}) { + t.Error("create or delete dropped, want both passed") + } +} + +// newTestListener returns testListenerName in testNamespace reporting +// backends. +func newTestListener(backends ...galacticv1alpha1.EdgeListenerBackend) *galacticv1alpha1.EdgeListener { + return &galacticv1alpha1.EdgeListener{ + ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testListenerName}, + Status: galacticv1alpha1.EdgeListenerStatus{Backends: backends}, + } +} + +// newListenerBindingRule returns an accepted listener service as core writes +// it, with one IPv6 VIP. +func newListenerBindingRule() *bgpv1alpha1.NetworkService { + rule := newListenerRule(testRuleName, testBindingVIP) + rule.UID = "rule-uid" + acceptRule(rule) + return rule +} + +// TestNetworkServiceBindingReconciler_EdgeListener covers the router on a +// listener backend's node: it writes a veth binding for its own serving +// backend only, and removes it once core stops reporting that backend +// serving, so the node's rows follow the gateways' Maglev table. +func TestNetworkServiceBindingReconciler_EdgeListener(t *testing.T) { + l := newTestListener( + servingListenerBackend("local", testComputeNodeName, testBackendAddr), + servingListenerBackend("remote", "edge-b", "fd00:10::2"), + ) + r, c := newBindingWriter(t, newListenerBindingRule(), l) + r.Namespace = testNamespace + r.listenersServed = true + + reconcileBindings(t, r) + bindings := listBindings(t, c) + if got := backendAddresses(bindings); len(got) != 1 || got[0] != testBackendAddr { + t.Fatalf("bindings = %v, want only the local backend %s", got, testBackendAddr) + } + if bindings[0].Spec.EgressKind != bgpv1alpha1.ServiceVIPBindingEgressKindVeth || + bindings[0].Spec.VPCRef != testVPCRef || bindings[0].Spec.BackendPort != testBackendPort { + t.Errorf("binding spec = %+v, want a veth binding in %s on %d", bindings[0].Spec, testVPCRef, testBackendPort) + } + + l.Status.Backends[0].Serving = false + if err := c.Update(context.Background(), l); err != nil { + t.Fatalf("update EdgeListener: %v", err) + } + reconcileBindings(t, r) + if got := backendAddresses(listBindings(t, c)); len(got) != 0 { + t.Errorf("bindings = %v after the backend stopped serving, want none", got) + } +} + +// TestNetworkServiceBindingReconciler_EdgeListenerNotServed covers a router +// on a cluster without the EdgeListener API: a listener service gets no +// bindings, and nothing fails. +func TestNetworkServiceBindingReconciler_EdgeListenerNotServed(t *testing.T) { + r, c := newBindingWriter(t, newListenerBindingRule(), + newTestListener(servingListenerBackend("local", testComputeNodeName, testBackendAddr))) + r.Namespace = testNamespace + + reconcileBindings(t, r) + if got := backendAddresses(listBindings(t, c)); len(got) != 0 { + t.Errorf("bindings = %v, want none while EdgeListener is not served", got) + } +} + +// TestBackendHealthReconciler_EdgeListener covers the health probe of a +// listener backend: it leaves through the attachment's host link and its +// decision names the EdgeAttachment's UID, which the gateways' health gate +// compares against the backend. +func TestBackendHealthReconciler_EdgeListener(t *testing.T) { + rule := newListenerBindingRule() + rule.Spec.HealthCheck = &bgpv1alpha1.NetworkServiceHealthCheck{ + FailurePolicy: bgpv1alpha1.NetworkServiceHealthFailOpen, Port: 9443, + IntervalSeconds: 5, TimeoutSeconds: 2, UnhealthyThreshold: 3, HealthyThreshold: 3, + } + l := newTestListener(servingListenerBackend("local", testComputeNodeName, testBackendAddr)) + writer, c := newBindingWriter(t, rule, l) + writer.Namespace = testNamespace + writer.listenersServed = true + reconcileBindings(t, writer) + bindings := listBindings(t, c) + if len(bindings) != 1 { + t.Fatalf("bindings = %d, want 1", len(bindings)) + } + binding := &bindings[0] + + prober := newFakeProber(healthprobe.Decision{ + State: healthprobe.StateHealthy, Reason: healthprobe.ReasonProbeSucceeded, + }) + r := &BackendHealthReconciler{Client: c, NodeName: testComputeNodeName, Prober: prober, listenersServed: true} + reconcileHealth(t, r, binding) + + target := prober.targets[client.ObjectKeyFromObject(binding).String()] + if target.Interface != "eh-local" || target.Addr.String() != testBackendAddr || target.Port != 9443 { + t.Errorf("target = %+v, want %s port 9443 over eh-local", target, testBackendAddr) + } + if got := getHealth(t, c, binding); got == nil || got.AttachmentUID != "uid-local" { + t.Errorf("status.health = %+v, want a decision naming uid-local", got) + } +} + +// stoppedListenerBackend returns backend "a" on testEdgeNodeA, which core +// does not report serving. +func stoppedListenerBackend() galacticv1alpha1.EdgeListenerBackend { + b := servingListenerBackend("a", testEdgeNodeA, "fd00:20::1") + b.Serving = false + return b +} + +// TestListenerVPCRuleRequests covers the router's EdgeListener watch: it +// re-queues every rule in the VPC of the services naming the listener, since +// they compete for backend claims, and no rule in another VPC. +func TestListenerVPCRuleRequests(t *testing.T) { + naming := newListenerRule(testRuleName, testVIP) + competing := newTestRule("competing", testVPCRef, "2001:db8:5::6") + elsewhere := newTestRule("elsewhere", "vpc-2", "2001:db8:5::7") + _, c := newBindingWriter(t, naming, competing, elsewhere, newTestListener()) + + reqs := listenerVPCRuleRequests(context.Background(), c, newTestListener()) + got := make([]string, 0, len(reqs)) + for _, req := range reqs { + got = append(got, req.Name) + } + slices.Sort(got) + if strings.Join(got, ",") != "competing,"+testRuleName { + t.Errorf("requests = %v, want [competing %s]", got, testRuleName) + } +} diff --git a/internal/controller/networkgateway_controller.go b/internal/controller/networkgateway_controller.go index fa6c0b93c..638d4280a 100644 --- a/internal/controller/networkgateway_controller.go +++ b/internal/controller/networkgateway_controller.go @@ -35,6 +35,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/gateway" ) @@ -149,6 +150,10 @@ type NetworkGatewayReconciler struct { // now returns the current time. Nil means time.Now; tests set it to step // past ruleDrainDelay. now func() time.Time + + // listenersServed is whether the API server serves EdgeListener, set by + // SetupWithManager. While it is false every listener service is pending. + listenersServed bool } const ( @@ -516,8 +521,15 @@ func (r *NetworkGatewayReconciler) reconcileServingGateway(ctx context.Context, if err != nil { return ctrl.Result{}, err } + // A listener service takes its backends from its EdgeListener's status + // instead (listenerCandidateBackends). + listeners, err := listListenerBackends(ctx, r.Client, gw.Namespace, r.listenersServed) + if err != nil { + return ctrl.Result{}, err + } - desired, outcomes, requeueAfter, err := r.gatherRules(ctx, gw.Namespace, served, allRules, attachments, sidIndex) + desired, outcomes, requeueAfter, err := r.gatherRules(ctx, gw.Namespace, served, allRules, attachments, listeners, + sidIndex) if err != nil { return ctrl.Result{}, err } @@ -769,7 +781,7 @@ func (r *NetworkGatewayReconciler) passBindings( // long until a held rule's drain delay ends, or zero. func (r *NetworkGatewayReconciler) gatherRules( ctx context.Context, namespace string, rules, allRules []bgpv1alpha1.NetworkService, - attachments []*cloudv1alpha1.VPCAttachment, sidIndex *backendSIDIndex, + attachments []*cloudv1alpha1.VPCAttachment, listeners listenerBackends, sidIndex *backendSIDIndex, ) (gateway.EngineState, []ruleOutcome, time.Duration, error) { logger := log.FromContext(ctx) desired := gateway.EngineState{Rules: make(map[string]gateway.DesiredRule)} @@ -795,7 +807,7 @@ func (r *NetworkGatewayReconciler) gatherRules( // Every rule competes for its backends with every other rule in the // cluster, the same set each backend node's binding writer compares. - owners := ruleBackendOwners(allRules, attachments, namespace) + owners := ruleBackendOwners(allRules, attachments, listeners, namespace) vipLost := tenantVIPConflicts(allRules, namespace) byVPC := groupAttachmentsByVPC(attachments) @@ -814,7 +826,7 @@ func (r *NetworkGatewayReconciler) gatherRules( // the Programmed condition alone. Once they are gone, the drain // tracker keeps it for ruleDrainDelay so the withdrawal can reach // every peer before the datapath drops it. - o, draining, err := r.drainingOutcome(ctx, namespace, rule, byVPC[rule.Spec.VPCRef], sidIndex, owners, + o, draining, err := r.drainingOutcome(ctx, namespace, rule, byVPC[rule.Spec.VPCRef], listeners, sidIndex, owners, bindings, health) if err != nil { return desired, nil, 0, err @@ -847,8 +859,8 @@ func (r *NetworkGatewayReconciler) gatherRules( continue } - dr, unresolved, ipv4, rh, err := buildDesiredRule(rule, byVPC[rule.Spec.VPCRef], sidIndex, owners, r.IPv4VIPs, - bindings, health, namespace) + dr, unresolved, ipv4, rh, err := buildDesiredRule(rule, byVPC[rule.Spec.VPCRef], listeners, sidIndex, owners, + r.IPv4VIPs, bindings, health, namespace) if err != nil { logger.Error(err, "build desired rule; skipping", "networkRule", rule.Name) outcomes = append(outcomes, ruleOutcome{rule: rule, buildErr: err, ipv4: ipv4}) @@ -888,7 +900,8 @@ func (r *NetworkGatewayReconciler) clock() time.Time { // attachments, bindings and health are as for buildDesiredRule. func (r *NetworkGatewayReconciler) drainingOutcome( ctx context.Context, objNS string, rule *bgpv1alpha1.NetworkService, attachments []*cloudv1alpha1.VPCAttachment, - sidIndex *backendSIDIndex, owners backendOwners, bindings serviceBindings, health healthGate, + listeners listenerBackends, sidIndex *backendSIDIndex, owners backendOwners, bindings serviceBindings, + health healthGate, ) (ruleOutcome, bool, error) { if !controllerutil.ContainsFinalizer(rule, networkRuleFinalizer) { return ruleOutcome{}, false, nil @@ -902,7 +915,8 @@ func (r *NetworkGatewayReconciler) drainingOutcome( return ruleOutcome{}, false, nil } - dr, _, _, _, err := buildDesiredRule(rule, attachments, sidIndex, owners, r.IPv4VIPs, bindings, health, objNS) + dr, _, _, _, err := buildDesiredRule(rule, attachments, listeners, sidIndex, owners, r.IPv4VIPs, bindings, + health, objNS) if err != nil { var ok bool if dr, ok = r.drain.lastLoaded(rule.Namespace + "/" + rule.Name); !ok { @@ -1688,7 +1702,7 @@ func hasIPv4VIP(rule *bgpv1alpha1.NetworkService) bool { // first Bound binding is not filtered. A FailClosed rule instead leaves out a // family with no healthy backend, its IPv4 VIPs as ipv4NoHealthyBackends. func buildDesiredRule( - rule *bgpv1alpha1.NetworkService, attachments []*cloudv1alpha1.VPCAttachment, + rule *bgpv1alpha1.NetworkService, attachments []*cloudv1alpha1.VPCAttachment, listeners listenerBackends, sidIndex *backendSIDIndex, owners backendOwners, serveIPv4 bool, bindings serviceBindings, health healthGate, objNS string, ) (dr gateway.DesiredRule, unresolved []string, ipv4 ipv4Family, rh ruleHealth, err error) { @@ -1764,7 +1778,8 @@ func buildDesiredRule( if rule.Spec.HealthCheck != nil && health.apply { unhealthy = func(b ruleBackend) bool { return bindings.unhealthy(rule, objNS, vip, b) } } - fam, err := resolveFamilyBackends(rule, attachments, sidIndex, owners, f.family, objNS, unbound, unhealthy) + fam, err := resolveFamilyBackends(rule, attachments, listeners, sidIndex, owners, f.family, objNS, unbound, + unhealthy) unresolved = append(unresolved, fam.unresolved...) rh.unhealthy = append(rh.unhealthy, fam.unhealthy...) rh.noneHealthy = rh.noneHealthy || fam.noneHealthy @@ -1864,11 +1879,11 @@ type familyBackends struct { // Unhealthy, when all are kept and noneHealthy is set. It does not apply while // noneBound is set. func resolveFamilyBackends( - rule *bgpv1alpha1.NetworkService, attachments []*cloudv1alpha1.VPCAttachment, + rule *bgpv1alpha1.NetworkService, attachments []*cloudv1alpha1.VPCAttachment, listeners listenerBackends, sidIndex *backendSIDIndex, owners backendOwners, family addrFamily, objNS string, unbound func(ruleBackend) string, unhealthy func(ruleBackend) bool, ) (familyBackends, error) { - sel, err := selectRuleBackends(rule, attachments, owners, family, objNS) + sel, err := selectRuleBackends(rule, attachments, listeners, owners, family, objNS) if err != nil { return familyBackends{}, err } @@ -2192,6 +2207,11 @@ func prefixesByFamily(vips []netip.Addr) (v4, v6 []string) { // SetupWithManager registers the NetworkGatewayReconciler with the manager. func (r *NetworkGatewayReconciler) SetupWithManager(mgr ctrl.Manager) error { + served, err := edgeListenerServed(mgr.GetRESTMapper()) + if err != nil { + return err + } + r.listenersServed = served b := ctrl.NewControllerManagedBy(mgr). For(&bgpv1alpha1.NetworkGateway{}). Watches(&bgpv1alpha1.NetworkServiceAddress{}, handler.EnqueueRequestsFromMapFunc( @@ -2273,6 +2293,17 @@ func (r *NetworkGatewayReconciler) SetupWithManager(mgr ctrl.Manager) error { builder.WithPredicates(bindingReadinessChanged(true)), ) } + if r.listenersServed { + // A listener service's backends are its EdgeListener's serving + // backends, so a change to the listener's status.backends changes + // that service. Listeners live in the gateways' namespace. + b = b.Watches(&galacticv1alpha1.EdgeListener{}, handler.EnqueueRequestsFromMapFunc( + func(ctx context.Context, obj client.Object) []ctrlreconcile.Request { + return broadcastToGatewayRequests(ctx, r.Client, obj.GetNamespace(), "EdgeListener", obj.GetName()) + }), + builder.WithPredicates(edgeListenerBackendsChanged()), + ) + } if r.BackendHealth { // Health applies only while every NetworkGateway in the namespace // reports BackendHealthFiltering, so a gateway appearing, going, or diff --git a/internal/controller/networkgateway_controller_test.go b/internal/controller/networkgateway_controller_test.go index 40c88cdee..8974addf5 100644 --- a/internal/controller/networkgateway_controller_test.go +++ b/internal/controller/networkgateway_controller_test.go @@ -589,7 +589,7 @@ func TestBuildDesiredRule_BackendResolution(t *testing.T) { } rule := newTestRule(testRuleName, "vpc-1", testVIP) - dr, unresolved, _, _, err := buildDesiredRule(rule, tt.attachments, idx, nil, false, nil, healthGate{}, "") + dr, unresolved, _, _, err := buildDesiredRule(rule, tt.attachments, nil, idx, nil, false, nil, healthGate{}, "") if tt.wantErr { if err == nil { t.Fatalf("buildDesiredRule: err = nil, want an error; got %+v", dr) @@ -625,12 +625,12 @@ func TestBuildDesiredRule_RefusesSecondIPv6VIP(t *testing.T) { } attachments := []*cloudv1alpha1.VPCAttachment{newBackendAttachment("vpc-1")} rule := newTestRule(testRuleName, "vpc-1", "2001:db8:100::32", "2001:db8:100::33", testVIP4) - if _, _, _, _, err := buildDesiredRule(rule, attachments, idx, nil, false, nil, healthGate{}, ""); err == nil { + if _, _, _, _, err := buildDesiredRule(rule, attachments, nil, idx, nil, false, nil, healthGate{}, ""); err == nil { t.Fatal("buildDesiredRule: err = nil, want an error for two IPv6 VIPs") } rule.Spec.VIPAddresses = []string{"2001:db8:100::32", testVIP4} - if _, _, _, _, err := buildDesiredRule(rule, attachments, idx, nil, false, nil, healthGate{}, ""); err != nil { + if _, _, _, _, err := buildDesiredRule(rule, attachments, nil, idx, nil, false, nil, healthGate{}, ""); err != nil { t.Fatalf("buildDesiredRule with one IPv6 and one IPv4 VIP: %v", err) } } @@ -662,7 +662,7 @@ func TestGatherRules_SharedBackendServesOldestRule(t *testing.T) { } r := &NetworkGatewayReconciler{NodeName: testNodeGWA} - desired, outcomes, _, err := r.gatherRules(context.Background(), testNamespace, rules, rules, attachments, idx) + desired, outcomes, _, err := r.gatherRules(context.Background(), testNamespace, rules, rules, attachments, nil, idx) if err != nil { t.Fatalf("gatherRules: %v", err) } @@ -700,8 +700,8 @@ func TestBuildDesiredRule_SameNodeBackendsGetTheirOwnSlot(t *testing.T) { } attachments := []*cloudv1alpha1.VPCAttachment{newBackendAttachment("vpc-1", testBackendAddr, "fd00:10::2")} - dr, _, _, _, err := buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP), attachments, idx, nil, false, nil, - healthGate{}, "") + dr, _, _, _, err := buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP), attachments, nil, idx, nil, false, + nil, healthGate{}, "") if err != nil { t.Fatalf("buildDesiredRule: %v", err) } @@ -2010,7 +2010,7 @@ func TestBuildDesiredRule_CarriesSessionAffinity(t *testing.T) { } { rule := newTestRule(testRuleName, "vpc-1", testVIP) rule.Spec.SessionAffinity = affinity - dr, _, _, _, err := buildDesiredRule(rule, attachments, idx, nil, false, nil, healthGate{}, "") + dr, _, _, _, err := buildDesiredRule(rule, attachments, nil, idx, nil, false, nil, healthGate{}, "") if err != nil { t.Fatalf("affinity %q: %v", affinity, err) } diff --git a/internal/controller/networkgateway_health_test.go b/internal/controller/networkgateway_health_test.go index c06114f21..f060a0aa2 100644 --- a/internal/controller/networkgateway_health_test.go +++ b/internal/controller/networkgateway_health_test.go @@ -184,7 +184,7 @@ func TestBuildDesiredRule_Health(t *testing.T) { bindings[b.Name] = b } - dr, _, _, rh, err := buildDesiredRule(rule, []*cloudv1alpha1.VPCAttachment{newHealthAttachment()}, idx, + dr, _, _, rh, err := buildDesiredRule(rule, []*cloudv1alpha1.VPCAttachment{newHealthAttachment()}, nil, idx, nil, false, bindings, tt.gate, "") if err != nil { t.Fatalf("buildDesiredRule: %v", err) @@ -215,9 +215,9 @@ func TestBuildDesiredRule_HealthIsDeterministic(t *testing.T) { sick := healthBinding(rule, testSickAddr, decision(bgpv1alpha1.BackendHealthUnhealthy)) attachments := []*cloudv1alpha1.VPCAttachment{newHealthAttachment()} - a, _, _, _, errA := buildDesiredRule(rule, attachments, idx, nil, false, + a, _, _, _, errA := buildDesiredRule(rule, attachments, nil, idx, nil, false, serviceBindings{healthy.Name: healthy, sick.Name: sick}, healthGate{apply: true}, "") - b, _, _, _, errB := buildDesiredRule(rule, attachments, idx, nil, false, + b, _, _, _, errB := buildDesiredRule(rule, attachments, nil, idx, nil, false, serviceBindings{sick.Name: sick, healthy.Name: healthy}, healthGate{apply: true}, "") if errA != nil || errB != nil { t.Fatalf("buildDesiredRule: %v, %v", errA, errB) @@ -465,7 +465,7 @@ func TestBuildDesiredRuleFailClosedHealth(t *testing.T) { } b := healthBinding(rule, testHealthyAddr, h) dr, _, _, _, err := buildDesiredRule(rule, []*cloudv1alpha1.VPCAttachment{newHealthAttachment()}, - idx, nil, false, serviceBindings{b.Name: b}, healthGate{apply: !tc.disabled}, "") + nil, idx, nil, false, serviceBindings{b.Name: b}, healthGate{apply: !tc.disabled}, "") if tc.want { if err != nil { t.Fatal(err) diff --git a/internal/controller/networkgateway_ipv4_test.go b/internal/controller/networkgateway_ipv4_test.go index 2a165327a..f0a3f1d9c 100644 --- a/internal/controller/networkgateway_ipv4_test.go +++ b/internal/controller/networkgateway_ipv4_test.go @@ -196,7 +196,7 @@ func TestBuildDesiredRule_LeavesOutIPv4VIPs(t *testing.T) { } attachments := []*cloudv1alpha1.VPCAttachment{newBackendAttachment("vpc-1")} - dr, _, _, _, err := buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP4, testVIP), attachments, idx, nil, + dr, _, _, _, err := buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP4, testVIP), attachments, nil, idx, nil, false, nil, healthGate{}, "") if err != nil { t.Fatalf("dual-stack rule: %v", err) @@ -205,13 +205,13 @@ func TestBuildDesiredRule_LeavesOutIPv4VIPs(t *testing.T) { t.Errorf("dual-stack rule VIPs = %v, want only %s", dr.VIPAddresses, testVIP) } - _, _, _, _, err = buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP4, "198.51.100.7"), attachments, idx, + _, _, _, _, err = buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP4, "198.51.100.7"), attachments, nil, idx, nil, false, nil, healthGate{}, "") if !errors.Is(err, errNoServedVIP) { t.Errorf("IPv4-only rule: err = %v, want errNoServedVIP", err) } - _, _, _, _, err = buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP4, "not-an-ip"), attachments, idx, + _, _, _, _, err = buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP4, "not-an-ip"), attachments, nil, idx, nil, false, nil, healthGate{}, "") if err == nil || errors.Is(err, errNoServedVIP) { t.Errorf("rule with an unparseable VIP: err = %v, want a parse error", err) @@ -221,7 +221,7 @@ func TestBuildDesiredRule_LeavesOutIPv4VIPs(t *testing.T) { if !hasIPv4VIP(mapped) { t.Error("hasIPv4VIP missed an IPv4-mapped IPv6 VIP") } - dr, _, _, _, err = buildDesiredRule(mapped, attachments, idx, nil, false, nil, healthGate{}, "") + dr, _, _, _, err = buildDesiredRule(mapped, attachments, nil, idx, nil, false, nil, healthGate{}, "") if err != nil { t.Fatalf("rule with an IPv4-mapped VIP: %v", err) } @@ -265,7 +265,7 @@ func TestDrainingOutcome_WithholdsIPv4VIPs(t *testing.T) { fakeClient := newIndexedClientBuilder(scheme).WithObjects(rule, stillAdvertised).Build() r := newGatewayReconciler(fakeClient, scheme, newFakeGatewayEngine(), testNodeGWA) - o, draining, err := r.drainingOutcome(context.Background(), testNamespace, rule, attachments, idx, nil, nil, + o, draining, err := r.drainingOutcome(context.Background(), testNamespace, rule, attachments, nil, idx, nil, nil, healthGate{}) if err != nil { t.Fatalf("drainingOutcome: %v", err) @@ -290,7 +290,7 @@ func TestBuildDesiredRule_ServesIPv4WhenEnabled(t *testing.T) { attachments := []*cloudv1alpha1.VPCAttachment{newBackendAttachment("vpc-1", testBackendAddr, testBackendAddr4)} dr, unresolved, _, _, err := buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP, "::ffff:"+testVIP4), - attachments, idx, nil, true, nil, healthGate{}, "") + attachments, nil, idx, nil, true, nil, healthGate{}, "") if err != nil { t.Fatalf("dual-stack rule: %v", err) } @@ -329,8 +329,8 @@ func TestBuildDesiredRule_ServesIPv4WhenEnabled(t *testing.T) { dr.IPv4Backends[0], dr.Backends[0]) } - dr, _, _, _, err = buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP4), attachments, idx, nil, true, nil, - healthGate{}, "") + dr, _, _, _, err = buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP4), attachments, nil, idx, nil, true, + nil, healthGate{}, "") if err != nil { t.Fatalf("IPv4-only rule with IPv4 VIPs served: %v", err) } @@ -353,7 +353,7 @@ func TestBuildDesiredRule_IPv4FamilyWithoutBackends(t *testing.T) { backendClaimFor(rule, backend, familyIPv4): {Namespace: testNamespace, Name: "older-rule"}, } - dr, unresolved, ipv4, _, err := buildDesiredRule(rule, attachments, idx, owners, true, nil, healthGate{}, "") + dr, unresolved, ipv4, _, err := buildDesiredRule(rule, attachments, nil, idx, owners, true, nil, healthGate{}, "") if err != nil { t.Fatalf("dual-stack rule: %v", err) } @@ -370,7 +370,7 @@ func TestBuildDesiredRule_IPv4FamilyWithoutBackends(t *testing.T) { } ipv4Only := []*cloudv1alpha1.VPCAttachment{newBackendAttachment("vpc-1", testBackendAddr4)} - _, unresolved, ipv4, _, err = buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP4), ipv4Only, idx, nil, + _, unresolved, ipv4, _, err = buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP4), ipv4Only, nil, idx, nil, true, nil, healthGate{}, "") if err == nil || ipv4 != ipv4NoBackend { t.Errorf("IPv4-only rule over an IPv4-only attachment: err = %v, ipv4 = %d; want an error and %d", @@ -395,7 +395,7 @@ func TestBuildDesiredRule_SecondIPv4VIP(t *testing.T) { serveIPv4 bool want ipv4Family }{{true, ipv4MultipleVIPs}, {false, ipv4Off}} { - dr, _, ipv4, _, err := buildDesiredRule(rule, attachments, idx, nil, tc.serveIPv4, nil, healthGate{}, "") + dr, _, ipv4, _, err := buildDesiredRule(rule, attachments, nil, idx, nil, tc.serveIPv4, nil, healthGate{}, "") if err != nil { t.Fatalf("IPv4VIPs %v: %v", tc.serveIPv4, err) } @@ -408,7 +408,7 @@ func TestBuildDesiredRule_SecondIPv4VIP(t *testing.T) { } } - _, _, ipv4, _, err := buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP4, "198.51.100.7"), attachments, + _, _, ipv4, _, err := buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP4, "198.51.100.7"), attachments, nil, idx, nil, true, nil, healthGate{}, "") if err == nil || ipv4 != ipv4MultipleVIPs { t.Errorf("IPv4-only rule with two IPv4 VIPs: err = %v, ipv4 = %d; want an error and %d", diff --git a/internal/controller/networkservice_binding_controller.go b/internal/controller/networkservice_binding_controller.go index 40a6cf7af..0c9863fff 100644 --- a/internal/controller/networkservice_binding_controller.go +++ b/internal/controller/networkservice_binding_controller.go @@ -32,6 +32,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" ) @@ -130,6 +131,10 @@ type NetworkServiceBindingReconciler struct { // beside the BGPRouter its rows resolve against. Empty writes each // rule's bindings in the rule's own namespace. Namespace string + + // listenersServed is whether the API server serves EdgeListener, set by + // SetupWithManager. While it is false every listener service is pending. + listenersServed bool } // Reconcile converges this node's generated bindings for one NetworkService. @@ -198,8 +203,12 @@ func (r *NetworkServiceBindingReconciler) Reconcile(ctx context.Context, req ctr if err := r.List(ctx, rules); err != nil { return ctrl.Result{}, fmt.Errorf("list NetworkServices: %w", err) } - owners := ruleBackendOwners(rules.Items, attachments, r.Namespace) - desired, claimed, ipv4Err, buildErr := r.desiredBindings(rule, attachments, owners) + listeners, err := listListenerBackends(ctx, r.Client, r.Namespace, r.listenersServed) + if err != nil { + return ctrl.Result{}, err + } + owners := ruleBackendOwners(rules.Items, attachments, listeners, r.Namespace) + desired, claimed, ipv4Err, buildErr := r.desiredBindings(rule, attachments, listeners, owners) if buildErr != nil { // The spec cannot be built into bindings: a second IPv6 VIP, a // selector that does not parse, or a protocol or port the datapath @@ -251,7 +260,8 @@ func (r *NetworkServiceBindingReconciler) Reconcile(ctx context.Context, req ctr // bindings, since it invalidates the IPv4 family alone. The IPv4 VIP's // bindings are left out unless a gateway node has it loaded. func (r *NetworkServiceBindingReconciler) desiredBindings( - rule *bgpv1alpha1.NetworkService, attachments []*cloudv1alpha1.VPCAttachment, owners backendOwners, + rule *bgpv1alpha1.NetworkService, attachments []*cloudv1alpha1.VPCAttachment, listeners listenerBackends, + owners backendOwners, ) (desired []*bgpv1alpha1.ServiceVIPBinding, claimed []claimedBackend, ipv4Err, err error) { if _, _, err := rulePorts(rule); err != nil { return nil, nil, nil, err @@ -265,7 +275,7 @@ func (r *NetworkServiceBindingReconciler) desiredBindings( if tv.family == familyIPv4 && !ipv4Served { continue } - sel, err := selectRuleBackends(rule, attachments, owners, tv.family, r.Namespace) + sel, err := selectRuleBackends(rule, attachments, listeners, owners, tv.family, r.Namespace) if err != nil { return nil, nil, nil, err } @@ -601,7 +611,12 @@ func backendsBoundConditionType(node string) string { // SetupWithManager registers the NetworkServiceBindingReconciler with the manager. func (r *NetworkServiceBindingReconciler) SetupWithManager(mgr ctrl.Manager) error { r.APIReader = mgr.GetAPIReader() - return ctrl.NewControllerManagedBy(mgr). + served, err := edgeListenerServed(mgr.GetRESTMapper()) + if err != nil { + return err + } + r.listenersServed = served + b := ctrl.NewControllerManagedBy(mgr). // A rule's bindings depend on its spec and on whether it is // Accepted. Other status writes, including this reconciler's own // conditions and the gateways' Programmed conditions, change neither. @@ -659,9 +674,20 @@ func (r *NetworkServiceBindingReconciler) SetupWithManager(mgr ctrl.Manager) err func(_ context.Context, obj client.Object) []ctrlreconcile.Request { return r.bindingRuleRequests(obj) }), - ). - Named("networkservice-binding"). - Complete(r) + ) + if served { + // A listener service's backends are its EdgeListener's serving + // backends, so a change to the listener's status.backends changes + // those services and, since rules in one VPC compete for backends, + // every other rule in their VPC. + b = b.Watches(&galacticv1alpha1.EdgeListener{}, handler.EnqueueRequestsFromMapFunc( + func(ctx context.Context, obj client.Object) []ctrlreconcile.Request { + return listenerVPCRuleRequests(ctx, r.Client, obj) + }), + builder.WithPredicates(edgeListenerBackendsChanged()), + ) + } + return b.Named("networkservice-binding").Complete(r) } // ruleBindingInputsChanged passes NetworkService events that can change the diff --git a/internal/controller/networkservice_controller_test.go b/internal/controller/networkservice_controller_test.go index 11502b617..aa502d751 100644 --- a/internal/controller/networkservice_controller_test.go +++ b/internal/controller/networkservice_controller_test.go @@ -21,6 +21,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" ) @@ -85,6 +86,9 @@ func newRuleTestScheme(t *testing.T) *runtime.Scheme { if err := cloudv1alpha1.AddToScheme(scheme); err != nil { t.Fatalf("AddToScheme cloud: %v", err) } + if err := galacticv1alpha1.AddToScheme(scheme); err != nil { + t.Fatalf("AddToScheme galactic: %v", err) + } return scheme } diff --git a/internal/controller/rulebackends.go b/internal/controller/rulebackends.go index 8add2fdc8..2579e5d5c 100644 --- a/internal/controller/rulebackends.go +++ b/internal/controller/rulebackends.go @@ -25,8 +25,9 @@ import ( "go.datum.net/galactic/internal/plumbing/srv6" ) -// ruleBackend is one backend a NetworkService's BackendSelector picks: one IPv6 -// interface address of one selected VPCAttachment, on the rule's BackendPort. +// ruleBackend is one backend of a NetworkService, on the rule's BackendPort: +// one IPv6 interface address of one VPCAttachment its BackendSelector picks, +// or one serving backend of the EdgeListener it names. // Workloads are IPv6 only, so it serves the rule's VIPs of both families: its // node translates an IPv4 VIP's flows to and from IPv6. // @@ -192,10 +193,10 @@ func groupAttachmentsByVPC(attachments []*cloudv1alpha1.VPCAttachment) map[strin // // An invalid selector is a spec error and fails the rule. func selectRuleBackends( - rule *bgpv1alpha1.NetworkService, attachments []*cloudv1alpha1.VPCAttachment, owners backendOwners, - family addrFamily, objNS string, + rule *bgpv1alpha1.NetworkService, attachments []*cloudv1alpha1.VPCAttachment, listeners listenerBackends, + owners backendOwners, family addrFamily, objNS string, ) (ruleSelection, error) { - candidates, pending, err := ruleCandidateBackends(rule, attachments, objNS) + candidates, pending, err := ruleCandidateBackends(rule, attachments, listeners, objNS) if err != nil { return ruleSelection{}, err } @@ -216,20 +217,47 @@ func selectRuleBackends( // selected attachments that are not backends yet, as "namespace/name: reason". // See selectRuleBackends for which attachments qualify. // -// A rule that names an EdgeListener instead of a BackendSelector has no -// backends yet: gateways do not resolve listener attachments, so its listener -// is reported pending and its VIPs are never advertised. +// A rule that names an EdgeListener instead of a BackendSelector takes its +// backends from that listener's status in listeners +// (listenerCandidateBackends), never from attachments. func ruleCandidateBackends( - rule *bgpv1alpha1.NetworkService, attachments []*cloudv1alpha1.VPCAttachment, objNS string, + rule *bgpv1alpha1.NetworkService, attachments []*cloudv1alpha1.VPCAttachment, listeners listenerBackends, + objNS string, ) (backends []ruleBackend, pending []string, err error) { _, port, err := rulePorts(rule) if err != nil { return nil, nil, err } - if ref := rule.Spec.EdgeListenerRef; ref != nil { - key := types.NamespacedName{Namespace: rule.Namespace, Name: ref.Name} - return nil, []string{key.String() + ": edge listener backends are not resolved yet"}, nil + if rule.Spec.EdgeListenerRef != nil { + backends, pending = listenerCandidateBackends(rule, listeners, objNS, port) + } else { + backends, pending, err = selectorCandidateBackends(rule, attachments, objNS, port) + if err != nil { + return nil, nil, err + } } + + // The list order is the cache's, so sort for a stable Maglev input and a + // stable status message. Two attachments claiming one address keep their + // relative order by name. + sort.SliceStable(backends, func(i, j int) bool { + if c := backends[i].addr.Compare(backends[j].addr); c != 0 { + return c < 0 + } + return backends[i].attachment.String() < backends[j].attachment.String() + }) + backends, rejected := dropConflictingBackends(backends) + pending = append(pending, rejected...) + sort.Strings(pending) + return backends, pending, nil +} + +// selectorCandidateBackends returns, unsorted, the backends rule's +// BackendSelector picks from attachments on port, and the selected +// attachments that are not backends yet. See selectRuleBackends. +func selectorCandidateBackends( + rule *bgpv1alpha1.NetworkService, attachments []*cloudv1alpha1.VPCAttachment, objNS string, port uint16, +) (backends []ruleBackend, pending []string, err error) { selector, err := ruleBackendSelector(rule) if err != nil { return nil, nil, err @@ -264,19 +292,6 @@ func ruleCandidateBackends( }) } } - - // The list order is the cache's, so sort for a stable Maglev input and a - // stable status message. Two attachments claiming one address keep their - // relative order by name. - sort.SliceStable(backends, func(i, j int) bool { - if c := backends[i].addr.Compare(backends[j].addr); c != 0 { - return c < 0 - } - return backends[i].attachment.String() < backends[j].attachment.String() - }) - backends, rejected := dropConflictingBackends(backends) - pending = append(pending, rejected...) - sort.Strings(pending) return backends, pending, nil } @@ -380,7 +395,8 @@ func intervalsIntersect(a, endA, b, endB uint16) bool { // VIP, and a valid selector (ruleTranslatedVIPs). A rule being deleted keeps // its claims, since its bindings, and their rows, last until it is gone. func ruleBackendOwners( - rules []bgpv1alpha1.NetworkService, attachments []*cloudv1alpha1.VPCAttachment, objNS string, + rules []bgpv1alpha1.NetworkService, attachments []*cloudv1alpha1.VPCAttachment, listeners listenerBackends, + objNS string, ) backendOwners { ordered := make([]*bgpv1alpha1.NetworkService, 0, len(rules)) for i := range rules { @@ -394,7 +410,7 @@ func ruleBackendOwners( if err != nil { continue } - backends, _, err := ruleCandidateBackends(rule, attachments, objNS) + backends, _, err := ruleCandidateBackends(rule, attachments, listeners, objNS) if err != nil { continue } diff --git a/internal/controller/rulebackends_test.go b/internal/controller/rulebackends_test.go index 62a8fbcda..6d78bc3c2 100644 --- a/internal/controller/rulebackends_test.go +++ b/internal/controller/rulebackends_test.go @@ -107,7 +107,7 @@ func TestSelectRuleBackends_DropsConflictingBackends(t *testing.T) { slot := newBackendAttachment(testVPCRef, b.String()) slot.Name = "slot" - sel, err := selectRuleBackends(rule, []*cloudv1alpha1.VPCAttachment{slot, dup, first}, nil, familyIPv6, "") + sel, err := selectRuleBackends(rule, []*cloudv1alpha1.VPCAttachment{slot, dup, first}, nil, nil, familyIPv6, "") if err != nil { t.Fatalf("selectRuleBackends: %v", err) } @@ -121,29 +121,6 @@ func TestSelectRuleBackends_DropsConflictingBackends(t *testing.T) { } } -// TestSelectRuleBackends_EdgeListenerHasNoBackends covers a service that names -// an EdgeListener in place of a BackendSelector: until gateways resolve -// listener attachments it selects nothing, even an attachment in its VPC, and -// reports the listener pending rather than failing on an empty selector. -func TestSelectRuleBackends_EdgeListenerHasNoBackends(t *testing.T) { - rule := newTestRule(testRuleName, testVPCRef, testVIP) - rule.Spec.BackendSelector = metav1.LabelSelector{} - rule.Spec.EdgeListenerRef = &bgpv1alpha1.NetworkServiceEdgeListenerReference{Name: "masque-public"} - attachment := newBackendAttachment(testVPCRef, "fd00:10::1") - - sel, err := selectRuleBackends(rule, []*cloudv1alpha1.VPCAttachment{attachment}, nil, familyIPv6, "") - if err != nil { - t.Fatalf("selectRuleBackends: %v", err) - } - if len(sel.backends) != 0 || len(sel.claimed) != 0 { - t.Errorf("backends = %+v, claimed = %+v, want none", sel.backends, sel.claimed) - } - const want = "/masque-public: edge listener backends are not resolved yet" - if len(sel.pending) != 1 || !strings.Contains(sel.pending[0], want) { - t.Errorf("pending = %v, want the listener reported", sel.pending) - } -} - // newSharingRule returns a rule named name with the IPv6 VIP vip, created at // second created, selecting newBackendAttachment's attachments in testVPCRef. func newSharingRule(name, vip string, created int64) *bgpv1alpha1.NetworkService { @@ -228,7 +205,7 @@ func TestRuleBackendOwners(t *testing.T) { } attachments := []*cloudv1alpha1.VPCAttachment{newBackendAttachment(testVPCRef)} // The list order must not matter: the newer rule comes first. - owners := ruleBackendOwners([]bgpv1alpha1.NetworkService{*b, *a}, attachments, "") + owners := ruleBackendOwners([]bgpv1alpha1.NetworkService{*b, *a}, attachments, nil, "") owner := owners[backendClaimFor(a, ruleBackend{ addr: netip.MustParseAddr(testBackendAddr), port: testBackendPort, @@ -237,12 +214,12 @@ func TestRuleBackendOwners(t *testing.T) { t.Errorf("owner of rule a's backend = %q, want %q", owner.Name, tt.wantOwner) } - selB, err := selectRuleBackends(b, attachments, owners, familyIPv6, "") + selB, err := selectRuleBackends(b, attachments, nil, owners, familyIPv6, "") if err != nil { t.Fatalf("selectRuleBackends(b): %v", err) } if gotClaimed := len(selB.claimed) == 1; gotClaimed != tt.wantBClaimed { - t.Fatalf("rule b claimed = %+v, want claimed %v", selB.claimed, tt.wantBClaimed) + t.Fatalf("rule b claimed = %+v, nil, want claimed %v", selB.claimed, tt.wantBClaimed) } if tt.wantBClaimed { if len(selB.backends) != 0 { @@ -256,12 +233,12 @@ func TestRuleBackendOwners(t *testing.T) { t.Errorf("rule b backends = %+v, want its one backend", selB.backends) } - selA, err := selectRuleBackends(a, attachments, owners, familyIPv6, "") + selA, err := selectRuleBackends(a, attachments, nil, owners, familyIPv6, "") if err != nil { t.Fatalf("selectRuleBackends(a): %v", err) } if tt.wantOwner == "a" && (len(selA.backends) != 1 || len(selA.claimed) != 0) { - t.Errorf("rule a selection = %+v, want it to keep its backend", selA) + t.Errorf("rule a selection = %+v, nil, want it to keep its backend", selA) } }) } @@ -302,7 +279,7 @@ func TestAttachmentsByVPC_SelectSameBackends(t *testing.T) { for _, vpc := range []string{"vpc-blue", "vpc-green", "vpc-empty"} { t.Run(vpc, func(t *testing.T) { rule := newTestRule(testRuleName, vpc, testVIP) - want, err := selectRuleBackends(rule, all, nil, familyIPv6, "") + want, err := selectRuleBackends(rule, all, nil, nil, familyIPv6, "") if err != nil { t.Fatalf("selectRuleBackends over the full list: %v", err) } @@ -321,7 +298,7 @@ func TestAttachmentsByVPC_SelectSameBackends(t *testing.T) { "indexed list": indexed, "grouped list": byVPC[vpc], } { - got, err := selectRuleBackends(rule, candidates, nil, familyIPv6, "") + got, err := selectRuleBackends(rule, candidates, nil, nil, familyIPv6, "") if err != nil { t.Fatalf("selectRuleBackends over the %s: %v", name, err) } diff --git a/internal/controller/servicescope_test.go b/internal/controller/servicescope_test.go index 600696276..1614bb46c 100644 --- a/internal/controller/servicescope_test.go +++ b/internal/controller/servicescope_test.go @@ -195,7 +195,7 @@ func TestTenantService_BackendsOnlyFromOwnNamespace(t *testing.T) { intruder := newTestRule(testRuleName, testVPCRef, testVIP) intruder.Namespace = "intruder" - sel, err := selectRuleBackends(intruder, []*cloudv1alpha1.VPCAttachment{attachment}, nil, familyIPv6, + sel, err := selectRuleBackends(intruder, []*cloudv1alpha1.VPCAttachment{attachment}, nil, nil, familyIPv6, testNamespace) if err != nil { t.Fatalf("selectRuleBackends: %v", err) @@ -204,12 +204,12 @@ func TestTenantService_BackendsOnlyFromOwnNamespace(t *testing.T) { t.Errorf("backends = %+v, want none from another namespace", sel.backends) } if owners := ruleBackendOwners([]bgpv1alpha1.NetworkService{*intruder}, - []*cloudv1alpha1.VPCAttachment{attachment}, testNamespace); len(owners) != 0 { + []*cloudv1alpha1.VPCAttachment{attachment}, nil, testNamespace); len(owners) != 0 { t.Errorf("claims = %v, want none", owners) } own := newTenantRule(testRuleName, testVIP) - sel, err = selectRuleBackends(own, []*cloudv1alpha1.VPCAttachment{attachment}, nil, familyIPv6, testNamespace) + sel, err = selectRuleBackends(own, []*cloudv1alpha1.VPCAttachment{attachment}, nil, nil, familyIPv6, testNamespace) if err != nil { t.Fatalf("selectRuleBackends: %v", err) }