Documentation
¶
Overview ¶
Package agent implements agent-level runtime services.
Index ¶
- Constants
- Variables
- func Jitter(d time.Duration) time.Duration
- type AgentConfig
- type CapabilityClient
- type CapabilityReporter
- type DeviceKeyUpdater
- type HandshakeReportClient
- type HandshakeReporter
- type HeartbeatClient
- type HeartbeatConfig
- type HeartbeatService
- func (s *HeartbeatService) Run(ctx context.Context) error
- func (s *HeartbeatService) SetBuildRequest(fn func() api.HeartbeatRequest)
- func (s *HeartbeatService) SetOnCredentialRefused(fn func(refused bool))
- func (s *HeartbeatService) SetOnRotateKeys(fn func())
- func (s *HeartbeatService) SetReconcileTrigger(rt ReconcileTrigger)
- type KeyRotator
- type MeshPeerStatsSource
- type ReconcileTrigger
- type RotateClient
Constants ¶
const ( // DefaultMode is the default operating mode. DefaultMode = "node" // DefaultLogLevel is the default log level. DefaultLogLevel = "info" )
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.
const DefaultHeartbeatInterval = 30 * time.Second
DefaultHeartbeatInterval is the default heartbeat interval.
const MaxCredentialProbeInterval = time.Hour
MaxCredentialProbeInterval caps the delay between two heartbeats while the heartbeat service is parked.
Variables ¶
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 ¶
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"`
DNS meshdns.Config `yaml:"dns"`
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 CapabilityClient ¶ added in v0.25.0
type CapabilityClient interface {
UpdateCapabilities(ctx context.Context, nodeID string, caps api.CapabilityManifestRequest) error
}
CapabilityClient sends the capability manifest to the control plane.
type CapabilityReporter ¶ added in v0.25.0
type CapabilityReporter struct {
// contains filtered or unexported fields
}
CapabilityReporter owns the manifest at PUT /v1/nodes/{node_id}/capabilities. It sends the manifest when Run starts, sends it again after a Notify that changed it, and retries a failed send until one is accepted. Every attempt calls build, so a retry carries the newest content. The exception is a manifest the control plane refuses for its hook metadata: while the content stays the same, the Node keeps reporting in the short form, whose entries hold a name and a checksum. The wide form goes out again when its content changes and once an hour.
DECISION: a manifest the control plane is known to hold is never re-sent. The control plane raises an integrity alert on every accepted PUT that carries a drifted hook, whether or not the manifest changed, so a repeat of an accepted manifest would only repeat the alert. The hourly attempt is the one send that no change and no failure asks for, and it runs only while plexd holds back metadata the control plane has not seen. A refused attempt stores nothing and raises no integrity alert. An accepted one delivers new content once. The accepted manifest lives in memory, so a restart always sends once.
DECISION: every failure retries, a refusal included. A refused PUT stores nothing and raises nothing at the control plane, capabilityRetryMax bounds the rate, and a control plane that gets upgraded then clears the refusal without an agent restart. The exception is a wide manifest refused per api.IsHookMetadataRefused, which is not retried on the backoff. Its short form leaves at once, and the wide form is tried on a change or hourly, bounded by capabilityWideRetry rather than capabilityRetryMax. An upgraded control plane clears that refusal without a restart too.
DECISION: the fallback keys on an HTTP refusal, not on repeated transport failures. A control-plane outage must not strip metadata from every Node on recovery, and a count of unanswered PUTs cannot tell an outage from a path that cannot carry the wide form. So a wide manifest that fails with no HTTP answer keeps retrying wide. The cost falls on a Node whose link is too slow to carry a near-budget manifest or whose proxy cuts the upload silently: its manifest stops updating until the wide form gets through.
func NewCapabilityReporter ¶ added in v0.25.0
func NewCapabilityReporter(nodeID string, client CapabilityClient, build func() api.CapabilityManifestRequest, logger *slog.Logger) *CapabilityReporter
NewCapabilityReporter creates a CapabilityReporter that reports for nodeID through client. It calls build on every attempt, always on the Run goroutine.
func (*CapabilityReporter) Notify ¶ added in v0.25.0
func (r *CapabilityReporter) Notify()
Notify asks for an attempt once the quiet period ends. It never blocks, so it is safe to call from the hook watcher's onChange and before Run starts or after it ends.
func (*CapabilityReporter) Run ¶ added in v0.25.0
func (r *CapabilityReporter) Run(ctx context.Context) error
Run makes one attempt with no quiet period, so a failed boot PUT retries, and then attempts on every notification and whenever the retry timer or the wide timer fires, until ctx is cancelled. Run always returns nil.
type DeviceKeyUpdater ¶ added in v0.2.0
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.