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
109 changes: 97 additions & 12 deletions cmd/fabric-api/gateway.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package main
import (
"context"
"crypto/x509"
"errors"
"fmt"
"log/slog"
"net"
Expand All @@ -15,6 +16,7 @@ import (

"github.com/go-logr/logr"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"google.golang.org/grpc"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/labels"
Expand Down Expand Up @@ -53,7 +55,9 @@ type gatewayOptions struct {
maxInFlight int
retention, cleanupGrace time.Duration
serviceIdentities []string
serviceConfigMap string
aggregateBudgets bool
limits limit.Limits
}

func newGatewayCommand() *cobra.Command {
Expand All @@ -62,6 +66,11 @@ func newGatewayCommand() *cobra.Command {
Use: "gateway",
Short: "Execute this cell's FabricQuery objects and serve the operator debug service",
RunE: func(cmd *cobra.Command, _ []string) error {
limits, err := gatewayLimits(cmd.Flags(), o)
if err != nil {
return err
}
o.limits = limits
return runGateway(cmd.Context(), o)
},
}
Expand Down Expand Up @@ -99,13 +108,86 @@ func newGatewayCommand() *cobra.Command {
f.StringSliceVar(&o.serviceIdentities, "service-identities", nil,
"Names of the Looking Glass service identities (spiffe://fabric-api.datumapis.com/cell/<cell>/service/<name>) "+
"allowed to call this cell's gateway; empty allows none")
f.StringVar(&o.serviceConfigMap, "service-config-map", "",
"ConfigMap in --namespace whose key \"service\" turns Looking Glass execution on (\"enabled\") or off "+
"(\"disabled\") while the gateway runs, read every second; empty, missing, unreadable or any other "+
"value keeps it off. Execution also needs --aggregate-budgets")
f.BoolVar(&o.aggregateBudgets, "aggregate-budgets", false,
"Enforce the cell's aggregate admission and probe packet budgets on every caller, issue probe permits to "+
"nodes, and bound each principal's share of --cell-slots and --cell-queue to the contract defaults; "+
"every node must run with --probe-permits first")
"nodes, and bound each principal's share of --cell-slots and --cell-queue; every node must run with "+
"--probe-permits first")
registerLimitFlags(f, &o.limits)
return cmd
}

// limitFlags are the aggregate limits an operator may lower, each
// defaulting to the contract's qualified value, which is also its ceiling.
var limitFlags = []string{
"request-cell-rate", "request-cell-burst", "request-project-rate", "request-project-burst",
"packet-cell-rate", "packet-cell-burst", "packet-principal-rate", "packet-principal-burst",
"packet-host-rate", "packet-host-burst", "packet-prefix-rate", "packet-prefix-burst",
"principal-slots", "principal-queue", "service-streams", "project-streams", "queue-wait",
}

func registerLimitFlags(f *pflag.FlagSet, l *limit.Limits) {
*l = limit.Defaults()
rate := func(name, what string, r *limit.Rate) {
f.Float64Var(&r.PerSecond, name+"-rate", r.PerSecond, what+" tokens per second; may only be lowered")
f.Float64Var(&r.Burst, name+"-burst", r.Burst, what+" bucket size; may only be lowered")
}
rate("request-cell", "Looking Glass requests admitted in the cell:", &l.RequestCell)
rate("request-project", "Looking Glass requests admitted per project:", &l.RequestProject)
rate("packet-cell", "Worst-case probe packets charged in the cell:", &l.PacketCell)
rate("packet-principal", "Worst-case probe packets charged per project, FabricQuery source or operator:",
&l.PacketPrincipal)
rate("packet-host", "Worst-case probe packets charged per destination address:", &l.PacketHost)
rate("packet-prefix", "Worst-case probe packets charged per destination IPv4 /24 or IPv6 /64:", &l.PacketPrefix)
f.IntVar(&l.PrincipalSlots, "principal-slots", l.PrincipalSlots,
"Of --cell-slots, node jobs one principal may run at once; may only be lowered")
f.IntVar(&l.PrincipalQueue, "principal-queue", l.PrincipalQueue,
"Of --cell-queue, node jobs one principal may queue; may only be lowered")
f.IntVar(&l.Streams, "service-streams", l.Streams,
"Live Looking Glass streams in the cell, queued and draining ones included; may only be lowered")
f.IntVar(&l.ProjectStreams, "project-streams", l.ProjectStreams,
"Live Looking Glass streams per project; may only be lowered")
f.DurationVar(&l.QueueWait, "queue-wait", l.QueueWait,
"How long a Looking Glass router job or a direct operator's permit may wait for a slot; may only be lowered")
}

// gatewayLimits returns the aggregate limits the flags select, refusing
// limit flags or --service-config-map without --aggregate-budgets, a limit
// above its qualified ceiling and limits that break a cross-field rule. A
// principal's slots, queue and streams default to at most the cell's.
func gatewayLimits(f *pflag.FlagSet, o *gatewayOptions) (limit.Limits, error) {
if !o.aggregateBudgets {
if o.serviceConfigMap != "" {
return limit.Limits{}, errors.New("--service-config-map needs --aggregate-budgets: the service " +
"executes only under the cell's aggregate budgets")
}
for _, name := range limitFlags {
if f.Changed(name) {
return limit.Limits{}, fmt.Errorf("--%s needs --aggregate-budgets", name)
}
}
return limit.Limits{}, nil
}
l := o.limits
l.Slots, l.Queue = o.slots, o.queue
if !f.Changed("principal-slots") {
l.PrincipalSlots = min(l.PrincipalSlots, o.slots)
}
if !f.Changed("principal-queue") {
l.PrincipalQueue = min(l.PrincipalQueue, o.queue)
}
if !f.Changed("project-streams") {
l.ProjectStreams = min(l.ProjectStreams, l.Streams)
}
if err := errors.Join(l.Qualified(), l.Validate()); err != nil {
return limit.Limits{}, fmt.Errorf("--aggregate-budgets: %w", err)
}
return l, nil
}

func runGateway(parent context.Context, o *gatewayOptions) error {
required := map[string]string{
"site": o.site,
Expand Down Expand Up @@ -180,23 +262,23 @@ func runGateway(parent context.Context, o *gatewayOptions) error {
}

executor := gateway.NewExecutor(o.slots, o.expensiveSlots, o.queue)
metrics := gateway.NewMetrics(ctrlmetrics.Registry, func() float64 { return float64(executor.Depth()) })
var admission *gateway.Admission
if o.aggregateBudgets {
limits := limit.Defaults()
limits.Slots, limits.Queue = o.slots, o.queue
// A smaller cell lowers each principal's share with it.
limits.PrincipalSlots = min(limits.PrincipalSlots, o.slots)
limits.PrincipalQueue = min(limits.PrincipalQueue, o.queue)
admission, err = gateway.NewAdmission(limits, &limit.Authority{
admission, err = gateway.NewAdmission(o.limits, &limit.Authority{
Reader: mgr.GetAPIReader(), Namespace: o.namespace, Name: o.leaseName, Identity: holder,
Clock: limit.KernelClock,
})
if err != nil {
return fmt.Errorf("--aggregate-budgets: %w", err)
}
executor.PrincipalSlots, executor.PrincipalQueue = limits.PrincipalSlots, limits.PrincipalQueue
executor.PrincipalSlots, executor.PrincipalQueue = o.limits.PrincipalSlots, o.limits.PrincipalQueue
go admission.Authority.Watch(ctx, limit.WatchInterval)
}
metrics := gateway.NewMetrics(ctrlmetrics.Registry, func() float64 { return float64(executor.Depth()) })
serviceSwitch := &gateway.ServiceSwitch{}
if o.serviceConfigMap != "" {
go serviceSwitch.Watch(ctx, mgr.GetAPIReader(), o.namespace, o.serviceConfigMap, gateway.ServiceSwitchInterval)
}
executor.ObserveWait = func(d time.Duration) { metrics.QueueWait(d.Seconds()) }
creds := o.tls.credentials(identity.Gateway(o.cell))
creds.OnLoad(func(leaf *x509.Certificate) { metrics.CertificateExpiry(float64(leaf.NotAfter.Unix())) })
Expand Down Expand Up @@ -231,7 +313,8 @@ func runGateway(parent context.Context, o *gatewayOptions) error {
discoverer := &gateway.Discoverer{
Reader: mgr.GetClient(), Namespace: o.namespace, Selector: sel, CertsSelector: certsSel,
}
runner := &gateway.Runner{Clients: pool, Executor: executor, Metrics: metrics, Admission: admission}
runner := &gateway.Runner{Clients: pool, Executor: executor, Metrics: metrics, Admission: admission,
QueueWait: o.limits.QueueWait}
rec := &gateway.Reconciler{
Client: mgr.GetClient(),
APIReader: mgr.GetAPIReader(),
Expand Down Expand Up @@ -271,10 +354,12 @@ func runGateway(parent context.Context, o *gatewayOptions) error {
Cell: o.cell,
DialOptions: []grpc.DialOption{clientStats()},
}
// Enabled is deliberately unset: the service authenticates, validates
// The service executes only while serviceSwitch is on and admission
// enforces the aggregate budgets; otherwise it authenticates, validates
// and reports capabilities, and refuses execution with ServiceDisabled.
service := &gateway.Service{
Cell: o.cell,
Switch: serviceSwitch,
Allowlist: allowlist,
Elected: debug.Elected,
Leader: debug,
Expand Down
102 changes: 102 additions & 0 deletions cmd/fabric-api/gateway_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// Copyright 2026 Datum Cloud, Inc.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

package main

import (
"strings"
"testing"
"time"

"github.com/spf13/pflag"

"go.datum.net/galactic/internal/fabric/gateway/limit"
)

// budgets is the flag every valid limit needs; qualified is in the error of
// a limit raised above its ceiling.
const (
budgets = "--aggregate-budgets"
qualified = "qualified"
)

// parseLimits parses args as the gateway's limit flags, with the cell slot,
// queue, budget and service switch flags they depend on.
func parseLimits(t *testing.T, args ...string) (limit.Limits, error) {
t.Helper()
o := &gatewayOptions{}
f := pflag.NewFlagSet("gateway", pflag.ContinueOnError)
f.IntVar(&o.slots, "cell-slots", 8, "")
f.IntVar(&o.queue, "cell-queue", 256, "")
f.BoolVar(&o.aggregateBudgets, "aggregate-budgets", false, "")
f.StringVar(&o.serviceConfigMap, "service-config-map", "", "")
registerLimitFlags(f, &o.limits)
if err := f.Parse(args); err != nil {
t.Fatal(err)
}
for _, name := range limitFlags {
if f.Lookup(name) == nil {
t.Fatalf("limit flag --%s is not registered", name)
}
}
return gatewayLimits(f, o)
}

func TestGatewayLimits(t *testing.T) {
l, err := parseLimits(t, budgets)
if err != nil {
t.Fatal(err)
}
if l != limit.Defaults() {
t.Errorf("default limits = %+v, want the contract's", l)
}

l, err = parseLimits(t, budgets, "--packet-host-rate=10", "--packet-host-burst=320",
"--principal-slots=1", "--project-streams=1", "--queue-wait=5s", "--request-cell-burst=4")
if err != nil {
t.Fatal(err)
}
if l.PacketHost != (limit.Rate{PerSecond: 10, Burst: 320}) || l.PrincipalSlots != 1 || l.ProjectStreams != 1 ||
l.QueueWait != 5*time.Second || l.RequestCell.Burst != 4 {
t.Errorf("lowered limits = %+v", l)
}

// A smaller cell lowers each principal's default share with it.
l, err = parseLimits(t, budgets, "--cell-slots=1", "--cell-queue=8", "--service-streams=1")
if err != nil {
t.Fatal(err)
}
if l.Slots != 1 || l.PrincipalSlots != 1 || l.Queue != 8 || l.PrincipalQueue != 8 || l.ProjectStreams != 1 {
t.Errorf("small cell limits = %+v", l)
}
}

func TestGatewayLimitsRefused(t *testing.T) {
cases := map[string]struct {
args []string
want string
}{
"limit without budgets": {[]string{"--packet-cell-rate=50"}, "needs --aggregate-budgets"},
"service without budgets": {[]string{"--service-config-map=fabric-api-service"}, "needs --aggregate-budgets"},
"raised rate": {[]string{budgets, "--packet-host-rate=21"}, qualified},
"raised burst": {[]string{budgets, "--request-project-burst=3"}, qualified},
"raised principal slots": {[]string{budgets, "--principal-slots=3"}, qualified},
"raised project streams": {[]string{budgets, "--project-streams=3"}, qualified},
"principal above cell": {
[]string{budgets, "--cell-slots=1", "--principal-slots=2"}, "principal slots",
},
"burst too long": {[]string{budgets, "--packet-host-rate=1"}, "burst/rate"},
"short burst": {[]string{budgets, "--packet-prefix-burst=19"}, "cannot fund"},
"zero rate": {[]string{budgets, "--request-cell-rate=0"}, "positive"},
"queue wait raised": {[]string{budgets, "--queue-wait=11s"}, "queue wait"},
}
for name, tc := range cases {
t.Run(name, func(t *testing.T) {
_, err := parseLimits(t, tc.args...)
if err == nil || !strings.Contains(err.Error(), tc.want) {
t.Fatalf("err = %v, want one mentioning %q", err, tc.want)
}
})
}
}
6 changes: 4 additions & 2 deletions cmd/fabric-api/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (
permitv1 "go.datum.net/galactic/api/fabric/permit/v1"
fabricv1 "go.datum.net/galactic/api/fabric/v1"
"go.datum.net/galactic/internal/fabric/frr"
"go.datum.net/galactic/internal/fabric/gateway/limit"
"go.datum.net/galactic/internal/fabric/identity"
"go.datum.net/galactic/internal/fabric/index"
"go.datum.net/galactic/internal/fabric/node"
Expand Down Expand Up @@ -273,7 +274,8 @@ func runNode(parent context.Context, o *nodeOptions) error {
}

// nodePermits returns the probe permit checker the flags select, or nil
// without --probe-permits.
// without --probe-permits. Its permits are refused while the kernel clock
// is unsynchronised.
func nodePermits(o *nodeOptions, creds *identity.Credentials) (*node.Permits, error) {
switch {
case !o.probePermits && (o.requirePermits || o.gatewayAddress != ""):
Expand All @@ -293,7 +295,7 @@ func nodePermits(o *nodeOptions, creds *identity.Credentials) (*node.Permits, er
}
p := &node.Permits{
Reader: reader, Namespace: o.namespace, LeaseName: o.gatewayLease, Require: o.requirePermits,
Started: time.Now(),
Started: time.Now(), Clock: limit.KernelClock,
}
if o.gatewayAddress != "" {
conn, err := grpc.NewClient(o.gatewayAddress,
Expand Down
28 changes: 28 additions & 0 deletions internal/fabric/gateway/admission.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@ import (

"google.golang.org/protobuf/types/known/timestamppb"

servicev1 "go.datum.net/galactic/api/fabric/service/v1"
fabricv1 "go.datum.net/galactic/api/fabric/v1"
"go.datum.net/galactic/internal/fabric/errcode"
"go.datum.net/galactic/internal/fabric/gateway/limit"
"go.datum.net/galactic/internal/fabric/identity"
"go.datum.net/galactic/internal/fabric/node"
"go.datum.net/galactic/internal/fabric/query"
)
Expand Down Expand Up @@ -93,6 +95,32 @@ func (a *Admission) openStream(project string) (func(), error) {
}, nil
}

// admit admits a service request before its discovery: it confirms the
// election, charges the cell's and the project's request tokens, registers
// the attempt key and opens a live stream. It returns the epoch's context
// and the function that ends the stream.
func (a *Admission) admit(
ctx context.Context, caller identity.ID, req *servicev1.RunDiagnosticRequest,
) (context.Context, func(), error) {
project := req.GetProjectId()
_, epochCtx, err := a.Authority.Check(ctx)
if err != nil {
return nil, nil, err
}
if err := a.Buckets.ChargeRequest(project, a.now()); err != nil {
return nil, nil, err
}
if err := a.Attempts.Register(attemptKey(caller, req), requestDigest(req), req.GetExpiresAt().AsTime(),
a.now()); err != nil {
return nil, nil, err
}
closeStream, err := a.openStream(project)
if err != nil {
return nil, nil, err
}
return epochCtx, closeStream, nil
}

// probeCost is a probe's worst-case packet count.
func probeCost(t query.Type) int {
if t == query.TypeTraceroute {
Expand Down
Loading
Loading