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
15 changes: 12 additions & 3 deletions cmd/galactic-router/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ func runCmd(cfg *config.RouterConfig) error {
// serviceRouteControllerEnabled).
if serviceRouteControllerEnabled(cfg) {
if err := setupServiceRouteController(mgr, nodeName, cfg.GCNamespace, cfg.ServiceFrontendEnabled,
serviceRouteMetrics); err != nil {
cfg.ServiceSpreadPairing, serviceRouteMetrics); err != nil {
return fmt.Errorf("setup ServiceRoutePolicy controller: %w", err)
}
} else {
Expand Down Expand Up @@ -475,9 +475,13 @@ func serviceRouteControllerEnabled(cfg *config.RouterConfig) bool {

func setupServiceRouteController(
mgr ctrl.Manager,
nodeName, bgpNamespace string, frontendEnabled bool,
nodeName, bgpNamespace string, frontendEnabled bool, spreadPairingName string,
serviceRouteMetrics *serviceroute.Metrics,
) error {
spreadPairing, err := serviceroute.ParseSpreadPairing(spreadPairingName)
if err != nil {
return err
}
programmer := &serviceroute.EBPFRouteProgrammer{}
if err := programmer.Initialize(); err != nil {
ctrl.Log.Error(err, "service route eBPF maps are not available yet; initialization will retry on reconcile")
Expand All @@ -491,7 +495,8 @@ func setupServiceRouteController(
Programmer: programmer,
Metrics: serviceRouteMetrics,
FrontendEnabled: frontendEnabled,
Applied: make(map[types.NamespacedName]map[types.NamespacedName]serviceroute.RouteIntent),
SpreadPairing: spreadPairing,
Applied: make(map[types.NamespacedName]map[serviceroute.IntentSlot]serviceroute.RouteIntent),
}).SetupWithManager(mgr); err != nil {
return err
}
Expand Down Expand Up @@ -556,6 +561,10 @@ func newRootCommand() *cobra.Command {
"Cleanup interval")
cmd.Flags().Bool("service-frontend-enabled", false,
"Enable consumer-facing private-service address translation")
cmd.Flags().String("service-spread-pairing", config.DefaultRouterServiceSpreadPairing,
"Remote producer for this node's consumers of a Spread endpoint whose node has no producer: "+
"first (first producer by name) or rendezvous (spread across producers); set rendezvous only "+
"once every node runs a router that has this flag")
cmd.Flags().Bool("traffic-policy", false,
"Enforce TrafficPolicy on this node's tenant interfaces; needs the galactic.datumapis.com CRDs")
cmd.Flags().String("bmp-stations", "",
Expand Down
49 changes: 32 additions & 17 deletions docs/private-services/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,9 @@ How flows are spread:

- A TCP connection goes to the producer that received its first packet and
stays there while that producer is in the node's set, even after its health
check fails. A new connection goes to a producer chosen by its flow hash.
check fails. A new connection goes to the eligible producer that rendezvous
hashing of its flow ranks first, so a producer joining or leaving moves only
the connections it gains or loses.
- Each UDP datagram picks a producer at random, so the requests of one socket
spread too. This suits request/response protocols such as DNS. It does not
suit a protocol that needs a UDP flow to stay on one producer, such as QUIC;
Expand Down Expand Up @@ -132,26 +134,39 @@ longest request, then stop it. Its in-flight requests and open connections
finish while new ones go to the other producers.

When the consumer's node has no producer, `PreferNodeLocal` sends the consumer
to one remote producer, through the SRv6 service tunnel as with `Single`. It is
the first producer by namespace and name whose node currently reports it
`Healthy` or `Unknown`, or has no entry for it. If there is none, it is the
first producer whose entry expired, and failing that the first producer. So
when a node goes down while its producers' attachments still read ready,
consumers on other nodes move off those producers within 60 seconds of the
node's last renewal, as long as another node currently reports a producer that
can take them. A remote consumer does not spread. While a health change reaches the
to one remote producer, through the SRv6 service tunnel as with `Single`. It
is picked among the producers whose node currently reports them `Healthy` or
`Unknown`, or has no entry for them. If there are none, it is picked among the
producers whose entry expired, and failing that among all producers. The
consumer's node picks by its `galactic-router` setting
[`--service-spread-pairing`](../router/configuration.md#--service-spread-pairing--galactic_router_service_spread_pairing).
With `first`, the default, it picks the first producer by namespace and name,
so every remote consumer goes to the same producer. With `rendezvous`,
rendezvous hashing of the consumer's and each producer's attachment UID picks
it, so consumers spread across the remote producers, and a producer joining,
leaving or turning `Unhealthy` moves only the consumers it gains or loses. A
producer's node installs the producer half for the producer each pairing
picks, whatever its own setting, so the consumer's traffic is accepted while
its node and the producer's node use different settings. Set `rendezvous` only
after every node runs a router that has the option, since an older router
accepts only the `first` pairing. When a node
goes down while its producers' attachments still read ready, its consumers move
to other producers within 60 seconds of the node's last renewal, as long as
another node currently reports a producer that can take them. Each consumer's
requests all go to its one remote producer. While a health change reaches the
consumer's node and the producer's node at different moments, the two can
briefly disagree on that producer, and its requests are refused until they
agree.

A TCP connection keeps its producer only while its pin lasts. A pin ends after
300 seconds without traffic, the same idle limit replies already have, or when
the node evicts it under load or reloads the datapath. A packet of an
established connection with no pin goes to the producer its hash picks among
the current eligible ones, so if that set changed since the connection opened,
the connection resets. Changing an endpoint between `Single` and `Spread`
replaces its routes, which can drop a request in flight and moves existing TCP
connections.
A TCP connection's pin ends after 300 seconds without traffic, the same idle
limit replies have, or when the node evicts it under load or reloads the
datapath. A packet of an established connection with no pin stays with the
producer whose reply row, which the node keeps for four times as many flows,
shows it already carries the connection. Only a connection with neither is
placed by its hash again: it stays with its producer unless a producer that
joined since ranks first for it. Changing an endpoint between `Single` and
`Spread` replaces its routes, which can drop a request in flight and moves
existing TCP connections.

Apply the `ServiceEndpointProducerReport` CRD and the `galactic-router`
RBAC for it before upgrading `galactic-router` to a version that writes
Expand Down
13 changes: 13 additions & 0 deletions docs/router/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ Logging takes `--log-level` (`LOG_LEVEL`), without the `GALACTIC_ROUTER` prefix
| GoBGP API directory | `GALACTIC_ROUTER_GOBGP_API_DIR` | `--gobgp-api-dir` | _(empty; no API)_ |
| Traffic policy | `GALACTIC_ROUTER_TRAFFIC_POLICY` | `--traffic-policy` | `false` |
| Service frontends | `GALACTIC_ROUTER_SERVICE_FRONTEND_ENABLED` | `--service-frontend-enabled` | `false` |
| Spread remote pairing | `GALACTIC_ROUTER_SERVICE_SPREAD_PAIRING` | `--service-spread-pairing` | `first` |

## Required Options

Expand Down Expand Up @@ -263,6 +264,18 @@ CNI datapaths support the frontend maps. The publishing controller supplies
the producer address and `ServiceRoutePolicy.spec.frontend.address` supplies
the consumer address; ports are not translated. See [private service frontends](../private-services/README.md#consumer-service-frontends) for lifecycle, rollout and compatibility requirements.

### `--service-spread-pairing` / `GALACTIC_ROUTER_SERVICE_SPREAD_PAIRING`

Chooses the remote producer that this node's consumers of a `Spread`
`PreferNodeLocal` endpoint are sent to when their node has no producer. With
`first`, the default, every such consumer goes to the first eligible producer
by namespace and name. With `rendezvous`, the consumers spread across the
eligible producers. A producer's node accepts a consumer under either pairing,
whatever its own setting, so nodes with different settings interoperate. Set
`rendezvous` only after every node runs a router that has this option: an
older router accepts only the `first` pairing and refuses the others. See
[several producers on one node](../private-services/README.md#several-producers-on-one-node).

## Configuration Precedence

Values are resolved in the following order (highest to lowest priority):
Expand Down
26 changes: 26 additions & 0 deletions internal/config/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"net"
"slices"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -44,6 +45,18 @@ const (
// RouterBMPPolicies lists the accepted GALACTIC_ROUTER_BMP_POLICY values.
var RouterBMPPolicies = []string{"pre-policy", "post-policy", "local-rib", "all"}

// DefaultRouterServiceSpreadPairing sends the consumers of a Spread endpoint
// whose node has no producer to the first producer by name. Every node accepts
// consumers under both pairings, so the pairing can change node by node once
// every node runs a router that does.
const DefaultRouterServiceSpreadPairing = "first"

// RouterServiceSpreadPairings lists the accepted
// GALACTIC_ROUTER_SERVICE_SPREAD_PAIRING values: "first" sends every such
// consumer to the first producer by name, and "rendezvous" spreads them across
// the producers.
var RouterServiceSpreadPairings = []string{DefaultRouterServiceSpreadPairing, "rendezvous"}

// --- Router environment variable keys --------------------------------------

const (
Expand All @@ -56,6 +69,10 @@ const (
EnvRouterGCNamespace = "GALACTIC_ROUTER_GC_NAMESPACE"
EnvRouterGCInterval = "GALACTIC_ROUTER_GC_INTERVAL"
EnvRouterServiceFrontendEnabled = "GALACTIC_ROUTER_SERVICE_FRONTEND_ENABLED"
// EnvRouterServiceSpreadPairing chooses the remote producer this node's
// consumers of a Spread ServiceEndpoint are sent to; see
// RouterServiceSpreadPairings.
EnvRouterServiceSpreadPairing = "GALACTIC_ROUTER_SERVICE_SPREAD_PAIRING"
// EnvRouterTrafficPolicy runs the node's traffic policy reconciler. Off by
// default, because it watches the galactic.datumapis.com CRDs, which a
// cluster may not have installed.
Expand Down Expand Up @@ -98,6 +115,8 @@ type RouterConfig struct {
GCNamespace string
GCInterval time.Duration
ServiceFrontendEnabled bool
// ServiceSpreadPairing is one of RouterServiceSpreadPairings.
ServiceSpreadPairing string
// TrafficPolicy runs the node's traffic policy reconciler. It needs the
// galactic.datumapis.com CRDs, and a route reflector cannot run it.
TrafficPolicy bool
Expand Down Expand Up @@ -130,6 +149,7 @@ func NewRouterConfig() *RouterConfig {
v.SetDefault("gc_namespace", DefaultRouterGCNamespace)
v.SetDefault("gc_interval", DefaultRouterGCInterval.String())
v.SetDefault("service_frontend_enabled", false)
v.SetDefault("service_spread_pairing", DefaultRouterServiceSpreadPairing)
v.SetDefault("traffic_policy", false)
v.SetDefault("bmp_stations", "")
v.SetDefault("bmp_policy", DefaultRouterBMPPolicy)
Expand Down Expand Up @@ -160,6 +180,7 @@ func (c *RouterConfig) BindFlags(flags *pflag.FlagSet) {
{"gc-namespace", "gc_namespace"},
{"gc-interval", "gc_interval"},
{"service-frontend-enabled", "service_frontend_enabled"},
{"service-spread-pairing", "service_spread_pairing"},
{"traffic-policy", "traffic_policy"},
{"bmp-stations", "bmp_stations"},
{"bmp-policy", "bmp_policy"},
Expand Down Expand Up @@ -188,6 +209,7 @@ func (c *RouterConfig) readFields() {
c.GCNamespace = c.v.GetString("gc_namespace")
c.GCInterval = c.v.GetDuration("gc_interval")
c.ServiceFrontendEnabled = c.v.GetBool("service_frontend_enabled")
c.ServiceSpreadPairing = c.v.GetString("service_spread_pairing")
c.TrafficPolicy = c.v.GetBool("traffic_policy")
c.BMPStations = splitCommaList(c.v.GetString("bmp_stations"))
c.BMPPolicy = c.v.GetString("bmp_policy")
Expand All @@ -210,6 +232,10 @@ func (c *RouterConfig) Validate() error {
if c.GRPCHealthPort < 1 || c.GRPCHealthPort > 65535 {
return errors.New("grpc health port must be between 1 and 65535")
}
if !slices.Contains(RouterServiceSpreadPairings, c.ServiceSpreadPairing) {
return fmt.Errorf("%s must be one of %s, got %q", EnvRouterServiceSpreadPairing,
strings.Join(RouterServiceSpreadPairings, ", "), c.ServiceSpreadPairing)
}
if c.TrafficPolicy && c.Reflector {
return fmt.Errorf("%s needs a node with tenant interfaces, so a route reflector cannot enable it",
EnvRouterTrafficPolicy)
Expand Down
19 changes: 19 additions & 0 deletions internal/config/router_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -316,3 +316,22 @@ func TestRouterConfigTrafficPolicy(t *testing.T) {
t.Fatal("a route reflector accepted traffic policy")
}
}

func TestRouterConfigServiceSpreadPairing(t *testing.T) {
t.Setenv(EnvRouterNodeName, "node-a")
if got := NewRouterConfig().ServiceSpreadPairing; got != DefaultRouterServiceSpreadPairing {
t.Fatalf("default Spread pairing = %q, want %q", got, DefaultRouterServiceSpreadPairing)
}
t.Setenv(EnvRouterServiceSpreadPairing, "rendezvous")
cfg := NewRouterConfig()
if cfg.ServiceSpreadPairing != "rendezvous" {
t.Fatalf("Spread pairing = %q, want rendezvous", cfg.ServiceSpreadPairing)
}
if err := cfg.Validate(); err != nil {
t.Fatalf("Validate() = %v", err)
}
cfg.ServiceSpreadPairing = "hash"
if err := cfg.Validate(); err == nil {
t.Fatal("an unknown Spread pairing was accepted")
}
}
2 changes: 1 addition & 1 deletion internal/controller/serviceroute_access.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func (r *ServiceRoutePolicyReconciler) conflictingPolicies(
key := types.NamespacedName{Namespace: p.Namespace, Name: p.Name}
translated[key] = p.Spec.Frontend != nil
for node := range nodes {
intents, err := serviceroute.CompileForConsumerVPC(p, endpoint, attachments, node,
intents, err := r.compile(p, endpoint, attachments, node,
func(*cloudv1alpha1.VPCAttachment) (net.IP, error) { return net.ParseIP("fd00::1"), nil }, identity)
if err == nil {
desired[key] = append(desired[key], intents...)
Expand Down
47 changes: 30 additions & 17 deletions internal/controller/serviceroute_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,27 @@ type ServiceRoutePolicyReconciler struct {
Programmer serviceroute.RouteProgrammer
Metrics *serviceroute.Metrics
FrontendEnabled bool
Now func() time.Time
// SpreadPairing chooses the remote producer this node's consumers of a
// Spread endpoint are sent to. Empty is serviceroute.SpreadPairingFirst.
// Producer halves are installed under every pairing regardless.
SpreadPairing serviceroute.SpreadPairing
Now func() time.Time

// startupRetryWait waits between startup sync attempts and reports false
// once ctx is done. Tests replace it; nil waits on a real timer.
startupRetryWait func(ctx context.Context, d time.Duration) bool

mu sync.Mutex
Applied map[types.NamespacedName]map[types.NamespacedName]serviceroute.RouteIntent
Applied map[types.NamespacedName]map[serviceroute.IntentSlot]serviceroute.RouteIntent
}

// compile compiles policy for node with this router's options.
func (r *ServiceRoutePolicyReconciler) compile(policy *networkv1alpha1.ServiceRoutePolicy,
endpoint *networkv1alpha1.ServiceEndpoint, attachments []*cloudv1alpha1.VPCAttachment, node string,
resolveSID serviceroute.SIDResolver, vpcIdentity string,
) ([]serviceroute.RouteIntent, error) {
return serviceroute.CompileWithOptions(policy, endpoint, attachments, node, resolveSID,
serviceroute.CompileOptions{ConsumerVPCIdentity: vpcIdentity, SpreadPairing: r.SpreadPairing})
}

const serviceRouteMapResyncInterval = 30 * time.Second
Expand Down Expand Up @@ -211,7 +224,7 @@ func (r *ServiceRoutePolicyReconciler) Reconcile(ctx context.Context, req ctrl.R
"multiple policies claim a translated consumer tuple"))
return ctrl.Result{RequeueAfter: serviceRouteMapResyncInterval}, errors.Join(errs...)
}
intents, err := serviceroute.CompileForConsumerVPC(policy, endpoint, all, r.NodeName, r.sidResolver(ctx), vpcIdentity)
intents, err := r.compile(policy, endpoint, all, r.NodeName, r.sidResolver(ctx), vpcIdentity)
if err != nil {
var dependencyErr *serviceroute.DependencyNotReadyError
if errors.As(err, &dependencyErr) {
Expand Down Expand Up @@ -455,7 +468,7 @@ func (r *ServiceRoutePolicyReconciler) syncAllPolicies(ctx context.Context) erro
compiled = append(compiled, compiledPolicy{key: key})
continue
}
intents, err := serviceroute.CompileForConsumerVPC(
intents, err := r.compile(
policy, endpoint, allAttachments, r.NodeName, r.sidResolver(ctx), vpcIdentity)
if err != nil {
// Invalid policies and node-local dependencies that are not ready
Expand Down Expand Up @@ -695,24 +708,24 @@ func (r *ServiceRoutePolicyReconciler) replacePolicyLocked(
) error {
defer r.updateProgrammedGauge()
if r.Applied == nil {
r.Applied = make(map[types.NamespacedName]map[types.NamespacedName]serviceroute.RouteIntent)
r.Applied = make(map[types.NamespacedName]map[serviceroute.IntentSlot]serviceroute.RouteIntent)
}
current := r.Applied[key]
if current == nil {
current = make(map[types.NamespacedName]serviceroute.RouteIntent)
current = make(map[serviceroute.IntentSlot]serviceroute.RouteIntent)
r.Applied[key] = current
}
desired := make(map[types.NamespacedName]serviceroute.RouteIntent, len(intents))
desired := make(map[serviceroute.IntentSlot]serviceroute.RouteIntent, len(intents))
for _, intent := range intents {
desired[intent.Attachment] = intent
desired[intent.Slot()] = intent
}

// A LocalSet intent whose producers or their health changed is replaced
// in place: the new one goes in before the old one comes out, so the
// consumer's route never disappears and the flows of producers that stay
// keep going.
for attachment, existing := range current {
next, ok := desired[attachment]
for slot, existing := range current {
next, ok := desired[slot]
if !ok || existing.Kind != serviceroute.RouteIntentLocalSet || next.Kind != serviceroute.RouteIntentLocalSet ||
reflect.DeepEqual(existing, next) {
continue
Expand All @@ -734,14 +747,14 @@ func (r *ServiceRoutePolicyReconciler) replacePolicyLocked(
return errors.Join(&serviceRoutePolicyCleanupError{err: err}, r.Programmer.Remove(next))
}
r.Metrics.ObserveOperation("remove", nil)
current[attachment] = next
current[slot] = next
}

// Revoke obsolete or changed intents first. Each successful operation is
// reflected in Applied immediately, so a later failure leaves an accurate,
// retryable snapshot rather than leaking untracked kernel state.
for attachment, existing := range current {
next, ok := desired[attachment]
for slot, existing := range current {
next, ok := desired[slot]
if ok && reflect.DeepEqual(existing, next) {
continue
}
Expand All @@ -750,10 +763,10 @@ func (r *ServiceRoutePolicyReconciler) replacePolicyLocked(
return &serviceRoutePolicyCleanupError{err: err}
}
r.Metrics.ObserveOperation("remove", nil)
delete(current, attachment)
delete(current, slot)
}
for attachment, intent := range desired {
if existing, ok := current[attachment]; ok && reflect.DeepEqual(existing, intent) {
for slot, intent := range desired {
if existing, ok := current[slot]; ok && reflect.DeepEqual(existing, intent) {
continue
}
if err := r.Programmer.Apply(intent); err != nil {
Expand All @@ -764,7 +777,7 @@ func (r *ServiceRoutePolicyReconciler) replacePolicyLocked(
return err
}
r.Metrics.ObserveOperation("apply", nil)
current[attachment] = intent
current[slot] = intent
}
if len(current) == 0 {
delete(r.Applied, key)
Expand Down
Loading
Loading