Files
vpp-maglev/cmd/maglevd/main.go
Pim van Pelt 0049c2ae73 VPP reconciler: event-driven sync, pool failover, bug fixes
This commit wires the checker's state machine through to the VPP dataplane:
every backend state transition flows through a single code path that
recomputes the effective per-backend weight (with pool failover) and pushes
the result to VPP. Along the way several latent bugs in the state machine
and the sync path were fixed.

internal/vpp/reconciler.go (new)
- New Reconciler type subscribes to checker.Checker events and, on every
  transition, calls Client.SyncLBStateVIP for the affected frontend. This
  is the ONLY place in the codebase where backend state changes cause VPP
  calls — the "single path" discipline requested during design.
- Defines an EventSource interface (checker.Checker satisfies it) so the
  dependency direction stays vpp → checker; the checker never imports vpp.

internal/vpp/client.go
- Renamed ConfigSource → StateSource. The interface now has two methods:
  Config() and BackendState(name) — the reconciler and the desired-state
  builder both need live health state to compute effective weights.
- SetConfigSource → SetStateSource; internal cfgSrc field → stateSrc.
- New getStateSource() helper for internal locked access.
- lbSyncLoop still uses the state source for its periodic drift
  reconciliation; it's fully idempotent and runs the same code path as
  event-driven syncs.

internal/vpp/lbsync.go
- desiredAS grows a Flush bool so the mapping function can signal "on
  transition to weight 0, flush existing flow-table entries".
- asFromBackend is now the single source of truth for the state →
  (weight, flush) rule. Documented with a full truth table. Takes an
  activePool parameter so it can distinguish "up in active pool" from
  "up but standby".
- activePoolIndex(fe, states) implements priority failover: returns the
  index of the first pool containing any StateUp backend. pool[0] wins
  when at least one member is up; pool[1] takes over when pool[0] is
  empty; and so on. Defaults to 0 (unobservable, since all backends map
  to weight 0 when nothing is up).
- desiredFromFrontend snapshots backend states once, computes activePool,
  then walks every backend through asFromBackend. No more filtering on
  b.Enabled — disabled backends stay in the desired set so they keep
  their AS entry in VPP with weight=0. The previous filter caused delAS
  on disable, which destroyed the entry and broke enable afterwards.
- EffectiveWeights(fe, src) exported helper that returns the per-pool
  per-backend weight map for one frontend. Used by the gRPC GetFrontend
  handler and robot tests to observe failover without touching VPP.
- reconcileVIP computes flush at the weight-change call site:
    flush = desired.Flush && cur.Weight > 0 && desired.Weight == 0
  This ensures only the *transition* to disabled flushes sessions —
  steady-state syncs with already-zero weight skip the call entirely.
- setASWeight now plumbs IsFlush into lb_as_set_weight.

internal/vpp/lbsync_test.go (new)
- TestAsFromBackend: 15 cases locking down the truth table, including
  failover scenarios (up in standby pool, up promoted in pool[1]).
- TestActivePoolIndex: 8 cases covering pool[0]-has-up, pool[0]-all-down,
  all-disabled, all-paused, all-unknown, nothing-up-anywhere, and
  three-tier failover.
- TestDesiredFromFrontendFailover: 5 end-to-end scenarios wiring a fake
  StateSource through desiredFromFrontend and asserting the final
  per-IP weight map. Exercises the complete pipeline without VPP.

internal/checker/checker.go
- Added BackendState(name) (health.State, bool) — one-line method that
  satisfies vpp.StateSource. The checker is otherwise unchanged.
- EnableBackend rewritten to reuse the existing worker (parallel to
  ResumeBackend). The old code called startWorker which constructed a
  brand-new Backend via health.New, throwing away the transition
  history; the resulting 'backend-transition' log showed the bogus
  from=unknown,to=unknown. Now uses w.backend.Enable() to record a
  proper disabled→unknown transition and launches a fresh goroutine.
- Static (no-healthcheck) backends now fire their synthetic 'always up'
  pass on the first iteration of runProbe instead of sleeping 30s
  first. Previously static backends sat in StateUnknown for 30s after
  startup — useless for deterministic testing and surprising for
  operators. The fix is a simple first-iteration flag.

