diff --git a/cmd/fabric-api/gateway.go b/cmd/fabric-api/gateway.go index 139b7ceeb..827f3119d 100644 --- a/cmd/fabric-api/gateway.go +++ b/cmd/fabric-api/gateway.go @@ -7,6 +7,7 @@ package main import ( "context" "crypto/x509" + "errors" "fmt" "log/slog" "net" @@ -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" @@ -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 { @@ -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) }, } @@ -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//service/) "+ "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, @@ -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())) }) @@ -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(), @@ -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, diff --git a/cmd/fabric-api/gateway_test.go b/cmd/fabric-api/gateway_test.go new file mode 100644 index 000000000..ed687daa9 --- /dev/null +++ b/cmd/fabric-api/gateway_test.go @@ -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) + } + }) + } +} diff --git a/cmd/fabric-api/node.go b/cmd/fabric-api/node.go index 6150e9cff..9b3effa78 100644 --- a/cmd/fabric-api/node.go +++ b/cmd/fabric-api/node.go @@ -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" @@ -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 != ""): @@ -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, diff --git a/internal/fabric/gateway/admission.go b/internal/fabric/gateway/admission.go index 71a9f985f..6a2e39b8e 100644 --- a/internal/fabric/gateway/admission.go +++ b/internal/fabric/gateway/admission.go @@ -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" ) @@ -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 { diff --git a/internal/fabric/gateway/limit/authority.go b/internal/fabric/gateway/limit/authority.go index 6526e7d99..30d92ee1a 100644 --- a/internal/fabric/gateway/limit/authority.go +++ b/internal/fabric/gateway/limit/authority.go @@ -25,6 +25,14 @@ const ( RecoveryHold = 125 * time.Second // LeaseReadTimeout bounds each uncached election Lease read. LeaseReadTimeout = time.Second + // MaxClockError bounds the kernel's estimate of its clock's error: two + // clocks within it of true time are within the contract's 1 s of each + // other. + MaxClockError = 500 * time.Millisecond + // ClockGrace is how long the clock may stay unhealthy before the + // authority ends its epoch. Shorter runs refuse new work only, so one + // bad sample does not cost the cell a recovery hold. + ClockGrace = 3 * time.Second ) // Epoch identifies one term of the election: the Lease object's UID and @@ -67,7 +75,10 @@ func ReadEpoch(ctx context.Context, r client.Reader, namespace, name string, now // remaining delay; the first valid read after the hold empties the buckets // and admits from that instant. A failed read, another holder or an expired // term refuses with OwnershipLost and cancels the context of the epoch's -// work. +// work. While Clock reports unhealthy, Check refuses with +// LimiterUnavailable; once it has for ClockGrace, the epoch ends like on a +// failed read, so its work is cancelled and admission resumes only after a +// new hold. type Authority struct { // Reader must read uncached. Reader client.Reader @@ -77,6 +88,9 @@ type Authority struct { Identity string // Buckets are emptied when a hold ends. Buckets *Buckets + // Clock, when set, reports an error while this host's clock cannot be + // trusted within MaxClockError; KernelClock is the production check. + Clock func() error // Hold overrides RecoveryHold; tests only. Hold time.Duration // Now returns the current time; nil selects time.Now. @@ -88,6 +102,9 @@ type Authority struct { until time.Time epochCtx context.Context cancel context.CancelFunc + // clockBadSince is when Clock first reported unhealthy in its current + // run of failures; zero while it is healthy. + clockBadSince time.Time } func (a *Authority) now() time.Time { @@ -114,12 +131,24 @@ func (a *Authority) Check(ctx context.Context) (Epoch, context.Context, error) { if err == nil && epoch.Holder != a.Identity { err = errcode.Status(errcode.OwnershipLost, "this gateway does not hold the election lease") } + clockBad := err == nil && a.Clock != nil && a.Clock() != nil a.mu.Lock() defer a.mu.Unlock() if err != nil { a.loseLocked() return Epoch{}, nil, err } + if clockBad { + if a.clockBadSince.IsZero() { + a.clockBadSince = now + } + if now.Sub(a.clockBadSince) >= ClockGrace { + a.loseLocked() + } + return Epoch{}, nil, errcode.Retry(errcode.LimiterUnavailable, "this gateway's clock is not synchronised", + string(ScopeCell), time.Second) + } + a.clockBadSince = time.Time{} if epoch != a.epoch || a.epochCtx == nil { a.loseLocked() a.epoch, a.until = epoch, now.Add(a.hold()) @@ -136,6 +165,31 @@ func (a *Authority) Check(ctx context.Context) (Epoch, context.Context, error) { return a.epoch, a.epochCtx, nil } +// Authority states, as State reports them. +const ( + StateReady = "ready" + StateRecovering = "recovering" + StateUnavailable = "unavailable" +) + +// State reports StateReady while the authority admits work, +// StateRecovering during a recovery hold, and StateUnavailable while this +// process does not hold the election, could not confirm it at its last +// check, or is refusing work for an unhealthy clock. +func (a *Authority) State() string { + a.mu.Lock() + defer a.mu.Unlock() + switch { + case !a.clockBadSince.IsZero(): + return StateUnavailable + case a.active: + return StateReady + case a.epochCtx != nil: + return StateRecovering + } + return StateUnavailable +} + // WatchInterval is how often Watch confirms ownership. const WatchInterval = time.Second diff --git a/internal/fabric/gateway/limit/clock_linux.go b/internal/fabric/gateway/limit/clock_linux.go new file mode 100644 index 000000000..183689b5a --- /dev/null +++ b/internal/fabric/gateway/limit/clock_linux.go @@ -0,0 +1,38 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package limit + +import ( + "errors" + "fmt" + "time" + + "golang.org/x/sys/unix" +) + +// KernelClock reports an error unless the kernel considers its clock +// synchronised, with an estimated error of at most MaxClockError. It reads +// the clock discipline with adjtimex without changing it, which needs no +// capability and which the default containerd and Docker seccomp profiles +// allow: a host whose time daemon (chrony, ntpd, systemd-timesyncd, Talos +// timed) disciplines the kernel clock passes, and one with no daemon +// reports TIME_ERROR. The kernel's maximum error is not used: it grows by +// 500 µs every second between the daemon's updates, which chrony spaces up +// to about 17 minutes apart, so it exceeds the bound on a healthy host; the +// kernel reports TIME_ERROR itself once it reaches 16 s. +func KernelClock() error { + var tx unix.Timex + state, err := unix.Adjtimex(&tx) + if err != nil { + return fmt.Errorf("read the clock discipline: %w", err) + } + if state == unix.TIME_ERROR { + return errors.New("the kernel clock is not synchronised") + } + if estErr := time.Duration(tx.Esterror) * time.Microsecond; estErr > MaxClockError { + return fmt.Errorf("the kernel clock's estimated error %s exceeds %s", estErr, MaxClockError) + } + return nil +} diff --git a/internal/fabric/gateway/limit/clock_other.go b/internal/fabric/gateway/limit/clock_other.go new file mode 100644 index 000000000..749627337 --- /dev/null +++ b/internal/fabric/gateway/limit/clock_other.go @@ -0,0 +1,13 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +//go:build !linux + +package limit + +import "errors" + +// KernelClock reports every clock unhealthy: only Linux exposes the clock +// discipline it reads. +func KernelClock() error { return errors.New("clock health is unknown on this platform") } diff --git a/internal/fabric/gateway/limit/limit_test.go b/internal/fabric/gateway/limit/limit_test.go index ff3701fce..fb0ced4f5 100644 --- a/internal/fabric/gateway/limit/limit_test.go +++ b/internal/fabric/gateway/limit/limit_test.go @@ -48,6 +48,38 @@ func TestDefaultsValidate(t *testing.T) { } } +func TestQualified(t *testing.T) { + if err := Defaults().Qualified(); err != nil { + t.Fatalf("defaults above their own ceilings: %v", err) + } + lower := Defaults() + lower.PacketHost = Rate{PerSecond: 10, Burst: 320} + lower.PrincipalSlots, lower.ProjectStreams = 1, 1 + if err := lower.Qualified(); err != nil { + t.Errorf("lowered limits refused: %v", err) + } + cases := map[string]func(*Limits){ + "request cell rate": func(l *Limits) { l.RequestCell.PerSecond = 3 }, + "request project": func(l *Limits) { l.RequestProject.Burst = 3 }, + "packet cell burst": func(l *Limits) { l.PacketCell.Burst = 641 }, + "packet principal": func(l *Limits) { l.PacketPrincipal.PerSecond = 21 }, + "packet host": func(l *Limits) { l.PacketHost.PerSecond = 21 }, + "packet prefix": func(l *Limits) { l.PacketPrefix.Burst = 700 }, + "principal slots": func(l *Limits) { l.PrincipalSlots = 3 }, + "principal queue": func(l *Limits) { l.PrincipalQueue = 33 }, + "project streams": func(l *Limits) { l.ProjectStreams = 3 }, + } + for name, mod := range cases { + t.Run(name, func(t *testing.T) { + l := Defaults() + mod(&l) + if err := l.Qualified(); err == nil { + t.Fatal("limit above its qualified ceiling accepted") + } + }) + } +} + func TestValidateRejects(t *testing.T) { cases := map[string]func(*Limits){ "zero rate": func(l *Limits) { l.PacketCell.PerSecond = 0 }, @@ -437,3 +469,72 @@ func TestAuthorityIgnoresCallerCancellation(t *testing.T) { t.Fatalf("authority left its active state: %v", err) } } + +// An unhealthy clock refuses new work at once; once it stays unhealthy for +// ClockGrace it is uncertainty like a failed Lease read: the epoch's work is +// cancelled and admission resumes only after a new hold. +func TestAuthorityClockHealth(t *testing.T) { + clk := &clock{now: t0} + lc := newLease(t, holderA, t0) + var clockErr error + a := &Authority{Reader: lc, Namespace: leaseNS, Name: leaseName, Identity: holderA, + Buckets: NewBuckets(Defaults(), t0), Now: clk.Now, Hold: time.Second, + Clock: func() error { return clockErr }} + if s := a.State(); s != StateUnavailable { + t.Fatalf("state before any check = %s", s) + } + _, _, _ = a.Check(t.Context()) + if s := a.State(); s != StateRecovering { + t.Fatalf("state in hold = %s", s) + } + clk.now = t0.Add(time.Second) + lc.set(t, "u1", clk.now) + _, ctx, err := a.Check(t.Context()) + if err != nil { + t.Fatal(err) + } + if s := a.State(); s != StateReady { + t.Fatalf("state after hold = %s", s) + } + + // A short run of bad samples refuses, but keeps the epoch. + clockErr = errors.New("unsynchronised") + _, _, err = a.Check(t.Context()) + wantCode(t, err, errcode.LimiterUnavailable) + clk.now = clk.now.Add(ClockGrace - time.Millisecond) + _, _, err = a.Check(t.Context()) + wantCode(t, err, errcode.LimiterUnavailable) + if ctx.Err() != nil { + t.Fatal("a clock unhealthy for less than ClockGrace ended the epoch") + } + if s := a.State(); s != StateUnavailable { + t.Fatalf("state while refusing for the clock = %s", s) + } + clockErr = nil + if _, _, err := a.Check(t.Context()); err != nil { + t.Fatalf("recovered within grace: %v", err) + } + if s := a.State(); s != StateReady { + t.Fatalf("state after recovering within grace = %s", s) + } + + // A run as long as ClockGrace ends the epoch. + clockErr = errors.New("unsynchronised") + _, _, _ = a.Check(t.Context()) + clk.now = clk.now.Add(ClockGrace) + _, _, err = a.Check(t.Context()) + wantCode(t, err, errcode.LimiterUnavailable) + if ctx.Err() == nil { + t.Fatal("epoch context survived a clock unhealthy for ClockGrace") + } + if s := a.State(); s != StateUnavailable { + t.Fatalf("state with an unhealthy clock = %s", s) + } + + clockErr = nil + _, _, err = a.Check(t.Context()) + wantCode(t, err, errcode.LimiterUnavailable) + if d, _ := errcode.RetryDelay(err); d != time.Second { + t.Fatalf("hold after the clock recovered = %s", d) + } +} diff --git a/internal/fabric/gateway/limit/limits.go b/internal/fabric/gateway/limit/limits.go index 449cff6c5..1d02d1b5b 100644 --- a/internal/fabric/gateway/limit/limits.go +++ b/internal/fabric/gateway/limit/limits.go @@ -153,3 +153,33 @@ func (l Limits) Validate() error { } return errors.Join(errs...) } + +// Qualified refuses limits above the contract's qualified ceilings, its +// Defaults: a cell may lower a rate, burst or count, never raise one, until +// a contract revision qualifies the higher value. It complements Validate, +// which checks the cross-field rules every set of limits must meet. +func (l Limits) Qualified() error { + d := Defaults() + var errs []error + rate := func(name string, r, top Rate) { + if r.PerSecond > top.PerSecond || r.Burst > top.Burst { + errs = append(errs, fmt.Errorf("%s: rate %g burst %g exceeds the qualified rate %g burst %g", + name, r.PerSecond, r.Burst, top.PerSecond, top.Burst)) + } + } + rate("request cell", l.RequestCell, d.RequestCell) + rate("request project", l.RequestProject, d.RequestProject) + rate("packet cell", l.PacketCell, d.PacketCell) + rate("packet principal", l.PacketPrincipal, d.PacketPrincipal) + rate("packet host", l.PacketHost, d.PacketHost) + rate("packet prefix", l.PacketPrefix, d.PacketPrefix) + count := func(name string, v, top int) { + if v > top { + errs = append(errs, fmt.Errorf("%s: %d exceeds the qualified %d", name, v, top)) + } + } + count("principal slots", l.PrincipalSlots, d.PrincipalSlots) + count("principal queue", l.PrincipalQueue, d.PrincipalQueue) + count("project streams", l.ProjectStreams, d.ProjectStreams) + return errors.Join(errs...) +} diff --git a/internal/fabric/gateway/runner.go b/internal/fabric/gateway/runner.go index 621286e20..f1a6567fc 100644 --- a/internal/fabric/gateway/runner.go +++ b/internal/fabric/gateway/runner.go @@ -243,9 +243,9 @@ var errOwnershipLost = errors.New("the gateway lost execution ownership") var errOutputLimit = errors.New("the stream's output budget is exhausted") // requestErr reports a failure that ctx's end, or the request's expiration, -// caused as the request's own DeadlineExceeded, Cancelled or, when the -// election was lost or the output budget ran out, OwnershipLost or -// OutputLimitExceeded. +// caused as the request's own DeadlineExceeded, Cancelled (also when the +// service was turned off) or, when the election was lost or the output +// budget ran out, OwnershipLost or OutputLimitExceeded. func requestErr(ctx context.Context, err error, expired bool) error { if err == nil || (ctx.Err() == nil && !expired) { return err @@ -258,6 +258,9 @@ func requestErr(ctx context.Context, err error, expired bool) error { if errors.Is(context.Cause(ctx), errOwnershipLost) { return errcode.Status(errcode.OwnershipLost, "the gateway lost execution ownership before the router finished") } + if errors.Is(context.Cause(ctx), errServiceDisabled) { + return errcode.Status(errcode.Cancelled, "the service was disabled before the router finished") + } if errors.Is(context.Cause(ctx), errOutputLimit) { return errcode.Status(errcode.OutputLimitExceeded, "the stream's output budget ran out before the router finished") } diff --git a/internal/fabric/gateway/service.go b/internal/fabric/gateway/service.go index df7bbf392..916df2a12 100644 --- a/internal/fabric/gateway/service.go +++ b/internal/fabric/gateway/service.go @@ -78,7 +78,7 @@ const ( // probes are charged too. func (s *Service) features() []string { f := []string{FeatureRouterOutcomes, FeatureTerminalCoverage} - if s.Enabled && s.Admission != nil { + if s.enabled() { f = append(f, FeatureAggregateProbeBudgets) } return f @@ -218,15 +218,16 @@ type LeaderDialer interface { // Service implements the Looking Glass service. Any replica authenticates // and validates a request; a follower forwards it once to the leader, which -// validates it again before executing. Unless Enabled and given an +// validates it again before executing. Unless its Switch is on and it has an // Admission, the leader refuses a valid request with ServiceDisabled. type Service struct { servicev1.UnimplementedLookingGlassServiceServer // Cell is the cell this gateway serves. Cell string - // Enabled makes the leader execute valid requests. - Enabled bool + // Switch, while on, makes the leader execute valid requests; turning it + // off cancels those running. A nil Switch is off. + Switch *ServiceSwitch // Admission enforces the cell's aggregate admission and probe budgets. // It must be the Runner's; without it nothing executes. Admission *Admission @@ -257,6 +258,13 @@ func (s *Service) now() time.Time { return time.Now() } +// enabled reports whether the service executes requests: its Switch is on +// and it has an Admission. +func (s *Service) enabled() bool { + on, _ := s.Switch.State() + return on && s.Admission != nil +} + // GetCapabilities reports the cell's service policy. func (s *Service) GetCapabilities( ctx context.Context, req *servicev1.GetCapabilitiesRequest, @@ -282,7 +290,7 @@ func (s *Service) capabilities() *servicev1.GetCapabilitiesResponse { resp := &servicev1.GetCapabilitiesResponse{ Cell: s.Cell, ApiMajor: ServiceAPIMajor, - Enabled: s.Enabled && s.Admission != nil, + Enabled: s.enabled(), Operations: []*servicev1.Operation{ {Type: fabricv1.QueryType_QUERY_TYPE_ROUTE_LOOKUP, AddressFamilies: families}, {Type: fabricv1.QueryType_QUERY_TYPE_BGP_SUMMARY, AddressFamilies: families}, @@ -584,7 +592,8 @@ func (s *Service) forward( // write or a hand-off to the buffer blocked for SendBound, cancels every // router still running and ends the stream without complete; the deadline, // the loss of the election and the output budget cancel them too, but the -// stream still ends with complete. An outcome larger than +// stream still ends with complete, as it does when the Switch is turned off. +// An outcome larger than // maxOutcomeBytes is delivered as a ResponseTooLarge failure, and once the // stream's output budget cannot hold an outcome, that router and every // router still running fail with OutputLimitExceeded. A failure before the @@ -599,36 +608,28 @@ func (s *Service) execute( return errcode.Status(errcode.DeadlineExceeded, "request's deadline has passed") } adm := s.Admission - if !s.Enabled || adm == nil || s.Discoverer == nil || s.Runner == nil { + on, offCtx := s.Switch.State() + if !on || adm == nil || s.Discoverer == nil || s.Runner == nil { return errcode.Status(errcode.ServiceDisabled, "this cell does not execute Looking Glass service diagnostics") } project := req.GetProjectId() - _, epochCtx, err := adm.Authority.Check(ctx) - if err != nil { - return err - } - if err := adm.Buckets.ChargeRequest(project, adm.now()); err != nil { - return err - } - if err := adm.Attempts.Register(attemptKey(caller, req), requestDigest(req), req.GetExpiresAt().AsTime(), - adm.now()); err != nil { - return err - } - closeStream, err := adm.openStream(project) + epochCtx, closeStream, err := adm.admit(ctx, caller, req) if err != nil { return err } defer closeStream() // sendCtx ends when the stream does, a write fails or the consumer - // stalls; runCtx also ends at the deadline, when the election is lost or - // when the output budget runs out. Outcomes those cut short still reach - // the writer, so the consumer can see them while the stream lasts. + // stalls; runCtx also ends at the deadline, when the election is lost, + // when the service is turned off or when the output budget runs out. + // Outcomes those cut short still reach the writer, so the consumer can + // see them while the stream lasts. sendCtx, abort := context.WithCancelCause(ctx) defer abort(nil) ownedCtx, lose := context.WithCancelCause(sendCtx) defer lose(nil) defer context.AfterFunc(epochCtx, func() { lose(errOwnershipLost) })() + defer context.AfterFunc(offCtx, func() { lose(errServiceDisabled) })() runCtx, cancel := context.WithDeadline(ownedCtx, deadline) defer cancel() @@ -640,6 +641,8 @@ func (s *Service) execute( switch { case errors.Is(context.Cause(runCtx), errOwnershipLost): return errcode.Status(errcode.OwnershipLost, "the election was lost during router discovery") + case errors.Is(context.Cause(runCtx), errServiceDisabled): + return errcode.Status(errcode.ServiceDisabled, "the service was disabled during router discovery") case errors.Is(runCtx.Err(), context.DeadlineExceeded): return errcode.Status(errcode.DeadlineExceeded, "request's deadline passed during router discovery") case runCtx.Err() != nil: diff --git a/internal/fabric/gateway/service_execution_test.go b/internal/fabric/gateway/service_execution_test.go index 30429b702..45cf6727b 100644 --- a/internal/fabric/gateway/service_execution_test.go +++ b/internal/fabric/gateway/service_execution_test.go @@ -174,7 +174,7 @@ func newService(t *testing.T, objs []client.Object, nodes *routerNodes, slots in certs, _ := labels.Parse(DefaultCertsSelector) adm := newTestAdmission(t, roomyLimits()) return &Service{ - Cell: testSite, Allowlist: testAllowlist, Elected: elected, Enabled: true, Revision: "abc123", + Cell: testSite, Allowlist: testAllowlist, Elected: elected, Switch: switchedOn(), Revision: "abc123", Discoverer: &Discoverer{Reader: reader, Namespace: DefaultNamespace, Selector: sel, CertsSelector: certs}, Runner: &Runner{Clients: nodes, Executor: NewExecutor(slots, 0, 0), QueueWait: 200 * time.Millisecond, Admission: adm}, @@ -182,6 +182,13 @@ func newService(t *testing.T, objs []client.Object, nodes *routerNodes, slots in } } +// switchedOn returns a service switch that is on. +func switchedOn() *ServiceSwitch { + w := &ServiceSwitch{} + w.Set(true) + return w +} + // chanStream is a RunDiagnostic server stream that hands each event to a // channel, and fails a send once failAt events were sent, or every send // when failAt is negative. @@ -726,7 +733,7 @@ func TestServiceCapabilities(t *testing.T) { t.Errorf("features = %v", f) } again, _ := svc.GetCapabilities(ctx, req) - svc.Enabled = false + svc.Switch.Set(false) off, _ := svc.GetCapabilities(ctx, req) // With execution off nothing is advertised as enforced. if slices.Contains(off.GetFeatures(), FeatureAggregateProbeBudgets) || off.GetLimits().GetAdmission() != nil { @@ -738,7 +745,7 @@ func TestServiceCapabilities(t *testing.T) { // A request requiring an unserved feature, or a budget above its // maximum, is refused before any work. - svc.Enabled = true + svc.Switch.Set(true) for name, edit := range map[string]func(*runReq){ "unknown feature": func(r *runReq) { r.RequiredFeatures = []string{"router-outcomes-v2"} }, "large budget": func(r *runReq) { r.Budgets = &fabricv1.Budgets{MaxPathsPerPrefix: 9} }, diff --git a/internal/fabric/gateway/serviceswitch.go b/internal/fabric/gateway/serviceswitch.go new file mode 100644 index 000000000..af7817bcb --- /dev/null +++ b/internal/fabric/gateway/serviceswitch.go @@ -0,0 +1,130 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package gateway + +import ( + "context" + "errors" + "log/slog" + "sync" + "time" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +// ServiceSwitchKey is the key of the service ConfigMap that turns Looking +// Glass execution on: only ServiceSwitchEnabled does. +const ( + ServiceSwitchKey = "service" + ServiceSwitchEnabled = "enabled" + ServiceSwitchDisabled = "disabled" +) + +// ServiceSwitchInterval is how often Watch reads the service ConfigMap, and +// so how soon a change takes effect. +const ServiceSwitchInterval = time.Second + +// serviceSwitchReadTimeout bounds one read of the service ConfigMap. +const serviceSwitchReadTimeout = time.Second + +// errServiceDisabled is the cause with which a service request's execution +// is cancelled when the service is turned off. +var errServiceDisabled = errors.New("the Looking Glass service was disabled") + +// ServiceSwitch turns Looking Glass service execution on and off while the +// gateway runs. Its zero value is off. Turning it off cancels the context +// State handed every running request, so their routers stop; turning it +// back on admits new requests and resumes nothing. It never touches +// operator or FabricQuery work, or the limiter's state. +type ServiceSwitch struct { + mu sync.Mutex + on bool + ctx context.Context + cancel context.CancelCauseFunc +} + +// State reports whether the service executes and, when it does, a context +// that ends when it is turned off. A nil switch is off. +func (w *ServiceSwitch) State() (bool, context.Context) { + if w == nil { + return false, nil + } + w.mu.Lock() + defer w.mu.Unlock() + return w.on, w.ctx +} + +// Set turns the service on or off. +func (w *ServiceSwitch) Set(on bool) { + w.mu.Lock() + defer w.mu.Unlock() + if on == w.on { + return + } + w.on = on + if on { + w.ctx, w.cancel = context.WithCancelCause(context.Background()) + } else { + w.cancel(errServiceDisabled) + w.ctx, w.cancel = nil, nil + } + slog.Info("Looking Glass service execution switched", "enabled", on) +} + +// Watch reads key ServiceSwitchKey of ConfigMap namespace/name with reader, +// which should read uncached, every interval until ctx ends, and sets the +// switch from it. The service is on only while the read succeeds and the key +// is exactly ServiceSwitchEnabled: a missing ConfigMap or key, the value +// ServiceSwitchDisabled, a failed read or any other value turns it off, +// the last two with a warning when the problem first appears. It turns the +// service off when ctx ends. +func (w *ServiceSwitch) Watch(ctx context.Context, reader client.Reader, namespace, name string, + interval time.Duration) { + t := time.NewTicker(interval) + defer t.Stop() + var last string + for { + on, problem := readServiceSwitch(ctx, reader, namespace, name) + if ctx.Err() != nil { + w.Set(false) + return + } + if problem != "" && problem != last { + slog.Warn("Looking Glass execution is off: "+problem, "configmap", name, "key", ServiceSwitchKey) + } + last = problem + w.Set(on) + select { + case <-ctx.Done(): + w.Set(false) + return + case <-t.C: + } + } +} + +// readServiceSwitch reads the switch's ConfigMap and reports whether it +// turns the service on, and what is wrong with it when it cannot be read or +// holds an invalid value. +func readServiceSwitch(ctx context.Context, reader client.Reader, namespace, name string) (bool, string) { + ctx, cancel := context.WithTimeout(ctx, serviceSwitchReadTimeout) + defer cancel() + var cm corev1.ConfigMap + if err := reader.Get(ctx, client.ObjectKey{Namespace: namespace, Name: name}, &cm); err != nil { + if apierrors.IsNotFound(err) { + return false, "" + } + return false, "the service ConfigMap could not be read" + } + switch cm.Data[ServiceSwitchKey] { + case ServiceSwitchEnabled: + return true, "" + case ServiceSwitchDisabled, "": + return false, "" + } + return false, "the service ConfigMap's value is neither " + ServiceSwitchEnabled + " nor " + ServiceSwitchDisabled +} diff --git a/internal/fabric/gateway/serviceswitch_test.go b/internal/fabric/gateway/serviceswitch_test.go new file mode 100644 index 000000000..6e93c4fd9 --- /dev/null +++ b/internal/fabric/gateway/serviceswitch_test.go @@ -0,0 +1,187 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package gateway + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + + servicev1 "go.datum.net/galactic/api/fabric/service/v1" + "go.datum.net/galactic/internal/fabric/errcode" + "go.datum.net/galactic/internal/fabric/gateway/limit" + "go.datum.net/galactic/internal/fabric/query" +) + +const testSwitchName = "fabric-api-service" + +// switchConfig serves the service ConfigMap, whose reads fail while failing +// is set. +type switchConfig struct { + client.Client + mu sync.Mutex + failing bool +} + +func newSwitchConfig(t *testing.T) *switchConfig { + t.Helper() + s := runtime.NewScheme() + _ = clientgoscheme.AddToScheme(s) + c := &switchConfig{} + c.Client = fake.NewClientBuilder().WithScheme(s).WithInterceptorFuncs(interceptor.Funcs{ + Get: func(ctx context.Context, cl client.WithWatch, key client.ObjectKey, obj client.Object, + opts ...client.GetOption) error { + c.mu.Lock() + failing := c.failing + c.mu.Unlock() + if failing { + return errors.New("api unavailable") + } + return cl.Get(ctx, key, obj, opts...) + }, + }).Build() + return c +} + +// set writes the ConfigMap's service value; remove deletes it. +func (c *switchConfig) set(t *testing.T, value string) { + t.Helper() + cm := &corev1.ConfigMap{ + ObjectMeta: metav1.ObjectMeta{Namespace: DefaultNamespace, Name: testSwitchName}, + Data: map[string]string{ServiceSwitchKey: value}, + } + if err := c.Update(t.Context(), cm); err != nil { + if err := c.Create(t.Context(), cm); err != nil { + t.Fatal(err) + } + } +} + +func (c *switchConfig) remove(t *testing.T) { + t.Helper() + cm := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Namespace: DefaultNamespace, Name: testSwitchName}} + if err := c.Delete(t.Context(), cm); err != nil { + t.Fatal(err) + } +} + +func (c *switchConfig) fail(on bool) { + c.mu.Lock() + defer c.mu.Unlock() + c.failing = on +} + +// Only the exact value "enabled" turns the service on; everything else, +// including a failed read, turns it off. +func TestServiceSwitchWatch(t *testing.T) { + cfg := newSwitchConfig(t) + w := &ServiceSwitch{} + ctx, cancel := context.WithCancel(t.Context()) + done := make(chan struct{}) + go func() { + defer close(done) + w.Watch(ctx, cfg, DefaultNamespace, testSwitchName, 10*time.Millisecond) + }() + want := func(step string, on bool) { + t.Helper() + within(t, step, time.Now(), time.Second, func() bool { + got, _ := w.State() + return got == on + }) + } + want("missing ConfigMap", false) + cfg.set(t, ServiceSwitchEnabled) + want("enabled", true) + cfg.set(t, ServiceSwitchDisabled) + want("disabled", false) + cfg.set(t, ServiceSwitchEnabled) + want("enabled again", true) + cfg.set(t, "Enabled") + want("invalid value", false) + cfg.set(t, ServiceSwitchEnabled) + want("enabled after an invalid value", true) + cfg.fail(true) + want("unreadable", false) + cfg.fail(false) + want("readable again", true) + cfg.set(t, "") + want("empty value", false) + cfg.set(t, ServiceSwitchEnabled) + want("enabled before removal", true) + cfg.remove(t) + want("removed", false) + cfg.set(t, ServiceSwitchEnabled) + want("recreated", true) + cancel() + <-done + if on, _ := w.State(); on { + t.Error("the switch stayed on after its watch ended") + } +} + +// Turning the switch off cancels a running request within the contract's +// 2 s, ends its stream with Cancelled coverage, and refuses new requests +// with ServiceDisabled; the limiter keeps its state and operator probes +// keep running. +func TestServiceDisableCancelsRunningWork(t *testing.T) { + a := newCancelAnswer() + nodes := &routerNodes{answers: map[string]routerAnswer{routerA: a.answer}} + svc := newService(t, routerPods(routerA, routerB), nodes, 8) + events, done := run(t, svc, validRequest(time.Now()), 0) + if next(t, events).GetSnapshot() == nil { + t.Fatal("first event is not the snapshot") + } + <-a.started + + start := time.Now() + svc.Switch.Set(false) + within(t, "running router cancelled", start, releaseBound, a.cancelled) + var rest []*servicev1.DiagnosticEvent + for ev := range events { + rest = append(rest, ev) + } + if err := <-done; err != nil { + t.Fatalf("stream ended with %v, want OK with complete", err) + } + within(t, "execution released", start, releaseBound, func() bool { return idle(svc) }) + last := rest[len(rest)-1].GetComplete() + if last.GetReason() != string(errcode.Cancelled) { + t.Fatalf("terminal reason = %q", last.GetReason()) + } + for _, ev := range rest { + if o := ev.GetOutcome(); o.GetNode() == routerA && o.GetFailure().GetReason() != string(errcode.Cancelled) { + t.Errorf("router-a outcome = %v", o) + } + } + + if _, err := collect(t, svc, validRequest(time.Now())); errcode.Of(err) != errcode.ServiceDisabled { + t.Fatalf("request while disabled: %v", err) + } + if s := svc.Admission.Authority.State(); s != limit.StateReady { + t.Fatalf("limiter state after disabling = %s", s) + } + nodes.mu.Lock() + nodes.answers = nil + nodes.mu.Unlock() + ping, err := query.Canonicalize(query.Query{Type: query.TypePing, Target: probeTarget6}) + if err != nil { + t.Fatal(err) + } + out := svc.Runner.Run(t.Context(), operatorPrincipal("ops"), testRequestID, ping, + []Node{{Name: routerA, PodUID: podA, Selected: true}}, nil, time.Now().Add(30*time.Second)) + if len(out) != 1 || out[0].Err != nil { + t.Fatalf("operator probe while the service is off: %v", out) + } +} diff --git a/internal/fabric/node/permit.go b/internal/fabric/node/permit.go index 5164b7e13..df40d4266 100644 --- a/internal/fabric/node/permit.go +++ b/internal/fabric/node/permit.go @@ -56,7 +56,8 @@ type PermitGateway interface { // at least PermitStartupRefusal after the node started, and only while the // gateway election Lease, read uncached, still carries the permit's epoch. // Consumed IDs are kept until their deadline plus PermitGrace in a set that -// fails closed when full. +// fails closed when full. A node whose Clock is unhealthy refuses every +// permit. type Permits struct { // Reader reads the gateway's election Lease uncached. Reader client.Reader @@ -73,6 +74,9 @@ type Permits struct { // MaxConsumed and MaxConsumedBytes bound the consumed set; zero selects // the defaults. MaxConsumed, MaxConsumedBytes int + // Clock, when set, reports an error while this host's clock cannot be + // trusted within limit.MaxClockError; every permit is then refused. + Clock func() error mu sync.Mutex consumed map[string]consumedPermit @@ -111,6 +115,8 @@ func (p *Permits) consume(ctx context.Context, pm *fabricv1.ProbePermit, node, r return refuse("the probe permit has expired or is too long-lived") case p.starting(now): return refuse("this node accepts no probe permit until its startup refusal ends") + case p.Clock != nil && p.Clock() != nil: + return refuse("this node's clock is not synchronised") } epoch, err := limit.ReadEpoch(ctx, p.Reader, p.Namespace, p.LeaseName, now) if err != nil { diff --git a/internal/fabric/node/permit_test.go b/internal/fabric/node/permit_test.go index e34a6ca82..9d58aa9b3 100644 --- a/internal/fabric/node/permit_test.go +++ b/internal/fabric/node/permit_test.go @@ -167,6 +167,10 @@ func TestPermitRefusals(t *testing.T) { }, code: errcode.LimiterUnavailable}, "no id": {mod: func(p *fabricv1.ProbePermit) { p.Id = "" }, code: errcode.LimiterUnavailable}, "startup refusal": {perm: func(p *Permits) { p.Started = time.Now() }, code: errcode.LimiterUnavailable}, + "clock unsynchronised": { + perm: func(p *Permits) { p.Clock = func() error { return errors.New("unsynchronised") } }, + code: errcode.LimiterUnavailable, + }, "lease unreadable": {perm: func(p *Permits) { p.Reader = leaseReader(t, "gateway-0_a") p.LeaseName = "missing"