agent

package
v0.13.0 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: Apache-2.0 Imports: 33 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 implements agent-level runtime services.

Index

Constants

View Source
const (
	// DefaultMode is the default operating mode.
	DefaultMode = "node"

	// DefaultLogLevel is the default log level.
	DefaultLogLevel = "info"
)
View Source
const CredentialRefusedThreshold = 3

CredentialRefusedThreshold is the number of consecutive heartbeats the control plane must answer 401, with no accepted heartbeat between them, before the heartbeat service parks.

View Source
const DefaultHeartbeatInterval = 30 * time.Second

DefaultHeartbeatInterval is the default heartbeat interval.

View Source
const MaxCredentialProbeInterval = time.Hour

MaxCredentialProbeInterval caps the delay between two heartbeats while the heartbeat service is parked.

Variables

View Source
var DefaultDataDir = paths.DataDir()

DefaultDataDir is the default data directory. It is resolved per platform, which is why it is a var rather than a const.

Functions

This section is empty.

Types

type AgentConfig

type AgentConfig struct {
	// Mode is the operating mode: "node" or "bridge".
	// Default: "node"
	Mode string `yaml:"mode"`

	// LogLevel is the log level: "debug", "info", "warn", "error".
	// Default: "info"
	LogLevel string `yaml:"log_level"`

	// DataDir is the directory for persistent agent data.
	// Default: paths.DataDir()
	DataDir string `yaml:"data_dir"`

	API          api.Config          `yaml:"api"`
	Registration registration.Config `yaml:"registration"`
	Reconcile    reconcile.Config    `yaml:"reconcile"`
	NodeAPI      nodeapi.Config      `yaml:"node_api"`
	Health       health.Config       `yaml:"health"`
	Actions      actions.Config      `yaml:"actions"`
	Policy       policy.Config       `yaml:"policy"`
	WireGuard    wireguard.Config    `yaml:"wireguard"`
	Metrics      metrics.Config      `yaml:"metrics"`
	LogFwd       logfwd.Config       `yaml:"log_fwd"`
	AuditFwd     auditfwd.Config     `yaml:"audit_fwd"`
	Integrity    integrity.Config    `yaml:"integrity"`
	Upgrade      upgrade.Config      `yaml:"upgrade"`
	Tunnel       tunnel.Config       `yaml:"tunnel"`
	NAT          nat.Config          `yaml:"nat"`
	PeerExchange peerexchange.Config `yaml:"peer_exchange"`
	Bridge       bridge.Config       `yaml:"bridge"`
	Heartbeat    HeartbeatConfig     `yaml:"heartbeat"`
}

AgentConfig is the top-level configuration for the plexd agent. It aggregates all subsystem configurations and is populated from a YAML configuration file via ParseConfig.

func ParseConfig

func ParseConfig(path string) (*AgentConfig, bool, error)

ParseConfig reads a YAML configuration file and returns an AgentConfig with defaults applied. An absent file is not an error: it is treated as an empty config, and the returned bool reports whether the file was found. A file that exists but cannot be read, that is empty, or that does not parse, is an error. Validating the result is the caller's responsibility, once the CLI flag and environment overrides have been merged in.

func (*AgentConfig) ApplyDefaults

func (c *AgentConfig) ApplyDefaults()

ApplyDefaults sets default values for zero-valued fields.

func (*AgentConfig) Validate

func (c *AgentConfig) Validate() error

Validate checks that required fields are set and values are acceptable.

type DeviceKeyUpdater added in v0.2.0

type DeviceKeyUpdater interface {
	UpdatePrivateKey(privateKey []byte) error
}

DeviceKeyUpdater installs a rotated private key on the WireGuard device.

type HandshakeReportClient added in v0.10.0

type HandshakeReportClient interface {
	ReportHandshakes(ctx context.Context, nodeID string, req api.HandshakeReportRequest) (*api.HandshakeReportResponse, error)
}

HandshakeReportClient sends handshake reports to the control plane.

type HandshakeReporter added in v0.10.0

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

HandshakeReporter posts, once per interval, the age of the latest completed WireGuard handshake with each mesh peer and the endpoint WireGuard used for it to POST /v1/nodes/{node_id}/handshakes. The control plane derives each mesh edge's status, mode, handshake age and endpoint from these reports.

