diff --git a/cmd/galactic-controller/main.go b/cmd/galactic-controller/main.go index 12a37f158..c7157e665 100644 --- a/cmd/galactic-controller/main.go +++ b/cmd/galactic-controller/main.go @@ -78,6 +78,7 @@ type options struct { edgeIngressIDs []string edgeIngressPrefix string edgeVIPPrefixes []string + edgeWithdrawDelay time.Duration } func main() { @@ -132,6 +133,10 @@ func newRootCommand() *cobra.Command { f.StringVar(&o.edgeIngressPrefix, "edge-ingress-prefix", "", "Cell role with --edge: IPv6 unique local prefix, /64 or shorter, from which each ingress gVPC takes a /64; "+ "required with --edge-ingress-identity") + f.DurationVar(&o.edgeWithdrawDelay, "edge-listener-withdraw-delay", edgelistener.DefaultWithdrawDelay, + "Cell role with --edge: how long a refused or deleted EdgeListener's backend /128s outlive its "+ + "NetworkServices, covering the gateway's drain delay plus BGP convergence; it must exceed the gateway "+ + "drain delay") f.StringSliceVar(&o.edgeVIPPrefixes, "edge-listener-vip-prefixes", nil, "Cell role with --edge: comma-separated IPv6 and IPv4 prefixes of the cell's gateway VIPs; an EdgeListener "+ "address outside them is refused with AddressOutsidePool, as is every address when none are given") @@ -238,13 +243,18 @@ func setupListeners(mgr ctrl.Manager, o *options) error { if len(identities) > 0 && !prefix.IsValid() { return errors.New("--edge-ingress-prefix is required with --edge-ingress-identity") } + if o.edgeWithdrawDelay <= edgelistener.GatewayDrainDelay { + return fmt.Errorf("--edge-listener-withdraw-delay %s must exceed the gateway drain delay %s", + o.edgeWithdrawDelay, edgelistener.GatewayDrainDelay) + } vips, err := edgelistener.ParseVIPPrefixes(o.edgeVIPPrefixes) if err != nil { return fmt.Errorf("--edge-listener-vip-prefixes: %w", err) } if err := edgelistener.Setup(mgr, edgelistener.Config{ Namespace: galactic.SystemNamespace, Identities: identities, IngressPrefix: prefix, VIPPrefixes: vips, - MaxSkew: o.edgeMaxSkew, LeaseDuration: timing.Params.Duration, Events: mgr.GetEventRecorder("galactic-controller"), + MaxSkew: o.edgeMaxSkew, LeaseDuration: timing.Params.Duration, + WithdrawDelay: o.edgeWithdrawDelay, Events: mgr.GetEventRecorder("galactic-controller"), }); err != nil { return fmt.Errorf("set up edge listeners: %w", err) } diff --git a/config/galactic-edge/controller-rbac.yaml b/config/galactic-edge/controller-rbac.yaml index 3e7326b16..b106da238 100644 --- a/config/galactic-edge/controller-rbac.yaml +++ b/config/galactic-edge/controller-rbac.yaml @@ -159,10 +159,11 @@ subjects: # Public listeners, all in the gateway namespace: one ingress gVPC per # provider holding PublicListener, created with its fabric identifier in # status and deleted once its provider may no longer hold a listener and no -# EdgeService references it, and each EdgeListener's status. Kubernetes RBAC -# cannot scope a create by name, so the Role covers every VPC in the -# namespace, though core writes only those labelled -# galactic.datumapis.com/edge-ingress. +# EdgeService references it; each EdgeListener's status and finalizer; and +# the listener's NetworkServices. Kubernetes RBAC cannot scope a create by +# name, so the Role covers every VPC and NetworkService in the namespace, +# though core writes only the VPCs labelled galactic.datumapis.com/edge-ingress +# and the NetworkServices an EdgeListener controls. apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: @@ -178,6 +179,24 @@ rules: - apiGroups: [galactic.datumapis.com] resources: [edgelisteners/status] verbs: [patch] + # The finalizer that holds a deleted listener until its NetworkServices + # and /128 advertisements are gone, and the annotation recording when its + # services went, both written by merge patch. + - apiGroups: [galactic.datumapis.com] + resources: [edgelisteners] + verbs: [patch] + # Each NetworkService's owner reference to its listener blocks the + # listener's deletion, which OwnerReferencesPermissionEnforcement allows + # only with update on the listener's finalizers. + - apiGroups: [galactic.datumapis.com] + resources: [edgelisteners/finalizers] + verbs: [update] + # One NetworkService per port of each accepted listener. The + # galactic-edge-controller-listener-services policy (policies.yaml) limits + # these writes to listener services. + - apiGroups: [galactic.datumapis.com] + resources: [networkservices] + verbs: [create, update, delete] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding diff --git a/config/galactic-edge/policies.yaml b/config/galactic-edge/policies.yaml index a08aae188..cd9c37bb8 100644 --- a/config/galactic-edge/policies.yaml +++ b/config/galactic-edge/policies.yaml @@ -469,3 +469,42 @@ metadata: spec: policyName: galactic-edge-listener-namespace validationActions: [Deny] +--- +# galactic-controller writes NetworkServices in the gateway namespace only +# for EdgeListeners: Kubernetes RBAC cannot scope its Role there by label, +# so this policy holds it to services that name a listener and carry the +# listener label, before and after the write. +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: + name: galactic-edge-controller-listener-services +spec: + failurePolicy: Fail + matchConstraints: + resourceRules: + - apiGroups: [galactic.datumapis.com] + apiVersions: ["*"] + operations: [CREATE, UPDATE, DELETE] + resources: [networkservices] + matchConditions: + - name: controller + expression: request.userInfo.username == 'system:serviceaccount:galactic-system:galactic-controller' + validations: + - expression: >- + request.operation == 'DELETE' || + (has(object.spec.edgeListenerRef) && has(object.metadata.labels) && + 'galactic.datumapis.com/edge-listener' in object.metadata.labels) + message: galactic-controller writes only NetworkServices that name an EdgeListener and carry its label + - expression: >- + request.operation == 'CREATE' || + (has(oldObject.spec.edgeListenerRef) && has(oldObject.metadata.labels) && + 'galactic.datumapis.com/edge-listener' in oldObject.metadata.labels) + message: galactic-controller changes or deletes only NetworkServices that name an EdgeListener and carry its label +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: + name: galactic-edge-controller-listener-services +spec: + policyName: galactic-edge-controller-listener-services + validationActions: [Deny] diff --git a/docs/controller/README.md b/docs/controller/README.md index de3d27a5e..c83dd4ad8 100644 --- a/docs/controller/README.md +++ b/docs/controller/README.md @@ -31,16 +31,17 @@ Logging takes `--log-level` (`LOG_LEVEL`) and the standard `--zap-*` flags; see ## Cell flags -| Flag | Default | Meaning | -| ------------------------------ | ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `--webhook-port` | `9443` | Admission webhook listener | -| `--webhook-cert-dir` | `/tmp/k8s-webhook-server/serving-certs` | Directory containing `tls.crt` and `tls.key` | -| `--controller-username` | `system:serviceaccount::galactic-controller` | Identity allowed to write the reserved default policy | -| `--edge` | `false` | Enable Edge attachment, route and public listener controllers after their CRDs and admission prerequisites are installed | -| `--edge-max-skew` | `2s` | Maximum assumed clock error; must match `galactic-edge --max-skew` | -| `--edge-ingress-identity` | none | With `--edge`: `=`, the decimal fabric VPC identity of a provider's ingress gVPC. Repeat it or separate entries with commas. A provider that holds `PublicListener` without one gets no ingress gVPC, and an Event on the `EdgeProvider` says so. An identity another VPC already holds is not recorded: the ingress gVPC reports `Ready` False with reason `IdentityInUse` | -| `--edge-ingress-prefix` | none | With `--edge`: IPv6 unique local prefix, `/64` or shorter, from which each ingress gVPC takes a `/64`. Required with `--edge-ingress-identity` | -| `--edge-listener-vip-prefixes` | none | With `--edge`: comma-separated IPv6 and IPv4 prefixes of the cell's gateway VIPs. An `EdgeListener` address outside them is refused with `AddressOutsidePool`, as is every address when none are given | +| Flag | Default | Meaning | +| -------------------------------- | ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--webhook-port` | `9443` | Admission webhook listener | +| `--webhook-cert-dir` | `/tmp/k8s-webhook-server/serving-certs` | Directory containing `tls.crt` and `tls.key` | +| `--controller-username` | `system:serviceaccount::galactic-controller` | Identity allowed to write the reserved default policy | +| `--edge` | `false` | Enable Edge attachment, route and public listener controllers after their CRDs and admission prerequisites are installed | +| `--edge-max-skew` | `2s` | Maximum assumed clock error; must match `galactic-edge --max-skew` | +| `--edge-ingress-identity` | none | With `--edge`: `=`, the decimal fabric VPC identity of a provider's ingress gVPC. Repeat it or separate entries with commas. A provider that holds `PublicListener` without one gets no ingress gVPC, and an Event on the `EdgeProvider` says so. An identity another VPC already holds is not recorded: the ingress gVPC reports `Ready` False with reason `IdentityInUse` | +| `--edge-ingress-prefix` | none | With `--edge`: IPv6 unique local prefix, `/64` or shorter, from which each ingress gVPC takes a `/64`. Required with `--edge-ingress-identity` | +| `--edge-listener-vip-prefixes` | none | With `--edge`: comma-separated IPv6 and IPv4 prefixes of the cell's gateway VIPs. An `EdgeListener` address outside them is refused with `AddressOutsidePool`, as is every address when none are given | +| `--edge-listener-withdraw-delay` | `30s` | With `--edge`: how long a refused or deleted `EdgeListener`'s backend `/128`s outlive its `NetworkService`s. It covers the gateway's drain delay (5 s) plus BGP convergence and must exceed the drain delay; the controller refuses to start otherwise | ### Installing the cell role @@ -54,6 +55,19 @@ Admission fails closed. Deploy the webhook with its serving Deployment, and keep For `--edge`, first install the Edge prerequisites in `config/galactic-edge/` and its node agent on eligible nodes. Apply the bundle's CRDs (`config/crd/`) and `config/galactic-edge/`, with its RBAC, before rolling out a controller image that serves public listeners: without the `EdgeListener` CRD the controller logs that it does not start the listener controllers and runs the rest, and without the RBAC its caches cannot sync. A deleting attachment is held until the node reports `Released` or the node is removed. See [Edge troubleshooting](../edge/troubleshooting.md) and the [provider contract](../edge/provider-contract.md) for ownership and timing requirements. +### Rolling back the cell role + +Rolling `galactic-controller` back below the version that adds the listener controllers leaves every `EdgeListener` with core's `galactic.datumapis.com/edge-listener` finalizer, which nothing then removes, so a listener deleted after the rollback stays deleting. Delete the listener's `NetworkService`s, wait until they are gone and then the withdraw delay (30 s by default) more, delete its backend `/128` advertisements, and only then clear the finalizer by hand, for example: + +```sh +kubectl -n galactic-system delete networkservices -l galactic.datumapis.com/edge-listener= +kubectl -n galactic-system delete bgpadvertisements -l galactic.datumapis.com/edge-listener= +kubectl -n galactic-system patch edgelistener --type=json \ + -p '[{"op":"remove","path":"/metadata/finalizers"}]' +``` + +The listener's ingress gVPC (`edge-ingress-`) and the `galactic-edge-controller-listener-services` policy are left in place; remove them with the bundle that added them. + ### Pod-interface injection The pod webhook admits a pod labelled `networking.datumapis.com/inject-interfaces=true` only when its controlling `Instance` has a bound `NetworkInterface` for every declared interface. Each one needs a NetworkAttachmentDefinition of the same name that belongs to that instance. The definition, its `VPCAttachment` and its `NetworkInterface` are named after the interface slot, so a replacement instance of the same name can find its predecessor's objects until garbage collection removes them. A pod wired from those objects attaches under the previous attachment identifier and is never reported `Programmed`. diff --git a/docs/designs/edge-public-listener.md b/docs/designs/edge-public-listener.md index 123eb005f..89f5eee91 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, but nothing serves a listener yet. Phase 3's unmatched-egress drop is implemented. 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. 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. This design follows the [Datum enhancement template](https://github.com/datum-cloud/enhancements/blob/main/enhancements/template/README.md). @@ -165,7 +165,7 @@ Draft PR #845 ("Allow NLB backends by address within a VPC") also changes this r ### Ingress gVPC -Core creates one gVPC per provider holding `PublicListener`, named `edge-ingress-`, in the gateway namespace, with a `/64` from a platform ULA prefix that the operator configures. The gVPC is never exported to tenants and carries no egress policy. Its canonical host VRF exists only on nodes with a listener attachment, using the same mechanism that serves edge attachments on nodes without a local workload. +Core creates one gVPC per provider holding `PublicListener`, named `edge-ingress-`, in the gateway namespace, with a `/64` from a platform ULA prefix that the operator configures. The operator also assigns each provider's fabric VPC identity (`galactic-controller --edge-ingress-identity`); a provider without one gets no gVPC, and its listeners are refused with `CapabilityNotGranted`. The gVPC is never exported to tenants and carries no egress policy. Its canonical host VRF exists only on nodes with a listener attachment, using the same mechanism that serves edge attachments on nodes without a local workload. ### Control path @@ -261,6 +261,15 @@ Limits of the proof: The feature is enabled per provider by listing `PublicListener/v1` and creating an `EdgeListener`. Deleting the `EdgeListener` withdraws the VIPs through the gateway's drain path, then removes the listener's `NetworkService`s. Rolling back the controllers leaves `EdgeListener` objects unserved and the VIPs withdrawn. Providers keep working on tenant attachments. +Rolling `galactic-controller` back below the version that adds the listener controllers leaves every `EdgeListener` with core's `galactic.datumapis.com/edge-listener` finalizer, which nothing then removes, so a listener deleted after the rollback stays deleting. Delete the listener's `NetworkService`s, wait until they are gone and then the withdraw delay (30 s by default) more, delete its backend `/128` advertisements, and only then clear the finalizer by hand, for example: + +```sh +kubectl -n galactic-system delete networkservices -l galactic.datumapis.com/edge-listener= +kubectl -n galactic-system delete bgpadvertisements -l galactic.datumapis.com/edge-listener= +kubectl -n galactic-system patch edgelistener --type=json \ + -p '[{"op":"remove","path":"/metadata/finalizers"}]' +``` + ### Rollout, Upgrade and Rollback Planning Roll out to the staging labs first, with the existing overlay left in place on a different address. Move clients by DNS. Remove the overlay only after the Phase 5 gate passes on staging. @@ -294,6 +303,7 @@ Each listener has up to 16 ports and two addresses, and each port is one `Networ - 2026-11-27: proposed, after a staging test reached MASQUE only through a hand-made `NodePort`. - 2026-11-28: open decisions settled in [#1506](https://github.com/datum-cloud/galactic/issues/1506), and listener addresses scoped to one cell. - 2026-11-28: Phase 0 proved remote delivery and the reply path, and showed local delivery failing ([#1507](https://github.com/datum-cloud/galactic/issues/1507)). +- 2026-11-28: Phase 2 core controllers implemented ([#1509](https://github.com/datum-cloud/galactic/issues/1509)). - 2026-11-28: Phase 3 added the unmatched-egress drop on listener host links ([#1510](https://github.com/datum-cloud/galactic/issues/1510)). ## Drawbacks diff --git a/docs/edge/provider-contract.md b/docs/edge/provider-contract.md index c861e428d..e942f8db5 100644 --- a/docs/edge/provider-contract.md +++ b/docs/edge/provider-contract.md @@ -124,6 +124,7 @@ A ValidatingAdmissionPolicy reads only its own parameter object, so the provider 5. A person's writes are not checked by the policy: RBAC alone decides them, so an operator can still clear an object a provider left behind. 6. A second policy holds core's own RoleBinding writes to the provider ClusterRole. Kubernetes runs no admission policy on policy bindings themselves, so core's write access to those is bounded by RBAC alone. 7. `galactic-edge-provider-listener` has one binding, whose `paramRef` selects every `EdgeProvider` with `parameterNotFoundAction: Allow`. It refuses any create, update or delete of an `EdgeListener` or `NetworkService`, or their status, by a ServiceAccount an `EdgeProvider` lists. `galactic-edge-listener-namespace` refuses an `EdgeListener`, or a `NetworkService` with `edgeListenerRef`, outside `galactic-system`, which the file fixes as the gateway namespace, so a cell that runs the gateway with another `--gateway-namespace` must edit both expressions. +8. `galactic-edge-controller-listener-services` holds core's `NetworkService` writes: core may create, update or delete only a service that names an `EdgeListener` in `spec.edgeListenerRef` and carries the `galactic.datumapis.com/edge-listener` label, and for an update or delete the existing object must carry both too. Core's Role in `galactic-system` cannot be scoped by label, so without the policy it could rewrite any service there. ### Idempotency @@ -318,6 +319,10 @@ The listener's backends, in `status.backends`, are the attachments made against 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 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 | Event | Rule | diff --git a/internal/controller/networkgateway_drain_listener_test.go b/internal/controller/networkgateway_drain_listener_test.go new file mode 100644 index 000000000..a24f256c8 --- /dev/null +++ b/internal/controller/networkgateway_drain_listener_test.go @@ -0,0 +1,25 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package controller + +import ( + "testing" + + "go.datum.net/galactic/internal/edge/listener" +) + +// TestRuleDrainDelayMatchesListener: the listener controller holds a +// listener's backend /128s past the gateway's drain delay, which it knows as +// listener.GatewayDrainDelay; the two must not drift apart. +func TestRuleDrainDelayMatchesListener(t *testing.T) { + if ruleDrainDelay != listener.GatewayDrainDelay { + t.Errorf("ruleDrainDelay = %s, listener.GatewayDrainDelay = %s; update both together", + ruleDrainDelay, listener.GatewayDrainDelay) + } + if listener.DefaultWithdrawDelay <= ruleDrainDelay { + t.Errorf("listener.DefaultWithdrawDelay %s does not exceed ruleDrainDelay %s", + listener.DefaultWithdrawDelay, ruleDrainDelay) + } +} diff --git a/internal/edge/listener/admit_test.go b/internal/edge/listener/admit_test.go index d4b29bbbf..279123e70 100644 --- a/internal/edge/listener/admit_test.go +++ b/internal/edge/listener/admit_test.go @@ -318,8 +318,8 @@ func TestProgrammed(t *testing.T) { // TestListenersAdvertisement: only an advertisement carrying the listener // label and the listener's key is the listener's to update. func TestListenersAdvertisement(t *testing.T) { - l := listenerAt("public", 1, vip6) - key := crdnames.EdgeListenerKey(gatewayNS, "public") + l := listenerAt(publicListener, 1, vip6) + key := crdnames.EdgeListenerKey(gatewayNS, publicListener) for _, tt := range []struct { name string labels map[string]string diff --git a/internal/edge/listener/doc.go b/internal/edge/listener/doc.go index c461380eb..a60e2c1ea 100644 --- a/internal/edge/listener/doc.go +++ b/internal/edge/listener/doc.go @@ -6,6 +6,7 @@ // by galactic-controller --role=cell --edge. It keeps one ingress gVPC per // provider that may hold a listener, in the gateway namespace, with a fabric // identity and a /64 the operator configures. It admits each EdgeListener, -// reports which of its listener attachments serve, and publishes the /128 -// of each serving attachment. +// reports which of its listener attachments serve, publishes the /128 of +// each serving attachment, and writes one gateway NetworkService per port of +// each accepted listener. A listener's NetworkServices go before its /128s. package listener diff --git a/internal/edge/listener/fixture_envtest_test.go b/internal/edge/listener/fixture_envtest_test.go index 176163610..ac4a36d44 100644 --- a/internal/edge/listener/fixture_envtest_test.go +++ b/internal/edge/listener/fixture_envtest_test.go @@ -10,6 +10,7 @@ import ( "os" "path/filepath" "strings" + "sync" "testing" "time" @@ -162,8 +163,9 @@ func (f *fixture) config() Config { } // run starts a manager as galactic-controller with what setup registers, -// caching leases as galactic-controller --edge does. -func (f *fixture) run(setup func(ctrl.Manager) error) { +// caching leases as galactic-controller --edge does, and returns a function +// that stops it, which the test's cleanup also calls. +func (f *fixture) run(setup func(ctrl.Manager) error) (stop func()) { t := f.t mgr, err := ctrl.NewManager(f.controllerConfig(), ctrl.Options{ Scheme: f.scheme, Metrics: metricsserver.Options{BindAddress: "0"}, @@ -180,17 +182,23 @@ func (f *fixture) run(setup func(ctrl.Manager) error) { ctx, cancel := context.WithCancel(context.Background()) done := make(chan error, 1) go func() { done <- mgr.Start(ctx) }() - t.Cleanup(func() { - cancel() - if err := <-done; err != nil { - t.Errorf("manager: %v", err) - } - }) + var once sync.Once + stop = func() { + once.Do(func() { + cancel() + if err := <-done; err != nil { + t.Errorf("manager: %v", err) + } + }) + } + t.Cleanup(stop) + return stop } -// start runs the listener controllers with cfg, recording Events. -func (f *fixture) start(cfg Config) { - f.run(func(mgr ctrl.Manager) error { +// start runs the listener controllers with cfg, recording Events, and +// returns a function that stops them. +func (f *fixture) start(cfg Config) func() { + return f.run(func(mgr ctrl.Manager) error { cfg.Events = mgr.GetEventRecorder("galactic-controller") return Setup(mgr, cfg) }) diff --git a/internal/edge/listener/isolation_envtest_test.go b/internal/edge/listener/isolation_envtest_test.go index 9322874b2..7db944dfb 100644 --- a/internal/edge/listener/isolation_envtest_test.go +++ b/internal/edge/listener/isolation_envtest_test.go @@ -21,10 +21,10 @@ import ( "go.datum.net/galactic/internal/crdnames" ) -// programmedMessage reads the listener "public"'s Programmed message. +// programmedMessage reads the listener publicListener's Programmed message. func (f *fixture) programmedMessage() string { f.t.Helper() - c := meta.FindStatusCondition(f.listener("public").Status.Conditions, galacticv1alpha1.EdgeListenerProgrammed) + c := meta.FindStatusCondition(f.listener(publicListener).Status.Conditions, galacticv1alpha1.EdgeListenerProgrammed) if c == nil { return "" } @@ -50,7 +50,7 @@ func TestListenerOtherGVPC(t *testing.T) { f.expectPublished(a, true) f.attachmentStatus(a, func(s *galacticv1alpha1.EdgeAttachmentStatus) { s.VPC = other }) f.expectPublished(a, false) - f.expectCondition("public", galacticv1alpha1.EdgeListenerProgrammed, metav1.ConditionFalse, + f.expectCondition(publicListener, galacticv1alpha1.EdgeListenerProgrammed, metav1.ConditionFalse, galacticv1alpha1.EdgeListenerReasonNoBackends) eventually(t, "Programmed to name the other gVPC", func() bool { return strings.Contains(f.programmedMessage(), "is in gVPC "+other) @@ -83,14 +83,14 @@ func TestListenerUnlabelledAdvertisementKept(t *testing.T) { // The backend stops serving, which withdraws an advertisement core owns. f.setReady(a, metav1.ConditionFalse) - f.expectCondition("public", galacticv1alpha1.EdgeListenerProgrammed, metav1.ConditionFalse, + f.expectCondition(publicListener, galacticv1alpha1.EdgeListenerProgrammed, metav1.ConditionFalse, galacticv1alpha1.EdgeListenerReasonNoBackends) never(t, "withdrew or rewrote an advertisement core does not own", func() bool { return !unchanged() }) - if err := f.admin.Delete(ctx, f.listener("public")); err != nil { + if err := f.admin.Delete(ctx, f.listener(publicListener)); err != nil { t.Fatal(err) } - eventually(t, "the listener to be gone", func() bool { return f.listener("public") == nil }) + eventually(t, "the listener to be gone", func() bool { return f.listener(publicListener) == nil }) never(t, "withdrew an advertisement core does not own with its listener", func() bool { return !unchanged() }) } @@ -124,7 +124,7 @@ func TestListenerAdvertisementNameTaken(t *testing.T) { f.get(client.ObjectKeyFromObject(foreign), &cur) return f.serving()[a.att.Name] || cur.ResourceVersion != foreign.ResourceVersion }) - f.expectCondition("public", galacticv1alpha1.EdgeListenerProgrammed, metav1.ConditionFalse, + f.expectCondition(publicListener, galacticv1alpha1.EdgeListenerProgrammed, metav1.ConditionFalse, galacticv1alpha1.EdgeListenerReasonNoBackends) eventually(t, "a BGPAdvertisementNameTaken Event", func() bool { var list eventsv1.EventList @@ -132,7 +132,7 @@ func TestListenerAdvertisementNameTaken(t *testing.T) { t.Fatal(err) } for _, e := range list.Items { - if e.Reason == ReasonAdvertisementNameTaken && e.Regarding.Name == "public" { + if e.Reason == ReasonAdvertisementNameTaken && e.Regarding.Name == publicListener { return true } } diff --git a/internal/edge/listener/lifecycle_envtest_test.go b/internal/edge/listener/lifecycle_envtest_test.go new file mode 100644 index 000000000..1f0ea1c12 --- /dev/null +++ b/internal/edge/listener/lifecycle_envtest_test.go @@ -0,0 +1,223 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package listener + +import ( + "context" + "strings" + "testing" + "time" + + eventsv1 "k8s.io/api/events/v1" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + + bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" + galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" + "go.datum.net/galactic/internal/crdnames" +) + +// acceptance reads the listener's Accepted status and reason. +func (f *fixture) acceptance(name string) (metav1.ConditionStatus, string) { + f.t.Helper() + l := f.listener(name) + if l == nil { + return "", "" + } + c := meta.FindStatusCondition(l.Status.Conditions, galacticv1alpha1.EdgeListenerAccepted) + if c == nil || c.ObservedGeneration != l.Generation { + return "", "" + } + return c.Status, c.Reason +} + +// TestListenerTakeover checks that an older listener that becomes +// admissible takes its address back from a younger accepted one, while the +// gateways still hold the younger listener's services: the older ends +// Accepted and the younger AddressClaimed, neither flaps, and once the +// younger reports AddressClaimed none of its services is live beside the +// older's. +func TestListenerTakeover(t *testing.T) { + f := startAPI(t) + f.start(f.listenerConfig()) + vpc := f.readyVPC() + grants := []string{SocketAccess, PublicListener} + f.newListener("older", "older-grant", vip6) + f.expectCondition("older", galacticv1alpha1.EdgeListenerAccepted, metav1.ConditionFalse, + galacticv1alpha1.EdgeListenerReasonCapabilityNotGranted) + nextSecond() + f.newService("younger-grant", vpc, grants, nil) + f.newListener("younger", "younger-grant", vip6) + f.expectCondition("younger", galacticv1alpha1.EdgeListenerAccepted, metav1.ConditionTrue, + galacticv1alpha1.EdgeListenerReasonAccepted) + young := []string{ServiceName("younger", galacticv1alpha1.EdgeListenerProtocolUDP, 443), + ServiceName("younger", galacticv1alpha1.EdgeListenerProtocolTCP, 443)} + old := []string{ServiceName("older", galacticv1alpha1.EdgeListenerProtocolUDP, 443), + ServiceName("older", galacticv1alpha1.EdgeListenerProtocolTCP, 443)} + eventually(t, "the younger listener's services", func() bool { + return f.netsvc(young[0]) != nil && f.netsvc(young[1]) != nil + }) + for _, n := range young { + f.holdService(n, true) + } + + // The older listener becomes admissible. + f.newService("older-grant", vpc, grants, nil) + f.expectCondition("older", galacticv1alpha1.EdgeListenerAccepted, metav1.ConditionTrue, + galacticv1alpha1.EdgeListenerReasonAccepted) + f.expectCondition("younger", galacticv1alpha1.EdgeListenerAccepted, metav1.ConditionFalse, + galacticv1alpha1.EdgeListenerReasonAddressClaimed) + eventually(t, "the younger listener's services to be torn down", func() bool { + for _, n := range young { + if s := f.netsvc(n); s == nil || s.DeletionTimestamp.IsZero() { + return false + } + } + return true + }) + settled := func() bool { + os, _ := f.acceptance("older") + ys, yr := f.acceptance("younger") + if os != metav1.ConditionTrue || ys != metav1.ConditionFalse || + yr != galacticv1alpha1.EdgeListenerReasonAddressClaimed { + return false + } + for _, n := range young { + if s := f.netsvc(n); s != nil && s.DeletionTimestamp.IsZero() { + return false + } + } + return f.netsvc(old[0]) != nil && f.netsvc(old[1]) != nil + } + eventually(t, "the older listener's services", settled) + never(t, "flapped while the gateways hold the younger services", func() bool { return !settled() }) + for _, n := range young { + f.holdService(n, false) + } + eventually(t, "the younger listener's services to go", func() bool { + return f.netsvc(young[0]) == nil && f.netsvc(young[1]) == nil + }) + never(t, "flapped once the younger services are gone", func() bool { return !settled() }) +} + +// TestListenerGoneWithServices checks that the /128 of a listener removed +// without its finalizer is withdrawn only once its NetworkServices are gone. +func TestListenerGoneWithServices(t *testing.T) { + f := startAPI(t) + ctx := context.Background() + f.start(f.listenerConfig()) + vpc := f.readyVPC() + svc := &bgpv1alpha1.NetworkService{ + ObjectMeta: metav1.ObjectMeta{Name: "removed-udp-443", Namespace: gatewayNS, + Labels: map[string]string{crdnames.LabelEdgeListener: "uid-removed"}}, + Spec: bgpv1alpha1.NetworkServiceSpec{ + VPCRef: vpc.Status.VPC, VIPAddresses: []string{vip6}, Protocol: bgpv1alpha1.NetworkServiceProtocolUDP, + Port: 443, BackendPort: 8443, EdgeListenerRef: &bgpv1alpha1.NetworkServiceEdgeListenerReference{Name: "removed"}, + HealthCheck: &bgpv1alpha1.NetworkServiceHealthCheck{Port: 8443, IntervalSeconds: 5, TimeoutSeconds: 2, + UnhealthyThreshold: 3, HealthyThreshold: 3}, + }, + } + f.create(svc) + function := bgpv1alpha1.SRv6FunctionEndDT46 + adv := &bgpv1alpha1.BGPAdvertisement{ + ObjectMeta: metav1.ObjectMeta{Name: "edge-listener-removed", Namespace: gatewayNS, + Labels: map[string]string{crdnames.LabelEdgeListener: "uid-removed", + crdnames.LabelEdgeListenerKey: crdnames.EdgeListenerKey(gatewayNS, "removed")}, + Annotations: map[string]string{crdnames.AnnotationEdgeListener: gatewayNS + "/removed"}}, + Spec: bgpv1alpha1.BGPAdvertisementSpec{ + RouterRef: bgpv1alpha1.RouterRef{Name: "router-c"}, + AddressFamily: bgpv1alpha1.AddressFamily{AFI: bgpv1alpha1.AFIL2VPN, SAFI: bgpv1alpha1.SAFIEVPN}, + Prefixes: []bgpv1alpha1.Prefix{"fd00:e1::101/128"}, + Function: &function, + }, + } + f.create(adv) + exists := func() bool { + var cur bgpv1alpha1.BGPAdvertisement + return f.get(client.ObjectKeyFromObject(adv), &cur) + } + never(t, "withdrew a gone listener's /128 while its service exists", func() bool { return !exists() }) + if err := f.admin.Delete(ctx, svc); err != nil { + t.Fatal(err) + } + eventually(t, "the gone listener's /128 to be withdrawn", func() bool { return !exists() }) +} + +// TestListenerIdempotent checks that passes over an unchanged listener write +// nothing: not its status, its services, its /128 nor its ingress gVPC. +func TestListenerIdempotent(t *testing.T) { + f := startAPI(t) + ctx := context.Background() + vpc, svc := f.acceptedListener() + f.vrf(vpc, nodeA, "router-c", 5) + a := f.newBackend("a", svc, vpc, nodeA, 1) + f.expectPublished(a, true) + f.expectCondition(publicListener, galacticv1alpha1.EdgeListenerProgrammed, metav1.ConditionTrue, + galacticv1alpha1.EdgeListenerReasonBackendsReady) + eventually(t, "a NetworkService per port", func() bool { + return f.netsvc(udp443) != nil && f.netsvc(tcp443) != nil + }) + time.Sleep(time.Second) + versions := func() []string { + return []string{f.listener(publicListener).ResourceVersion, f.netsvc(udp443).ResourceVersion, + f.netsvc(tcp443).ResourceVersion, f.advertisement(a).ResourceVersion, + f.ingressVPC(providerName).ResourceVersion} + } + before := versions() + // Touching the provider and the attachment makes the controllers decide + // the listener and the gVPC again. + for i := range 3 { + var p galacticv1alpha1.EdgeProvider + f.get(client.ObjectKey{Name: providerName}, &p) + p.Annotations = map[string]string{"example.com/touch": strings.Repeat("x", i+1)} + if err := f.admin.Update(ctx, &p); err != nil { + t.Fatal(err) + } + f.attachmentStatus(a, func(s *galacticv1alpha1.EdgeAttachmentStatus) { + s.PodVRF = "vrf" + strings.Repeat("x", i+1) + }) + time.Sleep(500 * time.Millisecond) + } + time.Sleep(2 * time.Second) + if after := versions(); strings.Join(after, ",") != strings.Join(before, ",") { + t.Errorf("an unchanged listener's objects were written: resourceVersions %v, then %v", before, after) + } +} + +// TestListenerServiceNameTaken checks that a NetworkService of one of a +// listener's names that the listener does not control is left alone, named +// in Programmed's message and recorded in an Event, while the listener's +// other services are written. +func TestListenerServiceNameTaken(t *testing.T) { + f := startAPI(t) + ctx := context.Background() + foreign := netService(gatewayNS, udp443, "2001:db8:100::77", bgpv1alpha1.NetworkServiceProtocolUDP, 443) + foreign.Spec.VPCRef = "othervpc" + foreign.Spec.BackendSelector = webSelector + f.create(&foreign) + f.acceptedListener() + eventually(t, "the listener's other service", func() bool { return f.netsvc(tcp443) != nil }) + eventually(t, "Programmed to name the foreign service", func() bool { + c := meta.FindStatusCondition(f.listener(publicListener).Status.Conditions, + galacticv1alpha1.EdgeListenerProgrammed) + return c != nil && strings.Contains(c.Message, udp443) + }) + if s := f.netsvc(udp443); s.Spec.EdgeListenerRef != nil || len(s.OwnerReferences) > 0 { + t.Errorf("the foreign NetworkService was written: %+v", s) + } + eventually(t, "a NetworkServiceNameTaken Event", func() bool { + var list eventsv1.EventList + if err := f.admin.List(ctx, &list, client.InNamespace(gatewayNS)); err != nil { + t.Fatal(err) + } + for _, e := range list.Items { + if e.Reason == ReasonServiceNameTaken && e.Regarding.Name == publicListener { + return true + } + } + return false + }) +} diff --git a/internal/edge/listener/listener_envtest_test.go b/internal/edge/listener/listener_envtest_test.go index 5033d438f..2a48f8faf 100644 --- a/internal/edge/listener/listener_envtest_test.go +++ b/internal/edge/listener/listener_envtest_test.go @@ -115,22 +115,22 @@ func TestListenerAdmission(t *testing.T) { t.Fatal(err) } platform := service(gatewayNS, "platform") - f.newListener("public", ingressSvc, vip6, vip4) - expectRefused("public", galacticv1alpha1.EdgeListenerReasonAddressClaimed) - if c := meta.FindStatusCondition(f.listener("public").Status.Conditions, accepted); !strings.Contains(c.Message, + f.newListener(publicListener, ingressSvc, vip6, vip4) + expectRefused(publicListener, galacticv1alpha1.EdgeListenerReasonAddressClaimed) + if c := meta.FindStatusCondition(f.listener(publicListener).Status.Conditions, accepted); !strings.Contains(c.Message, gatewayNS+"/platform") { t.Errorf("AddressClaimed message = %q, want the gateway-namespace service", c.Message) } if err := f.admin.Delete(ctx, platform); err != nil { t.Fatal(err) } - f.expectCondition("public", accepted, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonAccepted) + f.expectCondition(publicListener, accepted, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonAccepted) // A service created after the listener does not evict it. nextSecond() late := service(gatewayNS, "late") never(t, "a newer NetworkService evicted an accepted listener", func() bool { - c := meta.FindStatusCondition(f.listener("public").Status.Conditions, accepted) + c := meta.FindStatusCondition(f.listener(publicListener).Status.Conditions, accepted) return c == nil || c.Status != metav1.ConditionTrue }) if err := f.admin.Delete(ctx, late); err != nil { @@ -145,8 +145,8 @@ func TestListenerAdmission(t *testing.T) { expectRefused("newer", galacticv1alpha1.EdgeListenerReasonAddressClaimed) f.newListener("same-service", ingressSvc, "2001:db8:100::99") expectRefused("same-service", notGranted) - f.expectCondition("public", accepted, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonAccepted) - if err := f.admin.Delete(ctx, f.listener("public")); err != nil { + f.expectCondition(publicListener, accepted, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonAccepted) + if err := f.admin.Delete(ctx, f.listener(publicListener)); err != nil { t.Fatal(err) } f.expectCondition("newer", accepted, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonAccepted) @@ -161,13 +161,13 @@ func TestListenerBackends(t *testing.T) { f := startAPI(t) programmed := galacticv1alpha1.EdgeListenerProgrammed vpc, svc := f.acceptedListener() - f.expectCondition("public", programmed, metav1.ConditionFalse, galacticv1alpha1.EdgeListenerReasonNoBackends) + f.expectCondition(publicListener, programmed, metav1.ConditionFalse, galacticv1alpha1.EdgeListenerReasonNoBackends) // A backend serves only once its address can be published. f.vrf(vpc, nodeA, "router-a", 5) a := f.newBackend("a", svc, vpc, nodeA, 1) - f.expectCondition("public", programmed, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonBackendsReady) - l := f.listener("public") + f.expectCondition(publicListener, programmed, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonBackendsReady) + l := f.listener(publicListener) if len(l.Status.Backends) != 1 { t.Fatalf("backends = %+v, want one", l.Status.Backends) } @@ -178,12 +178,12 @@ func TestListenerBackends(t *testing.T) { // The provider clears Ready. f.setReady(a, metav1.ConditionFalse) - f.expectCondition("public", programmed, metav1.ConditionFalse, galacticv1alpha1.EdgeListenerReasonNoBackends) + f.expectCondition(publicListener, programmed, metav1.ConditionFalse, galacticv1alpha1.EdgeListenerReasonNoBackends) if f.serving()[a.att.Name] { t.Error("a backend that is not Ready is serving") } f.setReady(a, metav1.ConditionTrue) - f.expectCondition("public", programmed, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonBackendsReady) + f.expectCondition(publicListener, programmed, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonBackendsReady) // A backend on a gateway node is excluded. f.gateway(nodeB) @@ -193,22 +193,22 @@ func TestListenerBackends(t *testing.T) { return ok && !s }) f.setReady(a, metav1.ConditionFalse) - f.expectCondition("public", programmed, metav1.ConditionFalse, + f.expectCondition(publicListener, programmed, metav1.ConditionFalse, galacticv1alpha1.EdgeListenerReasonLocalBackendsExcluded) f.setReady(a, metav1.ConditionTrue) - f.expectCondition("public", programmed, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonBackendsReady) + f.expectCondition(publicListener, programmed, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonBackendsReady) // A draining backend serves until its drain deadline. f.startDrain(a, time.Now().Add(6*time.Second).Truncate(time.Second)) never(t, "stopped serving before the drain deadline", func() bool { return !f.serving()[a.att.Name] }) - f.expectCondition("public", programmed, metav1.ConditionFalse, + f.expectCondition(publicListener, programmed, metav1.ConditionFalse, galacticv1alpha1.EdgeListenerReasonLocalBackendsExcluded) // A released lease stops a backend at once. c := f.newBackend("c", svc, vpc, nodeA, 3) - f.expectCondition("public", programmed, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonBackendsReady) + f.expectCondition(publicListener, programmed, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonBackendsReady) f.releaseLease(c) - f.expectCondition("public", programmed, metav1.ConditionFalse, + f.expectCondition(publicListener, programmed, metav1.ConditionFalse, galacticv1alpha1.EdgeListenerReasonLocalBackendsExcluded) if f.serving()[c.att.Name] { t.Error("a backend whose lease is released is serving") @@ -228,9 +228,9 @@ func TestListenerLeaseExpiry(t *testing.T) { vpc := f.readyVPC() f.vrf(vpc, nodeA, "router-a", 5) svc := f.newService(ingressSvc, vpc, []string{SocketAccess, PublicListener}, nil) - f.newListener("public", ingressSvc, vip6, vip4) + f.newListener(publicListener, ingressSvc, vip6, vip4) a := f.newBackend("a", svc, vpc, nodeA, 1) - f.expectCondition("public", programmed, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonBackendsReady) + f.expectCondition(publicListener, programmed, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonBackendsReady) expiry, held, err := provider.LeaseExpiry(context.Background(), f.admin, a.inst, cfg.LeaseDuration) if err != nil || !held { t.Fatalf("lease expiry: held %t, %v", held, err) @@ -250,9 +250,9 @@ func TestListenerLeaseExpiry(t *testing.T) { t.Errorf("the backend stopped serving at %s relative to its lease expiry, want %s plus at most %s", stopped.Sub(expiry), -cfg.MaxSkew, cfg.MaxSkew/2) } - f.expectCondition("public", programmed, metav1.ConditionFalse, galacticv1alpha1.EdgeListenerReasonNoBackends) + f.expectCondition(publicListener, programmed, metav1.ConditionFalse, galacticv1alpha1.EdgeListenerReasonNoBackends) f.renewLease(a) - f.expectCondition("public", programmed, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonBackendsReady) + f.expectCondition(publicListener, programmed, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonBackendsReady) } // TestListenerBackendInstance checks that an attachment serves only on a @@ -268,7 +268,7 @@ func TestListenerBackendInstance(t *testing.T) { f.vrf(vpc, nodeA, "router-a", 5) f.vrf(vpc, "edge-3", "router-c", 7) a := f.newBackend("a", svc, vpc, nodeA, 1) - f.expectCondition("public", programmed, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonBackendsReady) + f.expectCondition(publicListener, programmed, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonBackendsReady) // A replaced pod's attachment names its successor's instance. stale := f.newAttachment("stale", a.inst, svc, vpc, nodeA, 2, func(att *galacticv1alpha1.EdgeAttachment) { diff --git a/internal/edge/listener/listener_fixture_envtest_test.go b/internal/edge/listener/listener_fixture_envtest_test.go index c694eef53..4bc358d2e 100644 --- a/internal/edge/listener/listener_fixture_envtest_test.go +++ b/internal/edge/listener/listener_fixture_envtest_test.go @@ -28,6 +28,9 @@ import ( ) const ( + // publicListener is the name of the listener most tests make. + publicListener = "public" + nodeA = "edge-1" nodeB = "edge-2" ingressSvc = "ingress" @@ -46,6 +49,8 @@ func (f *fixture) listenerConfig() Config { cfg.MaxSkew = 2 * time.Second // Fixture leases record no duration and are never renewed. cfg.LeaseDuration = time.Hour + // No gateway drains in the fixture. + cfg.WithdrawDelay = time.Second return cfg } @@ -153,12 +158,12 @@ func (f *fixture) expectCondition(name, typ string, status metav1.ConditionStatu f.t.Fatalf("listener %s %s: got %q, want %s %s", name, typ, last, status, reason) } -// serving reports each backend of the listener "public" by attachment name +// serving reports each backend of the listener publicListener by attachment name // and whether it is serving. func (f *fixture) serving() map[string]bool { f.t.Helper() out := map[string]bool{} - for _, b := range f.listener("public").Status.Backends { + for _, b := range f.listener(publicListener).Status.Backends { _, n, _ := strings.Cut(b.Attachment, "/") out[n] = b.Serving } @@ -328,15 +333,15 @@ func (f *fixture) gateway(node string) { } // acceptedListener starts the controllers and creates the accepted listener -// "public" against an ingress service, returning the ingress gVPC and the -// service. +// publicListener against an ingress service, returning the ingress gVPC and +// the service. func (f *fixture) acceptedListener() (*cloudv1alpha1.VPC, *galacticv1alpha1.EdgeService) { f.t.Helper() f.start(f.listenerConfig()) vpc := f.readyVPC() svc := f.newService(ingressSvc, vpc, []string{SocketAccess, PublicListener}, nil) - f.newListener("public", ingressSvc, vip6, vip4) - f.expectCondition("public", galacticv1alpha1.EdgeListenerAccepted, metav1.ConditionTrue, + f.newListener(publicListener, ingressSvc, vip6, vip4) + f.expectCondition(publicListener, galacticv1alpha1.EdgeListenerAccepted, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonAccepted) return vpc, svc } diff --git a/internal/edge/listener/policy_envtest_test.go b/internal/edge/listener/policy_envtest_test.go new file mode 100644 index 000000000..d85b7d561 --- /dev/null +++ b/internal/edge/listener/policy_envtest_test.go @@ -0,0 +1,84 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package listener + +import ( + "context" + "strings" + "testing" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + + bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" + "go.datum.net/galactic/internal/crdnames" +) + +// TestControllerNetworkServicePolicy checks that galactic-controller, under +// the shipped RBAC and policies, may create, update and delete a +// NetworkService in the gateway namespace only when it names an EdgeListener +// and carries the listener label, and may not touch any other. +func TestControllerNetworkServicePolicy(t *testing.T) { + f := startAPI(t) + ctx := context.Background() + core, err := client.New(f.controllerConfig(), client.Options{Scheme: f.scheme}) + if err != nil { + t.Fatal(err) + } + const refusal, listenerUID = "galactic-controller", "uid-listener" + refused := func(what string, err error) { + t.Helper() + if err == nil || !strings.Contains(err.Error(), refusal) { + t.Errorf("%s: err = %v, want a policy refusal", what, err) + } + } + plain := netService(gatewayNS, "platform", vip6, bgpv1alpha1.NetworkServiceProtocolTCP, 443) + plain.Spec.VPCRef = "platformvpc" + plain.Spec.BackendSelector = webSelector + + // The policy takes a moment to load after it is created. + eventually(t, "core's create of a non-listener service to be refused", func() bool { + attempt := plain.DeepCopy() + err := core.Create(ctx, attempt) + if err == nil { + if err := f.admin.Delete(ctx, attempt); err != nil { + t.Fatal(err) + } + return false + } + return strings.Contains(err.Error(), refusal) + }) + + // One the platform wrote is not core's to change or delete. + existing := plain.DeepCopy() + f.create(existing) + existing.Spec.Port = 8443 + refused("update of a non-listener service", core.Update(ctx, existing)) + refused("delete of a non-listener service", core.Delete(ctx, existing)) + // Nor may core turn it into a listener's. + f.get(client.ObjectKeyFromObject(existing), existing) + existing.Labels = map[string]string{crdnames.LabelEdgeListener: listenerUID} + existing.Spec.BackendSelector = metav1.LabelSelector{} + existing.Spec.EdgeListenerRef = &bgpv1alpha1.NetworkServiceEdgeListenerReference{Name: publicListener} + refused("adoption of a non-listener service", core.Update(ctx, existing)) + + // A listener's service is core's to write. + own := netService(gatewayNS, udp443, vip6, bgpv1alpha1.NetworkServiceProtocolUDP, 443) + own.Labels = map[string]string{crdnames.LabelEdgeListener: listenerUID} + own.Spec.VPCRef = "ingressvpc" + own.Spec.EdgeListenerRef = &bgpv1alpha1.NetworkServiceEdgeListenerReference{Name: publicListener} + own.Spec.HealthCheck = &bgpv1alpha1.NetworkServiceHealthCheck{Port: 8443, IntervalSeconds: 5, TimeoutSeconds: 2, + UnhealthyThreshold: 3, HealthyThreshold: 3} + if err := core.Create(ctx, &own); err != nil { + t.Fatalf("create of a listener service: %v", err) + } + own.Spec.BackendPort = 9443 + if err := core.Update(ctx, &own); err != nil { + t.Fatalf("update of a listener service: %v", err) + } + if err := core.Delete(ctx, &own); err != nil { + t.Fatalf("delete of a listener service: %v", err) + } +} diff --git a/internal/edge/listener/publish.go b/internal/edge/listener/publish.go index 8081926a5..3fb845135 100644 --- a/internal/edge/listener/publish.go +++ b/internal/edge/listener/publish.go @@ -9,6 +9,7 @@ import ( "fmt" "maps" "net/netip" + "time" "k8s.io/apimachinery/pkg/api/equality" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -23,9 +24,12 @@ import ( // publish keeps one BGPAdvertisement of the /128 of each of l's serving // backends, in the gVPC's VRF on the backend's node, so the gateways can -// resolve the backend's uSID, and withdraws every other advertisement of l. -// A backend serves only once its advertisement can be built (see backends). -func (r *Reconciler) publish(ctx context.Context, l *galacticv1alpha1.EdgeListener, backends []backend) error { +// resolve the backend's uSID, and withdraws every other advertisement of l; +// while hold is set, only those whose backend would no longer serve +// (stillServes). A backend serves only once its advertisement can be +// built (see backends). +func (r *Reconciler) publish(ctx context.Context, l *galacticv1alpha1.EdgeListener, backends []backend, + hold bool, now time.Time) error { keep := map[string]bool{} for i := range backends { b := &backends[i] @@ -37,6 +41,11 @@ func (r *Reconciler) publish(ctx context.Context, l *galacticv1alpha1.EdgeListen } keep[b.adv.Name] = true } + if hold { + return r.withdrawIf(ctx, client.ObjectKeyFromObject(l), func(adv *bgpv1alpha1.BGPAdvertisement) bool { + return !keep[adv.Name] && !r.stillServes(ctx, adv, now) + }) + } return r.withdrawIf(ctx, client.ObjectKeyFromObject(l), func(adv *bgpv1alpha1.BGPAdvertisement) bool { return !keep[adv.Name] }) @@ -175,16 +184,42 @@ func subset(want, have map[string]string) bool { // withdrawGone withdraws the advertisements of the listener named key, which // was found gone, except those of a listener recreated under its name since: -// that listener's own pass decides them. -func (r *Reconciler) withdrawGone(ctx context.Context, key client.ObjectKey) error { +// that listener's own pass decides them. A listener removed without its +// finalizer still has NetworkServices, which the garbage collector deletes +// through its owner references and the gateways hold until they have +// withdrawn its addresses; an advertisement is kept while a NetworkService +// of the listener object it was published for exists, and withdrawGone then +// reports held. +func (r *Reconciler) withdrawGone(ctx context.Context, key client.ObjectKey) (bool, error) { var l galacticv1alpha1.EdgeListener err := r.APIReader.Get(ctx, key, &l) if err != nil && !apierrors.IsNotFound(err) { - return err + return false, err } - return r.withdrawIf(ctx, key, func(adv *bgpv1alpha1.BGPAdvertisement) bool { - return err != nil || adv.Labels[crdnames.LabelEdgeListener] != string(l.UID) + gone := err != nil + held := false + services := map[string]bool{} + werr := r.withdrawIf(ctx, key, func(adv *bgpv1alpha1.BGPAdvertisement) bool { + uid := adv.Labels[crdnames.LabelEdgeListener] + if !gone && uid == string(l.UID) { + return false + } + has, seen := services[uid] + if !seen { + var list bgpv1alpha1.NetworkServiceList + if err := r.APIReader.List(ctx, &list, client.InNamespace(key.Namespace), + client.MatchingLabels{crdnames.LabelEdgeListener: uid}); err != nil { + log.FromContext(ctx).Error(err, "list NetworkServices of a gone listener; keeping its advertisement") + has = true + } else { + has = len(list.Items) > 0 + } + services[uid] = has + } + held = held || has + return !has }) + return held, werr } // listenerAdvertisements reads the advertisements of the listener named key, @@ -231,3 +266,10 @@ func (r *Reconciler) withdrawIf(ctx context.Context, key client.ObjectKey, } return nil } + +// advertisements reports whether any advertisement annotated with the +// listener named key exists. +func (r *Reconciler) advertisements(ctx context.Context, key client.ObjectKey) (bool, error) { + list, err := r.listenerAdvertisements(ctx, key) + return len(list) > 0, err +} diff --git a/internal/edge/listener/publish_envtest_test.go b/internal/edge/listener/publish_envtest_test.go index 10da04917..e6e7e3f71 100644 --- a/internal/edge/listener/publish_envtest_test.go +++ b/internal/edge/listener/publish_envtest_test.go @@ -70,15 +70,15 @@ func TestListenerPublication(t *testing.T) { vpc, svc := f.acceptedListener() a := f.newBackend("a", svc, vpc, nodeA, 1) eventually(t, "the backend to be listed", func() bool { _, ok := f.serving()[a.att.Name]; return ok }) - f.expectCondition("public", programmed, metav1.ConditionFalse, galacticv1alpha1.EdgeListenerReasonNoBackends) + f.expectCondition(publicListener, programmed, metav1.ConditionFalse, galacticv1alpha1.EdgeListenerReasonNoBackends) never(t, "served or published a backend whose VRF is missing", func() bool { return f.serving()[a.att.Name] || f.advertisement(a) != nil }) f.vrf(vpc, nodeA, "router-a", 5) f.expectPublished(a, true) - f.expectCondition("public", programmed, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonBackendsReady) + f.expectCondition(publicListener, programmed, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonBackendsReady) - l := f.listener("public") + l := f.listener(publicListener) adv := f.advertisement(a) s := adv.Spec if s.RouterRef.Name != "router-a" || s.VRFID == nil || *s.VRFID != 5 || s.Function == nil || @@ -91,9 +91,9 @@ func TestListenerPublication(t *testing.T) { if _, gated := adv.Labels[crdnames.LabelEdgeRoute]; gated || adv.Labels[crdnames.LabelEdgeListener] != string(l.UID) || adv.Labels[crdnames.LabelEdgeListenerAttachment] != string(a.att.UID) || - adv.Labels[crdnames.LabelEdgeListenerKey] != crdnames.EdgeListenerKey(gatewayNS, "public") || + adv.Labels[crdnames.LabelEdgeListenerKey] != crdnames.EdgeListenerKey(gatewayNS, publicListener) || adv.Labels[crdnames.LabelEdgeListenerVPC] != vpc.Status.VPC || - adv.Annotations[crdnames.AnnotationEdgeListener] != gatewayNS+"/public" || + adv.Annotations[crdnames.AnnotationEdgeListener] != gatewayNS+"/"+publicListener || adv.Annotations[crdnames.AnnotationEdgeListenerAttachment] != providerNS+"/"+a.att.Name { t.Errorf("advertisement labels %v, annotations %v", adv.Labels, adv.Annotations) } @@ -138,7 +138,7 @@ func TestListenerPublication(t *testing.T) { }) // Deleting the listener withdraws every /128. - if err := f.admin.Delete(ctx, f.listener("public")); err != nil { + if err := f.admin.Delete(ctx, f.listener(publicListener)); err != nil { t.Fatal(err) } f.expectPublished(b, false) @@ -183,7 +183,7 @@ func TestListenerUnpublishable(t *testing.T) { vpc, svc := f.acceptedListener() a := f.newBackend("a", svc, vpc, nodeA, 1) message := func() string { - c := meta.FindStatusCondition(f.listener("public").Status.Conditions, programmed) + c := meta.FindStatusCondition(f.listener(publicListener).Status.Conditions, programmed) if c == nil { return "" } @@ -196,7 +196,7 @@ func TestListenerUnpublishable(t *testing.T) { f.expectPublished(a, true) f.attachmentStatus(a, func(s *galacticv1alpha1.EdgeAttachmentStatus) { s.Address = "192.0.2.50" }) f.expectPublished(a, false) - f.expectCondition("public", programmed, metav1.ConditionFalse, galacticv1alpha1.EdgeListenerReasonNoBackends) + f.expectCondition(publicListener, programmed, metav1.ConditionFalse, galacticv1alpha1.EdgeListenerReasonNoBackends) eventually(t, "Programmed to name the address", func() bool { m := message() return strings.Contains(m, "plain IPv6") && !strings.Contains(m, "BGPVRFInstance") diff --git a/internal/edge/listener/reconciler.go b/internal/edge/listener/reconciler.go index abcfef8dc..721aa0b81 100644 --- a/internal/edge/listener/reconciler.go +++ b/internal/edge/listener/reconciler.go @@ -19,6 +19,7 @@ import ( "k8s.io/client-go/tools/events" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" @@ -28,11 +29,16 @@ import ( // waits for has just passed. const deadlineRetry = time.Second +// teardownRecheck bounds how long a listener waits, with no event, to see +// that its NetworkServices or advertisements are gone. +const teardownRecheck = 5 * time.Second + // defaultLeaseDuration is the foundation's lease duration, timing.Params'. const defaultLeaseDuration = 15 * time.Second -// Reconciler admits EdgeListeners, reports their backends and publishes the -// /128 of each serving backend. +// Reconciler admits EdgeListeners, reports their backends, publishes the +// /128 of each serving backend and writes each accepted listener's +// NetworkServices. // // A listener is Accepted when its provider may hold a listener, its // EdgeService grants the provider SocketAccess and PublicListener on the @@ -43,12 +49,17 @@ const defaultLeaseDuration = 15 * time.Second // instance's lease unexpired and not past its drain deadline, unless its // node runs a gateway, which cannot deliver to its own node. Each serving // backend's address is advertised into the gVPC's VRF on its node, and -// withdrawn once it stops serving or its listener is gone. +// withdrawn once it stops serving or its listener is gone. An accepted +// listener has one NetworkService per port in the gateway namespace; a +// listener refused or deleted loses them, and its /128s only once they are +// gone. type Reconciler struct { // Client reads listeners, attachments, instances, leases, services and - // gateways from the cache, and writes status. + // gateways from the cache, and writes status, finalizers, + // NetworkServices and advertisements. Client client.Client - // APIReader reads providers, EdgeServices and advertisements uncached. + // APIReader reads providers, EdgeServices, advertisements and the + // listener's own NetworkServices uncached. APIReader client.Reader // Namespace is the gateway namespace, where NetworkGateways and the // cell's BGP objects live. @@ -65,16 +76,24 @@ type Reconciler struct { // LeaseDuration is how long a renewal holds an instance lease that // records no duration of its own. Zero means defaultLeaseDuration. LeaseDuration time.Duration + // WithdrawDelay is how long a listener's /128s outlive its + // NetworkServices (withdrawHold). Zero means DefaultWithdrawDelay. + WithdrawDelay time.Duration // Now is the wall clock. Nil means time.Now. Now func() time.Time - // Events records backends whose advertisement name another object - // holds; nil records none. + // Events records listeners whose NetworkService names, or whose + // backends' advertisement names, another object holds; nil records + // none. Events events.EventRecorder } -// ReasonAdvertisementNameTaken is the reason of the Event core records on a -// listener whose backend's /128 advertisement name another object holds. -const ReasonAdvertisementNameTaken = "BGPAdvertisementNameTaken" +// Reasons of the Events core records on a listener one of whose +// NetworkService names, or one of whose backends' /128 advertisement names, +// another object holds. +const ( + ReasonServiceNameTaken = "NetworkServiceNameTaken" + ReasonAdvertisementNameTaken = "BGPAdvertisementNameTaken" +) func (r *Reconciler) now() time.Time { if r.Now != nil { @@ -100,12 +119,24 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu var l galacticv1alpha1.EdgeListener switch err := r.Client.Get(ctx, req.NamespacedName, &l); { case apierrors.IsNotFound(err): - return ctrl.Result{}, r.withdrawGone(ctx, req.NamespacedName) + held, err := r.withdrawGone(ctx, req.NamespacedName) + if held { + return ctrl.Result{RequeueAfter: teardownRecheck}, err + } + return ctrl.Result{}, err case err != nil: return ctrl.Result{}, err } if !l.DeletionTimestamp.IsZero() { - return ctrl.Result{}, nil + return r.finalize(ctx, &l) + } + if !controllerutil.ContainsFinalizer(&l, Finalizer) { + before := l.DeepCopy() + controllerutil.AddFinalizer(&l, Finalizer) + if err := r.Client.Patch(ctx, &l, + client.MergeFromWithOptions(before, client.MergeFromWithOptimisticLock{})); err != nil { + return ctrl.Result{}, fmt.Errorf("add EdgeListener %s finalizer: %w", req.NamespacedName, err) + } } now := r.now() d, err := r.decide(ctx, &l, now) @@ -118,13 +149,92 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu "%s: %s, so its address is not published", b.att.Namespace+"/"+b.att.Name, b.unpublishable) } } - if err := r.publish(ctx, &l, d.backends); err != nil { + var want []*bgpv1alpha1.NetworkService + if d.grant != nil { + want = desiredServices(&l, d.grant.vpc.Status.VPC) + } + leaving, taken, err := r.syncServices(ctx, &l, want) + if err != nil { + return ctrl.Result{}, err + } + if len(taken) > 0 { + msg := fmt.Sprintf("NetworkServices %s in %s exist and are not this listener's, so their ports are not "+ + "served", strings.Join(taken, ", "), l.Namespace) + d.programmed.Message += "; " + msg + if r.Events != nil { + r.Events.Eventf(&l, nil, corev1.EventTypeWarning, ReasonServiceNameTaken, "WriteNetworkService", "%s", msg) + } + } + // A listener no longer accepted keeps its backends' /128s until the + // gateways have let its services go and drained them (withdrawHold). + hold, wait := false, time.Duration(0) + if d.grant == nil { + if hold, wait, err = r.withdrawHold(ctx, &l, leaving, now); err != nil { + return ctrl.Result{}, err + } + } else if err := r.setServicesGone(ctx, &l, ""); err != nil { + return ctrl.Result{}, err + } + if err := r.publish(ctx, &l, d.backends, hold, now); err != nil { return ctrl.Result{}, err } if err := r.setStatus(ctx, &l, d); err != nil { return ctrl.Result{}, err } - return requeue(d.next, now), nil + res := requeue(d.next, now) + if leaving > 0 && (res.RequeueAfter == 0 || res.RequeueAfter > teardownRecheck) { + res.RequeueAfter = teardownRecheck + } + if hold && wait > 0 && (res.RequeueAfter == 0 || res.RequeueAfter > wait) { + res.RequeueAfter = wait + } + return res, nil +} + +// finalize tears a deleted listener down in order: it deletes its +// NetworkServices and waits until they are gone, which the gateways allow +// only once they have withdrawn its addresses, and then for the withdraw +// delay, while the gateways drain them (withdrawHold), withdrawing meanwhile +// only the /128s of backends that would no longer serve; then it withdraws +// every /128; then it removes its finalizer. +func (r *Reconciler) finalize(ctx context.Context, l *galacticv1alpha1.EdgeListener) (ctrl.Result, error) { + if !controllerutil.ContainsFinalizer(l, Finalizer) { + return ctrl.Result{}, nil + } + leaving, _, err := r.syncServices(ctx, l, nil) + if err != nil { + return ctrl.Result{}, err + } + key := client.ObjectKeyFromObject(l) + now := r.now() + hold, wait, err := r.withdrawHold(ctx, l, leaving, now) + if err != nil { + return ctrl.Result{}, err + } + if hold { + if err := r.withdrawIf(ctx, key, func(adv *bgpv1alpha1.BGPAdvertisement) bool { + return !r.stillServes(ctx, adv, now) + }); err != nil { + return ctrl.Result{}, err + } + return ctrl.Result{RequeueAfter: wait}, nil + } + if err := r.withdrawIf(ctx, key, func(*bgpv1alpha1.BGPAdvertisement) bool { return true }); err != nil { + return ctrl.Result{}, err + } + switch left, err := r.advertisements(ctx, key); { + case err != nil: + return ctrl.Result{}, err + case left: + return ctrl.Result{RequeueAfter: teardownRecheck}, nil + } + before := l.DeepCopy() + controllerutil.RemoveFinalizer(l, Finalizer) + if err := r.Client.Patch(ctx, l, + client.MergeFromWithOptions(before, client.MergeFromWithOptimisticLock{})); client.IgnoreNotFound(err) != nil { + return ctrl.Result{}, fmt.Errorf("remove EdgeListener %s finalizer: %w", key, err) + } + return ctrl.Result{}, nil } // decide admits l and decides its backends. diff --git a/internal/edge/listener/services.go b/internal/edge/listener/services.go new file mode 100644 index 000000000..cc9379c59 --- /dev/null +++ b/internal/edge/listener/services.go @@ -0,0 +1,213 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package listener + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "maps" + "slices" + "strconv" + "strings" + + "k8s.io/apimachinery/pkg/api/equality" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/log" + + bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" + galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" + "go.datum.net/galactic/internal/crdnames" +) + +// Finalizer holds a deleted EdgeListener until its NetworkServices are gone, +// which the gateways hold until they have withdrawn the listener's +// addresses, and then until its backends' /128s are withdrawn. +const Finalizer = "galactic.datumapis.com/edge-listener" + +// Health check timing of every listener NetworkService: the API's defaults, +// written out so a written service compares equal to the one read back. +const ( + healthInterval = 5 + healthTimeout = 2 + healthThreshold = 3 +) + +// maxServiceName is the longest name ServiceName returns, so a name fits a +// label value. +const maxServiceName = 63 + +// serviceNameHashLen is how many hex characters of the listener name's +// SHA-256 ServiceName appends when it cannot use the name as it is. +const serviceNameHashLen = 8 + +// ServiceName returns the name of the NetworkService for the port of +// protocol and number port of the listener named listener: +// "--", at most 63 characters. A listener name with +// a dot, which a label cannot hold, has its dots replaced by hyphens, and a +// name that is too long is cut; either way a hash of the listener's name is +// appended, so two listeners never share a service name. +func ServiceName(listener string, protocol galacticv1alpha1.EdgeListenerProtocol, port int32) string { + suffix := "-" + string(protocol) + "-" + strconv.Itoa(int(port)) + base := listener + if strings.Contains(base, ".") || len(base)+len(suffix) > maxServiceName { + sum := sha256.Sum256([]byte(listener)) + hash := "-" + hex.EncodeToString(sum[:])[:serviceNameHashLen] + base = strings.ReplaceAll(base, ".", "-") + if limit := maxServiceName - len(suffix) - len(hash); len(base) > limit { + base = base[:limit] + } + base = strings.TrimRight(base, "-") + hash + } + return base + suffix +} + +// healthPort is the TCP port probed on l's backends: its healthPort, or its +// first tcp port's backendPort. +func healthPort(l *galacticv1alpha1.EdgeListener) int32 { + if l.Spec.HealthPort != nil { + return *l.Spec.HealthPort + } + for _, p := range l.Spec.Ports { + if p.Protocol == galacticv1alpha1.EdgeListenerProtocolTCP { + return p.BackendPort + } + } + return 0 +} + +// desiredServices returns the NetworkServices accepted listener l needs, one +// per port, in the ingress gVPC with fabric identifier vpc. +func desiredServices(l *galacticv1alpha1.EdgeListener, vpc string) []*bgpv1alpha1.NetworkService { + affinity := bgpv1alpha1.NetworkServiceSessionAffinity(l.Spec.SessionAffinity) + if affinity == "" { + affinity = bgpv1alpha1.NetworkServiceSessionAffinityClientIPAndProtocol + } + failure := string(l.Spec.FailurePolicy) + if failure == "" { + failure = bgpv1alpha1.NetworkServiceHealthFailOpen + } + out := make([]*bgpv1alpha1.NetworkService, 0, len(l.Spec.Ports)) + for _, p := range l.Spec.Ports { + out = append(out, &bgpv1alpha1.NetworkService{ + ObjectMeta: metav1.ObjectMeta{ + Name: ServiceName(l.Name, p.Protocol, p.Port), Namespace: l.Namespace, + Labels: map[string]string{crdnames.LabelEdgeListener: string(l.UID)}, + OwnerReferences: []metav1.OwnerReference{{ + APIVersion: galacticv1alpha1.GroupVersion.String(), Kind: "EdgeListener", Name: l.Name, UID: l.UID, + Controller: ptr.To(true), BlockOwnerDeletion: ptr.To(true), + }}, + }, + Spec: bgpv1alpha1.NetworkServiceSpec{ + VPCRef: vpc, + VIPAddresses: slices.Clone(l.Spec.Addresses), + Protocol: bgpv1alpha1.NetworkServiceProtocol(p.Protocol), + Port: p.Port, + BackendPort: p.BackendPort, + SessionAffinity: affinity, + EdgeListenerRef: &bgpv1alpha1.NetworkServiceEdgeListenerReference{Name: l.Name}, + HealthCheck: &bgpv1alpha1.NetworkServiceHealthCheck{ + FailurePolicy: failure, Port: healthPort(l), IntervalSeconds: healthInterval, + TimeoutSeconds: healthTimeout, UnhealthyThreshold: healthThreshold, HealthyThreshold: healthThreshold, + }, + }, + }) + } + return out +} + +// ownedServices reads the NetworkServices l controls. +func (r *Reconciler) ownedServices(ctx context.Context, l *galacticv1alpha1.EdgeListener, +) ([]bgpv1alpha1.NetworkService, error) { + var list bgpv1alpha1.NetworkServiceList + if err := r.APIReader.List(ctx, &list, client.InNamespace(l.Namespace), + client.MatchingLabels{crdnames.LabelEdgeListener: string(l.UID)}); err != nil { + return nil, fmt.Errorf("list NetworkServices of EdgeListener %s/%s: %w", l.Namespace, l.Name, err) + } + var out []bgpv1alpha1.NetworkService + for i := range list.Items { + if metav1.IsControlledBy(&list.Items[i], l) { + out = append(out, list.Items[i]) + } + } + return out, nil +} + +// syncServices writes the NetworkServices want and deletes every other one +// l controls; want is nil when l is not accepted. A wanted name held by a +// service l does not control is left alone and returned in taken. leaving +// is how many of the services l controls that want does not hold still +// exist, being deleted. +func (r *Reconciler) syncServices(ctx context.Context, l *galacticv1alpha1.EdgeListener, + want []*bgpv1alpha1.NetworkService) (leaving int, taken []string, err error) { + owned, err := r.ownedServices(ctx, l) + if err != nil { + return 0, nil, err + } + wanted := map[string]bool{} + for _, w := range want { + wanted[w.Name] = true + switch ok, err := r.applyService(ctx, l, w); { + case err != nil: + return 0, nil, err + case !ok: + taken = append(taken, w.Name) + } + } + for i := range owned { + s := &owned[i] + if wanted[s.Name] { + continue + } + leaving++ + if !s.DeletionTimestamp.IsZero() { + continue + } + uid := s.UID + if err := r.Client.Delete(ctx, s, client.Preconditions{UID: &uid}); client.IgnoreNotFound(err) != nil { + return 0, nil, fmt.Errorf("delete NetworkService %s/%s: %w", s.Namespace, s.Name, err) + } + log.FromContext(ctx).Info("deleting listener NetworkService", "networkService", s.Name) + } + return leaving, taken, nil +} + +// applyService creates want, or updates l's service of its name to it. A +// service of that name l does not control is left alone, and applyService +// reports false. +func (r *Reconciler) applyService(ctx context.Context, l *galacticv1alpha1.EdgeListener, + want *bgpv1alpha1.NetworkService) (bool, error) { + var cur bgpv1alpha1.NetworkService + switch err := r.APIReader.Get(ctx, client.ObjectKeyFromObject(want), &cur); { + case apierrors.IsNotFound(err): + if err := r.Client.Create(ctx, want); err != nil { + return false, fmt.Errorf("create NetworkService %s/%s: %w", want.Namespace, want.Name, err) + } + log.FromContext(ctx).Info("created listener NetworkService", "networkService", want.Name) + return true, nil + case err != nil: + return false, err + case !metav1.IsControlledBy(&cur, l): + return false, nil + case !cur.DeletionTimestamp.IsZero(): + // Recreated once the gateways have let it go. + return true, nil + case equality.Semantic.DeepEqual(cur.Spec, want.Spec) && subset(want.Labels, cur.Labels): + return true, nil + } + cur.Spec = want.Spec + if cur.Labels == nil { + cur.Labels = map[string]string{} + } + maps.Copy(cur.Labels, want.Labels) + if err := r.Client.Update(ctx, &cur); err != nil { + return false, fmt.Errorf("update NetworkService %s/%s: %w", cur.Namespace, cur.Name, err) + } + return true, nil +} diff --git a/internal/edge/listener/services_envtest_test.go b/internal/edge/listener/services_envtest_test.go new file mode 100644 index 000000000..06d933ab8 --- /dev/null +++ b/internal/edge/listener/services_envtest_test.go @@ -0,0 +1,191 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package listener + +import ( + "context" + "slices" + "testing" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/util/retry" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + + bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" + galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" +) + +// gatewayFinalizer is the finalizer the gateway holds a NetworkService with +// until it has withdrawn the service's addresses. +const gatewayFinalizer = "galactic.datum.net/networkservice-teardown" + +var ( + udp443 = ServiceName(publicListener, galacticv1alpha1.EdgeListenerProtocolUDP, 443) + tcp443 = ServiceName(publicListener, galacticv1alpha1.EdgeListenerProtocolTCP, 443) +) + +// netsvc reads the named NetworkService in the gateway namespace, or nil. +func (f *fixture) netsvc(name string) *bgpv1alpha1.NetworkService { + f.t.Helper() + var s bgpv1alpha1.NetworkService + if !f.get(client.ObjectKey{Namespace: gatewayNS, Name: name}, &s) { + return nil + } + return &s +} + +// updateListener changes the listener named name with mutate. +func (f *fixture) updateListener(name string, mutate func(*galacticv1alpha1.EdgeListener)) { + f.t.Helper() + if err := retry.RetryOnConflict(retry.DefaultRetry, func() error { + l := f.listener(name) + mutate(l) + return f.admin.Update(context.Background(), l) + }); err != nil { + f.t.Fatal(err) + } +} + +// holdService adds or removes the gateway's finalizer on the named +// NetworkService, as galactic-gateway does. +func (f *fixture) holdService(name string, hold bool) { + f.t.Helper() + if err := retry.RetryOnConflict(retry.DefaultRetry, func() error { + s := f.netsvc(name) + if s == nil { + return nil + } + if hold { + controllerutil.AddFinalizer(s, gatewayFinalizer) + } else { + controllerutil.RemoveFinalizer(s, gatewayFinalizer) + } + return f.admin.Update(context.Background(), s) + }); err != nil { + f.t.Fatal(err) + } +} + +// TestListenerServices checks that core writes one NetworkService per port +// of an accepted listener, with the listener's addresses, ports, affinity +// and health check in the ingress gVPC, follows the listener's changes, +// deletes the service of a port no longer listed, and deletes every service +// of a listener no longer accepted. +func TestListenerServices(t *testing.T) { + f := startAPI(t) + vpc, _ := f.acceptedListener() + l := f.listener(publicListener) + eventually(t, "a NetworkService per port", func() bool { + return f.netsvc(udp443) != nil && f.netsvc(tcp443) != nil + }) + if !controllerutil.ContainsFinalizer(l, Finalizer) { + t.Errorf("listener finalizers = %v, want %s", l.Finalizers, Finalizer) + } + for name, port := range map[string]galacticv1alpha1.EdgeListenerPort{ + udp443: {Protocol: galacticv1alpha1.EdgeListenerProtocolUDP, Port: 443, BackendPort: 8443}, + tcp443: {Protocol: galacticv1alpha1.EdgeListenerProtocolTCP, Port: 443, BackendPort: 8443}, + } { + s := f.netsvc(name) + sp := s.Spec + if sp.VPCRef != vpc.Status.VPC || !slices.Equal(sp.VIPAddresses, []string{vip6, vip4}) || + string(sp.Protocol) != string(port.Protocol) || sp.Port != port.Port || + sp.BackendPort != port.BackendPort || + sp.SessionAffinity != bgpv1alpha1.NetworkServiceSessionAffinityClientIPAndProtocol || + sp.EdgeListenerRef == nil || sp.EdgeListenerRef.Name != publicListener || len(sp.BackendSelector.MatchLabels) > 0 { + t.Errorf("NetworkService %s spec = %+v", name, sp) + } + hc := sp.HealthCheck + if hc == nil || hc.Port != 8443 || hc.FailurePolicy != bgpv1alpha1.NetworkServiceHealthFailOpen { + t.Errorf("NetworkService %s health check = %+v", name, sp.HealthCheck) + } + if !metav1.IsControlledBy(s, l) { + t.Errorf("NetworkService %s owners = %+v", name, s.OwnerReferences) + } + } + + // A port removed, and the health check and affinity changed. + f.updateListener(publicListener, func(l *galacticv1alpha1.EdgeListener) { + l.Spec.Ports = l.Spec.Ports[1:] + l.Spec.HealthPort = ptr.To[int32](9000) + l.Spec.FailurePolicy = galacticv1alpha1.EdgeListenerFailClosed + l.Spec.SessionAffinity = galacticv1alpha1.EdgeListenerSessionAffinityClientIP + }) + eventually(t, "the removed port's NetworkService to go and the other to follow", func() bool { + s := f.netsvc(tcp443) + return f.netsvc(udp443) == nil && s != nil && s.Spec.HealthCheck.Port == 9000 && + s.Spec.HealthCheck.FailurePolicy == bgpv1alpha1.NetworkServiceHealthFailClosed && + s.Spec.SessionAffinity == bgpv1alpha1.NetworkServiceSessionAffinityClientIP + }) + + // A listener no longer accepted loses its services, and gets them back + // once accepted again. + f.setApproved(providerName, false) + f.expectCondition(publicListener, galacticv1alpha1.EdgeListenerAccepted, metav1.ConditionFalse, + galacticv1alpha1.EdgeListenerReasonProviderNotApproved) + eventually(t, "a refused listener's NetworkService to go", func() bool { return f.netsvc(tcp443) == nil }) + f.setApproved(providerName, true) + eventually(t, "the NetworkService to return", func() bool { return f.netsvc(tcp443) != nil }) +} + +// TestListenerDeletionOrder checks that a listener's /128s outlive its +// NetworkServices, which the gateway holds until it has withdrawn their +// addresses: when the listener is refused, and when it is deleted, in which +// case its finalizer goes only once both are gone. +func TestListenerDeletionOrder(t *testing.T) { + f := startAPI(t) + ctx := context.Background() + vpc, svc := f.acceptedListener() + f.vrf(vpc, nodeA, "router-a", 5) + a := f.newBackend("a", svc, vpc, nodeA, 1) + f.expectPublished(a, true) + eventually(t, "a NetworkService per port", func() bool { + return f.netsvc(udp443) != nil && f.netsvc(tcp443) != nil + }) + hold := func(on bool) { + for _, n := range []string{udp443, tcp443} { + f.holdService(n, on) + } + } + + // Refused: the services go first, then the /128. + hold(true) + f.setApproved(providerName, false) + eventually(t, "the services to be deleting", func() bool { + s := f.netsvc(udp443) + return s != nil && !s.DeletionTimestamp.IsZero() + }) + never(t, "withdrew the /128 while the services exist", func() bool { return f.advertisement(a) == nil }) + hold(false) + f.expectPublished(a, false) + + // Deleted: the same order, and the finalizer last. + f.setApproved(providerName, true) + f.expectPublished(a, true) + eventually(t, "the services to return", func() bool { + s, u := f.netsvc(tcp443), f.netsvc(udp443) + return s != nil && u != nil && s.DeletionTimestamp.IsZero() && u.DeletionTimestamp.IsZero() + }) + hold(true) + if err := f.admin.Delete(ctx, f.listener(publicListener)); err != nil { + t.Fatal(err) + } + eventually(t, "the services to be deleting", func() bool { + s := f.netsvc(tcp443) + return s != nil && !s.DeletionTimestamp.IsZero() + }) + never(t, "withdrew the /128 or released the listener while the services exist", func() bool { + return f.advertisement(a) == nil || f.listener(publicListener) == nil + }) + hold(false) + eventually(t, "the listener to be released", func() bool { + gone := f.listener(publicListener) == nil + if gone && (f.advertisement(a) != nil || f.netsvc(udp443) != nil || f.netsvc(tcp443) != nil) { + t.Fatal("the listener's finalizer went before its services and /128s") + } + return gone + }) +} diff --git a/internal/edge/listener/services_test.go b/internal/edge/listener/services_test.go new file mode 100644 index 000000000..fe3c0bfe0 --- /dev/null +++ b/internal/edge/listener/services_test.go @@ -0,0 +1,101 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package listener + +import ( + "slices" + "strings" + "testing" + + "k8s.io/apimachinery/pkg/util/validation" + "k8s.io/utils/ptr" + + bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" + galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" +) + +func TestServiceName(t *testing.T) { + udp, tcp := galacticv1alpha1.EdgeListenerProtocolUDP, galacticv1alpha1.EdgeListenerProtocolTCP + long := strings.Repeat("a", 100) + tests := []struct { + name string + listener string + protocol galacticv1alpha1.EdgeListenerProtocol + port int32 + want string + }{ + {"Plain", publicListener, udp, 443, "public-udp-443"}, + {"OtherProtocol", publicListener, tcp, 443, "public-tcp-443"}, + {"Dotted", "public.example", udp, 443, ""}, + {"Long", long, udp, 65535, ""}, + } + seen := map[string]bool{} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := ServiceName(tt.listener, tt.protocol, tt.port) + if tt.want != "" && got != tt.want { + t.Errorf("ServiceName(%q) = %q, want %q", tt.listener, got, tt.want) + } + if errs := validation.IsDNS1123Label(got); len(errs) > 0 { + t.Errorf("ServiceName(%q) = %q is not a DNS-1123 label: %v", tt.listener, got, errs) + } + if !strings.Contains(got, "-"+string(tt.protocol)+"-") { + t.Errorf("ServiceName(%q) = %q does not name its protocol", tt.listener, got) + } + if seen[got] { + t.Errorf("ServiceName(%q) = %q is not unique", tt.listener, got) + } + seen[got] = true + }) + } + // Names that map to the same characters stay distinct. + if ServiceName("a.b", udp, 443) == ServiceName("a-b", udp, 443) { + t.Error("a dotted listener name collides with its hyphenated form") + } + if ServiceName(long+"x", udp, 443) == ServiceName(long+"y", udp, 443) { + t.Error("two long listener names sharing a prefix collide") + } +} + +func TestDesiredServices(t *testing.T) { + l := listenerAt(publicListener, 1, vip6, vip4) + l.UID = "uid-public" + svcs := desiredServices(&l, "vpc1") + if len(svcs) != 2 { + t.Fatalf("desiredServices = %d services, want one per port", len(svcs)) + } + for i, s := range svcs { + p := l.Spec.Ports[i] + if s.Name != ServiceName(l.Name, p.Protocol, p.Port) || s.Namespace != l.Namespace { + t.Errorf("service %d is %s/%s", i, s.Namespace, s.Name) + } + sp := s.Spec + if sp.VPCRef != "vpc1" || !slices.Equal(sp.VIPAddresses, l.Spec.Addresses) || + string(sp.Protocol) != string(p.Protocol) || sp.Port != p.Port || sp.BackendPort != p.BackendPort || + sp.SessionAffinity != bgpv1alpha1.NetworkServiceSessionAffinityClientIPAndProtocol || + sp.EdgeListenerRef == nil || sp.EdgeListenerRef.Name != l.Name { + t.Errorf("service %s spec = %+v", s.Name, sp) + } + // The first tcp port's backendPort, for the udp port too. + hc := sp.HealthCheck + if hc == nil || hc.Port != 8443 || hc.FailurePolicy != bgpv1alpha1.NetworkServiceHealthFailOpen { + t.Errorf("service %s health check = %+v", s.Name, sp.HealthCheck) + } + if len(s.OwnerReferences) != 1 || s.OwnerReferences[0].UID != l.UID || + !ptr.Deref(s.OwnerReferences[0].Controller, false) { + t.Errorf("service %s owners = %+v", s.Name, s.OwnerReferences) + } + } + + l.Spec.HealthPort = ptr.To[int32](9000) + l.Spec.FailurePolicy = galacticv1alpha1.EdgeListenerFailClosed + l.Spec.SessionAffinity = galacticv1alpha1.EdgeListenerSessionAffinityClientIP + for _, s := range desiredServices(&l, "vpc1") { + if hc := s.Spec.HealthCheck; hc.Port != 9000 || hc.FailurePolicy != bgpv1alpha1.NetworkServiceHealthFailClosed || + s.Spec.SessionAffinity != bgpv1alpha1.NetworkServiceSessionAffinityClientIP { + t.Errorf("service %s with healthPort, FailClosed and ClientIP = %+v", s.Name, s.Spec) + } + } +} diff --git a/internal/edge/listener/setup.go b/internal/edge/listener/setup.go index c096e0b4c..bcbe40d4b 100644 --- a/internal/edge/listener/setup.go +++ b/internal/edge/listener/setup.go @@ -57,6 +57,8 @@ type Config struct { MaxSkew time.Duration // LeaseDuration is Reconciler.LeaseDuration. LeaseDuration time.Duration + // WithdrawDelay is Reconciler.WithdrawDelay. + WithdrawDelay time.Duration // Events records why a provider has no ingress gVPC; nil records none. Events events.EventRecorder // PrefixRetry is IngressReconciler.PrefixRetry. @@ -115,7 +117,7 @@ func Setup(mgr ctrl.Manager, cfg Config) error { Client: mgr.GetClient(), APIReader: mgr.GetAPIReader(), Namespace: cfg.Namespace, VPCs: VPCLookup{Reader: mgr.GetAPIReader(), Namespace: cfg.Namespace}, VIPPrefixes: cfg.VIPPrefixes, MaxSkew: cfg.MaxSkew, Now: cfg.Now, LeaseDuration: cfg.LeaseDuration, - Events: cfg.Events, + WithdrawDelay: cfg.WithdrawDelay, Events: cfg.Events, } if err := listeners.setup(mgr); err != nil { return fmt.Errorf("set up EdgeListener reconciler: %w", err) @@ -313,7 +315,17 @@ func (r *Reconciler) setup(mgr ctrl.Manager) error { // Another listener's addresses, ports, age and acceptance decide // this one's claims, and so does every NetworkService's. Watches(&galacticv1alpha1.EdgeListener{}, all, builder.WithPredicates(contention)). - Watches(&bgpv1alpha1.NetworkService{}, all, builder.WithPredicates(specOrDeletion)). + Watches(&bgpv1alpha1.NetworkService{}, handler.EnqueueRequestsFromMapFunc( + func(ctx context.Context, o client.Object) []reconcile.Request { + out := where(ctx, func(*galacticv1alpha1.EdgeListener) bool { return true }) + // A listener removed without its finalizer withdraws its + // /128s only once its services are gone. + if s, ok := o.(*bgpv1alpha1.NetworkService); ok && s.Spec.EdgeListenerRef != nil { + out = append(out, reconcile.Request{NamespacedName: client.ObjectKey{ + Namespace: s.Namespace, Name: s.Spec.EdgeListenerRef.Name}}) + } + return out + }), builder.WithPredicates(specOrDeletion)). Watches(&galacticv1alpha1.EdgeProvider{}, handler.EnqueueRequestsFromMapFunc( func(ctx context.Context, o client.Object) []reconcile.Request { return byProvider(ctx, o.GetName()) diff --git a/internal/edge/listener/teardown.go b/internal/edge/listener/teardown.go new file mode 100644 index 000000000..209c5e28c --- /dev/null +++ b/internal/edge/listener/teardown.go @@ -0,0 +1,145 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package listener + +import ( + "context" + "fmt" + "net/netip" + "strings" + "time" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/log" + + bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" + galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" + "go.datum.net/galactic/internal/crdnames" +) + +// AnnotationServicesGone is the instant, in RFC 3339 with nanoseconds, core +// first saw a listener's NetworkServices gone while it held the listener's +// /128s. It is recorded on the listener so a restart of core cannot shorten +// the hold. +const AnnotationServicesGone = "galactic.datumapis.com/edge-listener-services-gone" + +// GatewayDrainDelay is how long each gateway node keeps serving a +// NetworkService after the service's advertisements are gone +// (ruleDrainDelay in internal/controller). A withdraw delay must exceed it. +const GatewayDrainDelay = 5 * time.Second + +// DefaultWithdrawDelay is the withdraw delay when none is configured: the +// gateway drain delay plus time for the withdrawal to converge in BGP. +const DefaultWithdrawDelay = 30 * time.Second + +// withdrawDelay is WithdrawDelay, or DefaultWithdrawDelay when it is zero. +func (r *Reconciler) withdrawDelay() time.Duration { + if r.WithdrawDelay == 0 { + return DefaultWithdrawDelay + } + return r.WithdrawDelay +} + +// withdrawHold decides whether a listener losing its NetworkServices, being +// refused or deleted, still holds its backends' /128s: while any of its +// services remains, leaving > 0, and then for the withdraw delay after core +// first saw them gone, which it records in AnnotationServicesGone. The +// gateways keep serving a service's addresses for their drain delay after +// its advertisements go, and BGP takes time to converge, so a backend must +// stay resolvable until then. It returns whether to hold and how soon to +// look again. A listener with no /128s left holds nothing. +func (r *Reconciler) withdrawHold(ctx context.Context, l *galacticv1alpha1.EdgeListener, leaving int, + now time.Time) (bool, time.Duration, error) { + if leaving > 0 { + return true, teardownRecheck, nil + } + has, err := r.advertisements(ctx, client.ObjectKeyFromObject(l)) + if err != nil || !has { + return false, 0, err + } + gone, err := time.Parse(time.RFC3339Nano, l.Annotations[AnnotationServicesGone]) + if err != nil { + gone = now + if err := r.setServicesGone(ctx, l, now.UTC().Format(time.RFC3339Nano)); err != nil { + return false, 0, err + } + } + if until := gone.Add(r.withdrawDelay()); now.Before(until) { + return true, until.Sub(now), nil + } + return false, 0, nil +} + +// setServicesGone sets AnnotationServicesGone on l to value, or removes it +// when value is "", unless l already holds that. +func (r *Reconciler) setServicesGone(ctx context.Context, l *galacticv1alpha1.EdgeListener, value string) error { + if l.Annotations[AnnotationServicesGone] == value { + return nil + } + before := l.DeepCopy() + if value == "" { + delete(l.Annotations, AnnotationServicesGone) + } else { + if l.Annotations == nil { + l.Annotations = map[string]string{} + } + l.Annotations[AnnotationServicesGone] = value + } + if err := r.Client.Patch(ctx, l, + client.MergeFromWithOptions(before, client.MergeFromWithOptimisticLock{})); err != nil { + return fmt.Errorf("record EdgeListener %s/%s services gone: %w", l.Namespace, l.Name, err) + } + return nil +} + +// stillServes reports whether the backend adv was published for would still +// serve but for its listener: its attachment exists as the object it was +// published for, still has the gVPC and address adv advertises +// (advertises), is eligible (attachmentEligible) and its instance holds an +// unexpired lease. While a listener's /128s are held, only these stay. An +// error reading them keeps the advertisement, and is logged. +func (r *Reconciler) stillServes(ctx context.Context, adv *bgpv1alpha1.BGPAdvertisement, now time.Time) bool { + ns, name, ok := strings.Cut(adv.Annotations[crdnames.AnnotationEdgeListenerAttachment], "/") + if !ok { + return false + } + var att galacticv1alpha1.EdgeAttachment + switch err := r.Client.Get(ctx, client.ObjectKey{Namespace: ns, Name: name}, &att); { + case apierrors.IsNotFound(err): + return false + case err != nil: + log.FromContext(ctx).Error(err, "read a held advertisement's attachment; keeping it", "advertisement", adv.Name) + return true + case string(att.UID) != adv.Labels[crdnames.LabelEdgeListenerAttachment], !advertises(adv, &att): + return false + } + if eligible, _ := attachmentEligible(&att, now); !eligible { + return false + } + until, held, err := r.instanceHolds(ctx, &att) + if err != nil { + log.FromContext(ctx).Error(err, "read a held advertisement's lease; keeping it", "advertisement", adv.Name) + return true + } + return held && now.Before(until) +} + +// advertises reports whether adv advertises att as att now is: adv's gVPC +// is att's status.vpc and its only prefix is the /128 of att's +// status.address. An attachment that moved to another gVPC or address no +// longer matches its old advertisement, which must not stay published in +// the old network. +func advertises(adv *bgpv1alpha1.BGPAdvertisement, att *galacticv1alpha1.EdgeAttachment) bool { + if adv.Labels[crdnames.LabelEdgeListenerVPC] != att.Status.VPC || len(adv.Spec.Prefixes) != 1 { + return false + } + addr, err := netip.ParseAddr(att.Status.Address) + if err != nil { + return false + } + p, err := netip.ParsePrefix(string(adv.Spec.Prefixes[0])) + return err == nil && p == netip.PrefixFrom(addr, 128) +} diff --git a/internal/edge/listener/withdraw_envtest_test.go b/internal/edge/listener/withdraw_envtest_test.go new file mode 100644 index 000000000..1c3871617 --- /dev/null +++ b/internal/edge/listener/withdraw_envtest_test.go @@ -0,0 +1,180 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package listener + +import ( + "context" + "net/netip" + "testing" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + + galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" + "go.datum.net/galactic/internal/cloud/identifier" +) + +// servedListener starts the controllers with cfg and makes the accepted +// listener publicListener with one published backend on nodeA, returning +// the backend and the controllers' stop function. +func (f *fixture) servedListener(cfg Config) (*listenerBackend, func()) { + f.t.Helper() + stop := f.start(cfg) + vpc := f.readyVPC() + svc := f.newService(ingressSvc, vpc, []string{SocketAccess, PublicListener}, nil) + f.newListener(publicListener, ingressSvc, vip6, vip4) + f.expectCondition(publicListener, galacticv1alpha1.EdgeListenerAccepted, metav1.ConditionTrue, + galacticv1alpha1.EdgeListenerReasonAccepted) + f.vrf(vpc, nodeA, "router-a", 5) + a := f.newBackend("a", svc, vpc, nodeA, 1) + f.expectPublished(a, true) + eventually(f.t, "a NetworkService per port", func() bool { + return f.netsvc(udp443) != nil && f.netsvc(tcp443) != nil + }) + return a, stop +} + +// servicesGoneAt waits for the listener's AnnotationServicesGone and +// returns it. +func (f *fixture) servicesGoneAt() time.Time { + f.t.Helper() + var at time.Time + eventually(f.t, "the services-gone instant to be recorded", func() bool { + l := f.listener(publicListener) + if l == nil { + return false + } + t, err := time.Parse(time.RFC3339Nano, l.Annotations[AnnotationServicesGone]) + at = t + return err == nil + }) + return at +} + +// TestListenerWithdrawDelay checks that a deleted listener's /128s stay for +// the withdraw delay after its NetworkServices are gone, while the gateways +// drain them, and only then go with the listener. +func TestListenerWithdrawDelay(t *testing.T) { + f := startAPI(t) + ctx := context.Background() + cfg := f.listenerConfig() + cfg.WithdrawDelay = 6 * time.Second + a, _ := f.servedListener(cfg) + if err := f.admin.Delete(ctx, f.listener(publicListener)); err != nil { + t.Fatal(err) + } + eventually(t, "the services to go", func() bool { return f.netsvc(udp443) == nil && f.netsvc(tcp443) == nil }) + gone := f.servicesGoneAt() + never(t, "withdrew the /128 or released the listener within the delay", func() bool { + return f.advertisement(a) == nil || f.listener(publicListener) == nil + }) + f.expectPublished(a, false) + if withdrawn := time.Now(); withdrawn.Before(gone.Add(cfg.WithdrawDelay)) { + t.Errorf("withdrawn at %s, before the services-gone instant %s plus the delay", withdrawn, gone) + } + eventually(t, "the listener to be released", func() bool { return f.listener(publicListener) == nil }) +} + +// TestListenerWithdrawDelayRestart checks that a restart of core during the +// hold does not shorten it: the instant the services went is read back. +func TestListenerWithdrawDelayRestart(t *testing.T) { + f := startAPI(t) + ctx := context.Background() + cfg := f.listenerConfig() + cfg.WithdrawDelay = 10 * time.Second + a, stop := f.servedListener(cfg) + if err := f.admin.Delete(ctx, f.listener(publicListener)); err != nil { + t.Fatal(err) + } + gone := f.servicesGoneAt() + stop() + time.Sleep(3 * time.Second) + f.start(cfg) + // The restarted controller reads the recorded instant back rather than + // starting the hold again. + if got := f.servicesGoneAt(); !got.Equal(gone) { + t.Errorf("the restart moved the services-gone instant from %s to %s", gone, got) + } + f.expectPublished(a, false) + if withdrawn := time.Now(); withdrawn.Before(gone.Add(cfg.WithdrawDelay)) { + t.Errorf("withdrawn at %s after a restart, before the services-gone instant %s plus the delay", withdrawn, gone) + } +} + +// TestListenerHeldWithdrawsNonServing checks that while a deleted +// listener's NetworkServices are held by the gateway, a backend whose +// attachment goes, or whose provider clears Ready, loses its /128, and one +// that still serves keeps it. +func TestListenerHeldWithdrawsNonServing(t *testing.T) { + f := startAPI(t) + ctx := context.Background() + a, _ := f.servedListener(f.listenerConfig()) + vpc, svc := f.ingressVPC(providerName), &galacticv1alpha1.EdgeService{} + f.get(client.ObjectKey{Namespace: gatewayNS, Name: ingressSvc}, svc) + b := f.newBackend("b", svc, vpc, nodeA, 2) + c := f.newBackend("c", svc, vpc, nodeA, 3) + f.expectPublished(b, true) + f.expectPublished(c, true) + for _, n := range []string{udp443, tcp443} { + f.holdService(n, true) + } + if err := f.admin.Delete(ctx, f.listener(publicListener)); err != nil { + t.Fatal(err) + } + eventually(t, "the services to be deleting", func() bool { + s := f.netsvc(udp443) + return s != nil && !s.DeletionTimestamp.IsZero() + }) + if err := f.admin.Delete(ctx, a.att); err != nil { + t.Fatal(err) + } + f.expectPublished(a, false) + f.setReady(b, metav1.ConditionFalse) + f.expectPublished(b, false) + never(t, "withdrew a backend that still serves while the services exist", func() bool { + return f.advertisement(c) == nil || f.netsvc(udp443) == nil + }) +} + +// TestListenerHeldWithdrawsMoved checks that while a deleted listener's +// NetworkServices drain, a backend whose attachment changes address or +// moves to another gVPC loses its old /128, though it is still ready and +// leased, and a backend that did not move keeps its /128. +func TestListenerHeldWithdrawsMoved(t *testing.T) { + f := startAPI(t) + ctx := context.Background() + a, _ := f.servedListener(f.listenerConfig()) + vpc, svc := f.ingressVPC(providerName), &galacticv1alpha1.EdgeService{} + f.get(client.ObjectKey{Namespace: gatewayNS, Name: ingressSvc}, svc) + readdressed := f.newBackend("b", svc, vpc, nodeA, 2) + moved := f.newBackend("c", svc, vpc, nodeA, 3) + f.expectPublished(readdressed, true) + f.expectPublished(moved, true) + for _, n := range []string{udp443, tcp443} { + f.holdService(n, true) + } + if err := f.admin.Delete(ctx, f.listener(publicListener)); err != nil { + t.Fatal(err) + } + eventually(t, "the services to be deleting", func() bool { + s := f.netsvc(udp443) + return s != nil && !s.DeletionTimestamp.IsZero() + }) + network := netip.MustParsePrefix(string(vpc.Spec.Networks[0])) + f.attachmentStatus(readdressed, func(s *galacticv1alpha1.EdgeAttachmentStatus) { + s.Address = addrIn(network, 0x1ff).String() + }) + other, err := identifier.VPCBase62(ingressIdentity + 9) + if err != nil { + t.Fatal(err) + } + f.attachmentStatus(moved, func(s *galacticv1alpha1.EdgeAttachmentStatus) { s.VPC = other }) + f.expectPublished(readdressed, false) + f.expectPublished(moved, false) + never(t, "withdrew a backend that did not move while the services exist", func() bool { + return f.advertisement(a) == nil || f.netsvc(udp443) == nil + }) +}