agent

package
v0.1.6 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: AGPL-3.0 Imports: 46 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 agent is the node agent core: it enrolls with the panel, keeps ONE AgentService.Connect stream open (reconnecting with backoff), applies the desired state to the protocol engines, reports traffic reliably (seq + ack), executes commands and serves its own log. The wire protocol is specified in the comment block of proto/mistgate/agent/v1/agent.proto; this package implements it, nothing more.

Concurrency model: one worker goroutine owns every mutation of engine and host state (desired-state apply, kick, restart, retire, credential-expiry sweep), so the engines see one caller for Apply/Remove/ Kick as their contract demands. Each stream has a reader (the Connect goroutine) and one writer; the statistics collector, certificate renewal and the expiry timer run for the agent's whole life, across reconnects.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotEnrolled is returned by New when the state directory holds no identity.
	ErrNotEnrolled = errors.New("agent is not enrolled (run `mistgate-node enroll` first)")
	// ErrRetired is returned by Run after the panel retired the node; the caller should exit 0.
	ErrRetired = errors.New("node retired by the panel")
)

Functions

func IsEnrolled

func IsEnrolled(dir string) bool

IsEnrolled reports whether dir holds an identity (enroll writes identity.pem last).

Types

type Agent

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

Agent is the node agent. Build it with New and run it with Run.

func New

func New(cfg Config, engines map[string]engine.Factory, host hostctl.Host) (*Agent, error)

New loads the identity from cfg.StateDir and builds the engines. The panel is not contacted. Returns ErrNotEnrolled when `enroll` has not been run.

func (*Agent) AwgBackend

func (a *Agent) AwgBackend() string

AwgBackend returns NodeSettings.awg_backend ("" = auto). The awg engine factory asks for it when it builds its backend, like the engines ask for DNS.

func (*Agent) DNS

func (a *Agent) DNS() []string

DNS returns the resolvers from NodeSettings (empty = engine default). Engines call it per use.

func (*Agent) Run

func (a *Agent) Run(ctx context.Context) error

Run blocks until ctx is cancelled (returns nil) or the panel retires the node (returns ErrRetired). On a normal stop the engines are closed but host state (hop rules, sysctl) is left in place so the node keeps its baseline across an agent restart.

func (*Agent) WarpEvent

func (a *Agent) WarpEvent(ev warp.Event)

WarpEvent turns an event of the WARP manager into an agent Event (warp_state, warp_needs_attention). The manager is built before the agent, so its Emit option calls this through a closure.

type Config

type Config struct {
	// StateDir holds the identity and the persisted desired state (created by Enroll).
	StateDir string
	// Version is reported in Hello; defaults to buildinfo.Version.
	Version string
	// Built is the Unix time of the source commit (Hello.built); 0 = buildinfo.BuiltUnix().
	Built int64
	// Updater is the self-update machinery (internal/node/update). Nil = this agent never lists "update/1" and
	// refuses UpdateAgent and RollbackAgent.
	Updater *update.Updater
	// Log receives the agent's records; every record also goes to the in-memory ring that LogRequest reads.
	// Nil = slog.Default().
	Log *slog.Logger

	// Host-side services handed to the engines (engine.Env). Nil Certs means engines get no certificates,
	// nil Egress means only a "no egress configured" error, nil Masquerade serves a plain 404.
	Certs      engine.CertSource
	Egress     func(name string) (engine.Egress, error)
	Masquerade func(inboundID string) http.Handler

	// DoctorEnv adjusts the doctor's view of the machine before the doctor is built (tests point it at a fake
	// root directory and fake commands). Nil = the real host.
	DoctorEnv func(doctor.Env) doctor.Env

	// Warp is the node-level WARP manager (internal/node/warp.Manager). Nil = this build has no WARP: the agent does not
	// list "warp/1", and an inbound whose egress is WARP is not started. The manager is also what Egress("warp") returns.
	Warp WarpManager
	// UnitGen is the generation of the systemd unit the agent runs from (MISTGATE_UNIT_GEN); 3 is listed as "unit/3".
	UnitGen int
	// AwgPrepare builds the AmneziaWG kernel module on request (internal/node/awgprep). Nil = this agent does not list
	// "awg-prepare/1", and the admin UI keeps showing the manual command.
	AwgPrepare *awgprep.Controller

	// MaxPending and MaxPendingBytes bound the queue of unacked reliable messages (defaults 2160 = 6 h of
	// 10 s batches, and 32 MiB).
	MaxPending      int
	MaxPendingBytes int
}

Config is what the caller (cmd/mistgate-node, or a test) provides.

type EnrollConfig

type EnrollConfig struct {
	StateDir         string
	Panel            string // host:port
	SNI              string
	CASHA256         string // hex fingerprint of the panel CA certificate (colons and case ignored)
	Token            string
	Version          string // defaults to buildinfo.Version
	Force            bool   // overwrite an existing identity
	ResumePendingKey bool   // persist and reuse the CSR key if enrollment is interrupted
	Timeout          time.Duration
}

EnrollConfig is the input of the `enroll` command.

type Meta

type Meta struct {
	Panel  string `json:"panel"`   // host:port
	SNI    string `json:"sni"`     // secret agent SNI
	NodeID string `json:"node_id"` // informational; the certificate is authoritative
}

Meta is what enrollment leaves next to the key material.

func Enroll

func Enroll(ctx context.Context, cfg EnrollConfig) (Meta, error)

Enroll generates a P-256 key and a CSR, exchanges the one-time token for a node certificate over TLS that trusts ONLY a CA with the given fingerprint, and stores key, certificate, CA and panel address.

type SettingsAware

type SettingsAware interface {
	NodeSettings(ctx context.Context, st *pb.NodeSettings) (reset bool)
}

SettingsAware is implemented by an engine whose configuration comes from NodeSettings (awg: the backend). The worker calls NodeSettings before every reconcile with the settings the agent holds; an engine that dropped its inbounds because of a change returns reset=true and every inbound of its protocol is applied again in the same reconcile.

type WarpManager

type WarpManager interface {
	// Apply makes the node match the spec: nil removes WARP, Enabled=false pauses it. Idempotent and cheap for a
	// spec it already runs (it only re-asserts the routing).
	Apply(ctx context.Context, spec *plugin.WarpSpec) error
	// Reconnect rebuilds a down tunnel without changing its account or routed subnets. False means it recovered already.
	Reconnect(ctx context.Context) (bool, error)
	// CheckNow retries one current failed check and reports whether WARP is down at its failure threshold.
	CheckNow(ctx context.Context) (checked, thresholdDown bool, err error)
	// SetRoutedSubnets sets the client subnets of the awg inbounds with egress "warp".
	SetRoutedSubnets(ctx context.Context, subnets []netip.Prefix) error
	// Configured says whether the node has a WARP configuration (paused included).
	Configured() bool
	// Health is the last measured state; ok=false when the node has no WARP.
	Health() (warp.Health, bool)
	// Preflight lists clashes with the host (routing table, rule preferences, a FORWARD drop policy); the doctor shows them.
	Preflight(ctx context.Context) []warp.Finding
	// Run drives the health checks until ctx ends.
	Run(ctx context.Context)
	// Cleanup removes everything the manager installed on the host.
	Cleanup(ctx context.Context) error
}

WarpManager is what the agent needs of internal/node/warp.Manager (the real one implements it; tests use a fake). The manager is handed to the engines through Config.Egress; the agent owns its lifecycle and feeds it the spec.

Jump to

Keyboard shortcuts

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