Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
173 changes: 173 additions & 0 deletions api/network/v1alpha1/serviceendpoint_spread_envtest_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
// Copyright 2026 Datum Cloud, Inc.
// SPDX-License-Identifier: AGPL-3.0-or-later

package v1alpha1_test

import (
"context"
"encoding/json"
"os"
"path/filepath"
"testing"

corev1 "k8s.io/api/core/v1"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/envtest"
"sigs.k8s.io/yaml"

networkv1alpha1 "go.datum.net/galactic/api/network/v1alpha1"
)

func TestServiceEndpointSpreadAdmission(t *testing.T) {
if os.Getenv("KUBEBUILDER_ASSETS") == "" {
t.Skip("set KUBEBUILDER_ASSETS for isolated API admission tests")
}
apiRoot := os.Getenv("GALACTIC_TEST_NETWORK_API")
if apiRoot == "" {
apiRoot = "../../.."
}
data, err := os.ReadFile(filepath.Join(apiRoot, "config", "crd", "galactic.datumapis.com_serviceendpoints.yaml"))
if err != nil {
t.Fatal(err)
}
crd := &apiextensionsv1.CustomResourceDefinition{}
if err := yaml.Unmarshal(data, crd); err != nil {
t.Fatal(err)
}
environment := &envtest.Environment{CRDs: []*apiextensionsv1.CustomResourceDefinition{crd}}
cfg, err := environment.Start()
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := environment.Stop(); err != nil {
t.Errorf("stop API: %v", err)
}
})
scheme := runtime.NewScheme()
_ = corev1.AddToScheme(scheme)
_ = networkv1alpha1.AddToScheme(scheme)
c, err := client.New(cfg, client.Options{Scheme: scheme})
if err != nil {
t.Fatal(err)
}
ctx := context.Background()
const namespace = "spread-admission"
if err := c.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace}}); err != nil {
t.Fatal(err)
}
endpoint := func(name string) *networkv1alpha1.ServiceEndpoint {
return &networkv1alpha1.ServiceEndpoint{
ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace},
Spec: networkv1alpha1.ServiceEndpointSpec{
ServiceClass: "dns", Address: "fd53::53", Port: 53,
Protocol: networkv1alpha1.NetworkServiceProtocolUDP,
DeliveryMode: networkv1alpha1.ServiceEndpointDeliveryModeNodeLocal,
AttachmentSelector: &metav1.LabelSelector{MatchLabels: map[string]string{"role": "dns"}},
Distribution: networkv1alpha1.ServiceEndpointDistributionSpread,
HealthCheck: &networkv1alpha1.ServiceEndpointHealthCheck{Port: 8053},
},
}
}
for _, tt := range []struct {
name string
mutate func(*networkv1alpha1.ServiceEndpoint)
wantError bool
}{
{"spread", func(*networkv1alpha1.ServiceEndpoint) {}, false},
{"single-default", func(e *networkv1alpha1.ServiceEndpoint) {
e.Spec.Distribution, e.Spec.HealthCheck = "", nil
}, false},
{"single", func(e *networkv1alpha1.ServiceEndpoint) {
e.Spec.Distribution, e.Spec.HealthCheck = networkv1alpha1.ServiceEndpointDistributionSingle, nil
}, false},
{"spread-without-health-check", func(e *networkv1alpha1.ServiceEndpoint) { e.Spec.HealthCheck = nil }, true},
{"single-with-health-check", func(e *networkv1alpha1.ServiceEndpoint) {
e.Spec.Distribution = networkv1alpha1.ServiceEndpointDistributionSingle
}, true},
{"udp-without-health-check-port", func(e *networkv1alpha1.ServiceEndpoint) {
e.Spec.HealthCheck.Port = 0
}, true},
{"tcp-without-health-check-port", func(e *networkv1alpha1.ServiceEndpoint) {
e.Spec.Protocol = networkv1alpha1.NetworkServiceProtocolTCP
e.Spec.HealthCheck.Port = 0
}, false},
{"unknown-distribution", func(e *networkv1alpha1.ServiceEndpoint) { e.Spec.Distribution = "RoundRobin" }, true},
} {
t.Run(tt.name, func(t *testing.T) {
e := endpoint(tt.name)
tt.mutate(e)
err := c.Create(ctx, e)
if (err != nil) != tt.wantError {
t.Fatalf("create error=%v", err)
}
if tt.wantError && !apierrors.IsInvalid(err) {
t.Fatalf("expected schema rejection, got %v", err)
}
})
}