internal/health/state.go
- New Enable(maxHistory) method parallel to Disable. Transitions the
  backend from whatever state it's in (typically StateDisabled) to
  StateUnknown, resets the health counter to rise-1 so the expedited
  resolution kicks in on the first probe result, and emits a transition
  with code 'enabled'.

proto/maglev.proto
- PoolBackendInfo gains effective_weight: the state-aware weight that
  would be programmed into VPP (distinct from the configured weight in
  the YAML). Exposed via GetFrontend.

internal/grpcapi/server.go
- frontendToProto takes a vpp.StateSource, computes effective weights
  via vpp.EffectiveWeights, and populates PoolBackendInfo.EffectiveWeight.
- GetFrontend and SetFrontendPoolBackendWeight updated to pass the
  checker in.

cmd/maglevc/commands.go
- 'show frontends <name>' now renders every pool backend row as
    <name>  weight <cfg>  effective <eff>  [disabled]?
  so both values are always visible. The VPP-style key/value format
  avoids the ANSI-alignment pitfall we hit earlier and makes the output
  regex-parseable for robot tests.

cmd/maglevd/main.go
- Construct and start the Reconciler alongside the VPP client. Two
  extra lines, no other changes to startup.

tests/01-maglevd/maglevd-lab/maglev.yaml
- Two new static backends (static-primary, static-fallback) and a new
  failover-vip frontend with one backend per pool. No healthcheck, so
  the state machine resolves them to 'up' immediately via the synthetic
  pass. Used by the failover robot tests.

tests/01-maglevd/01-healthcheck.robot
- Three new test cases exercising pool failover end-to-end:
  1. primary up, secondary standby (initial state)
  2. disable primary → fallback takes over (effective weight flips)
  3. enable primary → fallback steps back
  All run without VPP: they scrape 'maglevc show frontends <name>' and
  regex-match the effective weight in the output. Deterministic and
  fast (~2s total) because the static backends don't probe.
- Two helper keywords: Static Backend Should Be Up and
  Effective Weight Should Be.

Net result: 16/16 robot tests pass. Backend state transitions now
flow through a single documented path (checker event → reconciler →
SyncLBStateVIP → desiredFromFrontend → asFromBackend → reconcileVIP →
setASWeight), and the pool failover / enable-after-disable / static-
backend-startup bugs are all fixed.
2026-04-12 12:40:09 +02:00

172 lines
5.6 KiB
Go

