server

package
v0.2.0-rc.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 3, 2026 License: Apache-2.0 Imports: 51 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package server is the upgradescope continuous-mode server: snapshot ingest, persisted evaluations, a read API, and on-demand what-if re-evaluation. Storage is behind store.Store; the CLI owns flag parsing and store construction (DB path never reaches this package).

Index

Constants

View Source
const DefaultMaxGateBytes = 10 << 20 // 10 MiB

DefaultMaxGateBytes caps the /gate manifest stream when Config.MaxGateBytes is unset. Lower than the snapshot cap: the gate body is buffered whole and is reachable with only the read token (or none).

View Source
const DefaultMaxSnapshotBytes = 20 << 20 // 20 MiB

DefaultMaxSnapshotBytes caps the snapshot push body when Config.MaxSnapshotBytes is unset — enforced on the wire bytes AND on the decompressed stream (gzip-bomb guard).

View Source
const DefaultStaleAfter = 2 * time.Hour

DefaultStaleAfter is how long a cluster may go without a push before the API and /metrics call it stale. An agent pushes on every change and at least every --force-sync-every (1h), on its next tick (10m by default), so an unchanged, healthy cluster pushes about every 70 minutes; 2h leaves room for that and one missed push. It matches the chart's UpgradescopeClusterStale alert (7200s).

View Source
const ExtraTargetsCost = "each one adds a report of up to --max-snapshot-bytes to every push and to the re-evaluation pass, " +
	"and the server's memory bound is measured at that many (see Memory and request limits in the operations guide)"

ExtraTargetsCost says why MaxExtraTargets exists, for its refusals.

View Source
const MaxExtraTargets = 4

MaxExtraTargets is how many distinct Config.ExtraTargets (serve --targets) New accepts. Each one adds a report of up to --max-snapshot-bytes to every ingest and to the re-evaluation pass, so the server's memory bound (docs/operations.md, make test-heap) is measured at this many.

Variables

This section is empty.

Functions

func ComputeDelta

func ComputeDelta(prev *engine.Report, curr engine.Report) []notify.Change

ComputeDelta implements the notification delta rules for one target:

  • prev == nil (first-ever evaluation of this cluster+target) → nothing.
  • Blocker findings added since prev (diff by stable finding key) → one new-blocker change each.
  • Blocker count went >0 → 0 AND curr.Verdict is ready → one became-ready change. Zero blockers with verdict unknown (a required check was not assessed, e.g. a transient collector failure) is not readiness.
  • eol-approaching warnings added since prev (by key) → one change each.

Identity is Finding.Key — deliberately count-free, so a title-only change ("3 objects" → "2 objects") never re-alerts the same blocker. Findings with an empty Key (reports stored before Key existed) fall back to Title. Duplicate keys within one report give one change (first occurrence wins).

Every change lists curr's target; buildNotification merges and caps the changes of one pass across targets. Order is deterministic: new-blockers in report order, became-ready, eol-approaching in report order.

func WhatIf

func WhatIf(ctx context.Context, st store.Store, k kb.KB, tm TeamMap, clusterID int64, target inventory.Version, now time.Time) (engine.Report, error)

WhatIf re-evaluates a cluster's latest stored snapshot against an arbitrary target using the server's KB. Nothing is stored. now is injected by the caller (the server passes s.now()) so EOL-window math stays deterministic and testable. tm (nil = no-op) applies the server's namespace→team override, matching what ingest stores. Returns store.ErrNotFound (wrapped) when the cluster has no snapshots.

Types

type Config