// Each node applies only its own producers' entries; one node's apply
// neither replaces nor removes another node's.
shared := endpoint("shared")
if err := c.Create(ctx, shared); err != nil {
t.Fatal(err)
}
entry := func(name, node string) networkv1alpha1.ServiceEndpointProducerStatus {
return networkv1alpha1.ServiceEndpointProducerStatus{
Namespace: namespace, Name: name, AttachmentUID: types.UID(name + "-uid"), Node: node, Port: 8053,
State: networkv1alpha1.BackendHealthHealthy, Reason: "ProbeSucceeded",
LastTransitionTime: metav1.Now(),
}
}
apply := func(node string, entries ...networkv1alpha1.ServiceEndpointProducerStatus) {
t.Helper()
if entries == nil {
entries = []networkv1alpha1.ServiceEndpointProducerStatus{}
}
body, err := json.Marshal(map[string]any{
"apiVersion": networkv1alpha1.GroupVersion.String(), "kind": "ServiceEndpoint",
"metadata": map[string]string{"name": shared.Name, "namespace": namespace},
"status": map[string]any{"producers": entries},
})
if err != nil {
t.Fatal(err)
}
obj := &networkv1alpha1.ServiceEndpoint{}
obj.Name, obj.Namespace = shared.Name, namespace
if err := c.Status().Patch(ctx, obj, client.RawPatch(types.ApplyPatchType, body),
client.FieldOwner("galactic-router/"+node), client.ForceOwnership); err != nil {
t.Fatal(err)
}
}
names := func() []string {
t.Helper()
got := &networkv1alpha1.ServiceEndpoint{}
if err := c.Get(ctx, client.ObjectKeyFromObject(shared), got); err != nil {
t.Fatal(err)
}
out := make([]string, 0, len(got.Status.Producers))
for _, p := range got.Status.Producers {
out = append(out, p.Name+"@"+p.Node)
}
return out
}
apply("node-a", entry("a1", "node-a"), entry("a2", "node-a"))
apply("node-b", entry("b1", "node-b"))
if got := names(); len(got) != 3 {
t.Fatalf("producers after both nodes applied = %v, want a1, a2 and b1", got)
}
apply("node-a", entry("a2", "node-a"))
if got := names(); len(got) != 2 || got[0] != "a2@node-a" || got[1] != "b1@node-b" {
t.Fatalf("producers after node-a dropped a1 = %v, want a2@node-a and b1@node-b", got)
}
apply("node-b")
if got := names(); len(got) != 1 || got[0] != "a2@node-a" {
t.Fatalf("producers after node-b dropped its entries = %v, want a2@node-a", got)
}
}
173 changes: 170 additions & 3 deletions api/network/v1alpha1/serviceroute_types.go
Original file line number Diff line number Diff line change
@@ -1,25 +1,35 @@
package v1alpha1

import metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
)

