agent

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 70 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 provides the node agent implementation.

Index

Constants

View Source
const EnrolledControllerKey = "enrolled-controller.pub"

EnrolledControllerKey is the file in agent.pki.key_dir of the controller's public key, which the agent saves when the controller admits it. It is not controller.pub: that is the name of the controller's own key pair, and the two share a directory when both run on one host with the default key_dir.

View Source
const EnrolledControllerNextKey = "enrolled-controller.next.pub"

EnrolledControllerNextKey is the file in agent.pki.key_dir of the key that the controller switches to, during a rotation of its key. The agent keeps it beside EnrolledControllerKey, so that it still has it after a restart.

View Source
const NATSJoinFile = "nats-join.json"

NATSJoinFile is the file in agent.pki.key_dir where an agent keeps what a join over NATS gave it: the server, its NATS user, and the certificate of the server. It is 0600: it holds the user's password.

Variables

View Source
var (
	// ErrJobEnvelopeMissing means the job data is not a
	// signed envelope at all, or is missing a required envelope field.
	ErrJobEnvelopeMissing = errors.New("job data is not a signed envelope")
	// ErrControllerKeyUnknown means this agent has not
	// completed enrollment, so it holds no controller public key to verify
	// against.
	ErrControllerKeyUnknown = errors.New("no cached controller public key: agent not enrolled")
	// ErrJobSignatureInvalid means the envelope signature did not verify
	// against the cached controller key (or the previous key, during a
	// rotation grace period).
	ErrJobSignatureInvalid = errors.New("invalid controller signature on job data")
)

Errors returned by unwrapJobEnvelope. Each names a distinct rejection reason so an operator reading agent logs or job termination reasons can tell an unenrolled agent apart from a forged or malformed job.

View Source
var ErrRotateRefused = errors.New("the controller refused the rotation")

ErrRotateRefused is a rotation that the controller refused. The new keys are removed, and the agent keeps its keys.

Functions

func MissingPrograms added in v0.3.0

func MissingPrograms(
	platform string,
) []string

MissingPrograms is each program a registered behavior declares, with behavior.Runs or behavior.Sudo, that the agent cannot find, once. A missing one fails only the behavior that runs it, so the agent warns rather than refusing to start, and reports the list in its registration.

func PingProblem added in v0.3.0

func PingProblem() string

PingProblem says why a ping from the agent fails, or "" when it can send one. On Linux the agent sends a ping on an ICMP datagram socket, also as root, and the kernel permits that only for the groups in net.ipv4.ping_group_range. Its default, "1 0", permits no group. A host without the setting, such as macOS, has no problem to report.

func ResolveFacts

func ResolveFacts(
	params map[string]any,
	fr *job.FactsRegistration,
	hostname string,
) (map[string]any, error)

ResolveFacts walks all string values in params and replaces @fact.X references with values from the agent's cached facts. Returns a new map with resolved values, or an error if any reference cannot be resolved.

func RotateKey added in v0.3.0

func RotateKey(
	ctx context.Context,
	log *slog.Logger,
	fs avfs.VFS,
	cfg config.Config,
) (string, error)

RotateKey replaces the agent's two keys with new ones that the controller takes in place of the admitted ones, with no new admission, and returns the fingerprint of the new keys.

It makes the new keys beside the old ones, in agent.next.*, and sends the new public keys to the controller over NATS, as the agent connects, signed with the old signing key and with the new one. When the controller takes them, it moves the new keys in place of the old ones; a running agent reads them at its next heartbeat. When the controller refuses, it removes the new keys. When the controller does not answer, it keeps them: the controller may have taken them, and a second rotation sends the same keys again.

Types

type Agent

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

Agent implements job processing with clean lifecycle management.

func New

func New(
	appFs avfs.VFS,
	appConfig config.Config,
	logger *slog.Logger,
	jobClient client.JobClient,
	streamName string,
	hostProvider nodeHost.Provider,
	diskProvider disk.Provider,
	memoryProvider memory.Provider,
	loadProvider load.Provider,
	processProvider process.Provider,
	registry *ProviderRegistry,
	registryBucket string,
	factsBucket string,
	execManager exec.Manager,
	natsClient NATSClient,
) *Agent

New creates a new agent instance.

func Setup added in v0.3.0

Setup connects to NATS as cfg.Agent.NATS tells, and makes the provider of each operation for this host. The metrics of each call to NATS go to mp, which can be nil. It returns the agent and its connection. The caller closes the connection after the agent stops.

func (*Agent) GetFacts

func (a *Agent) GetFacts() map[string]any

GetFacts returns the agent's current facts as a flat map suitable for template rendering. Returns nil if facts haven't been collected yet. Uses JSON round-trip so the map automatically includes all fields from FactsRegistration without hardcoding field names.

func (*Agent) IsReady

func (a *Agent) IsReady() error

IsReady returns nil when the agent is ready to process jobs, or an error describing why it is not.

func (*Agent) LastHeartbeatTime

func (a *Agent) LastHeartbeatTime() time.Time

LastHeartbeatTime returns the timestamp of the last successful heartbeat write. Returns zero time if no heartbeat has been written.

func (*Agent) SetLogLevel added in v0.3.0

func (a *Agent) SetLogLevel(
	level *slog.LevelVar,
)

SetLogLevel gives the agent the level of the process's logger, so that the log level of the controller's config of the agent changes it. Its level now is the level of the agent's config file.

func (*Agent) SetMeterProvider