// Copyright (c) 2026, Pim van Pelt <pim@ipng.ch>
package main
import (
"context"
"flag"
"fmt"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
buildinfo "git.ipng.ch/ipng/vpp-maglev/cmd"
"git.ipng.ch/ipng/vpp-maglev/internal/checker"
"git.ipng.ch/ipng/vpp-maglev/internal/config"
"git.ipng.ch/ipng/vpp-maglev/internal/grpcapi"
"git.ipng.ch/ipng/vpp-maglev/internal/metrics"
"git.ipng.ch/ipng/vpp-maglev/internal/vpp"
)
func main() {
if err := run(); err != nil {
slog.Error("startup-fatal", "err", err)
os.Exit(1)
}
}
func run() error {
// ---- flags / env --------------------------------------------------------
printVersion := flag.Bool("version", false, "print version and exit")
checkOnly := flag.Bool("check", false, "check config file and exit (0=ok, 1=parse error, 2=semantic error)")
enableReflection := flag.Bool("reflection", true, "enable gRPC server reflection (for grpcurl)")
configPath := stringFlag("config", "/etc/vpp-maglev/maglev.yaml", "MAGLEV_CONFIG", "path to maglev.yaml")
grpcAddr := stringFlag("grpc-addr", ":9090", "MAGLEV_GRPC_ADDR", "gRPC listen address")
metricsAddr := stringFlag("metrics-addr", ":9091", "MAGLEV_METRICS_ADDR", "Prometheus /metrics listen address (empty to disable)")
vppAPIAddr := stringFlag("vpp-api-addr", "/run/vpp/api.sock", "MAGLEV_VPP_API_ADDR", "VPP binary API socket path (empty to disable)")
vppStatsAddr := stringFlag("vpp-stats-addr", "/run/vpp/stats.sock", "MAGLEV_VPP_STATS_ADDR", "VPP stats socket path")
logLevel := stringFlag("log-level", "info", "MAGLEV_LOG_LEVEL", "log level (debug|info|warn|error)")
flag.Parse()
if *printVersion {
fmt.Printf("maglevd %s (commit %s, built %s)\n",
buildinfo.Version(), buildinfo.Commit(), buildinfo.Date())
return nil
}
if *checkOnly {
_, result := config.Check(*configPath)
if result.OK() {
fmt.Printf("config ok: %s\n", *configPath)
return nil
}
if result.ParseError != "" {
fmt.Fprintf(os.Stderr, "parse error: %s\n", result.ParseError)
os.Exit(1)
}
fmt.Fprintf(os.Stderr, "semantic error: %s\n", result.SemanticError)
os.Exit(2)
}
// ---- logging ------------------------------------------------------------
var level slog.Level
if err := level.UnmarshalText([]byte(*logLevel)); err != nil {
return fmt.Errorf("invalid log level %q: %w", *logLevel, err)
}
jsonHandler := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: level})
logBroadcaster := grpcapi.NewLogBroadcaster(jsonHandler)
slog.SetDefault(slog.New(logBroadcaster))
slog.Info("starting", "version", buildinfo.Version(), "commit", buildinfo.Commit(), "date", buildinfo.Date())
// ---- config -------------------------------------------------------------
cfg, err := config.Load(*configPath)
if err != nil {
return fmt.Errorf("load config: %w", err)
}
slog.Info("config-loaded", "path", *configPath, "frontends", len(cfg.Frontends))
// ---- checker ------------------------------------------------------------
chkr := checker.New(cfg)
ctx, rootCancel := context.WithCancel(context.Background())
defer rootCancel()
go func() {
if err := chkr.Run(ctx); err != nil {
slog.Error("checker-exited", "err", err)
}
}()
// ---- VPP connection -----------------------------------------------------
var vppClient *vpp.Client
if *vppAPIAddr != "" {
vppClient = vpp.New(*vppAPIAddr, *vppStatsAddr)
vppClient.SetStateSource(chkr)
go vppClient.Run(ctx)
// The reconciler subscribes to checker events and pushes per-VIP
// syncs into VPP on every backend state transition. This is the
// single place where transitions translate into dataplane changes.
reconciler := vpp.NewReconciler(vppClient, chkr, chkr)
go reconciler.Run(ctx)
}
// ---- gRPC server --------------------------------------------------------
lis, err := net.Listen("tcp", *grpcAddr)
if err != nil {
return fmt.Errorf("listen %s: %w", *grpcAddr, err)
}
srv := grpc.NewServer()
maglevServer := grpcapi.NewServer(ctx, chkr, logBroadcaster, *configPath, vppClient)
grpcapi.RegisterMaglevServer(srv, maglevServer)
if *enableReflection {
reflection.Register(srv)
}
slog.Info("grpc-listening", "addr", *grpcAddr, "reflection", *enableReflection)
go func() {
if err := srv.Serve(lis); err != nil {
slog.Error("grpc-serve-error", "err", err)
}
}()
// ---- Prometheus metrics -------------------------------------------------
if *metricsAddr != "" {
reg := prometheus.DefaultRegisterer
metrics.Register(reg, chkr)
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.Handler())
slog.Info("metrics-listening", "addr", *metricsAddr)
go func() {
if err := http.ListenAndServe(*metricsAddr, mux); err != nil && err != http.ErrServerClosed {
slog.Error("metrics-serve-error", "err", err)
}
}()
}
// ---- signal handling ----------------------------------------------------
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGHUP, syscall.SIGTERM, syscall.SIGINT)
for sig := range sigCh {
switch sig {
case syscall.SIGHUP:
maglevServer.TriggerReload()
case syscall.SIGTERM, syscall.SIGINT:
slog.Info("shutdown", "signal", sig)
rootCancel()
srv.GracefulStop()
return nil
}
}
return nil
}
// stringFlag declares a flag that falls back to an environment variable.
func stringFlag(name, defaultVal, envKey, usage string) *string {
val := defaultVal
if v := os.Getenv(envKey); v != "" {
val = v
}
return flag.String(name, val, fmt.Sprintf("%s (env: %s)", usage, envKey))
}