From 346ceef19541e7bae9ba69defafd98449535c814 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Sat, 28 Nov 2026 17:29:41 -0500 Subject: [PATCH 01/10] feat(edge): Admit EdgeListeners and report their backends Core now reconciles each EdgeListener's status. Accepted is True only while the provider exists, is approved and lists PublicListener at a version core implements (ProviderNotApproved); the EdgeService exists, names the provider, grants SocketAccess and PublicListener on the provider's ingress gVPC, has not expired and serves no older listener (CapabilityNotGranted); every address is in the cell's gateway VIP prefixes (AddressOutsidePool); and nothing older serves an address on one of the listener's protocols and ports (AddressClaimed). The oldest claim wins. An older listener, the NetworkServices of an older listener even while they linger, and any other NetworkService created no later than the listener claim against it. A younger listener's NetworkServices never do, whatever its status, so an older listener that becomes admissible takes its addresses back while the younger refuses itself, instead of both refusing each other while the gateways tear their services down. A listener refused at its current generation holds neither its service nor its addresses against a newer one. status.backends lists the attachments made against the listener's EdgeService. One serves while the listener is accepted and the attachment is Allocated, Programmed and Ready with its placement reported, is Admitted or Draining before its drain deadline, and its instance holds its lease. A backend on a NetworkGateway's node never serves, since a gateway cannot deliver to its own node. Programmed reports BackendsReady, LocalBackendsExcluded or NoBackends, and core decides the listener again at the earliest drain deadline. Listeners outside the gateway namespace are ignored. Lease renewals, EdgeInstance status and NetworkGateway status do not trigger a pass, and instances and leases are read from the cache. The new galactic-controller flag --edge-listener-vip-prefixes gives the cell's gateway VIP prefixes. provider.HoldsLease is the lease test the backends use. Refs #1509 --- cmd/galactic-controller/main.go | 19 +- config/galactic-edge/controller-rbac.yaml | 21 +- docs/controller/README.md | 21 +- docs/edge/provider-contract.md | 17 ++ internal/edge/listener/admit.go | 285 +++++++++++++++++ internal/edge/listener/admit_test.go | 289 ++++++++++++++++++ internal/edge/listener/backends.go | 145 +++++++++ internal/edge/listener/config.go | 22 ++ internal/edge/listener/doc.go | 3 +- .../edge/listener/listener_envtest_test.go | 176 +++++++++++ .../listener/listener_fixture_envtest_test.go | 286 +++++++++++++++++ internal/edge/listener/reconciler.go | 210 +++++++++++++ internal/edge/listener/setup.go | 182 ++++++++++- internal/edge/listener/setup_test.go | 62 ++++ internal/edge/provider/provider.go | 11 + internal/edge/provider/provider_test.go | 50 +++ 16 files changed, 1774 insertions(+), 25 deletions(-) create mode 100644 internal/edge/listener/admit.go create mode 100644 internal/edge/listener/admit_test.go create mode 100644 internal/edge/listener/backends.go create mode 100644 internal/edge/listener/listener_envtest_test.go create mode 100644 internal/edge/listener/listener_fixture_envtest_test.go create mode 100644 internal/edge/listener/reconciler.go create mode 100644 internal/edge/listener/setup_test.go diff --git a/cmd/galactic-controller/main.go b/cmd/galactic-controller/main.go index 0673b49c3..f69d03d31 100644 --- a/cmd/galactic-controller/main.go +++ b/cmd/galactic-controller/main.go @@ -77,6 +77,7 @@ type options struct { edgeMaxSkew time.Duration edgeIngressIDs []string edgeIngressPrefix string + edgeVIPPrefixes []string } func main() { @@ -118,9 +119,10 @@ func newRootCommand() *cobra.Command { f.StringVar(&o.platformProject, "platform-project", "", "Fabric role: platform project for IPAM") f.StringVar(&o.ipamKubeconfig, "ipam-kubeconfig", "", "Fabric role: IPAM cluster kubeconfig") f.StringVar(&o.hubKubeconfig, "hub-kubeconfig", "", "Fabric role: federation hub kubeconfig") - f.BoolVar(&o.edge, "edge", false, "Cell role: admit, allocate and drain Galactic Edge attachments, and "+ - "accept and revoke their route claims (requires the edge CRDs and config/galactic-edge applied first; "+ - "a deleted attachment is held until galactic-edge on its node reports it released, or the node is removed)") + f.BoolVar(&o.edge, "edge", false, "Cell role: admit, allocate and drain Galactic Edge attachments, "+ + "accept and revoke their route claims, and serve public listeners (requires the edge CRDs and "+ + "config/galactic-edge applied first; a deleted attachment is held until galactic-edge on its node "+ + "reports it released, or the node is removed)") f.DurationVar(&o.edgeMaxSkew, "edge-max-skew", 2*time.Second, "Cell role: maximum wall-clock error of any node; an EdgeService stops admitting this long before its "+ "validUntil. It must equal galactic-edge's --max-skew") @@ -130,6 +132,9 @@ 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.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") logOpts.BindFlags(cmd.PersistentFlags()) return cmd } @@ -233,9 +238,13 @@ 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") } + 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, - Events: mgr.GetEventRecorder("galactic-controller"), + Namespace: galactic.SystemNamespace, Identities: identities, IngressPrefix: prefix, VIPPrefixes: vips, + MaxSkew: o.edgeMaxSkew, 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 2a6f6dcbd..28b3e0252 100644 --- a/config/galactic-edge/controller-rbac.yaml +++ b/config/galactic-edge/controller-rbac.yaml @@ -111,6 +111,11 @@ rules: - apiGroups: [galactic.datumapis.com] resources: [bgpvrfinstances] verbs: [get, list, watch] + # Listener admission reads every EdgeListener; its writes are in the + # galactic-controller-edge-listener Role. + - apiGroups: [galactic.datumapis.com] + resources: [edgelisteners] + verbs: [get, list, watch] --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding @@ -151,12 +156,13 @@ subjects: name: galactic-controller namespace: galactic-system --- -# Public listeners: one ingress gVPC per provider holding PublicListener, -# created in the gateway namespace with its fabric identifier in status, -# and deleted once its provider may no longer hold a listener and no -# EdgeService references it. Kubernetes RBAC cannot scope a create by name, -# so the Role covers every VPC in the gateway namespace, though core writes -# only those labelled galactic.datumapis.com/edge-ingress. +# 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. apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: @@ -169,6 +175,9 @@ rules: - apiGroups: [galactic.datumapis.com] resources: [vpcs/status] verbs: [get, update, patch] + - apiGroups: [galactic.datumapis.com] + resources: [edgelisteners/status] + verbs: [get, update, patch] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding diff --git a/docs/controller/README.md b/docs/controller/README.md index 3f5558936..38bd1b8da 100644 --- a/docs/controller/README.md +++ b/docs/controller/README.md @@ -8,7 +8,7 @@ | ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | NSO cell manager | VPC, subnet-status and attachment reconciliation, attachment identifiers and NetworkAttachmentDefinitions when Galactic integration is enabled | | `galactic-controller --role=cell` | TrafficPolicy admission, default policies and binding resolution; pod-interface injection; projection of BGP programming status to attachments and NSO interfaces/claims; [running instances' attachment state](../observability/vpc-attachments.md) | -| `galactic-controller --role=cell --edge` | The cell role plus admission, allocation and draining of Edge attachments and acceptance/revocation of Edge route claims | +| `galactic-controller --role=cell --edge` | The cell role plus admission, allocation and draining of Edge attachments, acceptance/revocation of Edge route claims, and public listeners: ingress gVPCs, `EdgeListener` admission and status | | `galactic-controller --role=fabric` | Central NetworkFabricIdentity allocation using the federation hub and platform IPAM | | `galactic-router` | Node BGP and traffic-policy programming and node-owned status | | `galactic-edge` | Node-side Edge attachment programming, fencing and release | @@ -31,15 +31,16 @@ 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 and route 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 | -| `--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` | +| 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 | +| `--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 | ### Installing the cell role diff --git a/docs/edge/provider-contract.md b/docs/edge/provider-contract.md index 705ca1b9a..4f2ed65af 100644 --- a/docs/edge/provider-contract.md +++ b/docs/edge/provider-contract.md @@ -298,6 +298,23 @@ The node never deletes API objects. It closes gates and releases host state for A drain stops new routes and attachments for its scope at once. Forwarding continues until the earlier of the drain window (`EdgeService.spec.drainSeconds`, default 30, maximum 300) and the lease deadline. Core records the end of the window in the attachment's `status.drainDeadline` and deletes the attachment when it passes. The node then closes the gate, `galactic-router` withdraws, and the attachment is released. A grant's prefixes stay assigned to the service across drains; only its routes go. +### Public listener + +Core (`internal/edge/listener`) keeps one ingress gVPC per approved provider that lists `PublicListener/v1`: the VPC `edge-ingress-` in `galactic-system`, labelled `galactic.datumapis.com/edge-ingress`. Its `/64` comes from `galactic-controller --edge-ingress-prefix`, and its fabric identifier, `status.vpc`, from the provider's `--edge-ingress-identity`. A provider without an identity gets no gVPC, and core records an `IngressIdentityMissing` Event on its `EdgeProvider`. Neither the `/64` nor the identifier moves once recorded: a changed identity is reported as `Ready` False with reason `IdentityMismatch` on the VPC and is not applied. Core deletes the gVPC once its provider may no longer hold a listener, no `EdgeService` references it and no `NetworkService` names its identifier. A provider the prefix has no free `/64` for is retried every minute. A VPC of that name with a controller, such as one NSO adopted for a `NetworkContext` of the same name, is not core's, and core neither trusts nor writes it. + +Core accepts an `EdgeListener` only while all of these hold, and otherwise sets `Accepted` False with the reason of the first that fails: + +| Reason | Rule | +| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `ProviderNotApproved` | The provider exists, is approved and not being deleted, and lists `PublicListener` at a version core implements. | +| `CapabilityNotGranted` | The listener's `EdgeService` exists, is not being deleted, names the listener's provider, grants `SocketAccess` and `PublicListener` on the provider's ingress gVPC, has not passed `validUntil` less the maximum skew, and serves no older listener. | +| `AddressOutsidePool` | Every address falls in one of the prefixes of `--edge-listener-vip-prefixes`. | +| `AddressClaimed` | Nothing older serves one of the listener's addresses on one of its protocols and ports: no older listener, no `NetworkService` of an older listener, and no other `NetworkService`, in any namespace, created no later than the listener. | + +A listener refused at its current generation holds neither its service nor its addresses against a newer one, but its `NetworkService`s claim their addresses against newer listeners until they are gone. A newer listener's `NetworkService`s never claim against an older one, so an older listener that becomes admissible takes its addresses back, and the newer one refuses itself and withdraws. + +The listener's backends, in `status.backends`, are the attachments made against its `EdgeService`. One is serving while the listener is accepted and the attachment is `Allocated`, `Programmed` and `Ready`, with its node, gVPC, address and host link reported; is `Admitted`, or `Draining` before its `status.drainDeadline`; and its instance is its pod's, on its node, holding its lease. A backend on a node that a `NetworkGateway` in `galactic-system` targets is never serving, since a gateway cannot deliver to its own node. `Programmed` is True with `BackendsReady` while any backend serves, and otherwise False with `LocalBackendsExcluded` when an eligible backend is excluded that way, or `NoBackends`. + ### Restart and replacement | Event | Rule | diff --git a/internal/edge/listener/admit.go b/internal/edge/listener/admit.go new file mode 100644 index 000000000..6a138500e --- /dev/null +++ b/internal/edge/listener/admit.go @@ -0,0 +1,285 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package listener + +import ( + "context" + "fmt" + "net/netip" + "slices" + "strings" + "time" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + + cloudv1alpha1 "go.datum.net/galactic/api/cloud/v1alpha1" + bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" + galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" +) + +// refusal is why core does not accept a listener: an Accepted reason and a +// message. +type refusal struct { + reason, message string +} + +func refuse(reason, format string, args ...any) *refusal { + return &refusal{reason: reason, message: fmt.Sprintf(format, args...)} +} + +// grant is what an accepted listener's admission read. +type grant struct { + // vpc is the provider's ingress gVPC. + vpc *cloudv1alpha1.VPC + // notAfter is when the service stops granting, its validUntil less the + // cell's maximum skew, or zero for never. + notAfter time.Time +} + +// admit decides whether l is accepted, in order: its provider may hold a +// listener, svc grants it SocketAccess and PublicListener on the provider's +// ingress gVPC and serves no older listener that contends, every address is +// in the cell's gateway VIP prefixes, and no other service or older +// listener that contends serves one of its addresses on one of its ports. +// svc is the listener's EdgeService, nil when it does not exist, and +// listeners and services are every EdgeListener in l's namespace and every +// NetworkService. +func (r *Reconciler) admit(ctx context.Context, l *galacticv1alpha1.EdgeListener, svc *galacticv1alpha1.EdgeService, + listeners []galacticv1alpha1.EdgeListener, services []bgpv1alpha1.NetworkService, now time.Time, +) (*grant, *refusal, error) { + name := l.Spec.ProviderRef.Name + var prov *galacticv1alpha1.EdgeProvider + var p galacticv1alpha1.EdgeProvider + switch err := r.APIReader.Get(ctx, client.ObjectKey{Name: name}, &p); { + case err == nil: + prov = &p + case !apierrors.IsNotFound(err): + return nil, nil, err + } + if why := providerRefusal(prov, name); why != "" { + return nil, refuse(galacticv1alpha1.EdgeListenerReasonProviderNotApproved, "%s", why), nil + } + g, ref, err := r.checkGrant(ctx, l, svc, listeners, now) + if ref != nil || err != nil { + return nil, ref, err + } + if a, outside := outsidePool(l.Spec.Addresses, r.VIPPrefixes); outside { + if len(r.VIPPrefixes) == 0 { + return nil, refuse(galacticv1alpha1.EdgeListenerReasonAddressOutsidePool, + "address %s is outside the cell's gateway VIP prefixes: none are configured", a), nil + } + return nil, refuse(galacticv1alpha1.EdgeListenerReasonAddressOutsidePool, + "address %s is outside the cell's gateway VIP prefixes %s", a, joinPrefixes(r.VIPPrefixes)), nil + } + if by, c := claimedBy(l, listeners, services); by != "" { + return nil, refuse(galacticv1alpha1.EdgeListenerReasonAddressClaimed, + "%s already serves %s on %s port %d", by, c.addr, c.protocol, c.port), nil + } + return g, nil, nil +} + +// checkGrant checks l's EdgeService svc: it exists and is not being deleted, +// grants l's provider SocketAccess and PublicListener on the provider's +// ingress gVPC, has not expired, and serves no older listener that contends. +func (r *Reconciler) checkGrant(ctx context.Context, l *galacticv1alpha1.EdgeListener, + svc *galacticv1alpha1.EdgeService, listeners []galacticv1alpha1.EdgeListener, now time.Time, +) (*grant, *refusal, error) { + ref := l.Spec.ServiceRef + notGranted := galacticv1alpha1.EdgeListenerReasonCapabilityNotGranted + switch { + case svc == nil: + return nil, refuse(notGranted, "EdgeService %s/%s does not exist", ref.Namespace, ref.Name), nil + case !svc.DeletionTimestamp.IsZero(): + return nil, refuse(notGranted, "EdgeService %s/%s is being deleted", ref.Namespace, ref.Name), nil + case svc.Spec.ProviderRef != l.Spec.ProviderRef: + return nil, refuse(notGranted, "EdgeService %s/%s grants provider %q, not %q", ref.Namespace, ref.Name, + svc.Spec.ProviderRef.Name, l.Spec.ProviderRef.Name), nil + } + for _, c := range []string{SocketAccess, PublicListener} { + if !slices.Contains(svc.Spec.Capabilities, c) { + return nil, refuse(notGranted, "EdgeService %s/%s does not grant %s", ref.Namespace, ref.Name, c), nil + } + } + vpc, why, err := r.VPCs.IngressVPC(ctx, l.Spec.ProviderRef.Name) + if err != nil { + return nil, nil, err + } + if vpc == nil { + return nil, refuse(notGranted, "%s", why), nil + } + if svc.Namespace != vpc.Namespace || svc.Spec.VPCRef.UID != string(vpc.UID) { + return nil, refuse(notGranted, "EdgeService %s/%s grants VPC %s, not the provider's ingress gVPC %s/%s", + ref.Namespace, ref.Name, svc.Spec.VPCRef.Name, vpc.Namespace, vpc.Name), nil + } + var notAfter time.Time + if svc.Spec.ValidUntil != nil { + notAfter = svc.Spec.ValidUntil.Add(-r.MaxSkew) + if !now.Before(notAfter) { + return nil, refuse(notGranted, "EdgeService %s/%s expired", ref.Namespace, ref.Name), nil + } + } + for i := range listeners { + o := &listeners[i] + if o.UID != l.UID && contends(o) && o.Spec.ServiceRef == l.Spec.ServiceRef && older(o, l) { + return nil, refuse(notGranted, "EdgeService %s/%s already serves the older EdgeListener %s", + ref.Namespace, ref.Name, o.Name), nil + } + } + return &grant{vpc: vpc, notAfter: notAfter}, nil, nil +} + +// contends reports whether listener l may hold its addresses and service +// against a newer listener: it is not being deleted and has not been refused +// at its current generation. +func contends(l *galacticv1alpha1.EdgeListener) bool { + c := meta.FindStatusCondition(l.Status.Conditions, galacticv1alpha1.EdgeListenerAccepted) + return l.DeletionTimestamp.IsZero() && + (c == nil || c.Status != metav1.ConditionFalse || c.ObservedGeneration != l.Generation) +} + +// older reports whether listener a was created before b, breaking a tie by +// name. +func older(a, b *galacticv1alpha1.EdgeListener) bool { + if !a.CreationTimestamp.Equal(&b.CreationTimestamp) { + return a.CreationTimestamp.Before(&b.CreationTimestamp) + } + return a.Name < b.Name +} + +// serviceClaims reports whether NetworkService s, which serves no listener +// in l's namespace that still exists, claims its addresses against l: it was +// created no later than l, so a service created after an accepted listener +// never evicts it. +func serviceClaims(s *bgpv1alpha1.NetworkService, l *galacticv1alpha1.EdgeListener) bool { + return !l.CreationTimestamp.Before(&s.CreationTimestamp) +} + +// outsidePool returns the first of addresses that no prefix of pool +// contains, and true, or false when pool contains them all. An address that +// does not parse is outside. +func outsidePool(addresses []string, pool []netip.Prefix) (string, bool) { + for _, a := range addresses { + addr, err := netip.ParseAddr(a) + if err != nil || !slices.ContainsFunc(pool, func(p netip.Prefix) bool { return p.Contains(addr.Unmap()) }) { + return a, true + } + } + return "", false +} + +func joinPrefixes(ps []netip.Prefix) string { + out := make([]string, len(ps)) + for i, p := range ps { + out[i] = p.String() + } + return strings.Join(out, ", ") +} + +// vipPort is one address served on a protocol and an inclusive port range. +type vipPort struct { + addr netip.Addr + protocol string + port, end int32 +} + +func (a vipPort) overlaps(b vipPort) bool { + return a.addr == b.addr && a.protocol == b.protocol && a.port <= b.end && b.port <= a.end +} + +// listenerPorts is every address and port l serves. +func listenerPorts(l *galacticv1alpha1.EdgeListener) []vipPort { + var out []vipPort + for _, a := range l.Spec.Addresses { + addr, err := netip.ParseAddr(a) + if err != nil { + continue + } + for _, p := range l.Spec.Ports { + out = append(out, vipPort{addr: addr.Unmap(), protocol: string(p.Protocol), port: p.Port, end: p.Port}) + } + } + return out +} + +// servicePorts is every VIP address and port s serves. +func servicePorts(s *bgpv1alpha1.NetworkService) []vipPort { + start, end := s.Spec.Port, s.Spec.Port + if r := s.Spec.PortRange; r != nil { + start, end = r.Start, r.End + } + var out []vipPort + for _, v := range s.Spec.VIPAddresses { + addr, err := netip.ParseAddr(v) + if err != nil { + continue + } + out = append(out, vipPort{addr: addr.Unmap(), protocol: string(s.Spec.Protocol), port: start, end: end}) + } + return out +} + +// claimedBy returns what already serves one of l's addresses on one of its +// protocols and ports, and that address and port, or "" when nothing does. +// The oldest claim wins: +// +// - A NetworkService naming another listener in l's namespace that still +// exists claims only when that listener is older than l, whatever its +// status, so it claims while it lingers being torn down. One naming a +// younger listener never claims: that listener's own pass refuses +// itself and withdraws its services. +// - Any other NetworkService, in any namespace, claims when it was created +// no later than l (see serviceClaims). Those naming l never claim. +// - An older listener in l's namespace that contends claims its ports. +// +// Of several claims, the one with the least name is returned. +func claimedBy(l *galacticv1alpha1.EdgeListener, listeners []galacticv1alpha1.EdgeListener, + services []bgpv1alpha1.NetworkService) (string, vipPort) { + mine := listenerPorts(l) + byName := map[string]*galacticv1alpha1.EdgeListener{} + for i := range listeners { + if o := &listeners[i]; o.Namespace == l.Namespace { + byName[o.Name] = o + } + } + var by string + var at vipPort + claim := func(name string, theirs []vipPort) { + for _, m := range mine { + for _, t := range theirs { + if m.overlaps(t) && (by == "" || name < by) { + by, at = name, m + } + } + } + } + for i := range services { + s := &services[i] + if ref := s.Spec.EdgeListenerRef; ref != nil && s.Namespace == l.Namespace { + if ref.Name == l.Name { + continue + } + if o := byName[ref.Name]; o != nil { + if o.UID != l.UID && older(o, l) { + claim("NetworkService "+s.Namespace+"/"+s.Name, servicePorts(s)) + } + continue + } + } + if serviceClaims(s, l) { + claim("NetworkService "+s.Namespace+"/"+s.Name, servicePorts(s)) + } + } + for i := range listeners { + o := &listeners[i] + if o.UID == l.UID || o.Namespace != l.Namespace || !contends(o) || !older(o, l) { + continue + } + claim("EdgeListener "+o.Namespace+"/"+o.Name, listenerPorts(o)) + } + return by, at +} diff --git a/internal/edge/listener/admit_test.go b/internal/edge/listener/admit_test.go new file mode 100644 index 000000000..6c71c2407 --- /dev/null +++ b/internal/edge/listener/admit_test.go @@ -0,0 +1,289 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package listener + +import ( + "net/netip" + "slices" + "testing" + "time" + + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + + bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" + galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" + "go.datum.net/galactic/internal/edge/admission" +) + +const ( + vip6 = "2001:db8:100::10" + vip4 = "192.0.2.10" +) + +var vipPool = []netip.Prefix{netip.MustParsePrefix("2001:db8:100::/48"), netip.MustParsePrefix("192.0.2.0/24")} + +func TestParseVIPPrefixes(t *testing.T) { + tests := []struct { + name string + in []string + want []netip.Prefix + wantError bool + }{ + {"NoPrefixes", nil, []netip.Prefix{}, false}, + {"BothFamilies", []string{"2001:db8:100::/48", " 192.0.2.0/24 ", ""}, vipPool, false}, + {"Masked", []string{"192.0.2.7/24"}, []netip.Prefix{netip.MustParsePrefix("192.0.2.0/24")}, false}, + {"NotAPrefix", []string{"192.0.2.7"}, nil, true}, + {"Mapped", []string{"::ffff:192.0.2.0/120"}, nil, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := ParseVIPPrefixes(tt.in) + if (err != nil) != tt.wantError { + t.Fatalf("ParseVIPPrefixes(%q) error = %v, wantError = %v", tt.in, err, tt.wantError) + } + if !tt.wantError && !slices.Equal(got, tt.want) { + t.Errorf("ParseVIPPrefixes(%q) = %v, want %v", tt.in, got, tt.want) + } + }) + } +} + +func TestOutsidePool(t *testing.T) { + tests := []struct { + name string + addresses []string + pool []netip.Prefix + want string + outside bool + }{ + {"Inside", []string{vip6, vip4}, vipPool, "", false}, + {"IPv6Outside", []string{"2001:db8:200::10", vip4}, vipPool, "2001:db8:200::10", true}, + {"IPv4Outside", []string{vip6, "198.51.100.10"}, vipPool, "198.51.100.10", true}, + {"FamilyMismatch", []string{vip4}, vipPool[:1], vip4, true}, + {"NoPool", []string{vip6}, nil, vip6, true}, + {"Unparsable", []string{"x"}, vipPool, "x", true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, outside := outsidePool(tt.addresses, tt.pool) + if got != tt.want || outside != tt.outside { + t.Errorf("outsidePool(%q) = %q, %v; want %q, %v", tt.addresses, got, outside, tt.want, tt.outside) + } + }) + } +} + +// listenerAt is a listener in the gateway namespace created at second sec. +func listenerAt(name string, sec int64, addresses ...string) galacticv1alpha1.EdgeListener { + return galacticv1alpha1.EdgeListener{ + ObjectMeta: metav1.ObjectMeta{Namespace: gatewayNS, Name: name, UID: types.UID("uid-" + name), + CreationTimestamp: metav1.Unix(sec, 0)}, + Spec: galacticv1alpha1.EdgeListenerSpec{ + Addresses: addresses, + Ports: []galacticv1alpha1.EdgeListenerPort{ + {Protocol: galacticv1alpha1.EdgeListenerProtocolUDP, Port: 443, BackendPort: 8443}, + {Protocol: galacticv1alpha1.EdgeListenerProtocolTCP, Port: 443, BackendPort: 8443}, + }, + }, + } +} + +// netService is a NetworkService serving vip on protocol and port. +func netService(namespace, name, vip string, protocol bgpv1alpha1.NetworkServiceProtocol, port int32, +) bgpv1alpha1.NetworkService { + return bgpv1alpha1.NetworkService{ + ObjectMeta: metav1.ObjectMeta{Namespace: namespace, Name: name}, + Spec: bgpv1alpha1.NetworkServiceSpec{VIPAddresses: []string{vip}, Protocol: protocol, Port: port, + BackendPort: port}, + } +} + +func TestClaimedBy(t *testing.T) { + udp, tcp := bgpv1alpha1.NetworkServiceProtocolUDP, bgpv1alpha1.NetworkServiceProtocolTCP + self := listenerAt("self", 100, vip6, vip4) + withRef := func(s bgpv1alpha1.NetworkService, listener string) bgpv1alpha1.NetworkService { + s.Spec.EdgeListenerRef = &bgpv1alpha1.NetworkServiceEdgeListenerReference{Name: listener} + return s + } + ranged := netService("tenant", "range", vip6, udp, 0) + ranged.Spec.PortRange = &bgpv1alpha1.PortRange{Start: 400, End: 500} + deleting := listenerAt("old-deleting", 10, vip6) + deleting.DeletionTimestamp = &metav1.Time{Time: time.Unix(200, 0)} + refusedAt := func(name string, observed int64) galacticv1alpha1.EdgeListener { + o := listenerAt(name, 20, vip6) + o.Generation = 2 + o.Status.Conditions = []metav1.Condition{{Type: galacticv1alpha1.EdgeListenerAccepted, + Status: metav1.ConditionFalse, Reason: galacticv1alpha1.EdgeListenerReasonProviderNotApproved, + ObservedGeneration: observed}} + return o + } + refused, stale := refusedAt("refused", 2), refusedAt("stale", 1) + at := func(svc bgpv1alpha1.NetworkService, sec int64) bgpv1alpha1.NetworkService { + svc.CreationTimestamp = metav1.Unix(sec, 0) + return svc + } + newer := at(netService("tenant", "newer", vip6, udp, 443), 101) + sameAge := at(netService("tenant", "same", vip6, udp, 443), 100) + newerRefused := listenerAt("late", 300, vip6) + newerRefused.Status.Conditions = []metav1.Condition{{Type: galacticv1alpha1.EdgeListenerAccepted, + Status: metav1.ConditionFalse, Reason: galacticv1alpha1.EdgeListenerReasonAddressClaimed}} + // An older listener's service claims whenever it was created. + olderListenersLateService := at(withRef(netService(gatewayNS, "older-tcp-443", vip4, tcp, 443), "older"), 500) + + tests := []struct { + name string + listeners []galacticv1alpha1.EdgeListener + services []bgpv1alpha1.NetworkService + want string + }{ + {"Nothing", nil, nil, ""}, + {"OtherPort", nil, []bgpv1alpha1.NetworkService{netService("tenant", "a", vip6, udp, 8443)}, ""}, + {"OtherProtocol", nil, []bgpv1alpha1.NetworkService{netService("tenant", "a", vip6, "sctp", 443)}, ""}, + {"OtherAddress", nil, []bgpv1alpha1.NetworkService{netService("tenant", "a", "2001:db8:100::11", udp, 443)}, + ""}, + {"TenantService", nil, []bgpv1alpha1.NetworkService{netService("tenant", "a", vip4, tcp, 443)}, + "NetworkService tenant/a"}, + {"PortRange", nil, []bgpv1alpha1.NetworkService{ranged}, "NetworkService tenant/range"}, + {"LeastName", nil, []bgpv1alpha1.NetworkService{netService("tenant", "b", vip6, udp, 443), + netService("tenant", "a", vip4, udp, 443)}, "NetworkService tenant/a"}, + {"OwnService", []galacticv1alpha1.EdgeListener{self}, + []bgpv1alpha1.NetworkService{withRef(netService(gatewayNS, "self-udp-443", vip6, udp, 443), "self")}, ""}, + {"OwnServiceElsewhere", []galacticv1alpha1.EdgeListener{self}, + []bgpv1alpha1.NetworkService{withRef(netService("tenant", "x", vip6, udp, 443), "self")}, + "NetworkService tenant/x"}, + {"NewerListener", []galacticv1alpha1.EdgeListener{self, listenerAt("newer", 200, vip6)}, nil, ""}, + {"NewerListenersService", []galacticv1alpha1.EdgeListener{self, listenerAt("newer", 200, vip6)}, + []bgpv1alpha1.NetworkService{withRef(netService(gatewayNS, "newer-udp-443", vip6, udp, 443), "newer")}, ""}, + {"OlderListener", []galacticv1alpha1.EdgeListener{self, listenerAt("older", 50, vip4)}, nil, + "EdgeListener " + gatewayNS + "/older"}, + {"SameAgeLesserName", []galacticv1alpha1.EdgeListener{self, listenerAt("peer", 100, vip6)}, nil, + "EdgeListener " + gatewayNS + "/peer"}, + {"SameAgeGreaterName", []galacticv1alpha1.EdgeListener{self, listenerAt("then", 100, vip6)}, nil, ""}, + {"NewerService", nil, []bgpv1alpha1.NetworkService{newer}, ""}, + {"SameAgeService", nil, []bgpv1alpha1.NetworkService{sameAge}, "NetworkService tenant/same"}, + {"NewerRefusedListenersService", []galacticv1alpha1.EdgeListener{self, newerRefused}, + []bgpv1alpha1.NetworkService{withRef(netService(gatewayNS, "late-udp-443", vip6, udp, 443), "late")}, ""}, + {"OlderListenersServiceAfterSelf", []galacticv1alpha1.EdgeListener{self, listenerAt("older", 50, vip4)}, + []bgpv1alpha1.NetworkService{olderListenersLateService}, "EdgeListener " + gatewayNS + "/older"}, + {"DeletingListener", []galacticv1alpha1.EdgeListener{self, deleting}, nil, ""}, + {"RefusedListener", []galacticv1alpha1.EdgeListener{self, refused}, nil, ""}, + {"RefusedListenersService", []galacticv1alpha1.EdgeListener{self, refused}, + []bgpv1alpha1.NetworkService{withRef(netService(gatewayNS, "refused-udp-443", vip6, udp, 443), "refused")}, + "NetworkService " + gatewayNS + "/refused-udp-443"}, + {"StaleRefusal", []galacticv1alpha1.EdgeListener{self, stale}, nil, "EdgeListener " + gatewayNS + "/stale"}, + {"DeletingListenersService", []galacticv1alpha1.EdgeListener{self, deleting}, + []bgpv1alpha1.NetworkService{withRef(netService(gatewayNS, "old-udp-443", vip6, udp, 443), "old-deleting")}, + "NetworkService " + gatewayNS + "/old-udp-443"}, + {"GoneListenersService", []galacticv1alpha1.EdgeListener{self}, + []bgpv1alpha1.NetworkService{withRef(netService(gatewayNS, "gone-udp-443", vip6, udp, 443), "gone")}, + "NetworkService " + gatewayNS + "/gone-udp-443"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, _ := claimedBy(&self, tt.listeners, tt.services) + if got != tt.want { + t.Errorf("claimedBy = %q, want %q", got, tt.want) + } + }) + } +} + +// eligibleAttachment is an attachment as core and its node leave it once it +// is admitted, allocated, programmed and ready. +func eligibleAttachment() *galacticv1alpha1.EdgeAttachment { + att := &galacticv1alpha1.EdgeAttachment{Status: galacticv1alpha1.EdgeAttachmentStatus{ + NodeName: "edge-1", VPC: "vpc", Address: "fd00:e1::101", HostLink: "eh0"}} + for _, c := range []string{galacticv1alpha1.EdgeAttachmentAdmitted, galacticv1alpha1.EdgeAttachmentAllocated, + galacticv1alpha1.EdgeAttachmentProgrammed, galacticv1alpha1.EdgeAttachmentReady} { + meta.SetStatusCondition(&att.Status.Conditions, metav1.Condition{Type: c, Status: metav1.ConditionTrue, + Reason: c}) + } + return att +} + +func TestAttachmentEligible(t *testing.T) { + now := time.Unix(1000, 0) + drain := func(deadline time.Time) func(*galacticv1alpha1.EdgeAttachment) { + return func(a *galacticv1alpha1.EdgeAttachment) { + meta.SetStatusCondition(&a.Status.Conditions, metav1.Condition{Type: galacticv1alpha1.EdgeAttachmentAdmitted, + Status: metav1.ConditionFalse, Reason: string(admission.GrantRevoked)}) + meta.SetStatusCondition(&a.Status.Conditions, metav1.Condition{Type: galacticv1alpha1.EdgeAttachmentDraining, + Status: metav1.ConditionTrue, Reason: string(admission.GrantRevoked)}) + if !deadline.IsZero() { + a.Status.DrainDeadline = &metav1.Time{Time: deadline} + } + } + } + unset := func(cond string) func(*galacticv1alpha1.EdgeAttachment) { + return func(a *galacticv1alpha1.EdgeAttachment) { + meta.SetStatusCondition(&a.Status.Conditions, metav1.Condition{Type: cond, Status: metav1.ConditionFalse, + Reason: "Test"}) + } + } + tests := []struct { + name string + mutate func(*galacticv1alpha1.EdgeAttachment) + want bool + deadline time.Time + }{ + {"Eligible", func(*galacticv1alpha1.EdgeAttachment) {}, true, time.Time{}}, + {"NotReady", unset(galacticv1alpha1.EdgeAttachmentReady), false, time.Time{}}, + {"NotProgrammed", unset(galacticv1alpha1.EdgeAttachmentProgrammed), false, time.Time{}}, + {"NotAllocated", unset(galacticv1alpha1.EdgeAttachmentAllocated), false, time.Time{}}, + {"NotAdmitted", unset(galacticv1alpha1.EdgeAttachmentAdmitted), false, time.Time{}}, + {"NoHostLink", func(a *galacticv1alpha1.EdgeAttachment) { a.Status.HostLink = "" }, false, time.Time{}}, + {"NoAddress", func(a *galacticv1alpha1.EdgeAttachment) { a.Status.Address = "" }, false, time.Time{}}, + {"Deleting", func(a *galacticv1alpha1.EdgeAttachment) { + a.DeletionTimestamp = &metav1.Time{Time: now} + }, false, time.Time{}}, + {"DrainingBeforeDeadline", drain(now.Add(time.Second)), true, now.Add(time.Second)}, + {"DrainingAtDeadline", drain(now), false, time.Time{}}, + {"DrainingNoDeadline", drain(time.Time{}), false, time.Time{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + att := eligibleAttachment() + tt.mutate(att) + got, deadline := attachmentEligible(att, now) + if got != tt.want || !deadline.Equal(tt.deadline) { + t.Errorf("attachmentEligible = %v, %v; want %v, %v", got, deadline, tt.want, tt.deadline) + } + }) + } +} + +func TestProgrammed(t *testing.T) { + l := listenerAt("l", 1, vip6) + b := func(eligible, local, serving bool) backend { + return backend{att: eligibleAttachment(), eligible: eligible, local: local, serving: serving} + } + tests := []struct { + name string + accepted bool + backends []backend + status metav1.ConditionStatus + reason string + }{ + {"None", true, nil, metav1.ConditionFalse, galacticv1alpha1.EdgeListenerReasonNoBackends}, + {"Serving", true, []backend{b(true, false, true), b(true, true, false)}, metav1.ConditionTrue, + galacticv1alpha1.EdgeListenerReasonBackendsReady}, + {"OnlyLocal", true, []backend{b(true, true, false), b(false, false, false)}, metav1.ConditionFalse, + galacticv1alpha1.EdgeListenerReasonLocalBackendsExcluded}, + {"IneligibleLocal", true, []backend{b(false, true, false)}, metav1.ConditionFalse, + galacticv1alpha1.EdgeListenerReasonNoBackends}, + {"NotAccepted", false, []backend{b(true, true, false)}, metav1.ConditionFalse, + galacticv1alpha1.EdgeListenerReasonNoBackends}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c := programmed(&l, tt.accepted, tt.backends) + if c.Status != tt.status || c.Reason != tt.reason { + t.Errorf("programmed = %s %s, want %s %s", c.Status, c.Reason, tt.status, tt.reason) + } + }) + } +} diff --git a/internal/edge/listener/backends.go b/internal/edge/listener/backends.go new file mode 100644 index 000000000..8bccbea45 --- /dev/null +++ b/internal/edge/listener/backends.go @@ -0,0 +1,145 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package listener + +import ( + "context" + "fmt" + "slices" + "strings" + "time" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + "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/edge/provider" +) + +// maxBackends is the most backends a listener's status lists. +const maxBackends = 1024 + +// backend is one listener attachment and what core decided for it. +type backend struct { + att *galacticv1alpha1.EdgeAttachment + // eligible is whether the attachment may receive new flows wherever it + // is: programmed, ready, holding its lease and not drained. + eligible bool + // local is whether the attachment is on a node that advertises the + // listener's addresses. + local bool + // serving is whether it receives new flows: the listener is accepted, + // and it is eligible and not local. + serving bool +} + +// status is the backend as the listener's status reports it. +func (b *backend) status() galacticv1alpha1.EdgeListenerBackend { + return galacticv1alpha1.EdgeListenerBackend{ + Attachment: b.att.Namespace + "/" + b.att.Name, Node: b.att.Status.NodeName, + Address: b.att.Status.Address, Serving: b.serving, + } +} + +// attachmentEligible reports whether att may receive new flows at now as far +// as its own status says: it is not being deleted; Allocated, Programmed and +// Ready are True; its node, gVPC, address and host link are set; and either +// it is Admitted, or it is Draining with a drain deadline after now. It also +// returns that drain deadline, zero when att is not draining. +func attachmentEligible(att *galacticv1alpha1.EdgeAttachment, now time.Time) (bool, time.Time) { + c, s := att.Status.Conditions, &att.Status + switch { + case !att.DeletionTimestamp.IsZero(), + !meta.IsStatusConditionTrue(c, galacticv1alpha1.EdgeAttachmentAllocated), + !meta.IsStatusConditionTrue(c, galacticv1alpha1.EdgeAttachmentProgrammed), + !meta.IsStatusConditionTrue(c, galacticv1alpha1.EdgeAttachmentReady), + s.NodeName == "", s.VPC == "", s.Address == "", s.HostLink == "": + return false, time.Time{} + case meta.IsStatusConditionTrue(c, galacticv1alpha1.EdgeAttachmentDraining): + if s.DrainDeadline == nil || !now.Before(s.DrainDeadline.Time) { + return false, time.Time{} + } + return true, s.DrainDeadline.Time + } + return meta.IsStatusConditionTrue(c, galacticv1alpha1.EdgeAttachmentAdmitted), time.Time{} +} + +// backends reads the attachments made against svc, the listener's +// EdgeService, and decides each one. vpc is the ingress gVPC's fabric +// identifier when the listener is accepted, and "" otherwise; gateways are +// the nodes that advertise the listener's addresses. It also returns the +// earliest drain deadline of an eligible backend, zero for none. +func (r *Reconciler) backends(ctx context.Context, l *galacticv1alpha1.EdgeListener, + svc *galacticv1alpha1.EdgeService, vpc string, gateways map[string]bool, now time.Time, +) ([]backend, time.Time, error) { + if svc == nil { + return nil, time.Time{}, nil + } + var list galacticv1alpha1.EdgeAttachmentList + if err := r.Client.List(ctx, &list, client.MatchingFields{indexServiceUID: string(svc.UID)}); err != nil { + return nil, time.Time{}, fmt.Errorf("list attachments of EdgeService %s/%s: %w", svc.Namespace, svc.Name, err) + } + slices.SortFunc(list.Items, func(a, b galacticv1alpha1.EdgeAttachment) int { + return strings.Compare(a.Namespace+"/"+a.Name, b.Namespace+"/"+b.Name) + }) + var next time.Time + out := make([]backend, 0, len(list.Items)) + for i := range list.Items { + att := &list.Items[i] + b := backend{att: att} + eligible, deadline := attachmentEligible(att, now) + if eligible && att.Spec.ProviderRef == l.Spec.ProviderRef { + held, err := r.instanceHolds(ctx, att) + if err != nil { + return nil, time.Time{}, err + } + b.eligible = held + } + if b.eligible && !deadline.IsZero() && (next.IsZero() || deadline.Before(next)) { + next = deadline + } + b.local = gateways[att.Status.NodeName] + b.serving = b.eligible && !b.local && vpc != "" && att.Status.VPC == vpc + out = append(out, b) + } + return out, next, nil +} + +// instanceHolds reports whether att's instance is its pod's, on its node, +// and holds its lease. Both are read from the cache: the manager caches only +// Leases carrying the instance lease label, which every lease bound to an +// instance carries, so a Lease the cache lacks is one HoldsLease refuses +// anyway. +func (r *Reconciler) instanceHolds(ctx context.Context, att *galacticv1alpha1.EdgeAttachment) (bool, error) { + var inst galacticv1alpha1.EdgeInstance + key := client.ObjectKey{Namespace: att.Namespace, Name: att.Spec.InstanceRef.Name} + switch err := r.Client.Get(ctx, key, &inst); { + case apierrors.IsNotFound(err): + return false, nil + case err != nil: + return false, err + case inst.Spec.PodUID != att.Spec.PodUID || inst.Spec.NodeName != att.Status.NodeName: + return false, nil + } + return provider.HoldsLease(ctx, r.Client, &inst) +} + +// gatewayNodes is the set of nodes a NetworkGateway in the gateway namespace +// targets: every one of them advertises every accepted service's addresses. +func (r *Reconciler) gatewayNodes(ctx context.Context) (map[string]bool, error) { + var list bgpv1alpha1.NetworkGatewayList + if err := r.Client.List(ctx, &list, client.InNamespace(r.Namespace)); err != nil { + return nil, fmt.Errorf("list NetworkGateways in %s: %w", r.Namespace, err) + } + out := make(map[string]bool, len(list.Items)) + for i := range list.Items { + if ref := list.Items[i].Spec.TargetRef; (ref.Kind == "" || ref.Kind == "Node") && ref.Name != "" { + out[ref.Name] = true + } + } + return out, nil +} diff --git a/internal/edge/listener/config.go b/internal/edge/listener/config.go index fdef34a02..7108b1c28 100644 --- a/internal/edge/listener/config.go +++ b/internal/edge/listener/config.go @@ -130,3 +130,25 @@ func carve(parent netip.Prefix, provider string, taken func(netip.Prefix) bool) } return netip.Prefix{}, errPrefixExhausted } + +// ParseVIPPrefixes parses the cell's gateway VIP prefixes, of either family, +// and masks each. It returns an error for an entry that is not a prefix or +// is an IPv4-mapped IPv6 prefix. +func ParseVIPPrefixes(entries []string) ([]netip.Prefix, error) { + out := make([]netip.Prefix, 0, len(entries)) + for _, e := range entries { + e = strings.TrimSpace(e) + if e == "" { + continue + } + p, err := netip.ParsePrefix(e) + if err != nil { + return nil, fmt.Errorf("listener VIP prefix %q: %w", e, err) + } + if p.Addr().Is4In6() { + return nil, fmt.Errorf("listener VIP prefix %s is IPv4-mapped; write an IPv4 prefix in dotted form", p) + } + out = append(out, p.Masked()) + } + return out, nil +} diff --git a/internal/edge/listener/doc.go b/internal/edge/listener/doc.go index 122439c32..5d31786a5 100644 --- a/internal/edge/listener/doc.go +++ b/internal/edge/listener/doc.go @@ -5,5 +5,6 @@ // Package listener is core's half of the Galactic Edge public listener, run // by galactic-controller --role=cell --edge. It keeps one ingress gVPC per // provider that may hold a listener, in the gateway namespace, with a fabric -// identity and a /64 the operator configures. +// identity and a /64 the operator configures. It admits each EdgeListener +// and reports which of its listener attachments serve. package listener diff --git a/internal/edge/listener/listener_envtest_test.go b/internal/edge/listener/listener_envtest_test.go new file mode 100644 index 000000000..cb715efd8 --- /dev/null +++ b/internal/edge/listener/listener_envtest_test.go @@ -0,0 +1,176 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package listener + +import ( + "context" + "testing" + "time" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" + galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" +) + +// TestListenerAdmission checks every Accepted reason: a provider that is +// missing, unapproved or lacks PublicListener; a service that is missing, +// lacks a capability, grants another VPC, has expired or already serves an +// older listener; an address outside the gateway VIP prefixes; and an +// address another service or an older listener already serves. +func TestListenerAdmission(t *testing.T) { + f := startAPI(t) + ctx := context.Background() + f.newProvider("sockets-only") + f.newProvider("unapproved", PublicListener) + f.setApproved("unapproved", false) + f.start(f.listenerConfig()) + vpc := f.readyVPC(providerName) + accepted, programmed := galacticv1alpha1.EdgeListenerAccepted, galacticv1alpha1.EdgeListenerProgrammed + expectRefused := func(name, reason string) { + t.Helper() + f.expectCondition(name, accepted, metav1.ConditionFalse, reason) + f.expectCondition(name, programmed, metav1.ConditionFalse, galacticv1alpha1.EdgeListenerReasonNoBackends) + } + + // The provider. + for i, p := range []string{"missing", "sockets-only", "unapproved"} { + l := listenerObject("by-"+p, ingressSvc, addrIn(vipPool[0], uint64(0x200+i)).String()) + l.Spec.ProviderRef.Name = p + f.create(l) + expectRefused(l.Name, galacticv1alpha1.EdgeListenerReasonProviderNotApproved) + } + + // The service. + notGranted := galacticv1alpha1.EdgeListenerReasonCapabilityNotGranted + f.newListener("no-service", "missing", "2001:db8:100::301") + expectRefused("no-service", notGranted) + f.newService("sockets", vpc, []string{SocketAccess}, nil) + f.newListener("no-capability", "sockets", "2001:db8:100::302") + expectRefused("no-capability", notGranted) + other := f.ingressVPC(providerName).DeepCopy() + other.UID = "00000000-0000-0000-0000-000000000000" + f.newService("other-vpc", other, []string{SocketAccess, PublicListener}, nil) + f.newListener("wrong-vpc", "other-vpc", "2001:db8:100::303") + expectRefused("wrong-vpc", notGranted) + f.newService("expired", vpc, []string{SocketAccess, PublicListener}, func(s *galacticv1alpha1.EdgeService) { + s.Spec.ValidUntil = &metav1.Time{Time: time.Now().Add(time.Second)} + }) + f.newListener("expired", "expired", "2001:db8:100::304") + expectRefused("expired", notGranted) + + // The addresses. + f.newService(ingressSvc, vpc, []string{SocketAccess, PublicListener}, nil) + f.newListener("outside", ingressSvc, "2001:db8:200::10") + expectRefused("outside", galacticv1alpha1.EdgeListenerReasonAddressOutsidePool) + if err := f.admin.Delete(ctx, f.listener("outside")); err != nil { + t.Fatal(err) + } + + // A tenant service already serving the address claims it, until it + // goes. + f.create(&corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "tenant"}}) + tenant := netService("tenant", "web", vip4, bgpv1alpha1.NetworkServiceProtocolTCP, 443) + tenant.Spec.VPCRef = "tenantvpc" + tenant.Spec.BackendSelector = webSelector + f.create(&tenant) + f.newListener("public", ingressSvc, vip6, vip4) + expectRefused("public", galacticv1alpha1.EdgeListenerReasonAddressClaimed) + if err := f.admin.Delete(ctx, &tenant); err != nil { + t.Fatal(err) + } + f.expectCondition("public", accepted, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonAccepted) + + // A service created after the listener does not evict it. + nextSecond() + late := netService("tenant", "late", vip4, bgpv1alpha1.NetworkServiceProtocolTCP, 443) + late.Spec.VPCRef = "tenantvpc" + late.Spec.BackendSelector = webSelector + f.create(&late) + never(t, "a newer NetworkService evicted an accepted listener", func() bool { + c := meta.FindStatusCondition(f.listener("public").Status.Conditions, accepted) + return c == nil || c.Status != metav1.ConditionTrue + }) + if err := f.admin.Delete(ctx, &late); err != nil { + t.Fatal(err) + } + + // The older listener keeps its address against a newer one, and its + // service against a newer listener of the same service. + f.newService("second", vpc, []string{SocketAccess, PublicListener}, nil) + nextSecond() + f.newListener("newer", "second", vip6) + 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 { + t.Fatal(err) + } + f.expectCondition("newer", accepted, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonAccepted) + f.expectCondition("same-service", accepted, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonAccepted) +} + +// TestListenerBackends checks each listener attachment's serving and the +// Programmed reasons: no backends, backends ready, and only backends on a +// gateway node; and that a backend leaves the set when its provider clears +// Ready, when its drain deadline passes and when its lease is released. +func TestListenerBackends(t *testing.T) { + f := startAPI(t) + programmed := galacticv1alpha1.EdgeListenerProgrammed + vpc, svc := f.acceptedListener("public") + f.expectCondition("public", programmed, metav1.ConditionFalse, galacticv1alpha1.EdgeListenerReasonNoBackends) + + a := f.newBackend("a", svc, vpc, nodeA, 1) + f.expectCondition("public", programmed, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonBackendsReady) + l := f.listener("public") + if len(l.Status.Backends) != 1 { + t.Fatalf("backends = %+v, want one", l.Status.Backends) + } + if b := l.Status.Backends[0]; b.Attachment != providerNS+"/"+a.att.Name || b.Node != nodeA || + b.Address != a.att.Status.Address || !b.Serving { + t.Errorf("backend = %+v, want %s on %s at %s serving", b, a.att.Name, nodeA, a.att.Status.Address) + } + + // The provider clears Ready. + f.setReady(a, metav1.ConditionFalse) + f.expectCondition("public", 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) + + // A backend on a gateway node is excluded. + f.gateway(nodeB) + b := f.newBackend("b", svc, vpc, nodeB, 2) + eventually(t, "the gateway node's backend to be listed", func() bool { + s, ok := f.serving()[b.att.Name] + return ok && !s + }) + f.setReady(a, metav1.ConditionFalse) + f.expectCondition("public", programmed, metav1.ConditionFalse, + galacticv1alpha1.EdgeListenerReasonLocalBackendsExcluded) + f.setReady(a, metav1.ConditionTrue) + f.expectCondition("public", 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, + 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.releaseLease(c) + f.expectCondition("public", programmed, metav1.ConditionFalse, + galacticv1alpha1.EdgeListenerReasonLocalBackendsExcluded) + if f.serving()[c.att.Name] { + t.Error("a backend whose lease is released is serving") + } +} diff --git a/internal/edge/listener/listener_fixture_envtest_test.go b/internal/edge/listener/listener_fixture_envtest_test.go new file mode 100644 index 000000000..0cb17c6a7 --- /dev/null +++ b/internal/edge/listener/listener_fixture_envtest_test.go @@ -0,0 +1,286 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package listener + +import ( + "context" + "encoding/binary" + "errors" + "fmt" + "net/netip" + "strings" + "time" + + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/util/retry" + "sigs.k8s.io/controller-runtime/pkg/client" + + cloudv1alpha1 "go.datum.net/galactic/api/cloud/v1alpha1" + bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" + galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" + "go.datum.net/galactic/internal/edge/admission" + "go.datum.net/galactic/internal/edge/claim" + "go.datum.net/galactic/internal/edge/provider" +) + +const ( + nodeA = "edge-1" + nodeB = "edge-2" + ingressSvc = "ingress" + leaseHolder = "proc" +) + +// webSelector is the backend selector of every fixture tenant service. +var webSelector = metav1.LabelSelector{MatchLabels: map[string]string{"app": "web"}} + +// listenerConfig is config with the cell's gateway VIP prefixes. +func (f *fixture) listenerConfig() Config { + cfg := f.config() + cfg.VIPPrefixes = vipPool + cfg.MaxSkew = 2 * time.Second + return cfg +} + +// readyVPC waits for provider's ingress gVPC to have its identifier. +func (f *fixture) readyVPC(name string) *cloudv1alpha1.VPC { + f.t.Helper() + var vpc *cloudv1alpha1.VPC + eventually(f.t, "ingress gVPC "+IngressVPCName(name), func() bool { + vpc = f.ingressVPC(name) + return vpc != nil && vpc.Status.VPC != "" + }) + return vpc +} + +// newService creates an EdgeService in the gateway namespace granting +// providerName capabilities on vpc, changed by mutate when it is not nil. +func (f *fixture) newService(name string, vpc *cloudv1alpha1.VPC, capabilities []string, + mutate func(*galacticv1alpha1.EdgeService)) *galacticv1alpha1.EdgeService { + f.t.Helper() + s := &galacticv1alpha1.EdgeService{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: gatewayNS}, + Spec: galacticv1alpha1.EdgeServiceSpec{ + ProviderRef: galacticv1alpha1.EdgeProviderReference{Name: providerName}, + VPCRef: galacticv1alpha1.EdgeVPCReference{Name: vpc.Name, UID: string(vpc.UID)}, + Capabilities: capabilities, + }, + } + if mutate != nil { + mutate(s) + } + f.create(s) + return s +} + +// newListener creates listenerObject(name, service, addresses...). +func (f *fixture) newListener(name, service string, addresses ...string) { + f.t.Helper() + f.create(listenerObject(name, service, addresses...)) +} + +// listenerObject is a listener of providerName against service, serving +// addresses on UDP and TCP 443 from backend port 8443. +func listenerObject(name, service string, addresses ...string) *galacticv1alpha1.EdgeListener { + return &galacticv1alpha1.EdgeListener{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: gatewayNS}, + Spec: galacticv1alpha1.EdgeListenerSpec{ + ProviderRef: galacticv1alpha1.EdgeProviderReference{Name: providerName}, + ServiceRef: galacticv1alpha1.EdgeListenerServiceReference{Namespace: gatewayNS, Name: service}, + Addresses: addresses, + Ports: []galacticv1alpha1.EdgeListenerPort{ + {Protocol: galacticv1alpha1.EdgeListenerProtocolUDP, Port: 443, BackendPort: 8443}, + {Protocol: galacticv1alpha1.EdgeListenerProtocolTCP, Port: 443, BackendPort: 8443}, + }, + }, + } +} + +// listener reads the named listener, or nil. +func (f *fixture) listener(name string) *galacticv1alpha1.EdgeListener { + f.t.Helper() + var l galacticv1alpha1.EdgeListener + if !f.get(client.ObjectKey{Namespace: gatewayNS, Name: name}, &l) { + return nil + } + return &l +} + +// expectCondition waits for the listener's condition typ to have status and +// reason. +func (f *fixture) expectCondition(name, typ string, status metav1.ConditionStatus, reason string) { + f.t.Helper() + var last string + deadline := time.Now().Add(20 * time.Second) + for time.Now().Before(deadline) { + l := f.listener(name) + if l != nil { + if c := meta.FindStatusCondition(l.Status.Conditions, typ); c != nil { + last = fmt.Sprintf("%s %s: %s", c.Status, c.Reason, c.Message) + if c.Status == status && c.Reason == reason && c.ObservedGeneration == l.Generation && + l.Status.ObservedGeneration == l.Generation { + return + } + } + } + time.Sleep(100 * time.Millisecond) + } + 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 +// 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 { + _, n, _ := strings.Cut(b.Attachment, "/") + out[n] = b.Serving + } + return out +} + +// nextSecond waits for the next second, so an object created afterwards is +// newer than every one created before: creation times have one-second +// resolution. +func nextSecond() { + time.Sleep(time.Until(time.Now().Truncate(time.Second).Add(time.Second))) +} + +// addrIn is the n-th address of p. +func addrIn(p netip.Prefix, n uint64) netip.Addr { + b := p.Addr().As16() + binary.BigEndian.PutUint64(b[8:], binary.BigEndian.Uint64(b[8:])+n) + return netip.AddrFrom16(b) +} + +// listenerBackend is one provider instance and its listener attachment. +type listenerBackend struct { + inst *galacticv1alpha1.EdgeInstance + att *galacticv1alpha1.EdgeAttachment +} + +// newBackend creates an instance on node holding its lease, and its +// attachment against svc as core and the node leave it once admitted, +// allocated, programmed and ready, with the n-th address of vpc's network. +func (f *fixture) newBackend(name string, svc *galacticv1alpha1.EdgeService, vpc *cloudv1alpha1.VPC, node string, + n uint64) *listenerBackend { + f.t.Helper() + ctx := context.Background() + podUID := "pod-" + name + b := &listenerBackend{} + b.inst = &galacticv1alpha1.EdgeInstance{ + ObjectMeta: metav1.ObjectMeta{Name: provider.InstanceName(podUID), Namespace: providerNS}, + Spec: galacticv1alpha1.EdgeInstanceSpec{ProviderRef: galacticv1alpha1.EdgeProviderReference{Name: providerName}, + PodName: name, PodUID: podUID, NodeName: node, BootID: "boot"}, + } + f.create(b.inst) + if _, err := (provider.InstanceStore{Client: f.admin, Namespace: providerNS}).Create(ctx, + claim.Record{Key: b.inst.Name, Holder: leaseHolder, Epoch: 1}); err != nil { + f.t.Fatal(err) + } + b.att = &galacticv1alpha1.EdgeAttachment{ + ObjectMeta: metav1.ObjectMeta{Name: "ea-" + name, Namespace: providerNS}, + Spec: galacticv1alpha1.EdgeAttachmentSpec{ + ProviderRef: galacticv1alpha1.EdgeProviderReference{Name: providerName}, + ServiceRef: galacticv1alpha1.EdgeServiceReference{Namespace: gatewayNS, Name: svc.Name, UID: string(svc.UID)}, + InstanceRef: galacticv1alpha1.EdgeInstanceReference{Name: b.inst.Name}, + PodUID: podUID, + ContractVersion: "v1alpha1", + Capabilities: []galacticv1alpha1.EdgeCapability{{Name: SocketAccess, Version: "v1"}}, + }, + } + f.create(b.att) + network := netip.MustParsePrefix(string(vpc.Spec.Networks[0])) + f.attachmentStatus(b, func(s *galacticv1alpha1.EdgeAttachmentStatus) { + s.NodeName, s.VPC, s.Address, s.HostLink = node, vpc.Status.VPC, addrIn(network, 0x100+n).String(), "eh"+name + for _, c := range []string{galacticv1alpha1.EdgeAttachmentAdmitted, galacticv1alpha1.EdgeAttachmentAllocated, + galacticv1alpha1.EdgeAttachmentProgrammed, galacticv1alpha1.EdgeAttachmentReady} { + meta.SetStatusCondition(&s.Conditions, metav1.Condition{Type: c, Status: metav1.ConditionTrue, Reason: c}) + } + }) + return b +} + +// attachmentStatus changes b's attachment status with mutate. +func (f *fixture) attachmentStatus(b *listenerBackend, mutate func(*galacticv1alpha1.EdgeAttachmentStatus)) { + f.t.Helper() + if err := retry.RetryOnConflict(retry.DefaultRetry, func() error { + if err := f.admin.Get(context.Background(), client.ObjectKeyFromObject(b.att), b.att); err != nil { + return err + } + mutate(&b.att.Status) + return f.admin.Status().Update(context.Background(), b.att) + }); err != nil { + f.t.Fatal(err) + } +} + +// setReady sets b's attachment's Ready condition to status, as its provider +// does. +func (f *fixture) setReady(b *listenerBackend, status metav1.ConditionStatus) { + f.t.Helper() + f.attachmentStatus(b, func(s *galacticv1alpha1.EdgeAttachmentStatus) { + meta.SetStatusCondition(&s.Conditions, metav1.Condition{Type: galacticv1alpha1.EdgeAttachmentReady, + Status: status, Reason: "Test"}) + }) +} + +// startDrain drains b's attachment until deadline in one status write, as +// core does when its authority ends: Admitted False, Draining True and the +// drain deadline. +func (f *fixture) startDrain(b *listenerBackend, deadline time.Time) { + f.t.Helper() + f.attachmentStatus(b, func(s *galacticv1alpha1.EdgeAttachmentStatus) { + s.DrainDeadline = &metav1.Time{Time: deadline} + meta.SetStatusCondition(&s.Conditions, metav1.Condition{Type: galacticv1alpha1.EdgeAttachmentAdmitted, + Status: metav1.ConditionFalse, Reason: string(admission.GrantRevoked)}) + meta.SetStatusCondition(&s.Conditions, metav1.Condition{Type: galacticv1alpha1.EdgeAttachmentDraining, + Status: metav1.ConditionTrue, Reason: string(admission.GrantRevoked)}) + }) +} + +// releaseLease releases b's instance lease, as its provider does on exit. +func (f *fixture) releaseLease(b *listenerBackend) { + f.t.Helper() + ctx := context.Background() + store := provider.InstanceStore{Client: f.admin, Namespace: providerNS} + for range 5 { + cur, err := store.Get(ctx, b.inst.Name) + if err != nil { + f.t.Fatal(err) + } + cur.Released = true + if _, err = store.Update(ctx, cur); !errors.Is(err, claim.ErrConflict) { + if err != nil { + f.t.Fatal(err) + } + return + } + } + f.t.Fatal("lease write kept conflicting") +} + +// gateway registers node as a gateway node. +func (f *fixture) gateway(node string) { + f.create(&bgpv1alpha1.NetworkGateway{ + ObjectMeta: metav1.ObjectMeta{Name: node, Namespace: gatewayNS}, + Spec: bgpv1alpha1.NetworkGatewaySpec{TargetRef: bgpv1alpha1.TargetRef{Kind: "Node", Name: node}}, + }) +} + +// acceptedListener starts the controllers and creates an accepted listener +// named name against an ingress service, returning the ingress gVPC and the +// service. +func (f *fixture) acceptedListener(name string) (*cloudv1alpha1.VPC, *galacticv1alpha1.EdgeService) { + f.t.Helper() + f.start(f.listenerConfig()) + vpc := f.readyVPC(providerName) + svc := f.newService(ingressSvc, vpc, []string{SocketAccess, PublicListener}, nil) + f.newListener(name, ingressSvc, vip6, vip4) + f.expectCondition(name, galacticv1alpha1.EdgeListenerAccepted, metav1.ConditionTrue, + galacticv1alpha1.EdgeListenerReasonAccepted) + return vpc, svc +} diff --git a/internal/edge/listener/reconciler.go b/internal/edge/listener/reconciler.go new file mode 100644 index 000000000..38ce0b172 --- /dev/null +++ b/internal/edge/listener/reconciler.go @@ -0,0 +1,210 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package listener + +import ( + "context" + "fmt" + "net/netip" + "time" + + "k8s.io/apimachinery/pkg/api/equality" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + + bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" + galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" +) + +// deadlineRetry is how soon a listener is decided again when a deadline it +// waits for has just passed. +const deadlineRetry = time.Second + +// Reconciler admits EdgeListeners and reports their backends. +// +// A listener is Accepted when its provider may hold a listener, its +// EdgeService grants the provider SocketAccess and PublicListener on the +// provider's ingress gVPC, its addresses are in the cell's gateway VIP +// prefixes, and nothing else serves them on its ports. Its backends are the +// attachments made against its EdgeService; one serves while the listener +// is accepted and the attachment is programmed, ready, holding its +// instance's lease and not past its drain deadline, unless its node runs a +// gateway, which cannot deliver to its own node. +type Reconciler struct { + // Client reads listeners, attachments, instances, leases, services and + // gateways from the cache, and writes status. + Client client.Client + // APIReader reads providers and EdgeServices uncached. + APIReader client.Reader + // Namespace is the gateway namespace, where NetworkGateways live. + Namespace string + // VPCs finds each provider's ingress gVPC. + VPCs IngressVPCs + // VIPPrefixes are the cell's gateway VIP prefixes; a listener address + // outside them is refused. + VIPPrefixes []netip.Prefix + // MaxSkew is the cell's maximum wall-clock error; a grant stops + // admitting MaxSkew before its validUntil. + MaxSkew time.Duration + // Now is the wall clock. Nil means time.Now. + Now func() time.Time +} + +func (r *Reconciler) now() time.Time { + if r.Now != nil { + return r.Now() + } + return time.Now() +} + +// decision is what one pass decided for a listener. +type decision struct { + accepted metav1.Condition + programmed metav1.Condition + backends []backend + // grant is the accepted listener's grant, nil when it is not accepted. + grant *grant + // next is the earliest instant the decision may change with no API + // event, zero for none. + next time.Time +} + +// Reconcile implements reconcile.Reconciler for EdgeListeners. +func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + var l galacticv1alpha1.EdgeListener + if err := r.Client.Get(ctx, req.NamespacedName, &l); err != nil { + return ctrl.Result{}, client.IgnoreNotFound(err) + } + if !l.DeletionTimestamp.IsZero() { + return ctrl.Result{}, nil + } + now := r.now() + d, err := r.decide(ctx, &l, now) + if 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 +} + +// decide admits l and decides its backends. +func (r *Reconciler) decide(ctx context.Context, l *galacticv1alpha1.EdgeListener, now time.Time, +) (*decision, error) { + var svc *galacticv1alpha1.EdgeService + var s galacticv1alpha1.EdgeService + ref := l.Spec.ServiceRef + switch err := r.APIReader.Get(ctx, client.ObjectKey{Namespace: ref.Namespace, Name: ref.Name}, &s); { + case err == nil: + svc = &s + case !apierrors.IsNotFound(err): + return nil, err + } + var listeners galacticv1alpha1.EdgeListenerList + if err := r.Client.List(ctx, &listeners, client.InNamespace(l.Namespace)); err != nil { + return nil, fmt.Errorf("list EdgeListeners: %w", err) + } + var services bgpv1alpha1.NetworkServiceList + if err := r.Client.List(ctx, &services); err != nil { + return nil, fmt.Errorf("list NetworkServices: %w", err) + } + g, refused, err := r.admit(ctx, l, svc, listeners.Items, services.Items, now) + if err != nil { + return nil, err + } + d := &decision{grant: g, accepted: metav1.Condition{Type: galacticv1alpha1.EdgeListenerAccepted, + Status: metav1.ConditionTrue, Reason: galacticv1alpha1.EdgeListenerReasonAccepted, + Message: "the listener is admitted", ObservedGeneration: l.Generation}} + vpc := "" + if refused != nil { + d.accepted.Status, d.accepted.Reason, d.accepted.Message = metav1.ConditionFalse, refused.reason, + refused.message + } else { + vpc, d.next = g.vpc.Status.VPC, g.notAfter + } + gateways, err := r.gatewayNodes(ctx) + if err != nil { + return nil, err + } + backends, drain, err := r.backends(ctx, l, svc, vpc, gateways, now) + if err != nil { + return nil, err + } + d.backends = backends + if !drain.IsZero() && (d.next.IsZero() || drain.Before(d.next)) { + d.next = drain + } + d.programmed = programmed(l, refused == nil, backends) + return d, nil +} + +// programmed is l's Programmed condition from its backends. +func programmed(l *galacticv1alpha1.EdgeListener, accepted bool, backends []backend) metav1.Condition { + serving, local := 0, 0 + for i := range backends { + switch b := &backends[i]; { + case b.serving: + serving++ + case accepted && b.eligible && b.local: + local++ + } + } + c := metav1.Condition{Type: galacticv1alpha1.EdgeListenerProgrammed, Status: metav1.ConditionFalse, + Reason: galacticv1alpha1.EdgeListenerReasonNoBackends, ObservedGeneration: l.Generation} + switch { + case serving > 0: + c.Status, c.Reason = metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonBackendsReady + c.Message = fmt.Sprintf("%d of %d listener attachments are serving", serving, len(backends)) + if local > 0 { + c.Message += fmt.Sprintf("; %d on gateway nodes are excluded", local) + } + case !accepted: + c.Message = "the listener is not accepted" + case local > 0: + c.Reason = galacticv1alpha1.EdgeListenerReasonLocalBackendsExcluded + c.Message = fmt.Sprintf("every eligible listener attachment, %d, is on a gateway node, which cannot "+ + "deliver to its own node", local) + default: + c.Message = "no listener attachment is programmed, ready and holding its instance's lease" + } + return c +} + +// setStatus writes d into l's status, unless it already holds it. +func (r *Reconciler) setStatus(ctx context.Context, l *galacticv1alpha1.EdgeListener, d *decision) error { + before := l.DeepCopy() + s := &l.Status + s.ObservedGeneration = l.Generation + meta.SetStatusCondition(&s.Conditions, d.accepted) + meta.SetStatusCondition(&s.Conditions, d.programmed) + s.Backends = nil + for i := range d.backends { + if len(s.Backends) == maxBackends { + break + } + s.Backends = append(s.Backends, d.backends[i].status()) + } + if equality.Semantic.DeepEqual(before.Status, l.Status) { + return nil + } + if err := r.Client.Status().Patch(ctx, l, + client.MergeFromWithOptions(before, client.MergeFromWithOptimisticLock{})); err != nil { + return fmt.Errorf("update EdgeListener %s/%s status: %w", l.Namespace, l.Name, err) + } + return nil +} + +// requeue schedules the next pass at next, or soon after now when next has +// passed; zero next schedules none. +func requeue(next, now time.Time) ctrl.Result { + if next.IsZero() { + return ctrl.Result{} + } + return ctrl.Result{RequeueAfter: max(next.Sub(now), deadlineRetry)} +} diff --git a/internal/edge/listener/setup.go b/internal/edge/listener/setup.go index 60f362ac8..14279bd09 100644 --- a/internal/edge/listener/setup.go +++ b/internal/edge/listener/setup.go @@ -11,21 +11,32 @@ import ( "net/netip" "time" + coordinationv1 "k8s.io/api/coordination/v1" + "k8s.io/apimachinery/pkg/api/equality" "k8s.io/client-go/tools/events" ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/builder" "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/event" "sigs.k8s.io/controller-runtime/pkg/handler" "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/predicate" "sigs.k8s.io/controller-runtime/pkg/reconcile" cloudv1alpha1 "go.datum.net/galactic/api/cloud/v1alpha1" bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" + edgeroute "go.datum.net/galactic/internal/edge/route" ) +// indexServiceUID indexes an EdgeAttachment by its EdgeService's UID, which +// finds a listener's attachments. +const indexServiceUID = "listener.spec.serviceRef.uid" + // Config is what the listener controllers need from the command line. type Config struct { - // Namespace is the gateway namespace: it holds the ingress gVPCs. + // Namespace is the gateway namespace: it holds the ingress gVPCs, the + // listeners and the NetworkGateways. Namespace string // Identities maps a provider name to its ingress gVPC's fabric // identity. @@ -33,14 +44,23 @@ type Config struct { // IngressPrefix is the platform prefix ingress gVPCs take their /64s // from. It must be valid when Identities is not empty. IngressPrefix netip.Prefix + // VIPPrefixes are the cell's gateway VIP prefixes, which every listener + // address must fall in. + VIPPrefixes []netip.Prefix + // MaxSkew is the cell's maximum wall-clock error, galactic-controller's + // --edge-max-skew. + MaxSkew time.Duration // Events records why a provider has no ingress gVPC; nil records none. Events events.EventRecorder // PrefixRetry is IngressReconciler.PrefixRetry. PrefixRetry time.Duration + // Now is the wall clock. Nil means time.Now. + Now func() time.Time } -// Setup registers the ingress gVPC reconciler with mgr. It runs on the -// leader only. +// Setup registers the ingress gVPC reconciler and the listener reconciler +// with mgr. They run on the leader only. The manager's cache must hold only +// instance leases (see edgeroute.LeaseCache). func Setup(mgr ctrl.Manager, cfg Config) error { if len(cfg.Identities) > 0 && !cfg.IngressPrefix.IsValid() { return errors.New("an ingress prefix is required with ingress identities") @@ -52,6 +72,14 @@ func Setup(mgr ctrl.Manager, cfg Config) error { if err := ingress.setup(mgr); err != nil { return fmt.Errorf("set up ingress gVPC reconciler: %w", err) } + listeners := &Reconciler{ + 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, + } + if err := listeners.setup(mgr); err != nil { + return fmt.Errorf("set up EdgeListener reconciler: %w", err) + } return nil } @@ -105,3 +133,151 @@ func (r *IngressReconciler) setup(mgr ctrl.Manager) error { Watches(&bgpv1alpha1.NetworkService{}, byNetworkService). Complete(r) } + +// specOrDeletion admits creates, deletes, and updates that change an +// object's spec or start its deletion. +var specOrDeletion = predicate.Or(predicate.GenerationChangedPredicate{}, predicate.Funcs{ + CreateFunc: func(event.CreateEvent) bool { return false }, + DeleteFunc: func(event.DeleteEvent) bool { return false }, + GenericFunc: func(event.GenericEvent) bool { return false }, + UpdateFunc: func(e event.UpdateEvent) bool { + return e.ObjectOld.GetDeletionTimestamp().IsZero() != e.ObjectNew.GetDeletionTimestamp().IsZero() + }, +}) + +// contention admits what changes whether an EdgeListener contends with +// newer listeners for its addresses and service: creates, deletes, and +// updates that change its spec, start its deletion or change its Accepted +// condition. +var contention = predicate.Or[client.Object](specOrDeletion, predicate.Funcs{ + CreateFunc: func(event.CreateEvent) bool { return false }, + DeleteFunc: func(event.DeleteEvent) bool { return false }, + GenericFunc: func(event.GenericEvent) bool { return false }, + UpdateFunc: func(e event.UpdateEvent) bool { + o, ok1 := e.ObjectOld.(*galacticv1alpha1.EdgeListener) + n, ok2 := e.ObjectNew.(*galacticv1alpha1.EdgeListener) + return ok1 && ok2 && contends(o) != contends(n) + }, +}) + +// inNamespace admits only objects in namespace. +func inNamespace(namespace string) predicate.Predicate { + return predicate.NewPredicateFuncs(func(o client.Object) bool { return o.GetNamespace() == namespace }) +} + +// leaseHolding admits creates, deletes, and updates of a Lease that change +// what HoldsLease reads: its holder, epoch, released annotation, or what +// binds it to its instance. A renewal changes none of them. +var leaseHolding = predicate.Funcs{ + UpdateFunc: func(e event.UpdateEvent) bool { + o, ok1 := e.ObjectOld.(*coordinationv1.Lease) + n, ok2 := e.ObjectNew.(*coordinationv1.Lease) + if !ok1 || !ok2 { + return true + } + released, pod := galacticv1alpha1.EdgeLeaseReleasedAnnotation, galacticv1alpha1.EdgeLeasePodUIDAnnotation + return !equality.Semantic.DeepEqual(o.Spec.HolderIdentity, n.Spec.HolderIdentity) || + !equality.Semantic.DeepEqual(o.Spec.LeaseTransitions, n.Spec.LeaseTransitions) || + o.Annotations[released] != n.Annotations[released] || o.Annotations[pod] != n.Annotations[pod] || + o.Labels[galacticv1alpha1.EdgeLeaseProviderLabel] != n.Labels[galacticv1alpha1.EdgeLeaseProviderLabel] || + !equality.Semantic.DeepEqual(o.OwnerReferences, n.OwnerReferences) || + o.DeletionTimestamp.IsZero() != n.DeletionTimestamp.IsZero() + }, +} + +func (r *Reconciler) setup(mgr ctrl.Manager) error { + if err := mgr.GetFieldIndexer().IndexField(context.Background(), &galacticv1alpha1.EdgeAttachment{}, + indexServiceUID, func(o client.Object) []string { + a, ok := o.(*galacticv1alpha1.EdgeAttachment) + if !ok || a.Spec.ServiceRef.UID == "" { + return nil + } + return []string{a.Spec.ServiceRef.UID} + }); err != nil { + return fmt.Errorf("index EdgeAttachment %s: %w", indexServiceUID, err) + } + c := mgr.GetClient() + // where enqueues every listener match selects. + where := func(ctx context.Context, match func(*galacticv1alpha1.EdgeListener) bool) []reconcile.Request { + var list galacticv1alpha1.EdgeListenerList + if err := c.List(ctx, &list, client.InNamespace(r.Namespace)); err != nil { + log.FromContext(ctx).Error(err, "list EdgeListeners to enqueue") + return nil + } + var out []reconcile.Request + for i := range list.Items { + if match(&list.Items[i]) { + out = append(out, reconcile.Request{NamespacedName: client.ObjectKeyFromObject(&list.Items[i])}) + } + } + return out + } + all := handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, _ client.Object) []reconcile.Request { + return where(ctx, func(*galacticv1alpha1.EdgeListener) bool { return true }) + }) + byProvider := func(ctx context.Context, name string) []reconcile.Request { + return where(ctx, func(l *galacticv1alpha1.EdgeListener) bool { return l.Spec.ProviderRef.Name == name }) + } + byService := func(ctx context.Context, namespace, name string) []reconcile.Request { + return where(ctx, func(l *galacticv1alpha1.EdgeListener) bool { + return l.Spec.ServiceRef.Namespace == namespace && l.Spec.ServiceRef.Name == name + }) + } + // An instance or its lease reaches the listeners of the attachments + // that name it. + byInstance := handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, o client.Object) []reconcile.Request { + var list galacticv1alpha1.EdgeAttachmentList + if err := c.List(ctx, &list, client.InNamespace(o.GetNamespace())); err != nil { + log.FromContext(ctx).Error(err, "list EdgeAttachments to enqueue", "namespace", o.GetNamespace()) + return nil + } + var out []reconcile.Request + for i := range list.Items { + if a := &list.Items[i]; a.Spec.InstanceRef.Name == o.GetName() { + out = append(out, byService(ctx, a.Spec.ServiceRef.Namespace, a.Spec.ServiceRef.Name)...) + } + } + return out + }) + return ctrl.NewControllerManagedBy(mgr). + Named("edge-listener"). + // The galactic-edge-listener-namespace policy (config/galactic-edge) + // already refuses an EdgeListener outside galactic-system; the + // predicate also ignores one where that policy is not applied or the + // gateway namespace is another, rather than failing on it forever. + For(&galacticv1alpha1.EdgeListener{}, builder.WithPredicates(inNamespace(r.Namespace))). + // 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(&galacticv1alpha1.EdgeProvider{}, handler.EnqueueRequestsFromMapFunc( + func(ctx context.Context, o client.Object) []reconcile.Request { + return byProvider(ctx, o.GetName()) + })). + Watches(&galacticv1alpha1.EdgeService{}, handler.EnqueueRequestsFromMapFunc( + func(ctx context.Context, o client.Object) []reconcile.Request { + return byService(ctx, o.GetNamespace(), o.GetName()) + })). + Watches(&cloudv1alpha1.VPC{}, handler.EnqueueRequestsFromMapFunc( + func(ctx context.Context, o client.Object) []reconcile.Request { + if o.GetLabels()[LabelIngress] != LabelIngressValue { + return nil + } + return byProvider(ctx, o.GetAnnotations()[AnnotationIngressProvider]) + })). + Watches(&galacticv1alpha1.EdgeAttachment{}, handler.EnqueueRequestsFromMapFunc( + func(ctx context.Context, o client.Object) []reconcile.Request { + a, ok := o.(*galacticv1alpha1.EdgeAttachment) + if !ok { + return nil + } + return byService(ctx, a.Spec.ServiceRef.Namespace, a.Spec.ServiceRef.Name) + })). + Watches(&galacticv1alpha1.EdgeInstance{}, byInstance, builder.WithPredicates(specOrDeletion)). + // A lease has its instance's namespace and name. Only who holds it + // decides a backend, not its renewals. + Watches(&coordinationv1.Lease{}, byInstance, builder.WithPredicates(edgeroute.InstanceLeases, leaseHolding)). + // A gateway node cannot deliver to a backend on itself. + Watches(&bgpv1alpha1.NetworkGateway{}, all, builder.WithPredicates(predicate.GenerationChangedPredicate{})). + Complete(r) +} diff --git a/internal/edge/listener/setup_test.go b/internal/edge/listener/setup_test.go new file mode 100644 index 000000000..c1d757106 --- /dev/null +++ b/internal/edge/listener/setup_test.go @@ -0,0 +1,62 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package listener + +import ( + "testing" + + coordinationv1 "k8s.io/api/coordination/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/event" + + galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" +) + +// TestInNamespace: a listener outside the gateway namespace is ignored. +func TestInNamespace(t *testing.T) { + p := inNamespace(gatewayNS) + in := &galacticv1alpha1.EdgeListener{ObjectMeta: metav1.ObjectMeta{Namespace: gatewayNS, Name: "a"}} + out := &galacticv1alpha1.EdgeListener{ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "a"}} + if !p.Create(event.CreateEvent{Object: in}) || p.Create(event.CreateEvent{Object: out}) || + p.Update(event.UpdateEvent{ObjectOld: out, ObjectNew: out}) { + t.Error("inNamespace admits a listener outside the gateway namespace, or refuses one inside") + } +} + +// TestLeaseHolding: a renewal does not reach the listeners; a change of +// holder, epoch or release does. +func TestLeaseHolding(t *testing.T) { + base := &coordinationv1.Lease{ + ObjectMeta: metav1.ObjectMeta{Name: "ei-a", Annotations: map[string]string{ + galacticv1alpha1.EdgeLeaseReleasedAnnotation: "false", galacticv1alpha1.EdgeLeaseSequenceAnnotation: "1", + }}, + Spec: coordinationv1.LeaseSpec{HolderIdentity: ptr.To("proc"), LeaseTransitions: ptr.To[int32](1), + RenewTime: &metav1.MicroTime{}}, + } + for _, tt := range []struct { + name string + mutate func(*coordinationv1.Lease) + want bool + }{ + {"Renewal", func(l *coordinationv1.Lease) { + l.Spec.RenewTime = ptr.To(metav1.NowMicro()) + l.Annotations[galacticv1alpha1.EdgeLeaseSequenceAnnotation] = "2" + }, false}, + {"Holder", func(l *coordinationv1.Lease) { l.Spec.HolderIdentity = nil }, true}, + {"Epoch", func(l *coordinationv1.Lease) { l.Spec.LeaseTransitions = ptr.To[int32](2) }, true}, + {"Released", func(l *coordinationv1.Lease) { + l.Annotations[galacticv1alpha1.EdgeLeaseReleasedAnnotation] = "true" + }, true}, + } { + t.Run(tt.name, func(t *testing.T) { + n := base.DeepCopy() + tt.mutate(n) + if got := leaseHolding.Update(event.UpdateEvent{ObjectOld: base, ObjectNew: n}); got != tt.want { + t.Errorf("leaseHolding = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/internal/edge/provider/provider.go b/internal/edge/provider/provider.go index 437ca26d2..834696800 100644 --- a/internal/edge/provider/provider.go +++ b/internal/edge/provider/provider.go @@ -310,6 +310,17 @@ func ReadLease(ctx context.Context, reader client.Reader, inst *galacticv1alpha1 return r, true, nil } +// HoldsLease reports whether inst holds its lease, as read from reader: the +// Lease is bound to inst, as ReadLease requires, names a holder and is not +// released. It does not check the lease's epoch or renewal time. +func HoldsLease(ctx context.Context, reader client.Reader, inst *galacticv1alpha1.EdgeInstance) (bool, error) { + l, found, err := ReadLease(ctx, reader, inst) + if err != nil { + return false, err + } + return found && l.Holder != "" && !l.Released, nil +} + // bound reports whether l is inst's lease: owned by inst, labeled with // inst's provider and annotated with inst's pod. func bound(l *coordinationv1.Lease, inst *galacticv1alpha1.EdgeInstance) bool { diff --git a/internal/edge/provider/provider_test.go b/internal/edge/provider/provider_test.go index 1dbe2cfa8..b94e26b48 100644 --- a/internal/edge/provider/provider_test.go +++ b/internal/edge/provider/provider_test.go @@ -5,11 +5,16 @@ package provider import ( + "context" "testing" "time" coordinationv1 "k8s.io/api/coordination/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + utilruntime "k8s.io/apimachinery/pkg/util/runtime" + "sigs.k8s.io/controller-runtime/pkg/client/fake" galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" "go.datum.net/galactic/internal/edge/claim" @@ -56,3 +61,48 @@ func TestInstanceName(t *testing.T) { t.Errorf("NewInstance named %q, want %q", inst.Name, InstanceName(uid)) } } + +// TestHoldsLease: an instance holds its lease only while its bound Lease +// names a holder and is not released. +func TestHoldsLease(t *testing.T) { + scheme := runtime.NewScheme() + utilruntime.Must(coordinationv1.AddToScheme(scheme)) + inst := NewInstance("ns", "p", "pod", "pod-uid", "node", "boot") + inst.UID = "inst-uid" + lease := func(holder string, released bool, owner types.UID) *coordinationv1.Lease { + r := claim.Record{Key: inst.Name, Holder: holder, Epoch: 1, Released: released} + annotations := protocolAnnotations(r) + annotations[galacticv1alpha1.EdgeLeasePodUIDAnnotation] = inst.Spec.PodUID + return &coordinationv1.Lease{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: inst.Namespace, Name: inst.Name, + Labels: map[string]string{galacticv1alpha1.EdgeLeaseProviderLabel: "p"}, + Annotations: annotations, + OwnerReferences: []metav1.OwnerReference{{Kind: "EdgeInstance", Name: inst.Name, UID: owner}}, + }, + Spec: InstanceStore{}.spec(r, 1), + } + } + for _, tt := range []struct { + name string + lease *coordinationv1.Lease + want bool + }{ + {"NoLease", nil, false}, + {"Held", lease("proc", false, inst.UID), true}, + {"Released", lease("proc", true, inst.UID), false}, + {"NoHolder", lease("", false, inst.UID), false}, + {"NotBound", lease("proc", false, "other"), false}, + } { + t.Run(tt.name, func(t *testing.T) { + b := fake.NewClientBuilder().WithScheme(scheme) + if tt.lease != nil { + b = b.WithObjects(tt.lease) + } + got, err := HoldsLease(context.Background(), b.Build(), inst) + if err != nil || got != tt.want { + t.Errorf("HoldsLease = %v, %v; want %v", got, err, tt.want) + } + }) + } +} From b3b35312def0b0771567c815fee2e9beb5bb2151 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Sat, 28 Nov 2026 23:10:24 -0500 Subject: [PATCH 02/10] test(edge): Name the listener tests' tenant namespace once Merging the ingress gVPC tests brought the literal namespace name to the count goconst refuses; the listener tests now share one constant. Refs #1509 --- internal/edge/listener/listener_envtest_test.go | 2 +- internal/edge/listener/listener_fixture_envtest_test.go | 8 +++++--- internal/edge/listener/setup_test.go | 2 +- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/internal/edge/listener/listener_envtest_test.go b/internal/edge/listener/listener_envtest_test.go index cb715efd8..9030afb98 100644 --- a/internal/edge/listener/listener_envtest_test.go +++ b/internal/edge/listener/listener_envtest_test.go @@ -73,7 +73,7 @@ func TestListenerAdmission(t *testing.T) { // A tenant service already serving the address claims it, until it // goes. - f.create(&corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "tenant"}}) + f.create(&corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: tenantNS}}) tenant := netService("tenant", "web", vip4, bgpv1alpha1.NetworkServiceProtocolTCP, 443) tenant.Spec.VPCRef = "tenantvpc" tenant.Spec.BackendSelector = webSelector diff --git a/internal/edge/listener/listener_fixture_envtest_test.go b/internal/edge/listener/listener_fixture_envtest_test.go index 0cb17c6a7..f4ee77bfe 100644 --- a/internal/edge/listener/listener_fixture_envtest_test.go +++ b/internal/edge/listener/listener_fixture_envtest_test.go @@ -27,9 +27,11 @@ import ( ) const ( - nodeA = "edge-1" - nodeB = "edge-2" - ingressSvc = "ingress" + nodeA = "edge-1" + nodeB = "edge-2" + ingressSvc = "ingress" + // tenantNS is the namespace of every fixture tenant service. + tenantNS = "tenant" leaseHolder = "proc" ) diff --git a/internal/edge/listener/setup_test.go b/internal/edge/listener/setup_test.go index c1d757106..f15e1fc0c 100644 --- a/internal/edge/listener/setup_test.go +++ b/internal/edge/listener/setup_test.go @@ -19,7 +19,7 @@ import ( func TestInNamespace(t *testing.T) { p := inNamespace(gatewayNS) in := &galacticv1alpha1.EdgeListener{ObjectMeta: metav1.ObjectMeta{Namespace: gatewayNS, Name: "a"}} - out := &galacticv1alpha1.EdgeListener{ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "a"}} + out := &galacticv1alpha1.EdgeListener{ObjectMeta: metav1.ObjectMeta{Namespace: tenantNS, Name: "a"}} if !p.Create(event.CreateEvent{Object: in}) || p.Create(event.CreateEvent{Object: out}) || p.Update(event.UpdateEvent{ObjectOld: out, ObjectNew: out}) { t.Error("inNamespace admits a listener outside the gateway namespace, or refuses one inside") From f077a604cb83f8486d07f23040a719a989ec83c0 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Sun, 29 Nov 2026 00:21:05 -0500 Subject: [PATCH 03/10] fix(edge): Stop serving a listener backend once its lease expires A listener backend counted as serving while its instance lease named a holder and was not released, so a provider that hung and stopped renewing kept serving. Nothing looked again either, because renewals do not trigger a pass. A backend now serves only until its lease expires by the wall clock: the Lease's spec.renewTime plus spec.leaseDurationSeconds, both written from the holder's wall clock on every renewal, less the cell's maximum skew, as the grant expiry check does. A Lease that records no duration uses the cell's lease duration. Core decides the listener again at the earliest expiry, and a renewal of an expired lease triggers a pass. The holder's monotonic clock is not used. The provider contract said these Lease fields are never read; it now says core reads them for listener backends only. Refs #1509 --- cmd/galactic-controller/main.go | 2 +- docs/edge/provider-contract.md | 4 +- internal/edge/listener/backends.go | 31 +++++++++---- .../edge/listener/listener_envtest_test.go | 27 ++++++++++++ .../listener/listener_fixture_envtest_test.go | 24 ++++++++++ internal/edge/listener/reconciler.go | 11 ++++- internal/edge/listener/setup.go | 44 +++++++++++++------ internal/edge/listener/setup_test.go | 24 +++++++--- internal/edge/provider/provider.go | 40 +++++++++++++++++ internal/edge/provider/provider_test.go | 27 ++++++++++++ 10 files changed, 200 insertions(+), 34 deletions(-) diff --git a/cmd/galactic-controller/main.go b/cmd/galactic-controller/main.go index f69d03d31..12a37f158 100644 --- a/cmd/galactic-controller/main.go +++ b/cmd/galactic-controller/main.go @@ -244,7 +244,7 @@ func setupListeners(mgr ctrl.Manager, o *options) error { } if err := edgelistener.Setup(mgr, edgelistener.Config{ Namespace: galactic.SystemNamespace, Identities: identities, IngressPrefix: prefix, VIPPrefixes: vips, - MaxSkew: o.edgeMaxSkew, Events: mgr.GetEventRecorder("galactic-controller"), + MaxSkew: o.edgeMaxSkew, LeaseDuration: timing.Params.Duration, Events: mgr.GetEventRecorder("galactic-controller"), }); err != nil { return fmt.Errorf("set up edge listeners: %w", err) } diff --git a/docs/edge/provider-contract.md b/docs/edge/provider-contract.md index 5bdf0595c..06a9b10dc 100644 --- a/docs/edge/provider-contract.md +++ b/docs/edge/provider-contract.md @@ -230,7 +230,7 @@ The lease is a `coordination.k8s.io/v1` Lease with the instance's namespace and | Label `galactic.datumapis.com/edge-provider` | The instance's provider | | Annotation `galactic.datumapis.com/edge-pod-uid` | The instance's `podUID` | -Core and the node read a Lease as the instance's lease only when it is owned by that instance and its label and pod annotation match the instance; any other Lease of that name is no lease. A provider that finds its instance's or lease's name held by an object naming another pod gets `provider.ErrNameTaken`, which wraps `claim.ErrLost`, so it stops rather than retrying until that object is deleted. `spec.leaseDurationSeconds` and `spec.renewTime` are written for tools that display Leases and are never read: validity runs from the renew start on the node's clock, and observers time a lease on their own clocks. A provider takes a route by compare-and-swap on the route's current version (`provider.Claim`), at the next claim `epoch` whenever the holder changes or its claim ended. A provider's own wait is a courtesy, not the safety mechanism: the provider runs the code, so the foundation cannot rely on it. Safety comes from acceptance. +Core and the node read a Lease as the instance's lease only when it is owned by that instance and its label and pod annotation match the instance; any other Lease of that name is no lease. A provider that finds its instance's or lease's name held by an object naming another pod gets `provider.ErrNameTaken`, which wraps `claim.ErrLost`, so it stops rather than retrying until that object is deleted. `spec.leaseDurationSeconds` and `spec.renewTime` are written on every renewal, from the holder's wall clock. Forwarding never reads them: validity runs from the renew start on the node's clock, and observers time a lease on their own clocks. Core reads them only to stop a listener backend serving once its provider stops renewing (see [Public listener](#public-listener)). A provider takes a route by compare-and-swap on the route's current version (`provider.Claim`), at the next claim `epoch` whenever the holder changes or its claim ended. A provider's own wait is a courtesy, not the safety mechanism: the provider runs the code, so the foundation cannot rely on it. Safety comes from acceptance. ### Acceptance @@ -314,7 +314,7 @@ Core accepts an `EdgeListener` only while all of these hold, and otherwise sets A listener refused at its current generation holds neither its service nor its addresses against a newer one, but its `NetworkService`s claim their addresses against newer listeners until they are gone. A newer listener's `NetworkService`s never claim against an older one, so an older listener that becomes admissible takes its addresses back, and the newer one refuses itself and withdraws. -The listener's backends, in `status.backends`, are the attachments made against its `EdgeService`. One is serving while the listener is accepted and the attachment is `Allocated`, `Programmed` and `Ready`, with its node, gVPC, address and host link reported; is `Admitted`, or `Draining` before its `status.drainDeadline`; and its instance is its pod's, on its node, holding its lease. A backend on a node that a `NetworkGateway` in `galactic-system` targets is never serving, since a gateway cannot deliver to its own node. `Programmed` is True with `BackendsReady` while any backend serves, and otherwise False with `LocalBackendsExcluded` when an eligible backend is excluded that way, or `NoBackends`. +The listener's backends, in `status.backends`, are the attachments made against its `EdgeService`. One is serving while the listener is accepted and the attachment is `Allocated`, `Programmed` and `Ready`, with its node, gVPC, address and host link reported; is `Admitted`, or `Draining` before its `status.drainDeadline`; and its instance is its pod's, on its node, holding its lease, until the Lease's `spec.renewTime` plus its `spec.leaseDurationSeconds` (the cell's lease duration when unset) less the maximum skew. A backend on a node that a `NetworkGateway` in `galactic-system` targets is never serving, since a gateway cannot deliver to its own node. `Programmed` is True with `BackendsReady` while any backend serves, and otherwise False with `LocalBackendsExcluded` when an eligible backend is excluded that way, or `NoBackends`. ### Restart and replacement diff --git a/internal/edge/listener/backends.go b/internal/edge/listener/backends.go index 8bccbea45..a114cf99b 100644 --- a/internal/edge/listener/backends.go +++ b/internal/edge/listener/backends.go @@ -93,11 +93,14 @@ func (r *Reconciler) backends(ctx context.Context, l *galacticv1alpha1.EdgeListe b := backend{att: att} eligible, deadline := attachmentEligible(att, now) if eligible && att.Spec.ProviderRef == l.Spec.ProviderRef { - held, err := r.instanceHolds(ctx, att) + until, held, err := r.instanceHolds(ctx, att) if err != nil { return nil, time.Time{}, err } - b.eligible = held + b.eligible = held && now.Before(until) + if b.eligible && (next.IsZero() || until.Before(next)) { + next = until + } } if b.eligible && !deadline.IsZero() && (next.IsZero() || deadline.Before(next)) { next = deadline @@ -110,22 +113,26 @@ func (r *Reconciler) backends(ctx context.Context, l *galacticv1alpha1.EdgeListe } // instanceHolds reports whether att's instance is its pod's, on its node, -// and holds its lease. Both are read from the cache: the manager caches only +// and holds its lease, and until when by the wall clock: the lease's expiry +// (provider.LeaseExpiry) less the cell's maximum skew, so a holder whose +// clock runs ahead never keeps a backend serving past its lease. Both are read from the cache: the manager caches only // Leases carrying the instance lease label, which every lease bound to an // instance carries, so a Lease the cache lacks is one HoldsLease refuses // anyway. -func (r *Reconciler) instanceHolds(ctx context.Context, att *galacticv1alpha1.EdgeAttachment) (bool, error) { +func (r *Reconciler) instanceHolds(ctx context.Context, att *galacticv1alpha1.EdgeAttachment, +) (time.Time, bool, error) { var inst galacticv1alpha1.EdgeInstance key := client.ObjectKey{Namespace: att.Namespace, Name: att.Spec.InstanceRef.Name} switch err := r.Client.Get(ctx, key, &inst); { case apierrors.IsNotFound(err): - return false, nil + return time.Time{}, false, nil case err != nil: - return false, err + return time.Time{}, false, err case inst.Spec.PodUID != att.Spec.PodUID || inst.Spec.NodeName != att.Status.NodeName: - return false, nil + return time.Time{}, false, nil } - return provider.HoldsLease(ctx, r.Client, &inst) + until, held, err := provider.LeaseExpiry(ctx, r.Client, &inst, r.leaseDuration()) + return until.Add(-r.MaxSkew), held, err } // gatewayNodes is the set of nodes a NetworkGateway in the gateway namespace @@ -143,3 +150,11 @@ func (r *Reconciler) gatewayNodes(ctx context.Context) (map[string]bool, error) } return out, nil } + +// leaseDuration is LeaseDuration, or defaultLeaseDuration when it is zero. +func (r *Reconciler) leaseDuration() time.Duration { + if r.LeaseDuration == 0 { + return defaultLeaseDuration + } + return r.LeaseDuration +} diff --git a/internal/edge/listener/listener_envtest_test.go b/internal/edge/listener/listener_envtest_test.go index 9030afb98..cdb9341d9 100644 --- a/internal/edge/listener/listener_envtest_test.go +++ b/internal/edge/listener/listener_envtest_test.go @@ -174,3 +174,30 @@ func TestListenerBackends(t *testing.T) { t.Error("a backend whose lease is released is serving") } } + +// TestListenerLeaseExpiry checks that a backend whose provider stops +// renewing its lease stops serving once the lease expires by the wall +// clock, less the cell's maximum skew, and Programmed follows; and that a +// renewal brings it back. +func TestListenerLeaseExpiry(t *testing.T) { + f := startAPI(t) + programmed := galacticv1alpha1.EdgeListenerProgrammed + cfg := f.listenerConfig() + cfg.LeaseDuration = 8 * time.Second + f.start(cfg) + vpc := f.readyVPC(providerName) + svc := f.newService(ingressSvc, vpc, []string{SocketAccess, PublicListener}, nil) + f.newListener("public", ingressSvc, vip6, vip4) + a := f.newBackend("a", svc, vpc, nodeA, 1) + f.expectCondition("public", programmed, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonBackendsReady) + start := time.Now() + f.expectCondition("public", programmed, metav1.ConditionFalse, galacticv1alpha1.EdgeListenerReasonNoBackends) + if elapsed := time.Since(start); elapsed > 8*time.Second { + t.Errorf("the backend stopped serving %s after its last renewal, past its lease", elapsed) + } + if f.serving()[a.att.Name] { + t.Error("a backend whose lease expired is serving") + } + f.renewLease(a) + f.expectCondition("public", programmed, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonBackendsReady) +} diff --git a/internal/edge/listener/listener_fixture_envtest_test.go b/internal/edge/listener/listener_fixture_envtest_test.go index f4ee77bfe..1af36ab9c 100644 --- a/internal/edge/listener/listener_fixture_envtest_test.go +++ b/internal/edge/listener/listener_fixture_envtest_test.go @@ -43,6 +43,8 @@ func (f *fixture) listenerConfig() Config { cfg := f.config() cfg.VIPPrefixes = vipPool cfg.MaxSkew = 2 * time.Second + // Fixture leases record no duration and are never renewed. + cfg.LeaseDuration = time.Hour return cfg } @@ -244,6 +246,28 @@ func (f *fixture) startDrain(b *listenerBackend, deadline time.Time) { }) } +// renewLease renews b's instance lease, as its provider does, which stamps +// the Lease's renewal time. +func (f *fixture) renewLease(b *listenerBackend) { + f.t.Helper() + ctx := context.Background() + store := provider.InstanceStore{Client: f.admin, Namespace: providerNS} + for range 5 { + cur, err := store.Get(ctx, b.inst.Name) + if err != nil { + f.t.Fatal(err) + } + cur.Sequence++ + if _, err = store.Update(ctx, cur); !errors.Is(err, claim.ErrConflict) { + if err != nil { + f.t.Fatal(err) + } + return + } + } + f.t.Fatal("lease write kept conflicting") +} + // releaseLease releases b's instance lease, as its provider does on exit. func (f *fixture) releaseLease(b *listenerBackend) { f.t.Helper() diff --git a/internal/edge/listener/reconciler.go b/internal/edge/listener/reconciler.go index 38ce0b172..fe9cfaf79 100644 --- a/internal/edge/listener/reconciler.go +++ b/internal/edge/listener/reconciler.go @@ -25,6 +25,9 @@ import ( // waits for has just passed. const deadlineRetry = time.Second +// defaultLeaseDuration is the foundation's lease duration, timing.Params'. +const defaultLeaseDuration = 15 * time.Second + // Reconciler admits EdgeListeners and reports their backends. // // A listener is Accepted when its provider may hold a listener, its @@ -33,7 +36,7 @@ const deadlineRetry = time.Second // prefixes, and nothing else serves them on its ports. Its backends are the // attachments made against its EdgeService; one serves while the listener // is accepted and the attachment is programmed, ready, holding its -// instance's lease and not past its drain deadline, unless its node runs a +// instance's lease unexpired and not past its drain deadline, unless its node runs a // gateway, which cannot deliver to its own node. type Reconciler struct { // Client reads listeners, attachments, instances, leases, services and @@ -49,8 +52,12 @@ type Reconciler struct { // outside them is refused. VIPPrefixes []netip.Prefix // MaxSkew is the cell's maximum wall-clock error; a grant stops - // admitting MaxSkew before its validUntil. + // admitting MaxSkew before its validUntil, and a backend stops serving + // MaxSkew before its lease expires. MaxSkew time.Duration + // LeaseDuration is how long a renewal holds an instance lease that + // records no duration of its own. Zero means defaultLeaseDuration. + LeaseDuration time.Duration // Now is the wall clock. Nil means time.Now. Now func() time.Time } diff --git a/internal/edge/listener/setup.go b/internal/edge/listener/setup.go index 14279bd09..a863e10c6 100644 --- a/internal/edge/listener/setup.go +++ b/internal/edge/listener/setup.go @@ -26,6 +26,7 @@ import ( cloudv1alpha1 "go.datum.net/galactic/api/cloud/v1alpha1" bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" + "go.datum.net/galactic/internal/edge/provider" edgeroute "go.datum.net/galactic/internal/edge/route" ) @@ -50,6 +51,8 @@ type Config struct { // MaxSkew is the cell's maximum wall-clock error, galactic-controller's // --edge-max-skew. MaxSkew time.Duration + // LeaseDuration is Reconciler.LeaseDuration. + LeaseDuration time.Duration // Events records why a provider has no ingress gVPC; nil records none. Events events.EventRecorder // PrefixRetry is IngressReconciler.PrefixRetry. @@ -75,7 +78,7 @@ func Setup(mgr ctrl.Manager, cfg Config) error { listeners := &Reconciler{ 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, + VIPPrefixes: cfg.VIPPrefixes, MaxSkew: cfg.MaxSkew, Now: cfg.Now, LeaseDuration: cfg.LeaseDuration, } if err := listeners.setup(mgr); err != nil { return fmt.Errorf("set up EdgeListener reconciler: %w", err) @@ -166,23 +169,36 @@ func inNamespace(namespace string) predicate.Predicate { } // leaseHolding admits creates, deletes, and updates of a Lease that change -// what HoldsLease reads: its holder, epoch, released annotation, or what -// binds it to its instance. A renewal changes none of them. -var leaseHolding = predicate.Funcs{ - UpdateFunc: func(e event.UpdateEvent) bool { +// whether it is held: its holder, epoch, released annotation, or what binds +// it to its instance, or a renewal of a lease that had expired by the wall +// clock at now. Other renewals only move a lease's expiry later, and the +// listener is decided again at the expiry it last saw. +func (r *Reconciler) leaseHolding() predicate.Funcs { + return predicate.Funcs{UpdateFunc: func(e event.UpdateEvent) bool { o, ok1 := e.ObjectOld.(*coordinationv1.Lease) n, ok2 := e.ObjectNew.(*coordinationv1.Lease) if !ok1 || !ok2 { return true } - released, pod := galacticv1alpha1.EdgeLeaseReleasedAnnotation, galacticv1alpha1.EdgeLeasePodUIDAnnotation - return !equality.Semantic.DeepEqual(o.Spec.HolderIdentity, n.Spec.HolderIdentity) || - !equality.Semantic.DeepEqual(o.Spec.LeaseTransitions, n.Spec.LeaseTransitions) || - o.Annotations[released] != n.Annotations[released] || o.Annotations[pod] != n.Annotations[pod] || - o.Labels[galacticv1alpha1.EdgeLeaseProviderLabel] != n.Labels[galacticv1alpha1.EdgeLeaseProviderLabel] || - !equality.Semantic.DeepEqual(o.OwnerReferences, n.OwnerReferences) || - o.DeletionTimestamp.IsZero() != n.DeletionTimestamp.IsZero() - }, + if leaseChanged(o, n) { + return true + } + now := r.now() + oldUntil, oldOK, _ := provider.WallExpiry(o, r.leaseDuration()) + newUntil, newOK, _ := provider.WallExpiry(n, r.leaseDuration()) + return (!oldOK || !now.Before(oldUntil.Add(-r.MaxSkew))) && newOK && now.Before(newUntil.Add(-r.MaxSkew)) + }} +} + +// leaseChanged reports whether n differs from o in what HoldsLease reads. +func leaseChanged(o, n *coordinationv1.Lease) bool { + released, pod := galacticv1alpha1.EdgeLeaseReleasedAnnotation, galacticv1alpha1.EdgeLeasePodUIDAnnotation + return !equality.Semantic.DeepEqual(o.Spec.HolderIdentity, n.Spec.HolderIdentity) || + !equality.Semantic.DeepEqual(o.Spec.LeaseTransitions, n.Spec.LeaseTransitions) || + o.Annotations[released] != n.Annotations[released] || o.Annotations[pod] != n.Annotations[pod] || + o.Labels[galacticv1alpha1.EdgeLeaseProviderLabel] != n.Labels[galacticv1alpha1.EdgeLeaseProviderLabel] || + !equality.Semantic.DeepEqual(o.OwnerReferences, n.OwnerReferences) || + o.DeletionTimestamp.IsZero() != n.DeletionTimestamp.IsZero() } func (r *Reconciler) setup(mgr ctrl.Manager) error { @@ -276,7 +292,7 @@ func (r *Reconciler) setup(mgr ctrl.Manager) error { Watches(&galacticv1alpha1.EdgeInstance{}, byInstance, builder.WithPredicates(specOrDeletion)). // A lease has its instance's namespace and name. Only who holds it // decides a backend, not its renewals. - Watches(&coordinationv1.Lease{}, byInstance, builder.WithPredicates(edgeroute.InstanceLeases, leaseHolding)). + Watches(&coordinationv1.Lease{}, byInstance, builder.WithPredicates(edgeroute.InstanceLeases, r.leaseHolding())). // A gateway node cannot deliver to a backend on itself. Watches(&bgpv1alpha1.NetworkGateway{}, all, builder.WithPredicates(predicate.GenerationChangedPredicate{})). Complete(r) diff --git a/internal/edge/listener/setup_test.go b/internal/edge/listener/setup_test.go index f15e1fc0c..6a8c740fa 100644 --- a/internal/edge/listener/setup_test.go +++ b/internal/edge/listener/setup_test.go @@ -6,6 +6,7 @@ package listener import ( "testing" + "time" coordinationv1 "k8s.io/api/coordination/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -26,15 +27,18 @@ func TestInNamespace(t *testing.T) { } } -// TestLeaseHolding: a renewal does not reach the listeners; a change of -// holder, epoch or release does. +// TestLeaseHolding: a renewal of a live lease does not reach the listeners; +// a change of holder, epoch or release does, and so does a renewal that +// revives a lease that had expired. func TestLeaseHolding(t *testing.T) { + now := time.Date(2026, 11, 29, 12, 0, 0, 0, time.UTC) + r := &Reconciler{MaxSkew: 2 * time.Second, LeaseDuration: 15 * time.Second, Now: func() time.Time { return now }} base := &coordinationv1.Lease{ ObjectMeta: metav1.ObjectMeta{Name: "ei-a", Annotations: map[string]string{ galacticv1alpha1.EdgeLeaseReleasedAnnotation: "false", galacticv1alpha1.EdgeLeaseSequenceAnnotation: "1", }}, Spec: coordinationv1.LeaseSpec{HolderIdentity: ptr.To("proc"), LeaseTransitions: ptr.To[int32](1), - RenewTime: &metav1.MicroTime{}}, + RenewTime: ptr.To(metav1.NewMicroTime(now.Add(-5 * time.Second)))}, } for _, tt := range []struct { name string @@ -42,9 +46,10 @@ func TestLeaseHolding(t *testing.T) { want bool }{ {"Renewal", func(l *coordinationv1.Lease) { - l.Spec.RenewTime = ptr.To(metav1.NowMicro()) + l.Spec.RenewTime = ptr.To(metav1.NewMicroTime(now)) l.Annotations[galacticv1alpha1.EdgeLeaseSequenceAnnotation] = "2" }, false}, + {"RevivesExpired", nil, true}, {"Holder", func(l *coordinationv1.Lease) { l.Spec.HolderIdentity = nil }, true}, {"Epoch", func(l *coordinationv1.Lease) { l.Spec.LeaseTransitions = ptr.To[int32](2) }, true}, {"Released", func(l *coordinationv1.Lease) { @@ -52,9 +57,14 @@ func TestLeaseHolding(t *testing.T) { }, true}, } { t.Run(tt.name, func(t *testing.T) { - n := base.DeepCopy() - tt.mutate(n) - if got := leaseHolding.Update(event.UpdateEvent{ObjectOld: base, ObjectNew: n}); got != tt.want { + old, n := base.DeepCopy(), base.DeepCopy() + if tt.mutate == nil { + old.Spec.RenewTime = ptr.To(metav1.NewMicroTime(now.Add(-time.Minute))) + n.Spec.RenewTime = ptr.To(metav1.NewMicroTime(now)) + } else { + tt.mutate(n) + } + if got := r.leaseHolding().Update(event.UpdateEvent{ObjectOld: old, ObjectNew: n}); got != tt.want { t.Errorf("leaseHolding = %v, want %v", got, tt.want) } }) diff --git a/internal/edge/provider/provider.go b/internal/edge/provider/provider.go index 834696800..0658aba7e 100644 --- a/internal/edge/provider/provider.go +++ b/internal/edge/provider/provider.go @@ -321,6 +321,46 @@ func HoldsLease(ctx context.Context, reader client.Reader, inst *galacticv1alpha return found && l.Holder != "" && !l.Released, nil } +// LeaseExpiry returns the wall-clock instant inst's lease, as read from +// reader, stops being held, and true; or false when inst does not hold it +// (see HoldsLease) or the Lease records no renewal time. The instant is the +// Lease's spec.renewTime plus its spec.leaseDurationSeconds, or plus +// fallback when the Lease records no duration. Both fields are written from +// the holder's wall clock on every renewal, so a reader allows for the +// cell's clock skew. +func LeaseExpiry(ctx context.Context, reader client.Reader, inst *galacticv1alpha1.EdgeInstance, + fallback time.Duration) (time.Time, bool, error) { + var l coordinationv1.Lease + switch err := reader.Get(ctx, client.ObjectKeyFromObject(inst), &l); { + case apierrors.IsNotFound(err): + return time.Time{}, false, nil + case err != nil: + return time.Time{}, false, err + } + if !bound(&l, inst) { + return time.Time{}, false, nil + } + r, err := record(&l) + if err != nil || r.Holder == "" || r.Released { + return time.Time{}, false, nil + } + return WallExpiry(&l, fallback) +} + +// WallExpiry returns l's spec.renewTime plus its spec.leaseDurationSeconds, +// or plus fallback when l records no duration, and true; or false when l +// records no renewal time. +func WallExpiry(l *coordinationv1.Lease, fallback time.Duration) (time.Time, bool, error) { + if l.Spec.RenewTime == nil { + return time.Time{}, false, nil + } + d := fallback + if s := l.Spec.LeaseDurationSeconds; s != nil && *s > 0 { + d = time.Duration(*s) * time.Second + } + return l.Spec.RenewTime.Add(d), true, nil +} + // bound reports whether l is inst's lease: owned by inst, labeled with // inst's provider and annotated with inst's pod. func bound(l *coordinationv1.Lease, inst *galacticv1alpha1.EdgeInstance) bool { diff --git a/internal/edge/provider/provider_test.go b/internal/edge/provider/provider_test.go index b94e26b48..d1fe1ec2d 100644 --- a/internal/edge/provider/provider_test.go +++ b/internal/edge/provider/provider_test.go @@ -106,3 +106,30 @@ func TestHoldsLease(t *testing.T) { }) } } + +// TestWallExpiry: a lease expires its duration after its renewal time, by +// the cell's lease duration when it records none, and has no expiry without +// a renewal time. +func TestWallExpiry(t *testing.T) { + renew := metav1.NewMicroTime(time.Date(2026, 11, 29, 12, 0, 0, 0, time.UTC)) + for _, tt := range []struct { + name string + spec coordinationv1.LeaseSpec + want time.Time + wantOK bool + }{ + {"Recorded", coordinationv1.LeaseSpec{RenewTime: &renew, LeaseDurationSeconds: ptrInt32(10)}, + renew.Add(10 * time.Second), true}, + {"Fallback", coordinationv1.LeaseSpec{RenewTime: &renew}, renew.Add(15 * time.Second), true}, + {"NoRenewal", coordinationv1.LeaseSpec{LeaseDurationSeconds: ptrInt32(10)}, time.Time{}, false}, + } { + t.Run(tt.name, func(t *testing.T) { + got, ok, err := WallExpiry(&coordinationv1.Lease{Spec: tt.spec}, 15*time.Second) + if err != nil || ok != tt.wantOK || !got.Equal(tt.want) { + t.Errorf("WallExpiry = %v, %v, %v; want %v, %v", got, ok, err, tt.want, tt.wantOK) + } + }) + } +} + +func ptrInt32(v int32) *int32 { return &v } From 3a6edd6eda3d841736174b01caa59975b64b1746 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Sun, 29 Nov 2026 00:23:44 -0500 Subject: [PATCH 04/10] fix(edge): Claim a listener address only as the gateway would claimedBy counted every older NetworkService in any namespace, so a project-namespace service, or one the gateway itself refused, could keep a platform listener refused. It now follows the gateway's precedence (tenantVIPConflicts in internal/controller/servicescope.go): a gateway-namespace service never loses to a project-namespace one, so a project-namespace service never claims against a listener; a service the gateway refused (VIPClaimed, VIPOutsidePool, OwnershipDenied or ProjectServicesOff, on Accepted or a node's Programmed condition) claims nothing; and a gateway-namespace service claims only when it was created no later than the listener. The gateway does not choose between two gateway-namespace services without an address group and serves both, so core keeps refusing the newer listener there. Oldest-wins between listeners is unchanged. Refs #1509 --- docs/edge/provider-contract.md | 12 ++--- internal/edge/listener/admit.go | 33 ++++++++++--- internal/edge/listener/admit_test.go | 48 +++++++++++++------ .../edge/listener/listener_envtest_test.go | 38 ++++++++++----- 4 files changed, 92 insertions(+), 39 deletions(-) diff --git a/docs/edge/provider-contract.md b/docs/edge/provider-contract.md index 06a9b10dc..1b795d94e 100644 --- a/docs/edge/provider-contract.md +++ b/docs/edge/provider-contract.md @@ -305,12 +305,12 @@ Core (`internal/edge/listener`) keeps one ingress gVPC per approved provider tha Core accepts an `EdgeListener` only while all of these hold, and otherwise sets `Accepted` False with the reason of the first that fails: -| Reason | Rule | -| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `ProviderNotApproved` | The provider exists, is approved and not being deleted, and lists `PublicListener` at a version core implements. | -| `CapabilityNotGranted` | The listener's `EdgeService` exists, is not being deleted, names the listener's provider, grants `SocketAccess` and `PublicListener` on the provider's ingress gVPC, has not passed `validUntil` less the maximum skew, and serves no older listener. | -| `AddressOutsidePool` | Every address falls in one of the prefixes of `--edge-listener-vip-prefixes`. | -| `AddressClaimed` | Nothing older serves one of the listener's addresses on one of its protocols and ports: no older listener, no `NetworkService` of an older listener, and no other `NetworkService`, in any namespace, created no later than the listener. | +| Reason | Rule | +| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `ProviderNotApproved` | The provider exists, is approved and not being deleted, and lists `PublicListener` at a version core implements. | +| `CapabilityNotGranted` | The listener's `EdgeService` exists, is not being deleted, names the listener's provider, grants `SocketAccess` and `PublicListener` on the provider's ingress gVPC, has not passed `validUntil` less the maximum skew, and serves no older listener. | +| `AddressOutsidePool` | Every address falls in one of the prefixes of `--edge-listener-vip-prefixes`. | +| `AddressClaimed` | Nothing older serves one of the listener's addresses on one of its protocols and ports: no older listener, no `NetworkService` of an older listener, and no other `NetworkService` in `galactic-system` that the gateway serves and that was created no later than the listener. A project-namespace service never claims, since the gateway always prefers a gateway-namespace one, and neither does a service the gateway refused (`VIPClaimed`, `VIPOutsidePool`, `OwnershipDenied`, `ProjectServicesOff`). | A listener refused at its current generation holds neither its service nor its addresses against a newer one, but its `NetworkService`s claim their addresses against newer listeners until they are gone. A newer listener's `NetworkService`s never claim against an older one, so an older listener that becomes admissible takes its addresses back, and the newer one refuses itself and withdraws. diff --git a/internal/edge/listener/admit.go b/internal/edge/listener/admit.go index 6a138500e..7d80c0a6b 100644 --- a/internal/edge/listener/admit.go +++ b/internal/edge/listener/admit.go @@ -151,12 +151,32 @@ func older(a, b *galacticv1alpha1.EdgeListener) bool { return a.Name < b.Name } +// gatewayRefusals are the reasons the gateway gives on a NetworkService's +// Accepted condition, or on a node's Programmed condition, when it refuses +// to serve the service's addresses (internal/controller servicescope.go). +var gatewayRefusals = []string{"VIPClaimed", "VIPOutsidePool", "ProjectServicesOff", + bgpv1alpha1.AcceptedReasonOwnershipDenied} + +// gatewayRefused reports whether the gateway refuses to serve s: any of its +// conditions is False with one of gatewayRefusals. +func gatewayRefused(s *bgpv1alpha1.NetworkService) bool { + return slices.ContainsFunc(s.Status.Conditions, func(c metav1.Condition) bool { + return c.Status == metav1.ConditionFalse && slices.Contains(gatewayRefusals, c.Reason) + }) +} + // serviceClaims reports whether NetworkService s, which serves no listener -// in l's namespace that still exists, claims its addresses against l: it was -// created no later than l, so a service created after an accepted listener -// never evicts it. +// in l's namespace that still exists, claims its addresses against l, as +// the gateway decides between the two (tenantVIPConflicts in +// internal/controller/servicescope.go): s is in l's namespace, the gateway +// namespace, since a project-namespace service always loses to a gateway +// one; the gateway has not refused it; and it was created no later than l, +// so a service created after an accepted listener never evicts it. The +// gateway itself does not choose between two gateway-namespace services +// without an address group, and serves both; core refuses the newer +// listener instead. func serviceClaims(s *bgpv1alpha1.NetworkService, l *galacticv1alpha1.EdgeListener) bool { - return !l.CreationTimestamp.Before(&s.CreationTimestamp) + return s.Namespace == l.Namespace && !gatewayRefused(s) && !l.CreationTimestamp.Before(&s.CreationTimestamp) } // outsidePool returns the first of addresses that no prefix of pool @@ -232,8 +252,9 @@ func servicePorts(s *bgpv1alpha1.NetworkService) []vipPort { // status, so it claims while it lingers being torn down. One naming a // younger listener never claims: that listener's own pass refuses // itself and withdraws its services. -// - Any other NetworkService, in any namespace, claims when it was created -// no later than l (see serviceClaims). Those naming l never claim. +// - Any other NetworkService claims as serviceClaims says: only in the +// gateway namespace, only while the gateway serves it, and only when it +// was created no later than l. Those naming l never claim. // - An older listener in l's namespace that contends claims its ports. // // Of several claims, the one with the least name is returned. diff --git a/internal/edge/listener/admit_test.go b/internal/edge/listener/admit_test.go index 6c71c2407..84c822348 100644 --- a/internal/edge/listener/admit_test.go +++ b/internal/edge/listener/admit_test.go @@ -7,6 +7,7 @@ package listener import ( "net/netip" "slices" + "strings" "testing" "time" @@ -109,7 +110,10 @@ func TestClaimedBy(t *testing.T) { s.Spec.EdgeListenerRef = &bgpv1alpha1.NetworkServiceEdgeListenerReference{Name: listener} return s } - ranged := netService("tenant", "range", vip6, udp, 0) + gw := func(name, vip string, protocol bgpv1alpha1.NetworkServiceProtocol, port int32) bgpv1alpha1.NetworkService { + return netService(gatewayNS, name, vip, protocol, port) + } + ranged := gw("range", vip6, udp, 0) ranged.Spec.PortRange = &bgpv1alpha1.PortRange{Start: 400, End: 500} deleting := listenerAt("old-deleting", 10, vip6) deleting.DeletionTimestamp = &metav1.Time{Time: time.Unix(200, 0)} @@ -126,8 +130,16 @@ func TestClaimedBy(t *testing.T) { svc.CreationTimestamp = metav1.Unix(sec, 0) return svc } - newer := at(netService("tenant", "newer", vip6, udp, 443), 101) - sameAge := at(netService("tenant", "same", vip6, udp, 443), 100) + newer := at(gw("newer", vip6, udp, 443), 101) + sameAge := at(gw("same", vip6, udp, 443), 100) + refusedBy := func(typ, reason string) bgpv1alpha1.NetworkService { + svc := gw("refused-"+strings.ToLower(reason), vip6, udp, 443) + svc.Status.Conditions = []metav1.Condition{{Type: typ, Status: metav1.ConditionFalse, Reason: reason}} + return svc + } + noNodes := gw("no-nodes", vip6, udp, 443) + noNodes.Status.Conditions = []metav1.Condition{{Type: bgpv1alpha1.ConditionTypeAccepted, + Status: metav1.ConditionFalse, Reason: "NoGatewayNodes"}} newerRefused := listenerAt("late", 300, vip6) newerRefused.Status.Conditions = []metav1.Condition{{Type: galacticv1alpha1.EdgeListenerAccepted, Status: metav1.ConditionFalse, Reason: galacticv1alpha1.EdgeListenerReasonAddressClaimed}} @@ -141,20 +153,26 @@ func TestClaimedBy(t *testing.T) { want string }{ {"Nothing", nil, nil, ""}, - {"OtherPort", nil, []bgpv1alpha1.NetworkService{netService("tenant", "a", vip6, udp, 8443)}, ""}, - {"OtherProtocol", nil, []bgpv1alpha1.NetworkService{netService("tenant", "a", vip6, "sctp", 443)}, ""}, - {"OtherAddress", nil, []bgpv1alpha1.NetworkService{netService("tenant", "a", "2001:db8:100::11", udp, 443)}, - ""}, - {"TenantService", nil, []bgpv1alpha1.NetworkService{netService("tenant", "a", vip4, tcp, 443)}, - "NetworkService tenant/a"}, - {"PortRange", nil, []bgpv1alpha1.NetworkService{ranged}, "NetworkService tenant/range"}, - {"LeastName", nil, []bgpv1alpha1.NetworkService{netService("tenant", "b", vip6, udp, 443), - netService("tenant", "a", vip4, udp, 443)}, "NetworkService tenant/a"}, + {"OtherPort", nil, []bgpv1alpha1.NetworkService{gw("a", vip6, udp, 8443)}, ""}, + {"OtherProtocol", nil, []bgpv1alpha1.NetworkService{gw("a", vip6, "sctp", 443)}, ""}, + {"OtherAddress", nil, []bgpv1alpha1.NetworkService{gw("a", "2001:db8:100::11", udp, 443)}, ""}, + {"GatewayService", nil, []bgpv1alpha1.NetworkService{gw("a", vip4, tcp, 443)}, + "NetworkService " + gatewayNS + "/a"}, + {"PortRange", nil, []bgpv1alpha1.NetworkService{ranged}, "NetworkService " + gatewayNS + "/range"}, + {"LeastName", nil, []bgpv1alpha1.NetworkService{gw("b", vip6, udp, 443), gw("a", vip4, udp, 443)}, + "NetworkService " + gatewayNS + "/a"}, + {"ProjectService", nil, []bgpv1alpha1.NetworkService{netService("tenant", "a", vip4, tcp, 443)}, ""}, + {"VIPClaimedOnNode", nil, []bgpv1alpha1.NetworkService{refusedBy("node-a/Programmed", "VIPClaimed")}, ""}, + {"VIPOutsidePool", nil, []bgpv1alpha1.NetworkService{ + refusedBy(bgpv1alpha1.ConditionTypeAccepted, "VIPOutsidePool")}, ""}, + {"OwnershipDenied", nil, []bgpv1alpha1.NetworkService{ + refusedBy(bgpv1alpha1.ConditionTypeAccepted, bgpv1alpha1.AcceptedReasonOwnershipDenied)}, ""}, + {"NoGatewayNodesStillClaims", nil, []bgpv1alpha1.NetworkService{noNodes}, + "NetworkService " + gatewayNS + "/no-nodes"}, {"OwnService", []galacticv1alpha1.EdgeListener{self}, []bgpv1alpha1.NetworkService{withRef(netService(gatewayNS, "self-udp-443", vip6, udp, 443), "self")}, ""}, {"OwnServiceElsewhere", []galacticv1alpha1.EdgeListener{self}, - []bgpv1alpha1.NetworkService{withRef(netService("tenant", "x", vip6, udp, 443), "self")}, - "NetworkService tenant/x"}, + []bgpv1alpha1.NetworkService{withRef(netService("tenant", "x", vip6, udp, 443), "self")}, ""}, {"NewerListener", []galacticv1alpha1.EdgeListener{self, listenerAt("newer", 200, vip6)}, nil, ""}, {"NewerListenersService", []galacticv1alpha1.EdgeListener{self, listenerAt("newer", 200, vip6)}, []bgpv1alpha1.NetworkService{withRef(netService(gatewayNS, "newer-udp-443", vip6, udp, 443), "newer")}, ""}, @@ -164,7 +182,7 @@ func TestClaimedBy(t *testing.T) { "EdgeListener " + gatewayNS + "/peer"}, {"SameAgeGreaterName", []galacticv1alpha1.EdgeListener{self, listenerAt("then", 100, vip6)}, nil, ""}, {"NewerService", nil, []bgpv1alpha1.NetworkService{newer}, ""}, - {"SameAgeService", nil, []bgpv1alpha1.NetworkService{sameAge}, "NetworkService tenant/same"}, + {"SameAgeService", nil, []bgpv1alpha1.NetworkService{sameAge}, "NetworkService " + gatewayNS + "/same"}, {"NewerRefusedListenersService", []galacticv1alpha1.EdgeListener{self, newerRefused}, []bgpv1alpha1.NetworkService{withRef(netService(gatewayNS, "late-udp-443", vip6, udp, 443), "late")}, ""}, {"OlderListenersServiceAfterSelf", []galacticv1alpha1.EdgeListener{self, listenerAt("older", 50, vip4)}, diff --git a/internal/edge/listener/listener_envtest_test.go b/internal/edge/listener/listener_envtest_test.go index cdb9341d9..d15644aed 100644 --- a/internal/edge/listener/listener_envtest_test.go +++ b/internal/edge/listener/listener_envtest_test.go @@ -6,6 +6,7 @@ package listener import ( "context" + "strings" "testing" "time" @@ -71,31 +72,44 @@ func TestListenerAdmission(t *testing.T) { t.Fatal(err) } - // A tenant service already serving the address claims it, until it - // goes. + // Only an older gateway-namespace service the gateway serves claims the + // address, as the gateway decides: not a project-namespace service, + // which always loses to a gateway one, and not one the gateway refused. f.create(&corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: tenantNS}}) - tenant := netService("tenant", "web", vip4, bgpv1alpha1.NetworkServiceProtocolTCP, 443) - tenant.Spec.VPCRef = "tenantvpc" - tenant.Spec.BackendSelector = webSelector - f.create(&tenant) + service := func(namespace, name string) *bgpv1alpha1.NetworkService { + s := netService(namespace, name, vip4, bgpv1alpha1.NetworkServiceProtocolTCP, 443) + s.Spec.VPCRef = "tenantvpc" + s.Spec.BackendSelector = webSelector + f.create(&s) + return &s + } + service(tenantNS, "web") + refusedSvc := service(gatewayNS, "refused") + refusedSvc.Status.Conditions = []metav1.Condition{{Type: bgpv1alpha1.ConditionTypeAccepted, + Status: metav1.ConditionFalse, Reason: "VIPClaimed", Message: "refused", LastTransitionTime: metav1.Now()}} + if err := f.admin.Status().Update(ctx, refusedSvc); err != nil { + t.Fatal(err) + } + platform := service(gatewayNS, "platform") f.newListener("public", ingressSvc, vip6, vip4) expectRefused("public", galacticv1alpha1.EdgeListenerReasonAddressClaimed) - if err := f.admin.Delete(ctx, &tenant); err != nil { + if c := meta.FindStatusCondition(f.listener("public").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) // A service created after the listener does not evict it. nextSecond() - late := netService("tenant", "late", vip4, bgpv1alpha1.NetworkServiceProtocolTCP, 443) - late.Spec.VPCRef = "tenantvpc" - late.Spec.BackendSelector = webSelector - f.create(&late) + late := service(gatewayNS, "late") never(t, "a newer NetworkService evicted an accepted listener", func() bool { c := meta.FindStatusCondition(f.listener("public").Status.Conditions, accepted) return c == nil || c.Status != metav1.ConditionTrue }) - if err := f.admin.Delete(ctx, &late); err != nil { + if err := f.admin.Delete(ctx, late); err != nil { t.Fatal(err) } From 08d1fbf2720744f0a6ae42ef64a9a43916a547fa Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Sun, 29 Nov 2026 08:01:29 -0500 Subject: [PATCH 05/10] fix(edge): Refuse a listener whose EdgeService is not admitted checkGrant read the EdgeService's spec but ignored the service's own Admitted condition, which the EdgeService reconciler sets from its provider, VPC, client pool and expiry. A listener is now refused with CapabilityNotGranted unless its service reports Admitted True for the service's current generation; a condition not yet written, False, or written for an older generation refuses it. Refs #1509 --- docs/edge/provider-contract.md | 2 +- internal/edge/listener/admit.go | 18 +++++++++++++++ .../edge/listener/listener_envtest_test.go | 23 +++++++++++++++++++ .../listener/listener_fixture_envtest_test.go | 19 +++++++++++++++ 4 files changed, 61 insertions(+), 1 deletion(-) diff --git a/docs/edge/provider-contract.md b/docs/edge/provider-contract.md index 1b795d94e..49935b997 100644 --- a/docs/edge/provider-contract.md +++ b/docs/edge/provider-contract.md @@ -308,7 +308,7 @@ Core accepts an `EdgeListener` only while all of these hold, and otherwise sets | Reason | Rule | | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ProviderNotApproved` | The provider exists, is approved and not being deleted, and lists `PublicListener` at a version core implements. | -| `CapabilityNotGranted` | The listener's `EdgeService` exists, is not being deleted, names the listener's provider, grants `SocketAccess` and `PublicListener` on the provider's ingress gVPC, has not passed `validUntil` less the maximum skew, and serves no older listener. | +| `CapabilityNotGranted` | The listener's `EdgeService` exists, is not being deleted, names the listener's provider, reports `Admitted` True for its current generation, grants `SocketAccess` and `PublicListener` on the provider's ingress gVPC, has not passed `validUntil` less the maximum skew, and serves no older listener. | | `AddressOutsidePool` | Every address falls in one of the prefixes of `--edge-listener-vip-prefixes`. | | `AddressClaimed` | Nothing older serves one of the listener's addresses on one of its protocols and ports: no older listener, no `NetworkService` of an older listener, and no other `NetworkService` in `galactic-system` that the gateway serves and that was created no later than the listener. A project-namespace service never claims, since the gateway always prefers a gateway-namespace one, and neither does a service the gateway refused (`VIPClaimed`, `VIPOutsidePool`, `OwnershipDenied`, `ProjectServicesOff`). | diff --git a/internal/edge/listener/admit.go b/internal/edge/listener/admit.go index 7d80c0a6b..bd0931591 100644 --- a/internal/edge/listener/admit.go +++ b/internal/edge/listener/admit.go @@ -20,6 +20,7 @@ import ( cloudv1alpha1 "go.datum.net/galactic/api/cloud/v1alpha1" bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" + "go.datum.net/galactic/internal/edge/attachment" ) // refusal is why core does not accept a listener: an Accepted reason and a @@ -100,6 +101,9 @@ func (r *Reconciler) checkGrant(ctx context.Context, l *galacticv1alpha1.EdgeLis return nil, refuse(notGranted, "EdgeService %s/%s grants provider %q, not %q", ref.Namespace, ref.Name, svc.Spec.ProviderRef.Name, l.Spec.ProviderRef.Name), nil } + if why := serviceNotAdmitted(svc); why != "" { + return nil, refuse(notGranted, "EdgeService %s/%s %s", ref.Namespace, ref.Name, why), nil + } for _, c := range []string{SocketAccess, PublicListener} { if !slices.Contains(svc.Spec.Capabilities, c) { return nil, refuse(notGranted, "EdgeService %s/%s does not grant %s", ref.Namespace, ref.Name, c), nil @@ -142,6 +146,20 @@ func contends(l *galacticv1alpha1.EdgeListener) bool { (c == nil || c.Status != metav1.ConditionFalse || c.ObservedGeneration != l.Generation) } +// serviceNotAdmitted returns why svc's own Admitted condition does not admit +// it, or "" when it does: the condition is True and describes svc's current +// generation. +func serviceNotAdmitted(svc *galacticv1alpha1.EdgeService) string { + c := meta.FindStatusCondition(svc.Status.Conditions, attachment.ConditionServiceAdmitted) + switch { + case c == nil || c.ObservedGeneration != svc.Generation: + return fmt.Sprintf("has no Admitted condition for generation %d yet", svc.Generation) + case c.Status != metav1.ConditionTrue: + return fmt.Sprintf("is not admitted: %s: %s", c.Reason, c.Message) + } + return "" +} + // older reports whether listener a was created before b, breaking a tie by // name. func older(a, b *galacticv1alpha1.EdgeListener) bool { diff --git a/internal/edge/listener/listener_envtest_test.go b/internal/edge/listener/listener_envtest_test.go index d15644aed..654858735 100644 --- a/internal/edge/listener/listener_envtest_test.go +++ b/internal/edge/listener/listener_envtest_test.go @@ -13,6 +13,9 @@ import ( corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/meta" 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" bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" @@ -64,6 +67,26 @@ func TestListenerAdmission(t *testing.T) { f.newListener("expired", "expired", "2001:db8:100::304") expectRefused("expired", notGranted) + // The service's own Admitted condition: False, then True, then stale + // once the service's generation moves. + unadmitted := f.newService("unadmitted", vpc, []string{SocketAccess, PublicListener}, nil) + f.admitService(unadmitted, metav1.ConditionFalse) + f.newListener("unadmitted", "unadmitted", "2001:db8:100::305") + expectRefused("unadmitted", notGranted) + f.admitService(unadmitted, metav1.ConditionTrue) + f.expectCondition("unadmitted", accepted, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonAccepted) + if err := retry.RetryOnConflict(retry.DefaultRetry, func() error { + f.get(client.ObjectKeyFromObject(unadmitted), unadmitted) + unadmitted.Spec.DrainSeconds = ptr.To[int32](10) + return f.admin.Update(ctx, unadmitted) + }); err != nil { + t.Fatal(err) + } + expectRefused("unadmitted", notGranted) + if err := f.admin.Delete(ctx, f.listener("unadmitted")); err != nil { + t.Fatal(err) + } + // The addresses. f.newService(ingressSvc, vpc, []string{SocketAccess, PublicListener}, nil) f.newListener("outside", ingressSvc, "2001:db8:200::10") diff --git a/internal/edge/listener/listener_fixture_envtest_test.go b/internal/edge/listener/listener_fixture_envtest_test.go index 1af36ab9c..8d66f5ca9 100644 --- a/internal/edge/listener/listener_fixture_envtest_test.go +++ b/internal/edge/listener/listener_fixture_envtest_test.go @@ -22,6 +22,7 @@ import ( bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" "go.datum.net/galactic/internal/edge/admission" + "go.datum.net/galactic/internal/edge/attachment" "go.datum.net/galactic/internal/edge/claim" "go.datum.net/galactic/internal/edge/provider" ) @@ -76,9 +77,27 @@ func (f *fixture) newService(name string, vpc *cloudv1alpha1.VPC, capabilities [ mutate(s) } f.create(s) + f.admitService(s, metav1.ConditionTrue) return s } +// admitService sets s's Admitted condition, for its current generation, to +// status, as the EdgeService reconciler does. +func (f *fixture) admitService(s *galacticv1alpha1.EdgeService, status metav1.ConditionStatus) { + f.t.Helper() + if err := retry.RetryOnConflict(retry.DefaultRetry, func() error { + if err := f.admin.Get(context.Background(), client.ObjectKeyFromObject(s), s); err != nil { + return err + } + s.Status.ObservedGeneration = s.Generation + meta.SetStatusCondition(&s.Status.Conditions, metav1.Condition{Type: attachment.ConditionServiceAdmitted, + Status: status, Reason: "Admitted", ObservedGeneration: s.Generation}) + return f.admin.Status().Update(context.Background(), s) + }); err != nil { + f.t.Fatal(err) + } +} + // newListener creates listenerObject(name, service, addresses...). func (f *fixture) newListener(name, service string, addresses ...string) { f.t.Helper() From 1e373f9dfba0f595bf335933f9184178b7e6d566 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Sun, 29 Nov 2026 08:02:15 -0500 Subject: [PATCH 06/10] fix(edge): Grant only patch on EdgeListener status Core writes an EdgeListener's status only by merge patch, so the galactic-controller-edge-listener Role no longer grants get or update on edgelisteners/status. The envtests run under the shipped RBAC. Refs #1509 --- config/galactic-edge/controller-rbac.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/galactic-edge/controller-rbac.yaml b/config/galactic-edge/controller-rbac.yaml index 28b3e0252..5de7d8192 100644 --- a/config/galactic-edge/controller-rbac.yaml +++ b/config/galactic-edge/controller-rbac.yaml @@ -177,7 +177,7 @@ rules: verbs: [get, update, patch] - apiGroups: [galactic.datumapis.com] resources: [edgelisteners/status] - verbs: [get, update, patch] + verbs: [patch] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding From 3ee6e8271a9af2adb02f56d22900e797bce2546a Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Sun, 29 Nov 2026 08:03:49 -0500 Subject: [PATCH 07/10] fix(edge): Skip the listener controllers when EdgeListener is not served A controller image with the listener controllers, rolled out before the bundle's CRDs and RBAC, failed its cache sync on the missing EdgeListener kind and exited. listener.Setup now asks discovery whether the API server serves galactic.datumapis.com/v1alpha1 EdgeListener and, when it does not, logs that the public listener controllers are not started and registers neither, leaving the manager to run everything else. The ingress gVPC reconciler is skipped too: its gVPCs serve only listeners, and the Role that grants its VPC writes ships in the same bundle as the CRD. The controller docs now say to apply the bundle's CRDs and RBAC before the image. Refs #1509 --- docs/controller/README.md | 2 +- internal/edge/listener/setup.go | 32 ++++++++++++++++++++++++++++ internal/edge/listener/setup_test.go | 21 ++++++++++++++++++ 3 files changed, 54 insertions(+), 1 deletion(-) diff --git a/docs/controller/README.md b/docs/controller/README.md index e0185218d..de3d27a5e 100644 --- a/docs/controller/README.md +++ b/docs/controller/README.md @@ -52,7 +52,7 @@ Logging takes `--log-level` (`LOG_LEVEL`) and the standard `--zap-*` flags; see Admission fails closed. Deploy the webhook with its serving Deployment, and keep its certificates and Service reachable. Neither the controller nor its CRDs are installed by the root `config/` kustomization. -For `--edge`, first install the Edge prerequisites in `config/galactic-edge/` and its node agent on eligible nodes. 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. +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. ### Pod-interface injection diff --git a/internal/edge/listener/setup.go b/internal/edge/listener/setup.go index a863e10c6..5f1672aa4 100644 --- a/internal/edge/listener/setup.go +++ b/internal/edge/listener/setup.go @@ -13,6 +13,8 @@ import ( coordinationv1 "k8s.io/api/coordination/v1" "k8s.io/apimachinery/pkg/api/equality" + apimeta "k8s.io/apimachinery/pkg/api/meta" + "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/tools/events" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/builder" @@ -61,13 +63,43 @@ type Config struct { Now func() time.Time } +// ListenerAPIServed reports whether mapper, the API server's discovery, +// serves the EdgeListener kind. It is false, with no error, when the kind is +// not installed. +func ListenerAPIServed(mapper apimeta.RESTMapper) (bool, error) { + gk := schema.GroupKind{Group: galacticv1alpha1.GroupVersion.Group, Kind: "EdgeListener"} + _, err := mapper.RESTMapping(gk, galacticv1alpha1.GroupVersion.Version) + switch { + case err == nil: + return true, nil + case apimeta.IsNoMatchError(err): + return false, nil + } + return false, fmt.Errorf("discover %s: %w", gk, err) +} + // Setup registers the ingress gVPC reconciler and the listener reconciler // with mgr. They run on the leader only. The manager's cache must hold only // instance leases (see edgeroute.LeaseCache). +// +// When the API server does not serve EdgeListener, Setup registers neither +// and logs why, so a controller rolled out before the bundle's CRDs and RBAC +// runs everything else rather than failing its cache sync. The ingress gVPC +// reconciler is skipped too: its gVPCs serve only listeners, and the Role +// that grants its VPC writes ships in the same bundle as the CRD. func Setup(mgr ctrl.Manager, cfg Config) error { if len(cfg.Identities) > 0 && !cfg.IngressPrefix.IsValid() { return errors.New("an ingress prefix is required with ingress identities") } + served, err := ListenerAPIServed(mgr.GetRESTMapper()) + if err != nil { + return err + } + if !served { + log.Log.WithName("edge-listener").Info("the API server does not serve EdgeListener; public listener " + + "controllers are not started. Apply the bundle's CRDs and config/galactic-edge, then restart") + return nil + } ingress := &IngressReconciler{ Client: mgr.GetClient(), APIReader: mgr.GetAPIReader(), Namespace: cfg.Namespace, Identities: cfg.Identities, Prefix: cfg.IngressPrefix, Events: cfg.Events, PrefixRetry: cfg.PrefixRetry, diff --git a/internal/edge/listener/setup_test.go b/internal/edge/listener/setup_test.go index 6a8c740fa..0d0e14447 100644 --- a/internal/edge/listener/setup_test.go +++ b/internal/edge/listener/setup_test.go @@ -9,6 +9,7 @@ import ( "time" coordinationv1 "k8s.io/api/coordination/v1" + apimeta "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/utils/ptr" "sigs.k8s.io/controller-runtime/pkg/event" @@ -16,6 +17,26 @@ import ( galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" ) +// TestListenerAPIServed: the listener controllers run only where discovery +// serves EdgeListener. +func TestListenerAPIServed(t *testing.T) { + without := apimeta.NewDefaultRESTMapper(nil) + with := apimeta.NewDefaultRESTMapper(nil) + with.Add(galacticv1alpha1.GroupVersion.WithKind("EdgeListener"), apimeta.RESTScopeNamespace) + for _, tt := range []struct { + name string + mapper apimeta.RESTMapper + want bool + }{{"Served", with, true}, {"NotInstalled", without, false}} { + t.Run(tt.name, func(t *testing.T) { + got, err := ListenerAPIServed(tt.mapper) + if err != nil || got != tt.want { + t.Errorf("ListenerAPIServed = %v, %v; want %v", got, err, tt.want) + } + }) + } +} + // TestInNamespace: a listener outside the gateway namespace is ignored. func TestInNamespace(t *testing.T) { p := inNamespace(gatewayNS) From 702fc07259a224373c3f9b47bc9e30862e8cd25e Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Sun, 29 Nov 2026 08:04:14 -0500 Subject: [PATCH 08/10] docs(edge): Propose the listener service and claim rules as decisions Two contract rules came with the listener controllers without sign-off: one EdgeService serves at most one listener, and which claim on a listener address wins. The design's Decisions table now lists both, marked as proposed in this change and awaiting review, each with its reason. Behaviour is unchanged. The table is aligned per the coding conventions. Refs #1509 --- docs/designs/edge-public-listener.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/designs/edge-public-listener.md b/docs/designs/edge-public-listener.md index 6945c1824..123eb005f 100644 --- a/docs/designs/edge-public-listener.md +++ b/docs/designs/edge-public-listener.md @@ -101,12 +101,14 @@ The Kubernetes Service and any `LoadBalancer`, `NodePort` or `hostPort` overlay These were open when the design was proposed and were settled in [#1506](https://github.com/datum-cloud/galactic/issues/1506). -| Question | Decision | Reason | -| --- | --- | --- | -| Who supplies listener addresses | The platform authority, from the cell's gateway VIP prefixes. Core refuses any other address with `AddressOutsidePool`. | This is how gateway-namespace services get addresses today. An allocator can follow later without an API change. | -| How many ingress gVPCs exist | One per provider type, not one per listener | It isolates providers from each other at the cost of one VPC identifier each. A provider has one listener, so a gVPC per listener adds no isolation. | -| Who registers a listener attachment's host veth in `ifindex_vrf_table` | No new component. The node agent (`galactic-edge`) already registers every edge host link through `attachreg.RegisterHostLink`, which writes the `ifindex_vrf_table` row, sets the veth egress kind and attaches `usid_egress`. | The registration a listener needs exists today, and Phase 0 showed the VIP reverse translation working on an edge host link. | -| What happens to a backend on a node that also advertises the VIP | It is excluded, and the listener reports `LocalBackendsExcluded`. Phase 0 showed local delivery failing, so the exclusion stays until the gateway can deliver to its own node. | Excluding those backends keeps the rest of the work unblocked. | +| Question | Decision | Reason | +| -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Who supplies listener addresses | The platform authority, from the cell's gateway VIP prefixes. Core refuses any other address with `AddressOutsidePool`. | This is how gateway-namespace services get addresses today. An allocator can follow later without an API change. | +| How many ingress gVPCs exist | One per provider type, not one per listener | It isolates providers from each other at the cost of one VPC identifier each. A provider has one listener, so a gVPC per listener adds no isolation. | +| Who registers a listener attachment's host veth in `ifindex_vrf_table` | No new component. The node agent (`galactic-edge`) already registers every edge host link through `attachreg.RegisterHostLink`, which writes the `ifindex_vrf_table` row, sets the veth egress kind and attaches `usid_egress`. | The registration a listener needs exists today, and Phase 0 showed the VIP reverse translation working on an edge host link. | +| What happens to a backend on a node that also advertises the VIP | It is excluded, and the listener reports `LocalBackendsExcluded`. Phase 0 showed local delivery failing, so the exclusion stays until the gateway can deliver to its own node. | Excluding those backends keeps the rest of the work unblocked. | +| How many listeners one `EdgeService` serves (proposed in #1509, awaiting review) | One. A newer listener naming a service an older listener that is not refused already names is refused with `CapabilityNotGranted`. | Each listener attachment's `/128` advertisement is one object per attachment, so two listeners sharing its service would contend for it; a provider has one listener, so the limit costs nothing. | +| Which claim on a listener address wins (proposed in #1509, awaiting review) | The oldest, as the gateway decides between services: an older listener, the `NetworkService`s of an older listener while they exist, and a `galactic-system` `NetworkService` the gateway serves that was created no later than the listener. A project-namespace service, a service the gateway refused and a younger listener's services never claim. | It mirrors the gateway's own precedence, where a gateway-namespace service never loses to a project one, so a listener is never refused for an address the gateway would not give the other service. A younger listener refuses itself rather than both refusing each other while the gateways tear its services down. | A listener's addresses belong to one cell. Grants are scoped to one cell, so an address announced from two cells would send some clients to a cell that cannot authorize them. Core in one cell cannot see other cells' addresses, so address planning enforces the rule: each cell's gateway VIP prefixes are disjoint from every other cell's. From 7ea076baf05a57b8003851f5bb715606705b9758 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Sun, 29 Nov 2026 10:13:18 -0500 Subject: [PATCH 09/10] test(edge): Pin the listener backend lease and instance checks The guards that decide which backend a listener serves were not pinned: each of these could be removed with the listener suite still passing. - TestListenerLeaseExpiry now reads the lease's expiry and requires the backend to stop serving between expiry less MaxSkew and half a skew later. Serving until the expiry itself, without the skew allowance, now fails. - TestListenerBackendInstance puts three attachments behind one instance's lease: one of a replaced pod, one reported on another node and one of another provider. None may serve, while the instance's own attachment does, and the one on another node serves once it reports its instance's node. The fixture's newBackend is split so a test can create an attachment against an existing instance. Refs #1509 --- .../edge/listener/listener_envtest_test.go | 63 ++++++++++++++++--- .../listener/listener_fixture_envtest_test.go | 27 +++++--- 2 files changed, 73 insertions(+), 17 deletions(-) diff --git a/internal/edge/listener/listener_envtest_test.go b/internal/edge/listener/listener_envtest_test.go index 654858735..93cd27afd 100644 --- a/internal/edge/listener/listener_envtest_test.go +++ b/internal/edge/listener/listener_envtest_test.go @@ -19,6 +19,7 @@ import ( bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" + "go.datum.net/galactic/internal/edge/provider" ) // TestListenerAdmission checks every Accepted reason: a provider that is @@ -213,9 +214,9 @@ func TestListenerBackends(t *testing.T) { } // TestListenerLeaseExpiry checks that a backend whose provider stops -// renewing its lease stops serving once the lease expires by the wall -// clock, less the cell's maximum skew, and Programmed follows; and that a -// renewal brings it back. +// renewing its lease stops serving when the lease expires by the wall clock +// less the cell's maximum skew, not at the expiry itself, and Programmed +// follows; and that a renewal brings it back. func TestListenerLeaseExpiry(t *testing.T) { f := startAPI(t) programmed := galacticv1alpha1.EdgeListenerProgrammed @@ -227,14 +228,58 @@ func TestListenerLeaseExpiry(t *testing.T) { f.newListener("public", ingressSvc, vip6, vip4) a := f.newBackend("a", svc, vpc, nodeA, 1) f.expectCondition("public", programmed, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonBackendsReady) - start := time.Now() - f.expectCondition("public", programmed, metav1.ConditionFalse, galacticv1alpha1.EdgeListenerReasonNoBackends) - if elapsed := time.Since(start); elapsed > 8*time.Second { - t.Errorf("the backend stopped serving %s after its last renewal, past its lease", elapsed) + 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) } - if f.serving()[a.att.Name] { - t.Error("a backend whose lease expired is serving") + // The backend must stop at expiry less MaxSkew. Serving until the + // expiry itself is MaxSkew late, which this bound rejects. + want := expiry.Add(-cfg.MaxSkew) + var stopped time.Time + eventually(t, "the backend to stop serving", func() bool { + if !f.serving()[a.att.Name] { + stopped = time.Now() + return true + } + return false + }) + if stopped.Before(want) || stopped.After(want.Add(cfg.MaxSkew/2)) { + 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.renewLease(a) f.expectCondition("public", programmed, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonBackendsReady) } + +// TestListenerBackendInstance checks that an attachment serves only on a +// lease its own pod holds on its own node: an attachment behind an instance +// of another pod, one whose node is not its instance's, and one of another +// provider never serve, while the instance's own attachment does. +func TestListenerBackendInstance(t *testing.T) { + f := startAPI(t) + programmed := galacticv1alpha1.EdgeListenerProgrammed + vpc, svc := f.acceptedListener("public") + a := f.newBackend("a", svc, vpc, nodeA, 1) + f.expectCondition("public", 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) { + att.Spec.PodUID = "pod-replaced" + }) + // An attachment of the instance's pod reported on another node. + moved := f.newAttachment("moved", a.inst, svc, vpc, "edge-3", 3, nil) + // An attachment of another provider on the instance's lease. + foreign := f.newAttachment("foreign", a.inst, svc, vpc, nodeA, 4, func(att *galacticv1alpha1.EdgeAttachment) { + att.Spec.ProviderRef.Name = "other" + }) + eventually(t, "every attachment to be listed", func() bool { return len(f.serving()) == 4 }) + never(t, "an attachment served on a lease its pod and node do not hold", func() bool { + s := f.serving() + return !s[a.att.Name] || s[stale.att.Name] || s[moved.att.Name] || s[foreign.att.Name] + }) + + // Back on its instance's node, the attachment serves. + f.attachmentStatus(moved, func(s *galacticv1alpha1.EdgeAttachmentStatus) { s.NodeName = nodeA }) + eventually(t, "the attachment on its instance's node to serve", func() bool { return f.serving()[moved.att.Name] }) +} diff --git a/internal/edge/listener/listener_fixture_envtest_test.go b/internal/edge/listener/listener_fixture_envtest_test.go index 8d66f5ca9..6132fbf26 100644 --- a/internal/edge/listener/listener_fixture_envtest_test.go +++ b/internal/edge/listener/listener_fixture_envtest_test.go @@ -191,30 +191,41 @@ type listenerBackend struct { func (f *fixture) newBackend(name string, svc *galacticv1alpha1.EdgeService, vpc *cloudv1alpha1.VPC, node string, n uint64) *listenerBackend { f.t.Helper() - ctx := context.Background() podUID := "pod-" + name - b := &listenerBackend{} - b.inst = &galacticv1alpha1.EdgeInstance{ + inst := &galacticv1alpha1.EdgeInstance{ ObjectMeta: metav1.ObjectMeta{Name: provider.InstanceName(podUID), Namespace: providerNS}, Spec: galacticv1alpha1.EdgeInstanceSpec{ProviderRef: galacticv1alpha1.EdgeProviderReference{Name: providerName}, PodName: name, PodUID: podUID, NodeName: node, BootID: "boot"}, } - f.create(b.inst) - if _, err := (provider.InstanceStore{Client: f.admin, Namespace: providerNS}).Create(ctx, - claim.Record{Key: b.inst.Name, Holder: leaseHolder, Epoch: 1}); err != nil { + f.create(inst) + if _, err := (provider.InstanceStore{Client: f.admin, Namespace: providerNS}).Create(context.Background(), + claim.Record{Key: inst.Name, Holder: leaseHolder, Epoch: 1}); err != nil { f.t.Fatal(err) } + return f.newAttachment(name, inst, svc, vpc, node, n, nil) +} + +// newAttachment creates the attachment "ea-"+name of inst's pod against svc, +// changed by mutate when it is not nil, and gives it the status newBackend +// describes on node. +func (f *fixture) newAttachment(name string, inst *galacticv1alpha1.EdgeInstance, svc *galacticv1alpha1.EdgeService, + vpc *cloudv1alpha1.VPC, node string, n uint64, mutate func(*galacticv1alpha1.EdgeAttachment)) *listenerBackend { + f.t.Helper() + b := &listenerBackend{inst: inst} b.att = &galacticv1alpha1.EdgeAttachment{ ObjectMeta: metav1.ObjectMeta{Name: "ea-" + name, Namespace: providerNS}, Spec: galacticv1alpha1.EdgeAttachmentSpec{ ProviderRef: galacticv1alpha1.EdgeProviderReference{Name: providerName}, ServiceRef: galacticv1alpha1.EdgeServiceReference{Namespace: gatewayNS, Name: svc.Name, UID: string(svc.UID)}, - InstanceRef: galacticv1alpha1.EdgeInstanceReference{Name: b.inst.Name}, - PodUID: podUID, + InstanceRef: galacticv1alpha1.EdgeInstanceReference{Name: inst.Name}, + PodUID: inst.Spec.PodUID, ContractVersion: "v1alpha1", Capabilities: []galacticv1alpha1.EdgeCapability{{Name: SocketAccess, Version: "v1"}}, }, } + if mutate != nil { + mutate(b.att) + } f.create(b.att) network := netip.MustParsePrefix(string(vpc.Spec.Networks[0])) f.attachmentStatus(b, func(s *galacticv1alpha1.EdgeAttachmentStatus) { From 0377f193fb6865d8db7e8570ca2db5f8638ee8e0 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Sun, 29 Nov 2026 10:13:18 -0500 Subject: [PATCH 10/10] fix(edge): Log an error when EdgeListener is not served When the API server does not serve EdgeListener, Setup skips both the ingress gVPC and the listener controllers, and only a restart after the CRD is installed starts them. That was logged at info level and named only the listener controllers, so the cell could run without them unnoticed. It is now logged as an error naming both. Refs #1509 --- internal/edge/listener/setup.go | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/internal/edge/listener/setup.go b/internal/edge/listener/setup.go index 5f1672aa4..93cd27887 100644 --- a/internal/edge/listener/setup.go +++ b/internal/edge/listener/setup.go @@ -83,10 +83,11 @@ func ListenerAPIServed(mapper apimeta.RESTMapper) (bool, error) { // instance leases (see edgeroute.LeaseCache). // // When the API server does not serve EdgeListener, Setup registers neither -// and logs why, so a controller rolled out before the bundle's CRDs and RBAC -// runs everything else rather than failing its cache sync. The ingress gVPC -// reconciler is skipped too: its gVPCs serve only listeners, and the Role -// that grants its VPC writes ships in the same bundle as the CRD. +// and logs an error saying why, so a controller rolled out before the +// bundle's CRDs and RBAC runs everything else rather than failing its cache +// sync. The ingress gVPC reconciler is skipped too: its gVPCs serve only +// listeners, and the Role that grants its VPC writes ships in the same bundle +// as the CRD. Only a restart after the CRD is installed starts them. func Setup(mgr ctrl.Manager, cfg Config) error { if len(cfg.Identities) > 0 && !cfg.IngressPrefix.IsValid() { return errors.New("an ingress prefix is required with ingress identities") @@ -96,8 +97,9 @@ func Setup(mgr ctrl.Manager, cfg Config) error { return err } if !served { - log.Log.WithName("edge-listener").Info("the API server does not serve EdgeListener; public listener " + - "controllers are not started. Apply the bundle's CRDs and config/galactic-edge, then restart") + log.Log.WithName("edge-listener").Error(nil, "the API server does not serve EdgeListener; the ingress "+ + "gVPC and public listener controllers are not started. Apply the bundle's CRDs and config/galactic-edge, "+ + "then restart") return nil } ingress := &IngressReconciler{