// ServiceEndpoint publishes a platform service that can be reached through a
// VPC attachment. The object describes the service contract; the controller
// that owns the service is responsible for its health and implementation.
//
// +kubebuilder:object:root=true
// +kubebuilder:subresource:status
// +kubebuilder:resource:scope=Namespaced,shortName=svcendpoint
// +kubebuilder:printcolumn:name="ADDRESS",type="string",JSONPath=".spec.address"
// +kubebuilder:printcolumn:name="PORT",type="integer",JSONPath=".spec.port"
// +kubebuilder:printcolumn:name="DISTRIBUTION",type="string",JSONPath=".spec.distribution"
// +kubebuilder:printcolumn:name="AGE",type="date",JSONPath=".metadata.creationTimestamp"
type ServiceEndpoint struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`

Spec ServiceEndpointSpec `json:"spec,omitempty"`

// +optional
Status ServiceEndpointStatus `json:"status,omitempty"`
}

// ServiceEndpointSpec defines a platform service address and its scope.
// +kubebuilder:validation:XValidation:rule="has(self.attachmentRef) != has(self.attachmentSelector)",message="exactly one of attachmentRef or attachmentSelector must be set"
// +kubebuilder:validation:XValidation:rule="(has(self.distribution) && self.distribution == 'Spread') == has(self.healthCheck)",message="healthCheck must be set when distribution is Spread, and only then"
// +kubebuilder:validation:XValidation:rule="!has(self.healthCheck) || has(self.healthCheck.port) || self.protocol == 'tcp'",message="a udp endpoint's healthCheck must set port"
type ServiceEndpointSpec struct {
// ServiceClass identifies the platform capability implemented by this
// endpoint, for example "ipv6-egress-dns".
Expand Down Expand Up @@ -62,15 +72,172 @@ type ServiceEndpointSpec struct {

// AttachmentSelector selects the Cloud API VPCAttachments that host replicas
// of this endpoint. Labels used here must be assigned by the platform service
// controller, not by tenants. The dataplane selects one ready replica for
// each consumer according to DeliveryMode.
// controller, not by tenants. The dataplane selects ready replicas for each
// consumer according to DeliveryMode and Distribution.
// +optional
AttachmentSelector *metav1.LabelSelector `json:"attachmentSelector,omitempty"`

// Region limits endpoint selection to a region. An empty value means the
// endpoint is not region-scoped.
// +optional
Region string `json:"region,omitempty"`

// Distribution says how a consumer's traffic reaches the producers on
// its own node. Single, the default, allows one ready producer per node
// and VPC and sends every consumer on that node to it; an endpoint that
// selects more is refused. Spread sends new flows to any producer on the
// consumer's node that its health check has not found Unhealthy: each
// TCP connection stays with the producer that received its first packet,
// and each UDP datagram picks a producer of its own, which suits
// request/response protocols such as DNS but not ones that need a UDP
// flow to stay on one producer. An Unhealthy producer keeps its existing
// TCP connections and replies, and gets new flows again once it is
// Healthy. When every producer on a node is Unhealthy, all of them stay
// eligible. A node may hold at most 16 producers of a Spread endpoint.
// +optional
// +kubebuilder:validation:Enum=Single;Spread
Distribution ServiceEndpointDistribution `json:"distribution,omitempty"`

// HealthCheck configures the TCP health check of a Spread endpoint's
// producers. Each producer's own node probes it and publishes the
// decision in status.producers. Required when Distribution is Spread and
// refused otherwise.
//
// Where interface traffic policy is enforced, the producer's policy must
// allow TCP from fe80::/10 to the health check port on the Private path,
// and the replies back.
// +optional
HealthCheck *ServiceEndpointHealthCheck `json:"healthCheck,omitempty"`
}

// ServiceEndpointDistribution selects how traffic spreads across the
// producers on one node.
type ServiceEndpointDistribution string

const (
// ServiceEndpointDistributionSingle sends every consumer on a node to the
// one ready producer there.
ServiceEndpointDistributionSingle ServiceEndpointDistribution = "Single"

// ServiceEndpointDistributionSpread spreads flows across the healthy
// producers on the consumer's node.
ServiceEndpointDistributionSpread ServiceEndpointDistribution = "Spread"
)

// ServiceEndpointMaxProducersPerNode is the most producers of one Spread
// endpoint that a node can hold.
const ServiceEndpointMaxProducersPerNode = 16

// ServiceEndpointHealthCheck configures the TCP health check of an endpoint's
// producers. A probe opens a TCP connection to the producer attachment's first
// IPv6 address, not the endpoint's address, on Port, through the producer's
// host-side interface and from that interface's link-local address. A producer
// with no IPv6 address is never probed and stays Unknown. A probe succeeds when the handshake completes within
// TimeoutSeconds, and fails when the connection is refused, reset or times
// out. A producer's decision changes after UnhealthyThreshold consecutive
// failures or HealthyThreshold consecutive successes. A crashed producer
// therefore stops receiving new flows within IntervalSeconds ×
// UnhealthyThreshold, plus TimeoutSeconds.
//
// +kubebuilder:validation:XValidation:rule="self.timeoutSeconds <= self.intervalSeconds",message="timeoutSeconds must not exceed intervalSeconds"
type ServiceEndpointHealthCheck struct {
// Port is the TCP port probed on every producer, 1-65535. Unset, it is
// the endpoint's port, which must then be a tcp port. A udp endpoint must
// set it to a TCP port its producers listen on.
// +optional
// +kubebuilder:validation:Minimum=1
// +kubebuilder:validation:Maximum=65535
Port int32 `json:"port,omitempty"`

// IntervalSeconds is the time between two probes of one producer.
// +optional
// +kubebuilder:default=5
// +kubebuilder:validation:Minimum=1
// +kubebuilder:validation:Maximum=300
IntervalSeconds int32 `json:"intervalSeconds,omitempty"`

// TimeoutSeconds is how long a probe waits for the handshake. It must not
// exceed IntervalSeconds.
// +optional
// +kubebuilder:default=2
// +kubebuilder:validation:Minimum=1
// +kubebuilder:validation:Maximum=60
TimeoutSeconds int32 `json:"timeoutSeconds,omitempty"`

// UnhealthyThreshold is the number of consecutive failed probes that
// make a producer Unhealthy.
// +optional
// +kubebuilder:default=3
// +kubebuilder:validation:Minimum=1
// +kubebuilder:validation:Maximum=10
UnhealthyThreshold int32 `json:"unhealthyThreshold,omitempty"`

// HealthyThreshold is the number of consecutive successful probes that
// make a producer Healthy.
// +optional
// +kubebuilder:default=3
// +kubebuilder:validation:Minimum=1
// +kubebuilder:validation:Maximum=10
HealthyThreshold int32 `json:"healthyThreshold,omitempty"`
}

// ServiceEndpointStatus reports what the nodes observe of an endpoint.
type ServiceEndpointStatus struct {
// Producers holds the health decision of every producer of a Spread
// endpoint. Each node writes the entries of the producers on that node,
// under its own field manager, and removes them when the producer stops
// being selected. An entry whose attachmentUID no longer matches the
// attachment of that name describes an earlier attachment and is ignored.
// +optional
// +listType=map
// +listMapKey=namespace
// +listMapKey=name
// +kubebuilder:validation:MaxItems=4096
Producers []ServiceEndpointProducerStatus `json:"producers,omitempty"`
}

// ServiceEndpointProducerStatus is one producer's health decision.
type ServiceEndpointProducerStatus struct {
// Namespace is the producer VPCAttachment's namespace.
// +kubebuilder:validation:MinLength=1
Namespace string `json:"namespace"`

// Name is the producer VPCAttachment's name.
// +kubebuilder:validation:MinLength=1
Name string `json:"name"`

// AttachmentUID is the UID of the VPCAttachment that was probed.
// +kubebuilder:validation:Required
AttachmentUID types.UID `json:"attachmentUID"`

// Node is the node that hosts the producer and probes it.
// +kubebuilder:validation:MinLength=1
Node string `json:"node"`

// Port is the TCP port that was probed.
// +kubebuilder:validation:Minimum=1
// +kubebuilder:validation:Maximum=65535
Port int32 `json:"port"`

// State is the decision. Healthy and Unknown producers receive new
// flows; Unhealthy ones do not, unless every producer on the node is
// Unhealthy.
// +kubebuilder:validation:Required
State BackendHealthState `json:"state"`

// Reason is ProbeSucceeded, ProbeFailed, Pending or ProbeUnavailable.
// +kubebuilder:validation:Required
// +kubebuilder:validation:MaxLength=64
Reason string `json:"reason"`

// Message is the last probe error, when there is one.
// +optional
// +kubebuilder:validation:MaxLength=1024
Message string `json:"message,omitempty"`

// LastTransitionTime is when State last changed.
// +kubebuilder:validation:Required
LastTransitionTime metav1.Time `json:"lastTransitionTime"`
}

// ServiceEndpointDeliveryMode defines the placement contract for a service.
Expand Down
Loading
Loading