func (a *Agent) SetMeterProvider(
	mp *sdkmetric.MeterProvider,
)

SetMeterProvider creates OTEL instruments for job metrics.

func (*Agent) SetSubComponents

func (a *Agent) SetSubComponents(
	scs map[string]job.SubComponentInfo,
)

SetSubComponents sets the sub-component info published in heartbeats.

func (*Agent) SetVersion added in v0.3.0

func (a *Agent) SetVersion(
	version string,
)

SetVersion sets the build version of the agent binary, such as v1.4.0. osapi agent start calls it with the version the binary was built with; the agent writes it in the started event of each job and in its registration.

func (*Agent) Start

func (a *Agent) Start()

Start starts the agent without blocking. Call Stop to shut down.

func (*Agent) State

func (a *Agent) State() types.AgentState

State returns the agent's scheduling state. Read by the heartbeat on its own goroutine while a drain or an enrollment acceptance writes it.

func (*Agent) Stop

func (a *Agent) Stop(
	ctx context.Context,
)

Stop gracefully shuts down the agent, waiting for in-flight jobs to finish or the context deadline to expire.

func (*Agent) SubComponents added in v0.3.0

func (a *Agent) SubComponents() map[string]job.SubComponentInfo

SubComponents returns the parts of the agent that its heartbeat and its metrics server report.

type BehaviorProviders added in v0.3.0

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

BehaviorProviders are the providers the agent built for every registered behavior on its platform, as each declares them with behavior.Platform.

func BuildBehaviorProviders added in v0.3.0

func BuildBehaviorProviders(
	h host.Host,
	logger *slog.Logger,
) *BehaviorProviders

BuildBehaviorProviders builds each behavior's provider for host's platform once, at startup, and logs the outcome. A behavior with no provider on this platform has its methods skipped; one whose provider failed to build has them fail with that error.

type JobContext

type JobContext struct {
	// JobID from the original job request
	JobID string
	// AgentHostname identifies which agent is processing this job
	AgentHostname string
	// JobData contains the raw job request data
	JobData []byte
}

JobContext contains the context and data for a single job execution.

type NATSClient added in v0.3.0

type NATSClient interface {
	PublishCore(ctx context.Context, subject string, data []byte) error
	Subscribe(
		ctx context.Context,
		subject string,
		handler natsclient.MsgHandler,
	) (*nats.Subscription, error)
	KVPut(ctx context.Context, bucket string, key string, value []byte) (uint64, error)
	KVDelete(ctx context.Context, bucket string, key string) error
	KVGet(ctx context.Context, bucket string, key string) (jetstream.KeyValueEntry, error)
}

NATSClient is the access to NATS that the agent uses itself: the core messages of enrollment, and the writes of its registration and its facts. A *natsclient.Client is one.

type ObjectReader added in v0.3.0

type ObjectReader interface {
	ObjectGetBytes(ctx context.Context, bucket string, name string) ([]byte, error)
	ObjectInfo(ctx context.Context, bucket string, name string) (*jetstream.ObjectInfo, error)
}

ObjectReader reads the objects of the Object Store bucket. A *natsclient.Client is one.

type PreflightResult

type PreflightResult struct {
	Name   string
	Passed bool
	Error  string
	Fatal  bool
}

PreflightResult holds the outcome of a single preflight check. A failed fatal check stops the agent; any other failed check is a warning, because it fails only the operations that need it.

func RunPreflight

func RunPreflight(
	ctx context.Context,
	logger *slog.Logger,
	execManager exec.Manager,
	platform string,
) ([]PreflightResult, bool)

RunPreflight checks what privilege escalation needs. It fails only when sudo cannot run without a password at all. A program with no sudo rule, or a missing capability, is a failed check that is not fatal: it fails the operations that need it, and the agent still starts. A program that is not installed is not checked, since nothing on the host can run it.

type ProcessorFunc

type ProcessorFunc func(context.Context, job.Request) (json.RawMessage, error)

ProcessorFunc is a function that handles a job request and returns a JSON-encoded result.

func NewBehaviorProcessor added in v0.3.0

func NewBehaviorProcessor(
	providers *BehaviorProviders,
	logger *slog.Logger,
) ProcessorFunc

NewBehaviorProcessor returns a ProcessorFunc that runs any registered behavior's method with the provider built for it, so a behavior needs no wiring in the agent.

func NewNodeProcessor

func NewNodeProcessor(
	_ *slog.Logger,
) ProcessorFunc

NewNodeProcessor returns a ProcessorFunc for the node category. Each node operation is a behavior now, so no hand-written one is left, and it refuses each operation.

type ProviderRegistry

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

ProviderRegistry maps job categories to processor functions.

func NewProviderRegistry

func NewProviderRegistry() *ProviderRegistry

NewProviderRegistry creates an empty ProviderRegistry.

func (*ProviderRegistry) Dispatch

func (r *ProviderRegistry) Dispatch(
	ctx context.Context,
	req job.Request,
) (json.RawMessage, error)

Dispatch routes a job request to the registered processor for its category.

func (*ProviderRegistry) Register

func (r *ProviderRegistry) Register(
	category string,
	processFn ProcessorFunc,
)

Register associates a category with a processor function.

Directories

Path Synopsis
Package identity provides machine identity resolution for the agent, including machine ID and hostname discovery.
Package identity provides machine identity resolution for the agent, including machine ID and hostname discovery.
Package mocks provides mock implementations for testing.
Package mocks provides mock implementations for testing.

Jump to

Keyboard shortcuts

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