type Config struct {
	Listen       string          // listen address for Start, e.g. ":8080"
	Store        store.Store     // required
	KB           kb.KB           // evaluation knowledge base
	ExtraTargets []string        // minors evaluated for every snapshot, e.g. ["1.37"]
	Notifier     notify.Notifier // nil = notifications disabled
	IngestToken  string          // optional shared bearer for POST /api/v1/snapshots (any cluster); "" = per-cluster tokens only
	ReadToken    string          // optional bearer for the read API; "" = open on loopback only, unless AllowAnonymousRead
	// AllowAnonymousRead serves an open read API (ReadToken "") on an
	// address that is not loopback. Without it Start refuses one.
	AllowAnonymousRead bool
	AdminToken         string  // bearer for cluster delete/rename (also accepted for reads); "" = both refused
	TeamMap            TeamMap // optional namespace→team override, applied before every Evaluate
	Version            string  // build version: SARIF tool metadata ("" = omitted there) and toolVersion in report responses ("" when unset)

	// StaleAfter marks a cluster stale when its agent has not pushed
	// (duplicates included) for longer; 0 = DefaultStaleAfter.
	StaleAfter time.Duration
	// Retention prunes snapshots and evaluations older than this, except
	// each cluster's latest snapshot and its evaluations, at startup and
	// daily; 0 = keep everything.
	Retention time.Duration

	MaxSnapshotBytes int64 // POST /api/v1/snapshots body cap; 0 = DefaultMaxSnapshotBytes
	MaxGateBytes     int64 // POST /api/v1/gate body cap; 0 = DefaultMaxGateBytes

	// TLSCertFile/TLSKeyFile (PEM) make Start serve HTTPS; both or neither.
	// Loaded once in New, so a rotated certificate needs a restart.
	TLSCertFile string
	TLSKeyFile  string
}

Config wires a Server.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server serves the ingest + read API. Construct with New; a Server is single-use (one Start/Shutdown cycle).

func New

func New(cfg Config) (*Server, error)

New validates cfg and builds the route table.

func (*Server) Addr

func (s *Server) Addr() string

Addr returns the bound listen address ("" before Ready is closed).

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler exposes the full route table (API + dashboard fallback) for httptest and embedding.

func (*Server) Ready

func (s *Server) Ready() <-chan struct{}

Ready is closed once the listener is bound. It is NEVER closed when Listen fails — Start just returns the error — so callers must not block on Ready alone: run Start in a goroutine and select on Ready() AND the goroutine's error channel, or a bad Listen address hangs the caller.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully drains in-flight requests until ctx ends, then closes whatever is still open, and unblocks Start. A connection still active at the deadline is a stalled or abusive client (ReadTimeout and WriteTimeout bound every legitimate request), so cutting it off is the expected end of the drain, not a shutdown failure.

A Shutdown that comes before Start has started serving makes Start return nil without serving or starting any background work.

Background work stops after the drain: a notification mid-delivery is cancelled and stays in the outbox (its lease expires and the next start delivers it); a re-evaluation mid-commit rolls back.

func (*Server) Start

func (s *Server) Start() error

Start binds Config.Listen and serves until Shutdown. It returns nil after a clean Shutdown, otherwise the listen/serve error. Once Ready() is closed, Addr() reports the bound address (Listen ":0" works in tests).

Without a read token the read API is open, which Start allows only on a loopback address unless AllowAnonymousRead says otherwise. It checks the address it actually bound, after binding, so no name resolution decides it: "localhost" mapped to a routable address in /etc/hosts, a hostname, or ":8080" (every interface) is refused, and nothing is served on it in between.

type TeamMap

type TeamMap []TeamMapRule

TeamMap is the server-side namespace→team override (spec: labels + server override). It is applied over the namespace team labels carried in the inventory at evaluation time — a matching rule replaces the label; a namespace matching no rule keeps its label. A nil/empty TeamMap is a no-op.

func LoadTeamMap

func LoadTeamMap(p string) (TeamMap, error)

LoadTeamMap reads and parses a --team-map YAML file.

func ParseTeamMap

func ParseTeamMap(data []byte) (TeamMap, error)

ParseTeamMap parses YAML of the form:

  • pattern: "payments-*" team: payments

Every rule must have a non-empty pattern (valid path.Match glob) and team.

func (TeamMap) Apply

Apply returns a rewritten copy of ns: for each namespace, the first rule whose glob matches sets the team; no match keeps the inventory label. The input slice is never mutated (it may alias a caller's inventory).

type TeamMapRule

type TeamMapRule struct {
	Pattern string `json:"pattern"`
	Team    string `json:"team"`
}

TeamMapRule maps namespaces matching a glob Pattern (path.Match grammar) to Team. Rules are ordered; the first matching pattern wins.

Directories

Path Synopsis
Package notify defines the notification seam fired on finding deltas (new blocker, became-ready, add-on entering the EOL window) — never on every snapshot.
Package notify defines the notification seam fired on finding deltas (new blocker, became-ready, add-on entering the EOL window) — never on every snapshot.
Package store persists clusters, snapshots and evaluations for the upgradescope server.
Package store persists clusters, snapshots and evaluations for the upgradescope server.
storetest
Package storetest pins the behavioral contract of store.Store.
Package storetest pins the behavioral contract of store.Store.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL