Skip to content
Closed
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
21 changes: 21 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,27 @@ jobs:
hack/service-api-bundle.sh ci dist
cd dist && sha256sum -c SHA256SUMS

# The opt-in Kustomize Components that must be listed in order fail their
# build when one is missing; tests/manifests renders each composition.
manifests:
name: Manifests
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v7

- uses: actions/setup-go@v7
with:
go-version: ${{ env.GO_VERSION }}

- uses: arduino/setup-task@v3.0.0
with:
version: ${{ env.TASK_VERSION }}
repo-token: ${{ secrets.GITHUB_TOKEN }}

- name: Render the Component fixtures
run: task test:manifests

# Tier 2: Integration tests (every PR, main branch, and releases)
test-e2e:
name: E2E Tests
Expand Down
4 changes: 2 additions & 2 deletions AGENTS.md

Large diffs are not rendered by default.

34 changes: 34 additions & 0 deletions Taskfile.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@ vars:
[ -n "$gobin" ] && echo "$gobin" || echo "$(go env GOPATH)/bin"
GOLANGCI_LINT: '{{.LOCALBIN}}/golangci-lint'
YAMLFMT: '{{.LOCALBIN}}/yamlfmt'
KUSTOMIZE: '{{.LOCALBIN}}/kustomize'
GO_LICENSES: '{{.LOCALBIN}}/go-licenses'
GOLANGCI_LINT_VERSION: v2.12.2
YAMLFMT_VERSION: v0.21.0
KUSTOMIZE_VERSION: v5.8.1
GO_LICENSES_VERSION: v1.6.0
PROMETHEUS_VERSION: v3.15.0

Expand Down Expand Up @@ -229,6 +231,28 @@ tasks:
- CGO_ENABLED=0 GOBIN={{.GOBGP_BIN}} go install github.com/osrg/gobgp/v4/cmd/gobgpd@v4.10.0 github.com/osrg/gobgp/v4/cmd/gobgp@v4.10.0
- go run ./hack/fabric-api-loadtest --mrt {{.MRT}} --gobgp-bin {{.GOBGP_BIN}} {{.CLI_ARGS}}

test:manifests:
desc: Render the opt-in Component fixtures in tests/manifests
# Every fixture under tests/manifests/fabric-api composes Components the
# way a cell overlay does and must build; every fixture under
# tests/manifests/invalid omits a Component another requires and must
# fail to build.
deps: [kustomize]
cmds:
- |
status=0
for dir in tests/manifests/fabric-api/*/; do
if ! {{.KUSTOMIZE}} build "$dir" > /dev/null; then
echo "FAIL: $dir does not build"; status=1
fi
done
for dir in tests/manifests/invalid/*/; do
if {{.KUSTOMIZE}} build "$dir" > /dev/null 2>&1; then
echo "FAIL: $dir builds, but omits a required Component"; status=1
fi
done
exit $status

test:alerts:
desc: Unit-test the alert rules in config/monitoring/ with promtool
# promtool reads plain rule files, so the PrometheusRule's spec is
Expand Down Expand Up @@ -285,6 +309,16 @@ tasks:
PACKAGE: github.com/golangci/golangci-lint/v2/cmd/golangci-lint
VERSION: '{{.GOLANGCI_LINT_VERSION}}'

kustomize:
desc: Download kustomize if needed
run: once
cmds:
- task: install-tool
vars:
TARGET: '{{.KUSTOMIZE}}'
PACKAGE: sigs.k8s.io/kustomize/kustomize/v5
VERSION: '{{.KUSTOMIZE_VERSION}}'

yamlfmt:
desc: Download yamlfmt if needed
run: once
Expand Down
113 changes: 101 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,26 @@ 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
admission.Metrics = metrics
metrics.RegisterAdmission(admission, limit.KernelClock)
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{}
metrics.RegisterService(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 +316,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 +357,13 @@ 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,
Metrics: metrics,
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)
}
})
}
}
Loading
Loading