diff --git a/.crd-ref-docs.yaml b/.crd-ref-docs.yaml index 905dba044..c750e5f86 100644 --- a/.crd-ref-docs.yaml +++ b/.crd-ref-docs.yaml @@ -15,6 +15,7 @@ references: # Exclude collection wrappers by name: BGPPrefixList is a resource. - "[.]EdgeAttachmentList$" - "[.]EdgeInstanceList$" + - "[.]EdgeListenerList$" - "[.]EdgeProviderApprovalList$" - "[.]EdgeProviderList$" - "[.]EdgeRouteIndexList$" diff --git a/api/network/v1alpha1/networkservice_edgelistener_envtest_test.go b/api/network/v1alpha1/networkservice_edgelistener_envtest_test.go new file mode 100644 index 000000000..767a42386 --- /dev/null +++ b/api/network/v1alpha1/networkservice_edgelistener_envtest_test.go @@ -0,0 +1,90 @@ +// Copyright 2026 Datum Cloud, Inc. +// SPDX-License-Identifier: AGPL-3.0-or-later + +package v1alpha1_test + +import ( + "context" + "encoding/json" + "strings" + "testing" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + + networkv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" +) + +const ( + exactlyOneBackendSourceMsg = "exactly one of backendSelector and edgeListenerRef is required" + emptySelectorMsg = "backendSelector must not be empty" +) + +// TestNetworkServiceBackendSource covers the rule that a service takes its +// backends from exactly one of backendSelector and edgeListenerRef, and that a +// backendSelector that is set must still not be empty. +func TestNetworkServiceBackendSource(t *testing.T) { + c, _ := startProtocolAPI(t) + ctx := context.Background() + listener := &networkv1alpha1.NetworkServiceEdgeListenerReference{Name: "masque-public"} + + for _, tc := range []struct { + name string + mutate func(*networkv1alpha1.NetworkService) + want string // empty when the service is admitted + }{ + {"Selector", func(*networkv1alpha1.NetworkService) {}, ""}, + {"EdgeListener", func(s *networkv1alpha1.NetworkService) { + s.Spec.BackendSelector = metav1.LabelSelector{} + s.Spec.EdgeListenerRef = listener + }, ""}, + {"Both", func(s *networkv1alpha1.NetworkService) { s.Spec.EdgeListenerRef = listener }, exactlyOneBackendSourceMsg}, + {"Neither", func(s *networkv1alpha1.NetworkService) { + s.Spec.BackendSelector = metav1.LabelSelector{} + }, exactlyOneBackendSourceMsg}, + {"EmptyListenerName", func(s *networkv1alpha1.NetworkService) { + s.Spec.BackendSelector = metav1.LabelSelector{} + s.Spec.EdgeListenerRef = &networkv1alpha1.NetworkServiceEdgeListenerReference{} + }, "spec.edgeListenerRef.name"}, + } { + t.Run(tc.name, func(t *testing.T) { + svc := protocolService("source-"+strings.ToLower(tc.name), networkv1alpha1.NetworkServiceProtocolTCP, 443, 8443) + tc.mutate(svc) + err := c.Create(ctx, svc) + if tc.want == "" { + if err != nil { + t.Fatalf("Create: %v", err) + } + return + } + requireRefusal(t, err, []string{tc.want}, nil) + }) + } + + // A selector written as {} is present but empty, and keeps its own + // refusal rather than counting as absent. + t.Run("ExplicitEmptySelector", func(t *testing.T) { + svc := protocolService("source-explicit-empty", networkv1alpha1.NetworkServiceProtocolTCP, 443, 8443) + obj := unstructuredService(t, svc) + if err := unstructured.SetNestedMap(obj.Object, map[string]any{}, "spec", "backendSelector"); err != nil { + t.Fatal(err) + } + requireRefusal(t, c.Create(ctx, obj), []string{emptySelectorMsg}, nil) + }) +} + +// TestNetworkServiceOmitsEmptySelector checks that a service written from Go +// without a selector encodes no backendSelector, which the exactly-one rule +// depends on. +func TestNetworkServiceOmitsEmptySelector(t *testing.T) { + svc := protocolService("encode", networkv1alpha1.NetworkServiceProtocolTCP, 443, 8443) + svc.Spec.BackendSelector = metav1.LabelSelector{} + svc.Spec.EdgeListenerRef = &networkv1alpha1.NetworkServiceEdgeListenerReference{Name: "masque-public"} + data, err := json.Marshal(svc.Spec) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(data), "backendSelector") { + t.Errorf("spec = %s, want no backendSelector", data) + } +} diff --git a/api/network/v1alpha1/networkservice_types.go b/api/network/v1alpha1/networkservice_types.go index 9d60f78c9..0c2cfeaa7 100644 --- a/api/network/v1alpha1/networkservice_types.go +++ b/api/network/v1alpha1/networkservice_types.go @@ -118,7 +118,9 @@ const ( // serve the service, so the backend set follows attachments as they are // created, deleted or moved to another node, and galactic-router on each // node generates the ServiceVIPBinding its backends need from the same -// selection. +// selection. A service in the gateway namespace can instead name an +// EdgeListener with EdgeListenerRef, whose listener attachments are then its +// backends. // // +kubebuilder:object:root=true // +kubebuilder:subresource:status @@ -146,6 +148,7 @@ type NetworkService struct { // +kubebuilder:validation:XValidation:rule="!(self.protocol in ['esp', 'gre', 'icmp']) || !has(self.port)",message="port must not be set for esp, gre and icmp, which have no ports" // +kubebuilder:validation:XValidation:rule="!(self.protocol in ['esp', 'gre', 'icmp']) || !has(self.backendPort)",message="backendPort must not be set for esp, gre and icmp, which have no ports" // +kubebuilder:validation:XValidation:rule="self.protocol != 'udp' || !has(self.healthCheck) || has(self.healthCheck.port)",message="healthCheck.port is required for udp: a health check probes a TCP port" +// +kubebuilder:validation:XValidation:rule="has(self.backendSelector) != has(self.edgeListenerRef)",message="exactly one of backendSelector and edgeListenerRef is required" type NetworkServiceSpec struct { // VPCRef is the opaque identifier of the target VPC this service applies // to, a VPC's status.vpc. In a gateway namespace, the platform API that @@ -236,10 +239,20 @@ type NetworkServiceSpec struct { // and from IPv6, and its IPv4 addresses are never backends. An attachment // with no status.node, or no IPv6 address, is not a backend until it has // both. An empty selector is rejected rather than read as "every - // attachment in the VPC". - // +kubebuilder:validation:Required + // attachment in the VPC". Exactly one of BackendSelector and + // EdgeListenerRef is required. + // +optional // +kubebuilder:validation:XValidation:rule="(has(self.matchLabels) && size(self.matchLabels) > 0) || (has(self.matchExpressions) && size(self.matchExpressions) > 0)",message="backendSelector must not be empty" - BackendSelector metav1.LabelSelector `json:"backendSelector"` + BackendSelector metav1.LabelSelector `json:"backendSelector,omitzero"` + + // EdgeListenerRef names the EdgeListener, in the service's namespace, + // whose listener attachments are the service's backends, in place of + // BackendSelector. Core sets it on the services it writes for a + // listener, one per listener port. It is allowed only in the gateway + // namespace. Until gateways resolve listener backends, a service that + // sets it has no backends and its VIPs are not advertised. + // +optional + EdgeListenerRef *NetworkServiceEdgeListenerReference `json:"edgeListenerRef,omitempty"` // BackendPort is the destination port on every selected backend, 1-65535. // Like Port, it is required for tcp, udp and sctp and must be unset for @@ -280,6 +293,16 @@ type NetworkServiceSpec struct { HealthCheck *NetworkServiceHealthCheck `json:"healthCheck,omitempty"` } +// NetworkServiceEdgeListenerReference names an EdgeListener +// (galactic.datumapis.com/v1alpha1) in the service's namespace. +type NetworkServiceEdgeListenerReference struct { + // Name is the EdgeListener's name. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=253 + Name string `json:"name"` +} + const ( // NetworkServiceHealthFailOpen retains unknown backends and all-unhealthy sets. NetworkServiceHealthFailOpen = "FailOpen" diff --git a/api/network/v1alpha1/zz_generated.deepcopy.go b/api/network/v1alpha1/zz_generated.deepcopy.go index 72b5da76b..9d8c156dd 100644 --- a/api/network/v1alpha1/zz_generated.deepcopy.go +++ b/api/network/v1alpha1/zz_generated.deepcopy.go @@ -4087,6 +4087,21 @@ func (in *NetworkServiceAddressStatus) DeepCopy() *NetworkServiceAddressStatus { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *NetworkServiceEdgeListenerReference) DeepCopyInto(out *NetworkServiceEdgeListenerReference) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NetworkServiceEdgeListenerReference. +func (in *NetworkServiceEdgeListenerReference) DeepCopy() *NetworkServiceEdgeListenerReference { + if in == nil { + return nil + } + out := new(NetworkServiceEdgeListenerReference) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NetworkServiceHealthCheck) DeepCopyInto(out *NetworkServiceHealthCheck) { *out = *in @@ -4153,6 +4168,11 @@ func (in *NetworkServiceSpec) DeepCopyInto(out *NetworkServiceSpec) { (*in).DeepCopyInto(*out) } in.BackendSelector.DeepCopyInto(&out.BackendSelector) + if in.EdgeListenerRef != nil { + in, out := &in.EdgeListenerRef, &out.EdgeListenerRef + *out = new(NetworkServiceEdgeListenerReference) + **out = **in + } if in.HealthCheck != nil { in, out := &in.HealthCheck, &out.HealthCheck *out = new(NetworkServiceHealthCheck) diff --git a/api/v1alpha1/edgelistener_crd_test.go b/api/v1alpha1/edgelistener_crd_test.go new file mode 100644 index 000000000..fd38d7c6f --- /dev/null +++ b/api/v1alpha1/edgelistener_crd_test.go @@ -0,0 +1,228 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package v1alpha1_test + +import ( + "context" + "fmt" + "strings" + "testing" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + + galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" +) + +const ( + publicListener = "PublicListener" + socketAccess = "SocketAccess" + prefixReachability = "PrefixReachability" + listenerIPv6 = "2001:db8:100::10" + listenerIPv4 = "192.0.2.10" +) + +func edgeListener(name string) *galacticv1alpha1.EdgeListener { + return &galacticv1alpha1.EdgeListener{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: testNamespace}, + Spec: galacticv1alpha1.EdgeListenerSpec{ + ProviderRef: galacticv1alpha1.EdgeProviderReference{Name: edgeProviderName}, + ServiceRef: galacticv1alpha1.EdgeListenerServiceReference{Namespace: testNamespace, Name: "ingress"}, + Addresses: []string{listenerIPv6, listenerIPv4}, + Ports: []galacticv1alpha1.EdgeListenerPort{ + {Protocol: galacticv1alpha1.EdgeListenerProtocolUDP, Port: 443, BackendPort: 8443}, + {Protocol: galacticv1alpha1.EdgeListenerProtocolTCP, Port: 443, BackendPort: 8443}, + }, + }, + } +} + +// TestEdgeListenerSchema covers the listener's validation: addresses per +// family, ports, the all-UDP health port rule and immutable references. +func TestEdgeListenerSchema(t *testing.T) { + c, _ := startAPIServer(t) + ctx := context.Background() + + udpOnly := []galacticv1alpha1.EdgeListenerPort{ + {Protocol: galacticv1alpha1.EdgeListenerProtocolUDP, Port: 443, BackendPort: 8443}, + } + healthPort := int32(8443) + + creates := []struct { + name string + mutate func(*galacticv1alpha1.EdgeListener) + want string // empty when the listener is admitted + }{ + {"DualStack", func(*galacticv1alpha1.EdgeListener) {}, ""}, + {"IPv6Only", func(l *galacticv1alpha1.EdgeListener) { l.Spec.Addresses = []string{listenerIPv6} }, ""}, + {"NoAddress", func(l *galacticv1alpha1.EdgeListener) { l.Spec.Addresses = nil }, "spec.addresses"}, + {"TwoIPv6", func(l *galacticv1alpha1.EdgeListener) { + l.Spec.Addresses = []string{listenerIPv6, "2001:db8:100::11"} + }, "at most one IPv6 address"}, + {"TwoIPv4", func(l *galacticv1alpha1.EdgeListener) { + l.Spec.Addresses = []string{listenerIPv4, "192.0.2.11"} + }, "at most one IPv4 address"}, + {"NotAnAddress", func(l *galacticv1alpha1.EdgeListener) { + l.Spec.Addresses = []string{"2001:db8:100::/64"} + }, "valid IPv4 or IPv6 addresses"}, + {"IPv4Mapped", func(l *galacticv1alpha1.EdgeListener) { + l.Spec.Addresses = []string{"::ffff:192.0.2.10"} + }, "valid IPv4 or IPv6 addresses"}, + {"NoPort", func(l *galacticv1alpha1.EdgeListener) { l.Spec.Ports = nil }, "spec.ports"}, + {"SCTP", func(l *galacticv1alpha1.EdgeListener) { l.Spec.Ports[0].Protocol = "sctp" }, "spec.ports[0].protocol"}, + {"PortZero", func(l *galacticv1alpha1.EdgeListener) { l.Spec.Ports[0].Port = 0 }, "spec.ports[0].port"}, + {"DuplicatePort", func(l *galacticv1alpha1.EdgeListener) { + l.Spec.Ports = append(l.Spec.Ports, galacticv1alpha1.EdgeListenerPort{ + Protocol: galacticv1alpha1.EdgeListenerProtocolTCP, Port: 443, BackendPort: 9443, + }) + }, "Duplicate value"}, + {"SharedBackendPort", func(l *galacticv1alpha1.EdgeListener) { + l.Spec.Ports = append(l.Spec.Ports, galacticv1alpha1.EdgeListenerPort{ + Protocol: galacticv1alpha1.EdgeListenerProtocolTCP, Port: 8443, BackendPort: 8443, + }) + }, "cannot share a backendPort"}, + {"TooManyPorts", func(l *galacticv1alpha1.EdgeListener) { + l.Spec.Ports = nil + for i := range int32(17) { + l.Spec.Ports = append(l.Spec.Ports, galacticv1alpha1.EdgeListenerPort{ + Protocol: galacticv1alpha1.EdgeListenerProtocolTCP, Port: 1000 + i, BackendPort: 2000 + i, + }) + } + }, "spec.ports"}, + {"UDPOnlyWithoutHealthPort", func(l *galacticv1alpha1.EdgeListener) { + l.Spec.Ports = udpOnly + }, "healthPort is required"}, + {"UDPOnlyWithHealthPort", func(l *galacticv1alpha1.EdgeListener) { + l.Spec.Ports = udpOnly + l.Spec.HealthPort = &healthPort + }, ""}, + {"UnknownAffinity", func(l *galacticv1alpha1.EdgeListener) { + l.Spec.SessionAffinity = "Sticky" + }, "spec.sessionAffinity"}, + {"UnknownFailurePolicy", func(l *galacticv1alpha1.EdgeListener) { + l.Spec.FailurePolicy = "Retry" + }, "spec.failurePolicy"}, + } + for i, tt := range creates { + t.Run("Create"+tt.name, func(t *testing.T) { + l := edgeListener(fmt.Sprintf("create-%d", i)) + tt.mutate(l) + err := c.Create(ctx, l) + if tt.want == "" { + if err != nil { + t.Fatalf("Create: %v", err) + } + return + } + if err == nil || !strings.Contains(err.Error(), tt.want) { + t.Fatalf("Create: err = %v, want it to contain %q", err, tt.want) + } + }) + } + + t.Run("Defaults", func(t *testing.T) { + l := edgeListener("defaults") + if err := c.Create(ctx, l); err != nil { + t.Fatal(err) + } + if l.Spec.SessionAffinity != galacticv1alpha1.EdgeListenerSessionAffinityClientIPAndProtocol { + t.Errorf("sessionAffinity = %q, want ClientIPAndProtocol", l.Spec.SessionAffinity) + } + if l.Spec.FailurePolicy != galacticv1alpha1.EdgeListenerFailOpen { + t.Errorf("failurePolicy = %q, want FailOpen", l.Spec.FailurePolicy) + } + }) + + updates := []struct { + name string + mutate func(*galacticv1alpha1.EdgeListener) + want string + }{ + {"Ports", func(l *galacticv1alpha1.EdgeListener) { l.Spec.Ports[0].Port = 4443 }, ""}, + {"Addresses", func(l *galacticv1alpha1.EdgeListener) { l.Spec.Addresses = []string{listenerIPv6} }, ""}, + {"ProviderRef", func(l *galacticv1alpha1.EdgeListener) { + l.Spec.ProviderRef.Name = "tailnet" + }, "providerRef is immutable"}, + {"ServiceRef", func(l *galacticv1alpha1.EdgeListener) { + l.Spec.ServiceRef.Name = "other" + }, "serviceRef is immutable"}, + } + for i, tt := range updates { + t.Run("Update"+tt.name, func(t *testing.T) { + l := edgeListener(fmt.Sprintf("update-%d", i)) + if err := c.Create(ctx, l); err != nil { + t.Fatal(err) + } + tt.mutate(l) + err := c.Update(ctx, l) + if tt.want == "" { + if err != nil { + t.Fatalf("Update: %v", err) + } + return + } + if err == nil || !strings.Contains(err.Error(), tt.want) { + t.Fatalf("Update: err = %v, want it to contain %q", err, tt.want) + } + }) + } + + // Status is a subresource: a spec write does not change it, and a status + // write does not change the spec. + t.Run("StatusSubresource", func(t *testing.T) { + l := edgeListener("status") + if err := c.Create(ctx, l); err != nil { + t.Fatal(err) + } + l.Status.Backends = []galacticv1alpha1.EdgeListenerBackend{{Attachment: "edge/ea-1", Serving: true}} + if err := c.Status().Update(ctx, l); err != nil { + t.Fatalf("status update: %v", err) + } + var got galacticv1alpha1.EdgeListener + if err := c.Get(ctx, client.ObjectKeyFromObject(l), &got); err != nil { + t.Fatal(err) + } + if len(got.Status.Backends) != 1 || !got.Status.Backends[0].Serving { + t.Errorf("backends = %+v, want the one written", got.Status.Backends) + } + }) +} + +// TestPublicListenerCapability covers PublicListener on a provider and a +// grant, the grant's limit of four capabilities, and that an attachment still +// cannot request it. +func TestPublicListenerCapability(t *testing.T) { + c, _ := startAPIServer(t) + ctx := context.Background() + + provider := &galacticv1alpha1.EdgeProvider{ + ObjectMeta: metav1.ObjectMeta{Name: "listener-provider"}, + Spec: galacticv1alpha1.EdgeProviderSpec{ + ContractVersions: []string{galacticv1alpha1.GroupVersion.Version}, + Capabilities: []galacticv1alpha1.EdgeCapability{ + {Name: socketAccess, Version: "v1"}, {Name: publicListener, Version: "v1"}, + }, + ServiceAccounts: []galacticv1alpha1.ServiceAccountReference{{Namespace: "edge", Name: "listener"}}, + Configuration: galacticv1alpha1.ConfigurationKind{Group: "example.com", Kind: "Config"}, + }, + } + if err := c.Create(ctx, provider); err != nil { + t.Fatalf("EdgeProvider with PublicListener refused: %v", err) + } + + all := edgeService("all-capabilities") + all.Spec.Capabilities = []string{socketAccess, packetAccess, prefixReachability, publicListener} + if err := c.Create(ctx, all); err != nil { + t.Fatalf("EdgeService with four capabilities refused: %v", err) + } + + attachment := edgeAttachment("public-listener") + attachment.Spec.Capabilities = []galacticv1alpha1.EdgeCapability{{Name: publicListener, Version: "v1"}} + attachment.Spec.PacketDevice = nil + err := c.Create(ctx, attachment) + if err == nil || !strings.Contains(err.Error(), "only SocketAccess and PacketAccess") { + t.Fatalf("EdgeAttachment requesting PublicListener: err = %v, want refused", err) + } +} diff --git a/api/v1alpha1/edgelistener_types.go b/api/v1alpha1/edgelistener_types.go new file mode 100644 index 000000000..f8b4a5e21 --- /dev/null +++ b/api/v1alpha1/edgelistener_types.go @@ -0,0 +1,249 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// EdgeListenerServiceReference names the EdgeService that grants a listener's +// provider SocketAccess and PublicListener on its ingress gVPC. +type EdgeListenerServiceReference struct { + // Namespace is the EdgeService's namespace, the ingress gVPC's namespace. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=63 + Namespace string `json:"namespace"` + + // Name is the EdgeService's name. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=253 + Name string `json:"name"` +} + +// EdgeListenerProtocol is the transport protocol of one listener port. +// +kubebuilder:validation:Enum=tcp;udp +type EdgeListenerProtocol string + +// Listener port protocols. +const ( + EdgeListenerProtocolTCP EdgeListenerProtocol = "tcp" + EdgeListenerProtocolUDP EdgeListenerProtocol = "udp" +) + +// EdgeListenerPort is one public port and the port the provider's instances +// serve it on. +type EdgeListenerPort struct { + // Protocol is tcp or udp. + // +required + Protocol EdgeListenerProtocol `json:"protocol"` + + // Port is the public port on the listener's addresses. + // +required + // +kubebuilder:validation:Minimum=1 + // +kubebuilder:validation:Maximum=65535 + Port int32 `json:"port"` + + // BackendPort is the port each provider instance listens on, on its + // listener attachment's address. + // +required + // +kubebuilder:validation:Minimum=1 + // +kubebuilder:validation:Maximum=65535 + BackendPort int32 `json:"backendPort"` +} + +// EdgeListenerSessionAffinity selects which parts of a flow the gateway hashes +// to pick a backend, as NetworkService's sessionAffinity does. +// +kubebuilder:validation:Enum=None;ClientIP;ClientIPAndProtocol +type EdgeListenerSessionAffinity string + +// Listener session affinities. +const ( + EdgeListenerSessionAffinityNone EdgeListenerSessionAffinity = "None" + EdgeListenerSessionAffinityClientIP EdgeListenerSessionAffinity = "ClientIP" + EdgeListenerSessionAffinityClientIPAndProtocol EdgeListenerSessionAffinity = "ClientIPAndProtocol" +) + +// EdgeListenerFailurePolicy decides whether backends of unknown health, and a +// set whose backends are all unhealthy, receive traffic. +// +kubebuilder:validation:Enum=FailOpen;FailClosed +type EdgeListenerFailurePolicy string + +// Listener failure policies. +const ( + EdgeListenerFailOpen EdgeListenerFailurePolicy = "FailOpen" + EdgeListenerFailClosed EdgeListenerFailurePolicy = "FailClosed" +) + +// EdgeListenerSpec is the public addresses and ports the platform gives one +// provider. Only the platform authority writes it; no provider may. +// +kubebuilder:validation:XValidation:rule="self.providerRef == oldSelf.providerRef",message="providerRef is immutable" +// +kubebuilder:validation:XValidation:rule="self.serviceRef == oldSelf.serviceRef",message="serviceRef is immutable" +// +kubebuilder:validation:XValidation:rule="has(self.healthPort) || self.ports.exists(p, p.protocol == 'tcp')",message="healthPort is required when every port is udp: a health check probes a TCP port" +type EdgeListenerSpec struct { + // ProviderRef is the provider the listener serves. It must list + // PublicListener. + // +required + ProviderRef EdgeProviderReference `json:"providerRef"` + + // ServiceRef is the EdgeService granting the provider SocketAccess and + // PublicListener on its ingress gVPC. The provider's listener + // attachments are made against it. + // +required + ServiceRef EdgeListenerServiceReference `json:"serviceRef"` + + // Addresses are the public addresses, at most one IPv6 and one IPv4. Each + // must fall in one of the cell's gateway VIP prefixes; core refuses any + // other with AddressOutsidePool. An IPv4 address is written in dotted + // form. + // +required + // +listType=set + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=2 + // +kubebuilder:validation:items:MaxLength=39 + // +kubebuilder:validation:XValidation:rule="self.all(a, isIP(a))",message="addresses must be valid IPv4 or IPv6 addresses, IPv4 in dotted form" + // +kubebuilder:validation:XValidation:rule="self.filter(a, isIP(a) && ip(a).family() == 6).size() <= 1",message="addresses may hold at most one IPv6 address" + // +kubebuilder:validation:XValidation:rule="self.filter(a, isIP(a) && ip(a).family() == 4).size() <= 1",message="addresses may hold at most one IPv4 address" + Addresses []string `json:"addresses"` + + // Ports are the public ports. Core writes one gateway NetworkService per + // port. Two ports of one protocol cannot share a backendPort, since a + // backend's reply is translated back to one public port. + // +required + // +listType=map + // +listMapKey=protocol + // +listMapKey=port + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=16 + // +kubebuilder:validation:XValidation:rule="self.all(p, self.exists_one(q, q.protocol == p.protocol && q.backendPort == p.backendPort))",message="two ports of one protocol cannot share a backendPort" + Ports []EdgeListenerPort `json:"ports"` + + // HealthPort is the TCP port probed on each backend. Unset, it is the + // first tcp port's backendPort. It is required when every port is udp. + // +optional + // +kubebuilder:validation:Minimum=1 + // +kubebuilder:validation:Maximum=65535 + HealthPort *int32 `json:"healthPort,omitempty"` + + // SessionAffinity is copied into each of the listener's NetworkServices. + // +optional + // +kubebuilder:default=ClientIPAndProtocol + SessionAffinity EdgeListenerSessionAffinity `json:"sessionAffinity,omitempty"` + + // FailurePolicy is copied into the health check of each of the listener's + // NetworkServices. + // +optional + // +kubebuilder:default=FailOpen + FailurePolicy EdgeListenerFailurePolicy `json:"failurePolicy,omitempty"` +} + +// Condition types of an EdgeListener. Core (galactic-controller) sets both. +const ( + EdgeListenerAccepted = "Accepted" + EdgeListenerProgrammed = "Programmed" +) + +// Reasons core gives on an EdgeListener's conditions. +const ( + // EdgeListenerReasonAccepted: Accepted is True. + EdgeListenerReasonAccepted = "Accepted" + // EdgeListenerReasonProviderNotApproved: the provider is unknown, not + // approved, or does not list PublicListener. + EdgeListenerReasonProviderNotApproved = "ProviderNotApproved" + // EdgeListenerReasonCapabilityNotGranted: the service does not grant the + // provider SocketAccess and PublicListener. + EdgeListenerReasonCapabilityNotGranted = "CapabilityNotGranted" + // EdgeListenerReasonAddressOutsidePool: an address is outside the cell's + // gateway VIP prefixes. + EdgeListenerReasonAddressOutsidePool = "AddressOutsidePool" + // EdgeListenerReasonAddressClaimed: another service already serves an + // address on one of the listener's protocols and ports. + EdgeListenerReasonAddressClaimed = "AddressClaimed" + // EdgeListenerReasonBackendsReady: Programmed is True. + EdgeListenerReasonBackendsReady = "BackendsReady" + // EdgeListenerReasonNoBackends: no listener attachment is serving. + EdgeListenerReasonNoBackends = "NoBackends" + // EdgeListenerReasonLocalBackendsExcluded: backends on nodes that + // advertise the listener's addresses are excluded until gateway local + // delivery is qualified. + EdgeListenerReasonLocalBackendsExcluded = "LocalBackendsExcluded" +) + +// EdgeListenerBackend is one listener attachment and whether it receives new +// flows. +type EdgeListenerBackend struct { + // Attachment is the EdgeAttachment's namespace and name. + // +required + // +kubebuilder:validation:MaxLength=317 + Attachment string `json:"attachment"` + + // Node is the attachment's node. + // +optional + // +kubebuilder:validation:MaxLength=253 + Node string `json:"node,omitempty"` + + // Address is the attachment's IPv6 address in the ingress gVPC. + // +optional + // +kubebuilder:validation:MaxLength=39 + Address string `json:"address,omitempty"` + + // Serving is whether the attachment receives new flows: it is + // programmed, its instance lease is valid and its provider reports Ready. + // +optional + Serving bool `json:"serving,omitempty"` +} + +// EdgeListenerStatus is written by core only. +type EdgeListenerStatus struct { + // ObservedGeneration is the generation Conditions describe. + // +optional + ObservedGeneration int64 `json:"observedGeneration,omitempty"` + + // Conditions are Accepted and Programmed. + // +optional + // +listType=map + // +listMapKey=type + // +kubebuilder:validation:MaxItems=8 + Conditions []metav1.Condition `json:"conditions,omitempty"` + + // Backends are the provider's listener attachments. + // +optional + // +listType=map + // +listMapKey=attachment + // +kubebuilder:validation:MaxItems=1024 + Backends []EdgeListenerBackend `json:"backends,omitempty"` +} + +// EdgeListener gives an approved provider public addresses and ports, served +// by the gateway nodes of the cell. It lives in the gateway namespace. The +// platform authority writes its spec and core its status; no provider writes +// either. Core turns each port into a gateway NetworkService whose backends are +// the provider's listener attachments. +// +kubebuilder:object:root=true +// +kubebuilder:subresource:status +// +kubebuilder:resource:categories=galactic +// +kubebuilder:printcolumn:name="Provider",type=string,JSONPath=`.spec.providerRef.name` +// +kubebuilder:printcolumn:name="Accepted",type=string,JSONPath=`.status.conditions[?(@.type=="Accepted")].status` +// +kubebuilder:printcolumn:name="Programmed",type=string,JSONPath=`.status.conditions[?(@.type=="Programmed")].status` +// +kubebuilder:printcolumn:name="Age",type=date,JSONPath=`.metadata.creationTimestamp` +type EdgeListener struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + // +required + Spec EdgeListenerSpec `json:"spec"` + + // +optional + Status EdgeListenerStatus `json:"status,omitempty"` +} + +// EdgeListenerList is a list of EdgeListener. +// +kubebuilder:object:root=true +type EdgeListenerList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []EdgeListener `json:"items"` +} diff --git a/api/v1alpha1/edgeprovider_types.go b/api/v1alpha1/edgeprovider_types.go index d7e4c0f07..638e7dcd8 100644 --- a/api/v1alpha1/edgeprovider_types.go +++ b/api/v1alpha1/edgeprovider_types.go @@ -13,7 +13,7 @@ import ( type EdgeCapability struct { // Name is the capability's name. // +required - // +kubebuilder:validation:Enum=SocketAccess;PacketAccess;PrefixReachability + // +kubebuilder:validation:Enum=SocketAccess;PacketAccess;PrefixReachability;PublicListener Name string `json:"name"` // Version is the capability's version. diff --git a/api/v1alpha1/edgeservice_types.go b/api/v1alpha1/edgeservice_types.go index e8790c491..2b9c8a0c8 100644 --- a/api/v1alpha1/edgeservice_types.go +++ b/api/v1alpha1/edgeservice_types.go @@ -52,8 +52,8 @@ type EdgeServiceSpec struct { // +required // +listType=set // +kubebuilder:validation:MinItems=1 - // +kubebuilder:validation:MaxItems=3 - // +kubebuilder:validation:items:Enum=SocketAccess;PacketAccess;PrefixReachability + // +kubebuilder:validation:MaxItems=4 + // +kubebuilder:validation:items:Enum=SocketAccess;PacketAccess;PrefixReachability;PublicListener Capabilities []string `json:"capabilities"` // Prefixes bound the prefixes the provider may request in the VPC. Each diff --git a/api/v1alpha1/groupversion_info.go b/api/v1alpha1/groupversion_info.go index e75274493..a394ed100 100644 --- a/api/v1alpha1/groupversion_info.go +++ b/api/v1alpha1/groupversion_info.go @@ -10,7 +10,8 @@ // registration, its operator approval and a tenant grant, // EdgeInstance and EdgeAttachment, a provider pod and its connection to a // granted VPC, and EdgeRoute and EdgeRouteIndex, a prefix's forwarding claim -// and the record of every claim accepted in a VPC (see +// and the record of every claim accepted in a VPC, and EdgeListener, a +// provider's public addresses and ports (see // docs/enhancements/networking/galactic-edge). // +kubebuilder:object:generate=true // +groupName=galactic.datumapis.com @@ -44,6 +45,7 @@ func addKnownTypes(s *runtime.Scheme) error { &EdgeAttachment{}, &EdgeAttachmentList{}, &EdgeRoute{}, &EdgeRouteList{}, &EdgeRouteIndex{}, &EdgeRouteIndexList{}, + &EdgeListener{}, &EdgeListenerList{}, ) metav1.AddToGroupVersion(s, GroupVersion) return nil diff --git a/api/v1alpha1/zz_generated.deepcopy.go b/api/v1alpha1/zz_generated.deepcopy.go index 237a8f422..15ec0e6d7 100644 --- a/api/v1alpha1/zz_generated.deepcopy.go +++ b/api/v1alpha1/zz_generated.deepcopy.go @@ -311,6 +311,169 @@ func (in *EdgeInstanceSpec) DeepCopy() *EdgeInstanceSpec { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *EdgeListener) DeepCopyInto(out *EdgeListener) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EdgeListener. +func (in *EdgeListener) DeepCopy() *EdgeListener { + if in == nil { + return nil + } + out := new(EdgeListener) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *EdgeListener) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *EdgeListenerBackend) DeepCopyInto(out *EdgeListenerBackend) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EdgeListenerBackend. +func (in *EdgeListenerBackend) DeepCopy() *EdgeListenerBackend { + if in == nil { + return nil + } + out := new(EdgeListenerBackend) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *EdgeListenerList) DeepCopyInto(out *EdgeListenerList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]EdgeListener, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EdgeListenerList. +func (in *EdgeListenerList) DeepCopy() *EdgeListenerList { + if in == nil { + return nil + } + out := new(EdgeListenerList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *EdgeListenerList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *EdgeListenerPort) DeepCopyInto(out *EdgeListenerPort) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EdgeListenerPort. +func (in *EdgeListenerPort) DeepCopy() *EdgeListenerPort { + if in == nil { + return nil + } + out := new(EdgeListenerPort) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *EdgeListenerServiceReference) DeepCopyInto(out *EdgeListenerServiceReference) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EdgeListenerServiceReference. +func (in *EdgeListenerServiceReference) DeepCopy() *EdgeListenerServiceReference { + if in == nil { + return nil + } + out := new(EdgeListenerServiceReference) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *EdgeListenerSpec) DeepCopyInto(out *EdgeListenerSpec) { + *out = *in + out.ProviderRef = in.ProviderRef + out.ServiceRef = in.ServiceRef + if in.Addresses != nil { + in, out := &in.Addresses, &out.Addresses + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.Ports != nil { + in, out := &in.Ports, &out.Ports + *out = make([]EdgeListenerPort, len(*in)) + copy(*out, *in) + } + if in.HealthPort != nil { + in, out := &in.HealthPort, &out.HealthPort + *out = new(int32) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EdgeListenerSpec. +func (in *EdgeListenerSpec) DeepCopy() *EdgeListenerSpec { + if in == nil { + return nil + } + out := new(EdgeListenerSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *EdgeListenerStatus) DeepCopyInto(out *EdgeListenerStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Backends != nil { + in, out := &in.Backends, &out.Backends + *out = make([]EdgeListenerBackend, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EdgeListenerStatus. +func (in *EdgeListenerStatus) DeepCopy() *EdgeListenerStatus { + if in == nil { + return nil + } + out := new(EdgeListenerStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *EdgePacketDevice) DeepCopyInto(out *EdgePacketDevice) { *out = *in diff --git a/config/crd/galactic.datumapis.com_edgeattachments.yaml b/config/crd/galactic.datumapis.com_edgeattachments.yaml index 77cfa275a..a0bc48492 100644 --- a/config/crd/galactic.datumapis.com_edgeattachments.yaml +++ b/config/crd/galactic.datumapis.com_edgeattachments.yaml @@ -81,6 +81,7 @@ spec: - SocketAccess - PacketAccess - PrefixReachability + - PublicListener type: string version: description: Version is the capability's version. diff --git a/config/crd/galactic.datumapis.com_edgelisteners.yaml b/config/crd/galactic.datumapis.com_edgelisteners.yaml new file mode 100644 index 000000000..3c2561baf --- /dev/null +++ b/config/crd/galactic.datumapis.com_edgelisteners.yaml @@ -0,0 +1,305 @@ +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.23.0 + name: edgelisteners.galactic.datumapis.com +spec: + group: galactic.datumapis.com + names: + categories: + - galactic + kind: EdgeListener + listKind: EdgeListenerList + plural: edgelisteners + singular: edgelistener + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .spec.providerRef.name + name: Provider + type: string + - jsonPath: .status.conditions[?(@.type=="Accepted")].status + name: Accepted + type: string + - jsonPath: .status.conditions[?(@.type=="Programmed")].status + name: Programmed + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + EdgeListener gives an approved provider public addresses and ports, served + by the gateway nodes of the cell. It lives in the gateway namespace. The + platform authority writes its spec and core its status; no provider writes + either. Core turns each port into a gateway NetworkService whose backends are + the provider's listener attachments. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: |- + EdgeListenerSpec is the public addresses and ports the platform gives one + provider. Only the platform authority writes it; no provider may. + properties: + addresses: + description: |- + Addresses are the public addresses, at most one IPv6 and one IPv4. Each + must fall in one of the cell's gateway VIP prefixes; core refuses any + other with AddressOutsidePool. An IPv4 address is written in dotted + form. + items: + maxLength: 39 + type: string + maxItems: 2 + minItems: 1 + type: array + x-kubernetes-list-type: set + x-kubernetes-validations: + - message: addresses must be valid IPv4 or IPv6 addresses, IPv4 in dotted form + rule: self.all(a, isIP(a)) + - message: addresses may hold at most one IPv6 address + rule: self.filter(a, isIP(a) && ip(a).family() == 6).size() <= 1 + - message: addresses may hold at most one IPv4 address + rule: self.filter(a, isIP(a) && ip(a).family() == 4).size() <= 1 + failurePolicy: + default: FailOpen + description: |- + FailurePolicy is copied into the health check of each of the listener's + NetworkServices. + enum: + - FailOpen + - FailClosed + type: string + healthPort: + description: |- + HealthPort is the TCP port probed on each backend. Unset, it is the + first tcp port's backendPort. It is required when every port is udp. + format: int32 + maximum: 65535 + minimum: 1 + type: integer + ports: + description: |- + Ports are the public ports. Core writes one gateway NetworkService per + port. Two ports of one protocol cannot share a backendPort, since a + backend's reply is translated back to one public port. + items: + description: |- + EdgeListenerPort is one public port and the port the provider's instances + serve it on. + properties: + backendPort: + description: |- + BackendPort is the port each provider instance listens on, on its + listener attachment's address. + format: int32 + maximum: 65535 + minimum: 1 + type: integer + port: + description: Port is the public port on the listener's addresses. + format: int32 + maximum: 65535 + minimum: 1 + type: integer + protocol: + description: Protocol is tcp or udp. + enum: + - tcp + - udp + type: string + required: + - backendPort + - port + - protocol + type: object + maxItems: 16 + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - protocol + - port + x-kubernetes-list-type: map + x-kubernetes-validations: + - message: two ports of one protocol cannot share a backendPort + rule: self.all(p, self.exists_one(q, q.protocol == p.protocol && q.backendPort == p.backendPort)) + providerRef: + description: |- + ProviderRef is the provider the listener serves. It must list + PublicListener. + properties: + name: + description: Name is the EdgeProvider's name. + maxLength: 253 + minLength: 1 + type: string + required: + - name + type: object + serviceRef: + description: |- + ServiceRef is the EdgeService granting the provider SocketAccess and + PublicListener on its ingress gVPC. The provider's listener + attachments are made against it. + properties: + name: + description: Name is the EdgeService's name. + maxLength: 253 + minLength: 1 + type: string + namespace: + description: Namespace is the EdgeService's namespace, the ingress gVPC's namespace. + maxLength: 63 + minLength: 1 + type: string + required: + - name + - namespace + type: object + sessionAffinity: + default: ClientIPAndProtocol + description: SessionAffinity is copied into each of the listener's NetworkServices. + enum: + - None + - ClientIP + - ClientIPAndProtocol + type: string + required: + - addresses + - ports + - providerRef + - serviceRef + type: object + x-kubernetes-validations: + - message: providerRef is immutable + rule: self.providerRef == oldSelf.providerRef + - message: serviceRef is immutable + rule: self.serviceRef == oldSelf.serviceRef + - message: 'healthPort is required when every port is udp: a health check probes a TCP port' + rule: has(self.healthPort) || self.ports.exists(p, p.protocol == 'tcp') + status: + description: EdgeListenerStatus is written by core only. + properties: + backends: + description: Backends are the provider's listener attachments. + items: + description: |- + EdgeListenerBackend is one listener attachment and whether it receives new + flows. + properties: + address: + description: Address is the attachment's IPv6 address in the ingress gVPC. + maxLength: 39 + type: string + attachment: + description: Attachment is the EdgeAttachment's namespace and name. + maxLength: 317 + type: string + node: + description: Node is the attachment's node. + maxLength: 253 + type: string + serving: + description: |- + Serving is whether the attachment receives new flows: it is + programmed, its instance lease is valid and its provider reports Ready. + type: boolean + required: + - attachment + type: object + maxItems: 1024 + type: array + x-kubernetes-list-map-keys: + - attachment + x-kubernetes-list-type: map + conditions: + description: Conditions are Accepted and Programmed. + items: + description: Condition contains details for one aspect of the current state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + maxItems: 8 + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + observedGeneration: + description: ObservedGeneration is the generation Conditions describe. + format: int64 + type: integer + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/config/crd/galactic.datumapis.com_edgeproviders.yaml b/config/crd/galactic.datumapis.com_edgeproviders.yaml index ca302cf93..58989ce17 100644 --- a/config/crd/galactic.datumapis.com_edgeproviders.yaml +++ b/config/crd/galactic.datumapis.com_edgeproviders.yaml @@ -65,6 +65,7 @@ spec: - SocketAccess - PacketAccess - PrefixReachability + - PublicListener type: string version: description: Version is the capability's version. diff --git a/config/crd/galactic.datumapis.com_edgeservices.yaml b/config/crd/galactic.datumapis.com_edgeservices.yaml index 5c314c9d8..ca61409a2 100644 --- a/config/crd/galactic.datumapis.com_edgeservices.yaml +++ b/config/crd/galactic.datumapis.com_edgeservices.yaml @@ -65,8 +65,9 @@ spec: - SocketAccess - PacketAccess - PrefixReachability + - PublicListener type: string - maxItems: 3 + maxItems: 4 minItems: 1 type: array x-kubernetes-list-type: set diff --git a/config/crd/galactic.datumapis.com_networkservices.yaml b/config/crd/galactic.datumapis.com_networkservices.yaml index bf7093e64..7ffcd5e94 100644 --- a/config/crd/galactic.datumapis.com_networkservices.yaml +++ b/config/crd/galactic.datumapis.com_networkservices.yaml @@ -68,7 +68,9 @@ spec: serve the service, so the backend set follows attachments as they are created, deleted or moved to another node, and galactic-router on each node generates the ServiceVIPBinding its backends need from the same - selection. + selection. A service in the gateway namespace can instead name an + EdgeListener with EdgeListenerRef, whose listener attachments are then its + backends. properties: apiVersion: description: |- @@ -205,7 +207,8 @@ spec: and from IPv6, and its IPv4 addresses are never backends. An attachment with no status.node, or no IPv6 address, is not a backend until it has both. An empty selector is rejected rather than read as "every - attachment in the VPC". + attachment in the VPC". Exactly one of BackendSelector and + EdgeListenerRef is required. properties: matchExpressions: description: matchExpressions is a list of label selector requirements. @@ -254,6 +257,23 @@ spec: - message: backendSelector must not be empty rule: (has(self.matchLabels) && size(self.matchLabels) > 0) || (has(self.matchExpressions) && size(self.matchExpressions) > 0) + edgeListenerRef: + description: |- + EdgeListenerRef names the EdgeListener, in the service's namespace, + whose listener attachments are the service's backends, in place of + BackendSelector. Core sets it on the services it writes for a + listener, one per listener port. It is allowed only in the gateway + namespace. Until gateways resolve listener backends, a service that + sets it has no backends and its VIPs are not advertised. + properties: + name: + description: Name is the EdgeListener's name. + maxLength: 253 + minLength: 1 + type: string + required: + - name + type: object healthCheck: description: |- HealthCheck turns on health checks for the service's backends. Each @@ -459,7 +479,6 @@ spec: minLength: 1 type: string required: - - backendSelector - protocol - vipAddresses - vpcRef @@ -488,6 +507,8 @@ spec: - message: 'healthCheck.port is required for udp: a health check probes a TCP port' rule: self.protocol != 'udp' || !has(self.healthCheck) || has(self.healthCheck.port) + - message: exactly one of backendSelector and edgeListenerRef is required + rule: has(self.backendSelector) != has(self.edgeListenerRef) status: description: NetworkServiceStatus defines the observed state of a NetworkService. properties: diff --git a/config/crd/kustomization.yaml b/config/crd/kustomization.yaml index 0e7a4a2f6..bcdd608ee 100644 --- a/config/crd/kustomization.yaml +++ b/config/crd/kustomization.yaml @@ -13,6 +13,7 @@ resources: - galactic.datumapis.com_bgpvrfinstances.yaml - galactic.datumapis.com_edgeattachments.yaml - galactic.datumapis.com_edgeinstances.yaml + - galactic.datumapis.com_edgelisteners.yaml - galactic.datumapis.com_edgeproviderapprovals.yaml - galactic.datumapis.com_edgeproviders.yaml - galactic.datumapis.com_edgerouteindices.yaml diff --git a/config/galactic-edge/policies.yaml b/config/galactic-edge/policies.yaml index 64faa88d4..a08aae188 100644 --- a/config/galactic-edge/policies.yaml +++ b/config/galactic-edge/policies.yaml @@ -383,3 +383,89 @@ metadata: spec: policyName: galactic-edge-controller-lease validationActions: [Deny] +--- +# A provider never writes its own public listener or the gateway services +# core makes from it: the platform authority writes an EdgeListener's spec +# and core its status and the NetworkServices. RBAC already grants a +# provider neither, so this holds even where an operator binds a broader +# role to a provider's ServiceAccount. One binding evaluates the policy +# against every EdgeProvider, so it needs no per-provider binding, and +# allows every request while no provider is registered. +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: + name: galactic-edge-provider-listener +spec: + failurePolicy: Fail + paramKind: + apiVersion: galactic.datumapis.com/v1alpha1 + kind: EdgeProvider + matchConstraints: + resourceRules: + - apiGroups: [galactic.datumapis.com] + apiVersions: ["*"] + operations: [CREATE, UPDATE, DELETE] + resources: [edgelisteners, edgelisteners/status, networkservices, networkservices/status] + matchConditions: + - name: workload + expression: request.userInfo.username.startsWith('system:serviceaccount:') + variables: + # The resource written, with its subresource when there is one. + - name: resource + expression: >- + request.resource.resource + + (request.?subResource.orValue('') == '' ? '' : '/' + request.subResource) + validations: + - expression: >- + !params.spec.serviceAccounts.exists(sa, + request.userInfo.username == 'system:serviceaccount:' + sa.namespace + ':' + sa.name) + messageExpression: >- + 'a ServiceAccount of provider ' + params.metadata.name + ' cannot write ' + variables.resource +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: + name: galactic-edge-provider-listener +spec: + policyName: galactic-edge-provider-listener + paramRef: + selector: {} + parameterNotFoundAction: Allow + validationActions: [Deny] +--- +# An EdgeListener and every NetworkService naming one live in the gateway +# namespace. A project-namespace NetworkService is trusted for nothing, so +# it cannot take its backends from a provider's listener. The CRD's own +# validation cannot read an object's namespace. +# The policy assumes the gateway namespace is galactic-system, which this file +# fixes because kustomize does not rewrite names inside expressions. A cell +# that runs the gateway with another --gateway-namespace must change both +# expressions. +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: + name: galactic-edge-listener-namespace +spec: + failurePolicy: Fail + matchConstraints: + resourceRules: + - apiGroups: [galactic.datumapis.com] + apiVersions: ["*"] + operations: [CREATE, UPDATE] + resources: [edgelisteners, networkservices] + validations: + - expression: >- + request.resource.resource != 'edgelisteners' || object.metadata.namespace == 'galactic-system' + message: an EdgeListener lives only in the gateway namespace, galactic-system + - expression: >- + request.resource.resource != 'networkservices' || !has(object.spec.edgeListenerRef) || + object.metadata.namespace == 'galactic-system' + message: edgeListenerRef is allowed only in the gateway namespace, galactic-system +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: + name: galactic-edge-listener-namespace +spec: + policyName: galactic-edge-listener-namespace + validationActions: [Deny] diff --git a/config/galactic-edge/rbac.yaml b/config/galactic-edge/rbac.yaml index 844566184..4af7abf62 100644 --- a/config/galactic-edge/rbac.yaml +++ b/config/galactic-edge/rbac.yaml @@ -78,3 +78,17 @@ subjects: - kind: ServiceAccount name: galactic-edge namespace: galactic-system +--- +# Writing a provider's public listener. Nothing binds it here: an operator +# binds it, with a RoleBinding in galactic-system, to the platform authority +# that declares listener addresses. It grants no status: core writes an +# EdgeListener's status, and galactic-edge-provider-listener (policies.yaml) +# refuses every write by a provider's ServiceAccount. +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: galactic-edge-listener-authority +rules: + - apiGroups: [galactic.datumapis.com] + resources: [edgelisteners] + verbs: [get, list, watch, create, update, patch, delete] diff --git a/docs/api/galactic.md b/docs/api/galactic.md index 4921ccc56..9d998d9b2 100644 --- a/docs/api/galactic.md +++ b/docs/api/galactic.md @@ -18,12 +18,14 @@ EdgeProviderApproval and EdgeService, the Galactic Edge provider registration, its operator approval and a tenant grant, EdgeInstance and EdgeAttachment, a provider pod and its connection to a granted VPC, and EdgeRoute and EdgeRouteIndex, a prefix's forwarding claim -and the record of every claim accepted in a VPC (see +and the record of every claim accepted in a VPC, and EdgeListener, a +provider's public addresses and ports (see docs/enhancements/networking/galactic-edge). ### Resource Types - [EdgeAttachment](#edgeattachment) - [EdgeInstance](#edgeinstance) +- [EdgeListener](#edgelistener) - [EdgeProvider](#edgeprovider) - [EdgeProviderApproval](#edgeproviderapproval) - [EdgeRoute](#edgeroute) @@ -218,7 +220,7 @@ _Appears in:_ | Field | Description | Default | Validation | | --- | --- | --- | --- | -| `name` _string_ | Name is the capability's name. | | Enum: [SocketAccess PacketAccess PrefixReachability]
| +| `name` _string_ | Name is the capability's name. | | Enum: [SocketAccess PacketAccess PrefixReachability PublicListener]
| | `version` _string_ | Version is the capability's version. | | Pattern: `^v[1-9][0-9]*$`
| @@ -286,6 +288,186 @@ _Appears in:_ | `bootID` _string_ | BootID is the node's boot ID (/proc/sys/kernel/random/boot_id) when
the instance was created. Its lease's renew start is on that boot's
CLOCK_BOOTTIME, so galactic-edge applies no renewal of an instance
whose boot ID is not the node's current one. | | MaxLength: 36
MinLength: 1
| +#### EdgeListener + + + +EdgeListener gives an approved provider public addresses and ports, served +by the gateway nodes of the cell. It lives in the gateway namespace. The +platform authority writes its spec and core its status; no provider writes +either. Core turns each port into a gateway NetworkService whose backends are +the provider's listener attachments. + + + + + +| Field | Description | Default | Validation | +| --- | --- | --- | --- | +| `apiVersion` _string_ | `galactic.datumapis.com/v1alpha1` | | | +| `kind` _string_ | `EdgeListener` | | | +| `kind` _string_ | Kind is a string value representing the REST resource this object represents.
Servers may infer this from the endpoint the client submits requests to.
Cannot be updated.
In CamelCase.
More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds | | | +| `apiVersion` _string_ | APIVersion defines the versioned schema of this representation of an object.
Servers should convert recognized schemas to the latest internal value, and
may reject unrecognized values.
More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources | | | +| `metadata` _[ObjectMeta](https://kubernetes.io/docs/reference/generated/kubernetes-api/v/#objectmeta-v1-meta)_ | Refer to Kubernetes API documentation for fields of `metadata`. | | | +| `spec` _[EdgeListenerSpec](#edgelistenerspec)_ | | | | +| `status` _[EdgeListenerStatus](#edgelistenerstatus)_ | | | | + + +#### EdgeListenerBackend + + + +EdgeListenerBackend is one listener attachment and whether it receives new +flows. + + + +_Appears in:_ +- [EdgeListenerStatus](#edgelistenerstatus) + +| Field | Description | Default | Validation | +| --- | --- | --- | --- | +| `attachment` _string_ | Attachment is the EdgeAttachment's namespace and name. | | MaxLength: 317
| +| `node` _string_ | Node is the attachment's node. | | MaxLength: 253
| +| `address` _string_ | Address is the attachment's IPv6 address in the ingress gVPC. | | MaxLength: 39
| +| `serving` _boolean_ | Serving is whether the attachment receives new flows: it is
programmed, its instance lease is valid and its provider reports Ready. | | | + + +#### EdgeListenerFailurePolicy + +_Underlying type:_ _string_ + +EdgeListenerFailurePolicy decides whether backends of unknown health, and a +set whose backends are all unhealthy, receive traffic. + +_Validation:_ +- Enum: [FailOpen FailClosed] + +_Appears in:_ +- [EdgeListenerSpec](#edgelistenerspec) + +| Field | Description | +| --- | --- | +| `FailOpen` | | +| `FailClosed` | | + + +#### EdgeListenerPort + + + +EdgeListenerPort is one public port and the port the provider's instances +serve it on. + + + +_Appears in:_ +- [EdgeListenerSpec](#edgelistenerspec) + +| Field | Description | Default | Validation | +| --- | --- | --- | --- | +| `protocol` _[EdgeListenerProtocol](#edgelistenerprotocol)_ | Protocol is tcp or udp. | | Enum: [tcp udp]
| +| `port` _integer_ | Port is the public port on the listener's addresses. | | Maximum: 65535
Minimum: 1
| +| `backendPort` _integer_ | BackendPort is the port each provider instance listens on, on its
listener attachment's address. | | Maximum: 65535
Minimum: 1
| + + +#### EdgeListenerProtocol + +_Underlying type:_ _string_ + +EdgeListenerProtocol is the transport protocol of one listener port. + +_Validation:_ +- Enum: [tcp udp] + +_Appears in:_ +- [EdgeListenerPort](#edgelistenerport) + +| Field | Description | +| --- | --- | +| `tcp` | | +| `udp` | | + + +#### EdgeListenerServiceReference + + + +EdgeListenerServiceReference names the EdgeService that grants a listener's +provider SocketAccess and PublicListener on its ingress gVPC. + + + +_Appears in:_ +- [EdgeListenerSpec](#edgelistenerspec) + +| Field | Description | Default | Validation | +| --- | --- | --- | --- | +| `namespace` _string_ | Namespace is the EdgeService's namespace, the ingress gVPC's namespace. | | MaxLength: 63
MinLength: 1
| +| `name` _string_ | Name is the EdgeService's name. | | MaxLength: 253
MinLength: 1
| + + +#### EdgeListenerSessionAffinity + +_Underlying type:_ _string_ + +EdgeListenerSessionAffinity selects which parts of a flow the gateway hashes +to pick a backend, as NetworkService's sessionAffinity does. + +_Validation:_ +- Enum: [None ClientIP ClientIPAndProtocol] + +_Appears in:_ +- [EdgeListenerSpec](#edgelistenerspec) + +| Field | Description | +| --- | --- | +| `None` | | +| `ClientIP` | | +| `ClientIPAndProtocol` | | + + +#### EdgeListenerSpec + + + +EdgeListenerSpec is the public addresses and ports the platform gives one +provider. Only the platform authority writes it; no provider may. + + + +_Appears in:_ +- [EdgeListener](#edgelistener) + +| Field | Description | Default | Validation | +| --- | --- | --- | --- | +| `providerRef` _[EdgeProviderReference](#edgeproviderreference)_ | ProviderRef is the provider the listener serves. It must list
PublicListener. | | | +| `serviceRef` _[EdgeListenerServiceReference](#edgelistenerservicereference)_ | ServiceRef is the EdgeService granting the provider SocketAccess and
PublicListener on its ingress gVPC. The provider's listener
attachments are made against it. | | | +| `addresses` _string array_ | Addresses are the public addresses, at most one IPv6 and one IPv4. Each
must fall in one of the cell's gateway VIP prefixes; core refuses any
other with AddressOutsidePool. An IPv4 address is written in dotted
form. | | MaxItems: 2
MinItems: 1
items:MaxLength: 39
| +| `ports` _[EdgeListenerPort](#edgelistenerport) array_ | Ports are the public ports. Core writes one gateway NetworkService per
port. Two ports of one protocol cannot share a backendPort, since a
backend's reply is translated back to one public port. | | MaxItems: 16
MinItems: 1
| +| `healthPort` _integer_ | HealthPort is the TCP port probed on each backend. Unset, it is the
first tcp port's backendPort. It is required when every port is udp. | | Maximum: 65535
Minimum: 1
| +| `sessionAffinity` _[EdgeListenerSessionAffinity](#edgelistenersessionaffinity)_ | SessionAffinity is copied into each of the listener's NetworkServices. | ClientIPAndProtocol | Enum: [None ClientIP ClientIPAndProtocol]
| +| `failurePolicy` _[EdgeListenerFailurePolicy](#edgelistenerfailurepolicy)_ | FailurePolicy is copied into the health check of each of the listener's
NetworkServices. | FailOpen | Enum: [FailOpen FailClosed]
| + + +#### EdgeListenerStatus + + + +EdgeListenerStatus is written by core only. + + + +_Appears in:_ +- [EdgeListener](#edgelistener) + +| Field | Description | Default | Validation | +| --- | --- | --- | --- | +| `observedGeneration` _integer_ | ObservedGeneration is the generation Conditions describe. | | | +| `conditions` _[Condition](https://kubernetes.io/docs/reference/generated/kubernetes-api/v/#condition-v1-meta) array_ | Conditions are Accepted and Programmed. | | MaxItems: 8
| +| `backends` _[EdgeListenerBackend](#edgelistenerbackend) array_ | Backends are the provider's listener attachments. | | MaxItems: 1024
| + + #### EdgePacketDevice @@ -368,6 +550,7 @@ EdgeProviderReference names an EdgeProvider. _Appears in:_ - [EdgeAttachmentSpec](#edgeattachmentspec) - [EdgeInstanceSpec](#edgeinstancespec) +- [EdgeListenerSpec](#edgelistenerspec) - [EdgeRouteSpec](#edgeroutespec) - [EdgeServiceSpec](#edgeservicespec) @@ -656,7 +839,7 @@ _Appears in:_ | --- | --- | --- | --- | | `providerRef` _[EdgeProviderReference](#edgeproviderreference)_ | ProviderRef is the only provider the grant authorizes. | | | | `vpcRef` _[EdgeVPCReference](#edgevpcreference)_ | VPCRef is the only VPC the grant authorizes. | | | -| `capabilities` _string array_ | Capabilities are the capability names the provider may use in the VPC. | | MaxItems: 3
MinItems: 1
items:Enum: [SocketAccess PacketAccess PrefixReachability]
| +| `capabilities` _string array_ | Capabilities are the capability names the provider may use in the VPC. | | MaxItems: 4
MinItems: 1
items:Enum: [SocketAccess PacketAccess PrefixReachability PublicListener]
| | `prefixes` _string array_ | Prefixes bound the prefixes the provider may request in the VPC. Each
is a masked CIDR. Grants of services granting the same VPC must not
overlap: galactic-controller refuses the attachments and routes of the
later of two services whose prefixes overlap. | | MaxItems: 64
items:MaxLength: 43
| | `validUntil` _[Time](https://kubernetes.io/docs/reference/generated/kubernetes-api/v/#time-v1-meta)_ | ValidUntil, when set, is the wall-clock time after which the grant
authorizes nothing. Admission refuses it, and revokes what it issued,
once fewer than the cell's maximum clock skew remain. | | | | `clientPool` _string_ | ClientPool is the IPv6 range, inside the VPC, that attachments take
their addresses from: a masked CIDR from /64 to /120. At most 1024 of
its addresses are allocated, whatever its size. Pools of services
granting the same VPC must not overlap; galactic-controller refuses
the attachments of the later of two overlapping services. Without a
pool, the service admits no attachment. A pool can be added to a
service that has none, and is fixed from then on. | | MaxLength: 43
| diff --git a/docs/api/network-gateway.md b/docs/api/network-gateway.md index b9e1b811d..a0d772a7b 100644 --- a/docs/api/network-gateway.md +++ b/docs/api/network-gateway.md @@ -429,7 +429,9 @@ Backends are not listed. BackendSelector picks the VPCAttachments that serve the service, so the backend set follows attachments as they are created, deleted or moved to another node, and galactic-router on each node generates the ServiceVIPBinding its backends need from the same -selection. +selection. A service in the gateway namespace can instead name an +EdgeListener with EdgeListenerRef, whose listener attachments are then its +backends. @@ -543,6 +545,23 @@ _Appears in:_ | `conditions` _[Condition](https://kubernetes.io/docs/reference/generated/kubernetes-api/v/#condition-v1-meta) array_ | | | | +#### NetworkServiceEdgeListenerReference + + + +NetworkServiceEdgeListenerReference names an EdgeListener +(galactic.datumapis.com/v1alpha1) in the service's namespace. + + + +_Appears in:_ +- [NetworkServiceSpec](#networkservicespec) + +| Field | Description | Default | Validation | +| --- | --- | --- | --- | +| `name` _string_ | Name is the EdgeListener's name. | | MaxLength: 253
MinLength: 1
| + + #### NetworkServiceHealthCheck @@ -643,7 +662,8 @@ _Appears in:_ | `port` _integer_ | Port is the ingress port on VIPAddresses that this service load-balances,
1-65535. It is required when PortRange is absent for tcp, udp and sctp
and must be unset for one without (esp, gre and icmp). Zero means unset
and is omitted when encoding, and an explicit 0 is refused. | | Maximum: 65535
Minimum: 1
| | `portRange` _[PortRange](#portrange)_ | PortRange replaces Port for an inclusive IPv6 UDP interval. Backend ports
are preserved; BackendPort must be omitted. | | | | `addressGroup` _[NetworkServiceAddressGroup](#networkserviceaddressgroup)_ | AddressGroup binds this listener to a complete, authoritative address inventory. | | | -| `backendSelector` _[LabelSelector](https://kubernetes.io/docs/reference/generated/kubernetes-api/v/#labelselector-v1-meta)_ | BackendSelector selects the VPCAttachments (galactic.datumapis.com/v1alpha1)
that serve this service, matched against each VPCAttachment object's own
labels: in any namespace for a service in a gateway namespace, and only
in its own namespace for a service in a project namespace. Only
attachments whose status.vpc equals VPCRef are candidates, whatever their
labels, so a selector cannot reach into another tenant's VPC. Each selected attachment contributes the
IPv6 addresses in its spec.interface.addresses as backends, on
BackendPort, for both VIPs: its node translates the IPv4 VIP's flows to
and from IPv6, and its IPv4 addresses are never backends. An attachment
with no status.node, or no IPv6 address, is not a backend until it has
both. An empty selector is rejected rather than read as "every
attachment in the VPC". | | Required: \{\}
| +| `backendSelector` _[LabelSelector](https://kubernetes.io/docs/reference/generated/kubernetes-api/v/#labelselector-v1-meta)_ | BackendSelector selects the VPCAttachments (galactic.datumapis.com/v1alpha1)
that serve this service, matched against each VPCAttachment object's own
labels: in any namespace for a service in a gateway namespace, and only
in its own namespace for a service in a project namespace. Only
attachments whose status.vpc equals VPCRef are candidates, whatever their
labels, so a selector cannot reach into another tenant's VPC. Each selected attachment contributes the
IPv6 addresses in its spec.interface.addresses as backends, on
BackendPort, for both VIPs: its node translates the IPv4 VIP's flows to
and from IPv6, and its IPv4 addresses are never backends. An attachment
with no status.node, or no IPv6 address, is not a backend until it has
both. An empty selector is rejected rather than read as "every
attachment in the VPC". Exactly one of BackendSelector and
EdgeListenerRef is required. | | | +| `edgeListenerRef` _[NetworkServiceEdgeListenerReference](#networkserviceedgelistenerreference)_ | EdgeListenerRef names the EdgeListener, in the service's namespace,
whose listener attachments are the service's backends, in place of
BackendSelector. Core sets it on the services it writes for a
listener, one per listener port. It is allowed only in the gateway
namespace. Until gateways resolve listener backends, a service that
sets it has no backends and its VIPs are not advertised. | | | | `backendPort` _integer_ | BackendPort is the destination port on every selected backend, 1-65535.
Like Port, it is required for tcp, udp and sctp and must be unset for
esp, gre and icmp. Zero means unset and is omitted when encoding, and an
explicit 0 is refused. | | Maximum: 65535
Minimum: 1
| | `sessionAffinity` _[NetworkServiceSessionAffinity](#networkservicesessionaffinity)_ | SessionAffinity selects which connections from one client share a
backend: None, the default, balances each connection on its own;
ClientIP pins a client address to one backend; ClientIPAndProtocol pins
a client address and protocol to one. Two services pin a client to the
same backend only if both set the same affinity and select the same
backend addresses. A change takes effect on every gateway node without a
restart, and rehashes every connection of the service, so most open
connections reach a different backend afterwards. | None | Enum: [None ClientIP ClientIPAndProtocol]
| | `healthCheck` _[NetworkServiceHealthCheck](#networkservicehealthcheck)_ | HealthCheck turns on health checks for the service's backends. Each
backend's own node opens a TCP connection to it on the health check
port, from the link-local address of the backend's host-side interface,
and publishes a decision in status.health of the backend's
ServiceVIPBindings. The gateway nodes take a backend whose decision is
Unhealthy out of the service's Maglev table, and keep every backend
when all of them are Unhealthy by default. FailClosed instead requires
fresh Healthy results for the current configuration and withdraws a VIP
with no healthy backends. Unset, no backend is probed and every
one stays in the table.
Where interface traffic policy is enforced, the backend's policy must
allow TCP from fe80::/10 to the health check port on the Private path,
and the replies back. | | | diff --git a/docs/designs/README.md b/docs/designs/README.md index 67c868fc3..aed8dd624 100644 --- a/docs/designs/README.md +++ b/docs/designs/README.md @@ -12,6 +12,6 @@ These documents explain decisions and planned work. Their status describes imple | [Latency-aware routing](latency-aware-routing.md) | Exploratory proposal | [Router configuration](../router/configuration.md) for available settings | | [MASQUE gateway](masque-gateway.md) | Superseded for #970 by the connector contract | [Gateway configuration](../gateway/configuration.md) for the implemented XDP/DSR gateway | | [MASQUE connector](masque/contract.md) | Proposed contract; [acceptance checks](masque/acceptance.md) not yet run | [Provider contract](../edge/provider-contract.md) for the implemented foundation | -| [Edge public listener](edge-public-listener.md) | Proposed with decisions settled; not implemented | [Gateway architecture](../gateway/architecture.md) for the implemented VIP datapath | +| [Edge public listener](edge-public-listener.md) | Proposed with decisions settled; API implemented, not served | [Gateway architecture](../gateway/architecture.md) for the implemented VIP datapath | When implementing a proposal, move the available interface or operating procedure into its component guide and update this status. Retain decisions and alternatives here. Keep measurements tied to their revision and environment in the [evidence archive](../archive/README.md), rather than presenting old results as current readiness. diff --git a/docs/designs/edge-public-listener.md b/docs/designs/edge-public-listener.md index 91ec3bb1e..d75940089 100644 --- a/docs/designs/edge-public-listener.md +++ b/docs/designs/edge-public-listener.md @@ -1,6 +1,6 @@ # Galactic Edge public listener -Status: proposed, with its open decisions settled. The Phase 0 lab proof is done (see [Phase 0 results](#phase-0-results)); nothing else in this design is implemented. It extends the [Galactic Edge Foundation](galactic-edge.md) and reuses the [XDP/DSR gateway](../gateway/architecture.md). The [provider contract](../edge/provider-contract.md) remains the reference for behavior that exists today. +Status: proposed, with its open decisions settled. The Phase 0 lab proof is done (see [Phase 0 results](#phase-0-results)), and Phase 1, the API, is implemented: `EdgeListener`, the `PublicListener` capability and `NetworkService.spec.edgeListenerRef` exist, but nothing serves a listener yet. It extends the [Galactic Edge Foundation](galactic-edge.md) and reuses the [XDP/DSR gateway](../gateway/architecture.md). The [provider contract](../edge/provider-contract.md) remains the reference for behavior that exists today. This design follows the [Datum enhancement template](https://github.com/datum-cloud/enhancements/blob/main/enhancements/template/README.md). diff --git a/docs/edge/provider-contract.md b/docs/edge/provider-contract.md index d977b7b82..705ca1b9a 100644 --- a/docs/edge/provider-contract.md +++ b/docs/edge/provider-contract.md @@ -20,7 +20,7 @@ This document is the contract the [Galactic Edge foundation](../designs/galactic | Area | Decision | | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Contract representation | Kubernetes resources in `galactic.datumapis.com/v1alpha1`. A provider talks only to the cell's API server; there is no provider RPC. | -| Contract version | `v1alpha1`. Capabilities are versioned separately: `SocketAccess/v1`, `PacketAccess/v1`, `PrefixReachability/v1`. | +| Contract version | `v1alpha1`. Capabilities are versioned separately: `SocketAccess/v1`, `PacketAccess/v1`, `PrefixReachability/v1`, `PublicListener/v1`. | | Provider authority | The API server's authentication of the provider pod's bound ServiceAccount token, checked by a ValidatingAdmissionPolicy (see [Admission policy](#admission-policy)). A pod-UID field a provider writes is only checked against the token, never trusted on its own. | | Control packaging | Admission, allocation and publication run in `galactic-controller --role=cell`, leader-elected, one writer per cell. | | Node packaging | A new `galactic-edge` DaemonSet on nodes labeled `galactic.datumapis.com/node=edge` and `galactic.datumapis.com/edge=enabled`. The `edge=enabled` label is new, and [node labels](../operations/node-labels.md) gains it when the DaemonSet ships. `galactic-edge` is the only process that changes host state for an edge attachment. It writes only the CNI datapath's maps under `/sys/fs/bpf/galactic`, and never opens `/sys/fs/bpf/galactic-edge`, which is `galactic-gateway`'s pin directory despite the name (`internal/plumbing/ebpf/edgeattach/attach.go:38`). | @@ -44,8 +44,9 @@ All resources are in `galactic.datumapis.com/v1alpha1`. Object names that carry | `EdgeAttachment` | Namespace | `ea-` + pod UID + `-` + service UID | One instance's isolated connection to the service's gVPC. | | `EdgeRoute` | Namespace | `hash(gVPC UID, prefix)` | One prefix's forwarding claim and publication. | | `EdgeRouteIndex` | Namespace | gVPC UID | Core's record of every accepted route in one gVPC; serializes acceptance. | +| `EdgeListener` | Namespace | Platform authority's choice | A provider's public addresses and ports. | -`EdgeInstance`, its `Lease`, `EdgeAttachment` and `EdgeRoute` live in the provider's namespace. `EdgeService` and `EdgeRouteIndex` live in the namespace of the gVPC they reference. +`EdgeInstance`, its `Lease`, `EdgeAttachment` and `EdgeRoute` live in the provider's namespace. `EdgeService` and `EdgeRouteIndex` live in the namespace of the gVPC they reference. `EdgeListener` lives in the gateway namespace, `galactic-system`, and the `galactic-edge-listener-namespace` policy refuses it anywhere else. Core finds a route by its spec, never by its name. A route's name only has to be the same in every instance of one provider, so that they contend for a prefix through one object; the hash is the provider's choice. @@ -73,6 +74,9 @@ A field not listed is read-only to everyone but the control plane that owns the | `EdgeRoute.status.closedEpoch` | `galactic-edge` on `accepted.node` | Never decreases and never passes `accepted.epoch`. A ValidatingAdmissionPolicy requires the writer's token node name (`authentication.kubernetes.io/node-name`) to equal `accepted.node`, and the change to touch only `closedEpoch`. | | `EdgeRouteIndex` | Core | Compare-and-swap only. No provider ServiceAccount can read or write it. | | `BGPAdvertisement` for an `EdgeRoute` | Core | One per route in `galactic-system`, named `edge-`, labeled with the route's UID and accepted epoch. No owner reference: the route is in another namespace. See [Publication](#publication). | +| `EdgeListener.spec` | Platform authority | `providerRef` and `serviceRef` are immutable. No provider ServiceAccount may write it: the `galactic-edge-provider-listener` policy refuses every provider write, and the `galactic-edge-listener-authority` ClusterRole, bound by the operator, grants the authority access. | +| `EdgeListener.status` | Core | `Accepted` and `Programmed` conditions and the listener's backends. No provider ServiceAccount may write it. | +| `NetworkService` with `edgeListenerRef` | Core | One per listener port, in `galactic-system` only. No provider ServiceAccount may write any `NetworkService`. Until gateways resolve listener backends, such a service has none and its VIPs are not advertised. | | Deletion of dead `EdgeInstance`s and `EdgeRoute`s | Core | See [Reaping](#reaping). | `admission.Writer` knows two writers, core and provider (`internal/edge/admission/admission.go:169`). `galactic-controller` and `galactic-edge` both count as core there, so `MaySetCondition` separates core from providers, not one core process from the other. The split between them in this table is enforced by RBAC and admission policies that limit `galactic-edge`'s ServiceAccount to `Programmed`, `Released`, device names and `closedEpoch`. @@ -119,6 +123,7 @@ A ValidatingAdmissionPolicy reads only its own parameter object, so the provider 4. A provider that is not approved has no RoleBinding, so RBAC refuses its writes before the policy runs. Withdrawing approval, by deleting the `EdgeProviderApproval`, clears `status.approved` and deletes both bindings. 5. A person's writes are not checked by the policy: RBAC alone decides them, so an operator can still clear an object a provider left behind. 6. A second policy holds core's own RoleBinding writes to the provider ClusterRole. Kubernetes runs no admission policy on policy bindings themselves, so core's write access to those is bounded by RBAC alone. +7. `galactic-edge-provider-listener` has one binding, whose `paramRef` selects every `EdgeProvider` with `parameterNotFoundAction: Allow`. It refuses any create, update or delete of an `EdgeListener` or `NetworkService`, or their status, by a ServiceAccount an `EdgeProvider` lists. `galactic-edge-listener-namespace` refuses an `EdgeListener`, or a `NetworkService` with `edgeListenerRef`, outside `galactic-system`, which the file fixes as the gateway namespace, so a cell that runs the gateway with another `--gateway-namespace` must edit both expressions. ### Idempotency diff --git a/internal/controller/rulebackends.go b/internal/controller/rulebackends.go index fa499ac70..8add2fdc8 100644 --- a/internal/controller/rulebackends.go +++ b/internal/controller/rulebackends.go @@ -215,6 +215,10 @@ func selectRuleBackends( // from attachments, whatever other rules select, sorted by address, and the // selected attachments that are not backends yet, as "namespace/name: reason". // See selectRuleBackends for which attachments qualify. +// +// A rule that names an EdgeListener instead of a BackendSelector has no +// backends yet: gateways do not resolve listener attachments, so its listener +// is reported pending and its VIPs are never advertised. func ruleCandidateBackends( rule *bgpv1alpha1.NetworkService, attachments []*cloudv1alpha1.VPCAttachment, objNS string, ) (backends []ruleBackend, pending []string, err error) { @@ -222,6 +226,10 @@ func ruleCandidateBackends( if err != nil { return nil, nil, err } + if ref := rule.Spec.EdgeListenerRef; ref != nil { + key := types.NamespacedName{Namespace: rule.Namespace, Name: ref.Name} + return nil, []string{key.String() + ": edge listener backends are not resolved yet"}, nil + } selector, err := ruleBackendSelector(rule) if err != nil { return nil, nil, err diff --git a/internal/controller/rulebackends_test.go b/internal/controller/rulebackends_test.go index 3f7942eab..62a8fbcda 100644 --- a/internal/controller/rulebackends_test.go +++ b/internal/controller/rulebackends_test.go @@ -121,6 +121,29 @@ func TestSelectRuleBackends_DropsConflictingBackends(t *testing.T) { } } +// TestSelectRuleBackends_EdgeListenerHasNoBackends covers a service that names +// an EdgeListener in place of a BackendSelector: until gateways resolve +// listener attachments it selects nothing, even an attachment in its VPC, and +// reports the listener pending rather than failing on an empty selector. +func TestSelectRuleBackends_EdgeListenerHasNoBackends(t *testing.T) { + rule := newTestRule(testRuleName, testVPCRef, testVIP) + rule.Spec.BackendSelector = metav1.LabelSelector{} + rule.Spec.EdgeListenerRef = &bgpv1alpha1.NetworkServiceEdgeListenerReference{Name: "masque-public"} + attachment := newBackendAttachment(testVPCRef, "fd00:10::1") + + sel, err := selectRuleBackends(rule, []*cloudv1alpha1.VPCAttachment{attachment}, nil, familyIPv6, "") + if err != nil { + t.Fatalf("selectRuleBackends: %v", err) + } + if len(sel.backends) != 0 || len(sel.claimed) != 0 { + t.Errorf("backends = %+v, claimed = %+v, want none", sel.backends, sel.claimed) + } + const want = "/masque-public: edge listener backends are not resolved yet" + if len(sel.pending) != 1 || !strings.Contains(sel.pending[0], want) { + t.Errorf("pending = %v, want the listener reported", sel.pending) + } +} + // newSharingRule returns a rule named name with the IPv6 VIP vip, created at // second created, selecting newBackendAttachment's attachments in testVPCRef. func newSharingRule(name, vip string, created int64) *bgpv1alpha1.NetworkService { diff --git a/internal/edge/admission/admission.go b/internal/edge/admission/admission.go index 8a71e1a52..367b56113 100644 --- a/internal/edge/admission/admission.go +++ b/internal/edge/admission/admission.go @@ -60,6 +60,7 @@ var supportedCapabilities = []Capability{ {Name: "SocketAccess", Version: "v1"}, {Name: "PacketAccess", Version: "v1"}, {Name: "PrefixReachability", Version: "v1"}, + {Name: "PublicListener", Version: "v1"}, } // CoreImplements reports whether this core implements capability c at its diff --git a/internal/edge/admission/admission_test.go b/internal/edge/admission/admission_test.go index f7cd33a3f..00c65c60e 100644 --- a/internal/edge/admission/admission_test.go +++ b/internal/edge/admission/admission_test.go @@ -34,6 +34,7 @@ const ( routeExchange = "RouteExchange" prefixReachability = "PrefixReachability" + publicListener = "PublicListener" ) var ( @@ -193,6 +194,7 @@ func TestAdmitCapabilityVersions(t *testing.T) { {Name: socketAccess, Version: "v1"}, {Name: packetAccess, Version: "v1"}, {Name: prefixReachability, Version: "v1"}, + {Name: publicListener, Version: "v1"}, } providers := registry() p := providers[connectIP] @@ -226,6 +228,7 @@ func TestCoreImplements(t *testing.T) { {Capability{Name: socketAccess, Version: "v1"}, true}, {Capability{Name: packetAccess, Version: "v1"}, true}, {Capability{Name: prefixReachability, Version: "v1"}, true}, + {Capability{Name: publicListener, Version: "v1"}, true}, {Capability{Name: prefixReachability, Version: "v9"}, false}, {Capability{Name: routeExchange, Version: "v1"}, false}, } { diff --git a/internal/edge/attachment/listener_policy_envtest_test.go b/internal/edge/attachment/listener_policy_envtest_test.go new file mode 100644 index 000000000..aaa710e77 --- /dev/null +++ b/internal/edge/attachment/listener_policy_envtest_test.go @@ -0,0 +1,134 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package attachment + +import ( + "context" + "fmt" + "strings" + "testing" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + utilruntime "k8s.io/apimachinery/pkg/util/runtime" + + networkv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" + galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" +) + +const ( + gatewayNS = "galactic-system" + listenerName = "public" + listenerAddress = "2001:db8:100::10" +) + +func listenerObject(namespace, name string) *galacticv1alpha1.EdgeListener { + return &galacticv1alpha1.EdgeListener{ + ObjectMeta: metav1.ObjectMeta{Namespace: namespace, Name: name}, + Spec: galacticv1alpha1.EdgeListenerSpec{ + ProviderRef: galacticv1alpha1.EdgeProviderReference{Name: providerSA}, + ServiceRef: galacticv1alpha1.EdgeListenerServiceReference{Namespace: gatewayNS, Name: "listener-grant"}, + Addresses: []string{listenerAddress}, + Ports: []galacticv1alpha1.EdgeListenerPort{ + {Protocol: galacticv1alpha1.EdgeListenerProtocolTCP, Port: 443, BackendPort: 8443}, + }, + }, + } +} + +// gatewayService is a NetworkService in namespace that takes its backends +// from the listener named listener, or from a selector when listener is +// empty. +func gatewayService(namespace, name, listener string) *networkv1alpha1.NetworkService { + svc := &networkv1alpha1.NetworkService{ + ObjectMeta: metav1.ObjectMeta{Namespace: namespace, Name: name}, + Spec: networkv1alpha1.NetworkServiceSpec{ + VPCRef: "listener-vpc", + VIPAddresses: []string{listenerAddress}, + Protocol: networkv1alpha1.NetworkServiceProtocolTCP, + Port: 443, + BackendPort: 8443, + }, + } + if listener != "" { + svc.Spec.EdgeListenerRef = &networkv1alpha1.NetworkServiceEdgeListenerReference{Name: listener} + } else { + svc.Spec.BackendSelector = metav1.LabelSelector{MatchLabels: map[string]string{"app": "selected"}} + } + return svc +} + +// refused fails unless err is an admission refusal mentioning want. +func refused(t *testing.T, what string, err error, want string) { + t.Helper() + if err == nil || !strings.Contains(err.Error(), want) { + t.Errorf("%s: err = %v, want a refusal mentioning %q", what, err, want) + } +} + +// TestListenerPolicies checks that no provider ServiceAccount writes an +// EdgeListener or a NetworkService, while another ServiceAccount can, and +// that listeners and services naming one stay in the gateway namespace. +func TestListenerPolicies(t *testing.T) { + f := startAPI(t) + utilruntime.Must(networkv1alpha1.AddToScheme(f.scheme)) + ctx := context.Background() + provider := f.as("system:serviceaccount:"+providerNS+":"+providerSA, nil) + authority := f.as("system:serviceaccount:platform:authority", nil) + const ( + listenerWrite = "cannot write edgelisteners" + serviceWrite = "cannot write networkservices" + ) + + // The binding is enforced a moment after it is created. + n := 0 + eventually(t, "provider listener policy enforced", func() bool { + n++ + obj := listenerObject(gatewayNS, fmt.Sprintf("probe-%d", n)) + if err := provider.Create(ctx, obj); err != nil { + return true + } + _ = f.admin.Delete(ctx, obj) + return false + }) + + refused(t, "provider creates an EdgeListener", provider.Create(ctx, listenerObject(gatewayNS, "by-provider")), + "a ServiceAccount of provider "+providerSA+" "+listenerWrite) + refused(t, "provider creates a NetworkService", provider.Create(ctx, gatewayService(providerNS, "by-provider", "")), + serviceWrite) + refused(t, "provider creates a listener NetworkService", + provider.Create(ctx, gatewayService(gatewayNS, "by-provider-listener", listenerName)), serviceWrite) + + listener := listenerObject(gatewayNS, listenerName) + if err := authority.Create(ctx, listener); err != nil { + t.Fatalf("authority creates an EdgeListener: %v", err) + } + svc := gatewayService(gatewayNS, "public-443", listenerName) + if err := authority.Create(ctx, svc); err != nil { + t.Fatalf("a non-provider ServiceAccount creates a listener NetworkService: %v", err) + } + + // A provider can change neither the listener, nor its status, nor the + // service, nor delete them. + changed := listener.DeepCopy() + changed.Spec.Addresses = []string{"2001:db8:100::11"} + refused(t, "provider updates its EdgeListener", provider.Update(ctx, changed), listenerWrite) + status := listener.DeepCopy() + status.Status.Backends = []galacticv1alpha1.EdgeListenerBackend{{Attachment: "edge/ea-1", Serving: true}} + refused(t, "provider writes its EdgeListener's status", provider.Status().Update(ctx, status), + "cannot write edgelisteners/status") + refused(t, "provider deletes its EdgeListener", provider.Delete(ctx, listener), listenerWrite) + refused(t, "provider deletes the listener's NetworkService", provider.Delete(ctx, svc), serviceWrite) + + // Outside the gateway namespace, a listener and a service naming one are + // refused for every writer; a selector service is not. + refused(t, "EdgeListener in a project namespace", authority.Create(ctx, listenerObject(tenantNS, listenerName)), + "an EdgeListener lives only in the gateway namespace") + refused(t, "listener NetworkService in a project namespace", + authority.Create(ctx, gatewayService(tenantNS, "tenant-listener", listenerName)), + "edgeListenerRef is allowed only in the gateway namespace") + if err := authority.Create(ctx, gatewayService(tenantNS, "tenant-selector", "")); err != nil { + t.Errorf("selector NetworkService in a project namespace: %v", err) + } +}