DECISION: the reporter runs its own loop at the heartbeat interval rather than riding on HeartbeatService.sendHeartbeat. The contract asks for one report per heartbeat interval, and a slow report inside the heartbeat would delay the liveness signal the control plane times the node out on.

DECISION: a failed report is never retried within its tick. The control plane anchors every age on its own receive time, so a replayed body would make each handshake look newer than it was; the next tick builds a fresh body with a fresh observed_at and fresh ages instead.

func NewHandshakeReporter added in v0.10.0

func NewHandshakeReporter(interval time.Duration, nodeID string, client HandshakeReportClient, source MeshPeerStatsSource, logger *slog.Logger) *HandshakeReporter

NewHandshakeReporter creates a HandshakeReporter that reports for nodeID through client, reading the device through source. A non-positive interval becomes DefaultHeartbeatInterval, the same fallback the heartbeat applies, because the report's cadence is defined as the heartbeat interval.

func (*HandshakeReporter) Run added in v0.10.0

func (r *HandshakeReporter) Run(ctx context.Context) error

Run reports on every tick of the interval until ctx is cancelled. Unlike the heartbeat it sends nothing at start: the WireGuard interface has only just come up, so no handshake can have completed yet and the first report would carry nothing. Run always returns nil.

type HeartbeatClient

type HeartbeatClient interface {
	Heartbeat(ctx context.Context, nodeID string, req api.HeartbeatRequest) (*api.HeartbeatResponse, error)
}

HeartbeatClient sends heartbeat requests to the control plane.

type HeartbeatConfig

type HeartbeatConfig struct {
	// Interval is the heartbeat send interval.
	// Default: 30s
	Interval time.Duration `yaml:"interval"`

	// NodeID is the node identifier (required).
	NodeID string `yaml:"node_id"`
}

HeartbeatConfig holds the configuration for the heartbeat service.

func (*HeartbeatConfig) ApplyDefaults

func (c *HeartbeatConfig) ApplyDefaults()

ApplyDefaults sets default values for zero-valued fields.

func (*HeartbeatConfig) Validate

func (c *HeartbeatConfig) Validate() error

Validate checks that required fields are set.

type HeartbeatService

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

HeartbeatService sends periodic heartbeats to the control plane and dispatches directive flags from the response.

The heartbeat also decides whether the control plane still accepts the node's credential. After CredentialRefusedThreshold consecutive heartbeats answered 401 the service parks: it reports the refusal through the callback set by SetOnCredentialRefused, and from then on sends a heartbeat only as a probe, first after twice the interval and then at a delay that doubles on every probe that fails, up to MaxCredentialProbeInterval. The first accepted probe unparks it and the interval applies again.

DECISION: any heartbeat 401 counts, whatever its problem code, and a 401 on another route does not. The control plane answers nsk_invalid for a removed Node and nsk_revoked for a revoked credential, and an older one sends no code at all; keeping the decision in the heartbeat gives it one owner. Any other failure leaves the count unchanged, since it says nothing about the credential, and only an accepted heartbeat resets it.

func NewHeartbeatService

func NewHeartbeatService(cfg HeartbeatConfig, client HeartbeatClient, logger *slog.Logger) *HeartbeatService

NewHeartbeatService creates a new HeartbeatService with the given configuration and client. The config is validated; defaults are applied for any zero-valued optional fields.

func (*HeartbeatService) Run

func (s *HeartbeatService) Run(ctx context.Context) error

Run starts the heartbeat loop. It sends one heartbeat immediately and then waits nextDelay after every send, until ctx is cancelled. Run always returns nil.

func (*HeartbeatService) SetBuildRequest

func (s *HeartbeatService) SetBuildRequest(fn func() api.HeartbeatRequest)

SetBuildRequest sets a custom heartbeat request builder. If not set, the service sends a zero-valued HeartbeatRequest.

func (*HeartbeatService) SetOnCredentialRefused added in v0.11.0

func (s *HeartbeatService) SetOnCredentialRefused(fn func(refused bool))

SetOnCredentialRefused sets a callback invoked with true when the service parks on a credential the control plane keeps refusing, and with false when a probe is accepted again. It is called once per transition, on the Run goroutine, before the transition is logged.

func (*HeartbeatService) SetOnRotateKeys

func (s *HeartbeatService) SetOnRotateKeys(fn func())

SetOnRotateKeys sets a callback invoked when the control plane signals that keys should be rotated.

func (*HeartbeatService) SetReconcileTrigger

func (s *HeartbeatService) SetReconcileTrigger(rt ReconcileTrigger)

SetReconcileTrigger sets the reconcile trigger invoked when the control plane requests reconciliation.

type KeyRotator added in v0.2.0

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

KeyRotator runs the mesh-key rotation state machine. Both rotation signals drive the same single-flight cycle: the repeated heartbeat rotate_keys flag through Rotate, which rate-limits fresh starts, and the one-shot SSE rotate_keys event through RotateNow, which does not. The control plane keeps a rotation pending until the node confirms it, so repeated signals, retries, and the RecoverPending sweep all converge on the same crash-safe outcome.

func NewKeyRotator added in v0.2.0

func NewKeyRotator(client RotateClient, id *registration.NodeIdentity, dataDir string, device DeviceKeyUpdater, rt ReconcileTrigger, logger *slog.Logger) *KeyRotator

NewKeyRotator builds a KeyRotator that stages fresh keys under dataDir, submits their public half via client, installs the confirmed private key on device (may be nil), and triggers a reconcile through rt once a rotation commits.

func (*KeyRotator) RecoverPending added in v0.2.0

func (r *KeyRotator) RecoverPending(ctx context.Context)

RecoverPending drives staged-but-uncommitted rotations for the lifetime of ctx. A staged key that the control plane already accepted strands the node unless something resubmits it: the rotation completed server-side, so no further signal arrives, every peer holds the new public key, and the node still runs the old one. That state outlives startup — a submit whose response is lost (proxy 5xx, read timeout, reset connection) leaves exactly the same staged key at any point during the process lifetime — so this loop keeps sweeping instead of returning once nothing is staged.

While a key is staged it resubmits with a capped exponential backoff; with nothing staged it re-checks at the cap and makes no HTTP call, so an idle node never starts a rotation on its own.

func (*KeyRotator) Rotate added in v0.2.0

func (r *KeyRotator) Rotate(ctx context.Context) error

Rotate runs one single-flight rotation cycle. It stages a fresh key (or reuses one staged by an earlier attempt), submits its public half, and commits the durable identity only after the control plane confirms. A concurrent Rotate that loses the TryLock returns nil without touching the staging file, and starting a fresh rotation within minInterval of the last commit is skipped; a key already staged is always resubmitted. The outcome taxonomy over the submit result is:

  • success with a complete receipt: commit with the returned receipt;
  • success without a receipt: a control plane that predates this contract, so keep the staged key for a resubmit and return the error;
  • 422 keys_rotate_public_key_unchanged: a previous submission already landed (a crash between submit and persist), so commit with a nil receipt to keep the existing LastRotation;
  • 409 keys_rotate_no_pending_rotation: a stale or cancelled signal whose staged key never landed, so discard it and return nil;
  • a permanent rejection (400, 403, 413, 404 keys_rotate_peer_not_found, 422 keys_rotate_public_key_invalid): no retry changes the outcome, so discard the staged key and return the error;
  • anything else (auth, 5xx, transport errors): keep the staged key so RecoverPending or the next signal retries, and return the error.

func (*KeyRotator) RotateNow added in v0.2.0

func (r *KeyRotator) RotateNow(ctx context.Context) error

RotateNow runs the same rotation cycle as Rotate but starts a fresh rotation even within minInterval of the last commit. It serves the SSE rotate_keys event: the control plane sends it once per rotation decision and never repeats it, so a cooldown skip here would strand the rotation until the heartbeat flag catches up — or forever, for a control plane that signals via SSE alone. A redelivered event is harmless: with no rotation pending the submit is answered 409 keys_rotate_no_pending_rotation and the staged key is discarded without touching the device.

type MeshPeerStatsSource added in v0.10.0

type MeshPeerStatsSource interface {
	MeshPeerStats() ([]wireguard.MeshPeerStat, error)
}

MeshPeerStatsSource reads the runtime state of every mesh peer from the WireGuard device, keyed by the peer's node ID.

type ReconcileTrigger

type ReconcileTrigger interface {
	TriggerReconcile()
}

ReconcileTrigger triggers an immediate reconciliation.

type RotateClient added in v0.2.0

type RotateClient interface {
	RotateKeys(ctx context.Context, req api.KeyRotateRequest) (*api.KeyRotateResponse, error)
}

RotateClient submits a completed rotation's public key to the control plane.

Jump to

Keyboard shortcuts

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