job

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: 18 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 job provides NATS subject hierarchy for distributed job routing.

Subject Format: [namespace.]jobs.{type}.{routing_type}.{value...}

Routing Patterns:

  • Direct: jobs.query.host.<machineID> (specific host by machine ID)
  • Any: jobs.query._any (load-balanced across available agents)
  • Broadcast: jobs.modify._all (all agents receive)
  • Label: jobs.query.label.group.web (broadcast to label group)
  • Hierarchical: jobs.query.label.group.web.dev.us-east (prefix matching)

Agents subscribe to:

  • Their machine ID: jobs.*.host.<machineID> (permanent, never changes)
  • Load-balanced work: jobs.*._any (with queue group)
  • Broadcast messages: jobs.*._all
  • Label prefixes: jobs.*.label.group.web, jobs.*.label.group.web.dev, etc.

The controller resolves hostname targets to machine IDs before building subjects. This ensures direct routing uses the permanent machine ID, not the mutable hostname.

When a namespace is configured via Init(), all subjects are prefixed:

Init("osapi") -> osapi.jobs.query._any, osapi.jobs.*.host.<machineID>, etc.

Index

Constants

View Source
const (
	// AllHosts is a wildcard for targeting all hosts.
	AllHosts = "*"
	// AnyHost is load-balanced across available hosts.
	AnyHost = types.TargetAny
	// LocalHost targets the API server's host.
	LocalHost = "_local"
	// BroadcastHost broadcasts to all hosts (no queue group).
	BroadcastHost = types.TargetAll
)
View Source
const (
	SubjectCategoryNode    = "node"
	SubjectCategoryNetwork = "network"
	SubjectCategoryDocker  = "docker"
)

Subject categories for different operations

View Source
const (
	NodeOperationHostname = "hostname"
	NodeOperationStatus   = "status"
)

Node operation types

View Source
const (
	NetworkOperationDNS  = "dns"
	NetworkOperationPing = "ping"
)

Network operation types

View Source
const CategoryBehavior = "behavior"

CategoryBehavior is the job category every registered behavior runs under. Its operation is "<behavior>.<method>", such as "sysctl.get".

Variables

View Source
var (
	// ErrNotFound corresponds to ErrorCodeNotFound.
	ErrNotFound = errors.New("not found")
	// ErrNotManaged corresponds to ErrorCodeNotManaged.
	ErrNotManaged = errors.New("not managed by osapi")
	// ErrNotInstalled corresponds to ErrorCodeNotInstalled.
	ErrNotInstalled = errors.New("not installed")
	// ErrInvalid corresponds to ErrorCodeInvalid.
	ErrInvalid = errors.New("invalid input")
	// ErrUnsupported corresponds to ErrorCodeUnsupported.
	ErrUnsupported = errors.New("operation not supported on this OS family")

	// ErrTimeout corresponds to ErrorCodeTimeout: the agent never answered,
	// which is not the same as an operation that ran and failed.
	ErrTimeout = errors.New("agent did not respond")

	// ErrNoOperationData means a stored job carries nothing to re-dispatch, so
	// it cannot be retried. Not a missing job: the record is there and unusable,
	// which the API answers with 400 rather than 404.
	ErrNoOperationData = errors.New("job has no operation data")
)

The causes a handler can distinguish, as errors, because that is the shape Go code already knows how to test. A failed job's error wraps whichever one its code names, so a handler asks errors.Is rather than reading the message.

View Source
var (
	// JobsQueryPrefix is the subject hierarchy prefix for query operations.
	JobsQueryPrefix = "jobs.query"
	// JobsModifyPrefix is the subject hierarchy prefix for modify operations.
	JobsModifyPrefix = "jobs.modify"
)

StatusPriority is the rank of each status event of a host, which the controller uses to compute the state of the host from append-only events. A higher rank takes precedence: a completed event (4) is never overwritten by a started event (2) that sorts later in KV.

Functions

func AgentConfigKey added in v0.3.0

func AgentConfigKey(
	machineID string,
) string

AgentConfigKey is the key of the config of the agent with machineID in the state bucket.

func ApplyNamespaceToInfraName

func ApplyNamespaceToInfraName(
	namespace, name string,
) string

ApplyNamespaceToInfraName prefixes an infrastructure name (stream, KV bucket) with the namespace. Returns the name unchanged if namespace is empty.

ApplyNamespaceToInfraName("", "JOBS")      -> "JOBS"
ApplyNamespaceToInfraName("osapi", "JOBS")  -> "osapi-JOBS"

func ApplyNamespaceToSubjects

func ApplyNamespaceToSubjects(
	namespace, subjects string,
) string

ApplyNamespaceToSubjects prefixes a subject filter with the namespace. Returns the subject unchanged if namespace is empty.

ApplyNamespaceToSubjects("", "jobs.>")      -> "jobs.>"
ApplyNamespaceToSubjects("osapi", "jobs.>")  -> "osapi.jobs.>"

func BuildSubjectFromTarget

func BuildSubjectFromTarget(
	prefix, target string,
) string

BuildSubjectFromTarget builds the full NATS subject for any target value. For label targets with hierarchical values (e.g., "group:web.dev"), each dot-separated segment becomes a subject token: jobs.query.label.group.web.dev

func EffectiveState added in v0.3.0

func EffectiveState(
	reported types.AgentState,
	drainFlag bool,
) types.AgentState

EffectiveState is the scheduling state of an agent as the controller reports it, from the state the agent reported and whether its drain flag is set. A drain that the agent has not applied yet is Draining: the flag asks it to stop taking jobs, but it may still be running them, so it is not Cordoned until the agent says so. Otherwise it is the state the agent reported, and an agent that reported none is Ready.

func ExpectedAgentHostnames

func ExpectedAgentHostnames(
	agents []AgentInfo,
	target string,
) []string

ExpectedAgentHostnames returns the hostnames of agents expected to respond to a broadcast target. Uses the same filtering logic as CountExpectedAgents.

func FactKeys added in v0.3.0

func FactKeys() []string

FactKeys are the keys that a template reads under .Facts: the JSON names of FactsRegistration, as the agent hands its facts to a provider. facts holds what each collector adds, under its own keys.

func GetAgentHostname

func GetAgentHostname(
	configuredHostname string,
) (string, error)

GetAgentHostname returns the hostname that should be used by agents. It first checks the configured hostname, then falls back to the host's name from gohai.

func Init

func Init(
	namespace string,
)

Init configures the subject namespace. An empty namespace keeps the default "jobs.*" hierarchy. A non-empty namespace prepends it:

Init("")      -> jobs.query, jobs.modify
Init("osapi") -> osapi.jobs.query, osapi.jobs.modify

func IsBroadcastTarget

func IsBroadcastTarget(
	target string,
) bool

IsBroadcastTarget returns true if the target requires publishAndCollect (broadcast) semantics: _all or any key:value label target.

func ParseSubject

func ParseSubject(
	subject string,
) (prefix, hostname string, err error)

ParseSubject extracts the prefix and routing target from a job subject. Supported formats (with optional namespace prefix):

  • [ns.]jobs.{type}._any
  • [ns.]jobs.{type}._all
  • [ns.]jobs.{type}.host.{hostname}
  • [ns.]jobs.{type}.label.{key}.{value...}

func ParseTarget

func ParseTarget(
	target string,
) (routingType, key, value string)

ParseTarget parses a --target value into routing components. Returns routingType ("host", "label", AnyHost, or BroadcastHost), key, and value. Label values may contain dots for hierarchical targeting (e.g., "group:web.dev.us-east").

func RegistrationSigningBytes

func RegistrationSigningBytes(
	reg *AgentRegistration,
) []byte

RegistrationSigningBytes returns the canonical bytes an agent signs when it registers, and the controller verifies before letting a registration decide where work goes.

Only the fields that decide routing are covered, and every one of them is covered:

  • machine ID, because it selects the stored key the signature is checked against
  • hostname, because a target names it
  • fingerprint, because the fleet view reports it as this agent's key
  • state, because a Pending agent is refused work and a forged Ready would lift that
  • labels, because a label target routes on them, so an unsigned label is a way to attract another host's jobs
  • the controller keys, because the controller switches its key when each agent reports the next one. Each is in the bytes only when it is set, so a registration without them has the bytes that it had before.

The signature itself is excluded: it is carried beside these bytes, never inside them. Everything else in a registration — uptime, load, memory, conditions — is reporting rather than routing, and moves on every heartbeat.

The encoding is built field by field in a fixed order with the labels sorted, rather than marshalled, so that both sides derive the same bytes no matter how a struct field is ordered or a map is walked.

func SanitizeHostname

func SanitizeHostname(
	hostname string,
) string

SanitizeHostname converts a hostname to a valid NATS consumer/routing name. NATS consumer names and routing must be alphanumeric with underscores only.

func VerifyRegistration

func VerifyRegistration(
	reg *AgentRegistration,
	pubKey ed25519.PublicKey,
) bool

VerifyRegistration reports whether the registration's signature was produced by pubKey over its canonical bytes.

It answers one question only. Whether pubKey is the right key for this agent is the caller's to establish from the store, and an unsigned registration is not verified.

Types

type AgentConfig added in v0.3.0

type AgentConfig struct {
	// Version is one more at each change, and 0 when nothing was set.
	Version int `json:"version"`
	// Labels replace the labels of the agent's config file with the same
	// keys.
	Labels map[string]string `json:"labels,omitempty"`
	// MaxJobs replaces the max_jobs of the agent's config file, and 0 keeps
	// it.
	MaxJobs int `json:"max_jobs,omitempty"`
	// LogLevel is the level that the agent logs at, debug, info, warn or
	// error, and empty keeps the level of its config file.
	LogLevel types.LogLevel `json:"log_level,omitempty"`
	// FactsInterval is how often the agent collects its facts, as a Go
	// duration, and empty keeps the interval of its config file.
	FactsInterval string `json:"facts_interval,omitempty"`
	// UpdatedAt is when the config last changed.
	UpdatedAt time.Time `json:"updated_at,omitzero"`
}

AgentConfig is the config of an agent that the controller holds, under the agent's machine ID: what an operator set for the agent without its config file. The agent watches it, and applies a change at once.

type AgentInfo

type AgentInfo struct {
	// MachineID is the permanent host identifier.
	MachineID string `json:"machine_id"`
	// Hostname is the hostname of the agent.
	Hostname string `json:"hostname"`
	// Labels are the key-value labels configured on the agent.
	Labels map[string]string `json:"labels,omitempty"`
	// RegisteredAt is the timestamp when the agent last registered (heartbeat).
	RegisteredAt time.Time `json:"registered_at"`
	// StartedAt is the timestamp when the agent process started.
	StartedAt time.Time `json:"started_at"`
	// OSInfo contains operating system information.
	OSInfo *host.Result `json:"os_info,omitempty"`
	// Uptime is the system uptime.
	Uptime time.Duration `json:"uptime,omitempty"`
	// LoadAverages contains the system load averages.
	LoadAverages *load.Result `json:"load_averages,omitempty"`
	// MemoryStats contains memory usage information.
	MemoryStats *memory.Result `json:"memory_stats,omitempty"`
	// AgentVersion is the version of the agent binary.
	AgentVersion string `json:"agent_version,omitempty"`
	// ConfigVersion is the version of the controller's config of the agent
	// that the agent applied, 0 for none.
	ConfigVersion int `json:"config_version,omitempty"`
	// ControllerKey is the fingerprint of the controller key that the agent
	// verifies jobs with.
	ControllerKey string `json:"controller_key,omitempty"`
	// ControllerKeyNext is the fingerprint of the key that the controller
	// switches to, as the agent reports it during a rotation.
	ControllerKeyNext string `json:"controller_key_next,omitempty"`
	// NATSCertNext is the fingerprint of the NATS server's next certificate,
	// which the agent trusts during a rotation of it: empty when no rotation
	// is in progress, or the agent does not trust it yet.
	NATSCertNext string `json:"nats_cert_next,omitempty"`
	// MissingPrograms are the programs that the agent's behaviors declare
	// and that the host lacks.
	MissingPrograms []string `json:"missing_programs,omitempty"`
	// Architecture is the CPU architecture (e.g., x86_64, aarch64).
	Architecture string `json:"architecture,omitempty"`
	// KernelVersion is the kernel version string.
	KernelVersion string `json:"kernel_version,omitempty"`
	// CPUCount is the number of logical CPUs.
	CPUCount int `json:"cpu_count,omitempty"`
	// FQDN is the fully qualified domain name.
	FQDN string `json:"fqdn,omitempty"`
	// ServiceMgr is the init/service manager (e.g., systemd).
	ServiceMgr string `json:"service_mgr,omitempty"`
	// PackageMgr is the package manager (e.g., apt, yum).
	PackageMgr string `json:"package_mgr,omitempty"`
	// Interfaces contains network interface information.
	Interfaces []NetworkInterface `json:"interfaces,omitempty"`
	// PrimaryInterface is the name of the interface used for the default route.
	PrimaryInterface string `json:"primary_interface,omitempty"`
	// Routes contains the network routing table.
	Routes []Route `json:"routes,omitempty"`
	// Facts contains arbitrary key-value facts collected by the agent.
	Facts map[string]any `json:"facts,omitempty"`
	// Conditions contains the evaluated node conditions.
	Conditions []Condition `json:"conditions,omitempty"`
	// State is the agent's scheduling state (Ready, Draining, Cordoned, Pending).
	State types.AgentState `json:"state,omitempty"`
	// Fingerprint is the SHA256 fingerprint of the agent's PKI public key.
	// Empty until the agent loads its keys.
	Fingerprint string `json:"fingerprint,omitempty"`
	// Certificates are the certificates that the agent serves.
	Certificates []pki.Cert `json:"certificates,omitempty"`
	// Timeline contains the chronological sequence of state transition events.
	Timeline []TimelineEvent `json:"timeline,omitempty"`
	// Verified reports whether this registration's signature checked out
	// against the key stored for its machine ID. Only a verified registration
	// may decide where work goes. True when the controller is not enforcing,
	// which is the behaviour before verification existed.
	Verified bool `json:"verified"`
	// KeyStored reports whether the controller holds a key for this agent at
	// all, so an operator can tell an agent that has not re-enrolled from one
	// whose registration is being forged.
	KeyStored bool `json:"key_stored"`
}

AgentInfo represents information about an active agent.

func Recipients added in v0.3.0

func Recipients(
	agents []AgentInfo,
	target string,
	resolved string,
) []AgentInfo

Recipients are the agents that a job to target can reach: each agent that takes jobs for _all, _any or a label, and the agent whose machine ID is resolved, or whose hostname is target, for one host. The controller seals the secrets of the job to each of them.

type AgentRegistration

type AgentRegistration struct {
	// MachineID is the permanent host identifier.
	MachineID string `json:"machine_id"`
	// Hostname is the hostname of the agent.
	Hostname string `json:"hostname"`
	// Labels are the key-value labels configured on the agent.
	Labels map[string]string `json:"labels,omitempty"`
	// RegisteredAt is the timestamp when the agent last registered.
	RegisteredAt time.Time `json:"registered_at"`
	// StartedAt is the timestamp when the agent process started.
	StartedAt time.Time `json:"started_at"`
	// OSInfo contains operating system information.
	OSInfo *host.Result `json:"os_info,omitempty"`
	// Uptime is the system uptime.
	Uptime time.Duration `json:"uptime,omitempty"`
	// LoadAverages contains the system load averages.
	LoadAverages *load.Result `json:"load_averages,omitempty"`
	// MemoryStats contains memory usage information.
	MemoryStats *memory.Result `json:"memory_stats,omitempty"`
	// AgentVersion is the version of the agent binary.
	AgentVersion string `json:"agent_version,omitempty"`
	// ConfigVersion is the version of the controller's config of the agent
	// that the agent applied, 0 for none.
	ConfigVersion int `json:"config_version,omitempty"`
	// MissingPrograms are the programs that the agent's behaviors declare
	// and that the host lacks.
	MissingPrograms []string `json:"missing_programs,omitempty"`
	// Process holds process-level resource usage.
	Process *ProcessMetrics `json:"process,omitempty"`
	// Conditions contains the evaluated node conditions.
	Conditions []Condition `json:"conditions,omitempty"`
	// State is the agent's scheduling state (Ready, Draining, Cordoned, Pending).
	State types.AgentState `json:"state,omitempty"`
	// Fingerprint is the SHA256 fingerprint of the agent's PKI public key.
	// Empty until the agent loads its keys.
	Fingerprint string `json:"fingerprint,omitempty"`
	// Certificates are the certificates that the agent serves, such as the
	// one of its metrics server, read at each heartbeat.
	Certificates []pki.Cert `json:"certificates,omitempty"`
	// ControllerKey is the fingerprint of the controller key that the agent
	// verifies jobs with.
	ControllerKey string `json:"controller_key,omitempty"`
	// ControllerKeyNext is the fingerprint of the key that the controller
	// switches to, which the agent has from the rotation record: empty when
	// no rotation is in progress, or the agent has not read it yet.
	ControllerKeyNext string `json:"controller_key_next,omitempty"`
	// NATSCertNext is the fingerprint of the NATS server's next certificate,
	// which the agent trusts during a rotation of it: empty when no rotation
	// is in progress, or the agent does not trust it yet.
	NATSCertNext string `json:"nats_cert_next,omitempty"`
	// SubComponents reports the status of internal services.
	SubComponents map[string]SubComponentInfo `json:"sub_components,omitempty"`
	// Signature is the agent's Ed25519 signature over the routing fields of
	// this registration, as RegistrationSigningBytes encodes them. Empty before
	// the agent loads its keys, and then unverifiable rather than trusted.
	Signature []byte `json:"signature,omitempty"`
}

AgentRegistration represents an agent's registration entry in the KV registry.

type AgentState

type AgentState struct {
	Status    types.AgentJobStatus `json:"status"`
	Error     string               `json:"error,omitempty"`
	Duration  string               `json:"duration,omitempty"`
	StartTime time.Time            `json:"start_time,omitempty"`
	EndTime   time.Time            `json:"end_time,omitempty"`
}

AgentState represents the state of a specific agent processing a job

type ComponentRegistration

type ComponentRegistration struct {
	// Type is the component type: "controller" or "nats".
	Type string `json:"type"`
	// Hostname is the hostname of the component.
	Hostname string `json:"hostname"`
	// StartedAt is the timestamp when the component process started.
	StartedAt time.Time `json:"started_at"`
	// RegisteredAt is the timestamp of the last heartbeat.
	RegisteredAt time.Time `json:"registered_at"`
	// Process holds process-level resource usage.
	Process *ProcessMetrics `json:"process,omitempty"`
	// Conditions contains evaluated process conditions.
	Conditions []Condition `json:"conditions,omitempty"`
	// Version is the component binary version.
	Version string `json:"version,omitempty"`
	// SubComponents reports the status of internal services.
	SubComponents map[string]SubComponentInfo `json:"sub_components,omitempty"`
}

ComponentRegistration represents a non-agent component's heartbeat entry in the KV registry. Used by API server and NATS server.

type Condition

type Condition struct {
	Type               types.ConditionType `json:"type"`
	Status             bool                `json:"status"`
	Reason             string              `json:"reason,omitempty"`
	LastTransitionTime time.Time           `json:"last_transition_time"`
}

Condition represents a node condition evaluated agent-side.

type DeadLetter added in v0.3.0

type DeadLetter struct {
	// Seq is the dead letter's sequence in the dead letter stream.
	Seq uint64 `json:"seq"`
	// Time is when NATS gave up on the delivery.
	Time time.Time `json:"time"`
	// JobID is the job that the delivery carried, or empty when the job
	// stream no longer has its message.
	JobID string `json:"job_id,omitempty"`
	// Consumer is the consumer of the agents that the delivery was for.
	Consumer string `json:"consumer"`
	// Deliveries is how often NATS delivered it.
	Deliveries uint64 `json:"deliveries"`
	// StreamSeq is the sequence of the job's message in the job stream.
	StreamSeq uint64 `json:"stream_seq"`
}

DeadLetter is a job whose delivery to an agent used up its retries: the advisory that NATS wrote to the dead letter stream when a consumer reached its max deliveries, with the job that the delivery carried.

type ErrorCode

type ErrorCode string

ErrorCode names the cause of a failed job in a form that survives the trip from the agent to the controller. The message beside it is for a person; the code is what the API switches on.

const (
	// ErrorCodeNotFound means the thing the request named is not on the host.
	ErrorCodeNotFound ErrorCode = "not_found"
	// ErrorCodeNotManaged means it exists but osapi did not deploy it.
	ErrorCodeNotManaged ErrorCode = "not_managed"
	// ErrorCodeNotInstalled means a program the operation depends on is absent.
	ErrorCodeNotInstalled ErrorCode = "not_installed"
	// ErrorCodeInvalid means the host refuses the input.
	ErrorCodeInvalid ErrorCode = "invalid"
	// ErrorCodeUnsupported means the operation does not apply to this OS family.
	ErrorCodeUnsupported ErrorCode = "unsupported"
	// ErrorCodeTimeout means the agent never answered.
	ErrorCodeTimeout ErrorCode = "timeout"
)

type FactsRegistration

type FactsRegistration struct {
	Architecture     string             `json:"architecture,omitempty"`
	KernelVersion    string             `json:"kernel_version,omitempty"`
	CPUCount         int                `json:"cpu_count,omitempty"`
	FQDN             string             `json:"fqdn,omitempty"`
	ServiceMgr       string             `json:"service_mgr,omitempty"`
	PackageMgr       string             `json:"package_mgr,omitempty"`
	Containerized    bool               `json:"containerized"`
	Interfaces       []NetworkInterface `json:"interfaces,omitempty"`
	PrimaryInterface string             `json:"primary_interface,omitempty"`
	Routes           []Route            `json:"routes,omitempty"`
	Facts            map[string]any     `json:"facts,omitempty"`
}

FactsRegistration represents an agent's facts entry in the facts KV bucket.

type FileState

type FileState struct {
	ObjectName   string            `json:"object_name"`
	Path         string            `json:"path"`
	SHA256       string            `json:"sha256"`
	Mode         string            `json:"mode,omitempty"`
	Owner        string            `json:"owner,omitempty"`
	Group        string            `json:"group,omitempty"`
	DeployedAt   string            `json:"deployed_at"`
	ContentType  types.ContentType `json:"content_type"`
	UndeployedAt string            `json:"undeployed_at,omitempty"`
	Metadata     map[string]string `json:"metadata,omitempty"`
}

FileState represents a deployed file's state in the file-state KV. Keyed by <hostname>.<sha256-of-path>.

type HostnameProvider

type HostnameProvider interface {
	Hostname() (string, error)
}

HostnameProvider defines the interface for getting hostname

type NetworkInterface

type NetworkInterface struct {
	Name   string `json:"name"`
	IPv4   string `json:"ipv4,omitempty"`
	IPv6   string `json:"ipv6,omitempty"`
	MAC    string `json:"mac,omitempty"`
	Family string `json:"family,omitempty"`
}

NetworkInterface represents a network interface with its address.

type NodeDiskResponse

type NodeDiskResponse struct {
	Disks []disk.Result `json:"disks"`
}

NodeDiskResponse represents the response for node.disk.get operations.

type NodeHostnameGetData

type NodeHostnameGetData struct {
}

NodeHostnameGetData represents data for hostname retrieval

type NodeShutdownData

type NodeShutdownData struct {
	// Action specifies whether to reboot or shutdown the system
	Action string `json:"action"` // "reboot" or "shutdown"
	// DelaySeconds is an optional field to specify a delay in seconds before reboot/shutdown
	DelaySeconds int32 `json:"delay_seconds,omitempty"`
	// Message is an optional message to log or display before reboot/shutdown
	Message string `json:"message,omitempty"`
}

NodeShutdownData represents data for node shutdown/reboot operations

type NodeUptimeResponse

type NodeUptimeResponse struct {
	UptimeSeconds float64 `json:"uptime_seconds"`
	Uptime        string  `json:"uptime"`
}

NodeUptimeResponse represents the response for node.uptime.get operations.

type Operation

type Operation struct {
	// Type specifies the type of operation using hierarchical format
	// (e.g., "node.hostname.get", "network.dns.update")
	Type OperationType `json:"type"`
	// Data contains the operation-specific data as raw JSON
	Data json.RawMessage `json:"data"`
}

Operation represents an operation in the new hierarchical format

type OperationType

type OperationType = string

OperationType is the operation of a job, in dot notation, such as behavior.dns.update.

type ProcessMetrics

type ProcessMetrics struct {
	// CPUPercent is the process CPU usage as a percentage.
	CPUPercent float64 `json:"cpu_percent"`
	// RSSBytes is the resident set size in bytes.
	RSSBytes int64 `json:"rss_bytes"`
	// Goroutines is the number of active goroutines.
	Goroutines int `json:"goroutines"`
}

ProcessMetrics holds process-level resource usage.

type QueueStats

type QueueStats struct {
	TotalJobs    int                     `json:"total_jobs"`
	StatusCounts map[types.JobStatus]int `json:"status_counts"`
	DLQCount     int                     `json:"dlq_count"`
}

QueueStats represents statistics about the job queue.

type QueuedJob

type QueuedJob struct {
	// ID is the unique identifier for this job
	ID string `json:"id"`
	// Status is the status of the job, computed from its status events.
	Status types.JobStatus `json:"status"`
	// Created is the timestamp when the job was created
	Created string `json:"created"`
	// Subject is the NATS subject for this job (optional)
	Subject string `json:"subject,omitempty"`
	// Target is the target the request gave, such as _all, a hostname or a
	// label, as the controller stored it with the job.
	Target string `json:"target,omitempty"`
	// Operation contains the actual work to be performed (stored as flexible JSON)
	Operation map[string]interface{} `json:"operation"`
	// StatusHistory tracks status transitions (optional)
	StatusHistory []interface{} `json:"status_history,omitempty"`
	// Result contains the output when the job is completed (optional)
	Result json.RawMessage `json:"result,omitempty"`
	// Changed indicates whether the operation modified system state.
	// Nil for query operations; set for mutation operations.
	Changed *bool `json:"changed,omitempty"`
	// Error contains error details if the job failed (optional)
	Error string `json:"error,omitempty"`
	// Hostname identifies which agent processed this job (optional)
	Hostname string `json:"hostname,omitempty"`
	// UpdatedAt is the timestamp when the job was last updated (optional)
	UpdatedAt string `json:"updated_at,omitempty"`
	// AgentStates contains detailed state for each agent that processed this job
	AgentStates map[string]AgentState `json:"agent_states,omitempty"`
	// Timeline contains the chronological sequence of events for this job
	Timeline []TimelineEvent `json:"timeline,omitempty"`
	// Responses contains the actual response data from each agent
	Responses map[string]Response `json:"responses,omitempty"`
}

QueuedJob represents a job stored in the KV queue with metadata

type Request

type Request struct {
	// JobID is a unique identifier for this job.
	JobID string `json:"job_id"`
	// Type specifies whether this is a query or modify operation.
	Type types.JobType `json:"type"`
	// Category specifies the operation category (node, network, etc.).
	Category string `json:"category"`
	// Operation specifies the specific operation to perform.
	Operation OperationType `json:"operation"`
	// Data contains operation-specific parameters as raw JSON.
	Data json.RawMessage `json:"data,omitempty"`
	// SealedKeys is the job key, sealed to each target agent, by machine
	// ID, when Data has sealed secrets. Empty when it has none.
	SealedKeys map[string]string `json:"sealed_keys,omitempty"`
	// SealedFrom is the public P-256 key that sealed each job key, which
	// an agent needs to open its own.
	SealedFrom string `json:"sealed_from,omitempty"`
	// Timestamp indicates when the request was created.
	Timestamp time.Time `json:"timestamp"`
}

Request represents a request to perform a job operation.

type Response

type Response struct {
	// JobID matches the original job ID.
	JobID string `json:"job_id"`
	// Status is how the job ended on the host.
	Status types.AgentJobStatus `json:"status"`
	// Data contains the operation results as raw JSON.
	Data json.RawMessage `json:"data,omitempty"`
	// Error contains error information if the job failed.
	Error string `json:"error,omitempty"`
	// ErrorCode names the cause of the failure, so the controller can answer
	// differently without reading the message. Empty when the failure has no
	// cause the API distinguishes.
	ErrorCode ErrorCode `json:"error_code,omitempty"`
	// Changed indicates whether the operation modified system state.
	// Nil for query operations; set for mutation operations.
	Changed *bool `json:"changed,omitempty"`
	// Steps are the calls of other behaviors that the job's method made on
	// the host, also when one failed. Empty for a method that calls none.
	Steps []types.Step `json:"steps,omitempty"`
	// Hostname identifies which agent processed this job.
	Hostname string `json:"hostname"`
	// Timestamp indicates when the response was created.
	Timestamp time.Time `json:"timestamp"`
	// MachineID is the machine whose stored key verified the response. The
	// controller sets it after verification; the payload cannot.
	MachineID string `json:"-"`
}

Response represents the response from a job operation.

type ResponseError

type ResponseError struct {
	// Code names the cause, empty when the agent reported none.
	Code ErrorCode
	// Message is what the provider said, unchanged.
	Message string
	// Hostname is the agent that answered.
	Hostname string
}

ResponseError is the error a failed job becomes on the controller. It carries the agent's message for the reader and the code for the handler.

func NewResponseError

func NewResponseError(
	resp *Response,
) *ResponseError

NewResponseError builds the error for a failed response.

func (*ResponseError) Error

func (e *ResponseError) Error() string

Error reads the way the string it replaces did, so an operator sees no change in what a failed job says.

func (*ResponseError) Is

func (e *ResponseError) Is(
	target error,
) bool

Is reports whether this failure has the cause the caller is asking about, which is how a handler chooses a status code.

type Route

type Route struct {
	Destination string `json:"destination"`
	Gateway     string `json:"gateway"`
	Interface   string `json:"interface"`
	Mask        string `json:"mask,omitempty"`
	Metric      int    `json:"metric,omitempty"`
}

Route represents a network routing table entry.

type SignedEnvelope

type SignedEnvelope struct {
	// Payload is the raw JSON payload (job data or response data).
	Payload []byte `json:"payload"`
	// Signature is the Ed25519 signature of the payload.
	Signature []byte `json:"signature"`
	// Fingerprint is the SHA256 fingerprint of the signer's public key.
	Fingerprint string `json:"fingerprint"`
	// MachineID identifies the signer so a verifier can find the key to
	// check the signature against. It is self-reported and therefore only
	// an index: it selects which stored record to verify against, and a
	// signature that does not match that record's key is rejected. Empty
	// for controller-signed payloads, which agents verify against the
	// controller key they were given at enrollment.
	MachineID string `json:"machine_id,omitempty"`
}

SignedEnvelope wraps a job or response payload with an Ed25519 signature.

type SubComponentInfo

type SubComponentInfo struct {
	// Status is the sub-component status (e.g., "ok", "disabled").
	Status string `json:"status"`
	// Address is the optional network endpoint (e.g., "http://0.0.0.0:9090").
	Address string `json:"address,omitempty"`
	// URL is where a person opens the sub-component, from its url config key.
	// An agent of an older version sends none.
	URL string `json:"url,omitempty"`
}

SubComponentInfo holds the status and optional address of a sub-component.

type TimelineEvent

type TimelineEvent struct {
	Timestamp time.Time `json:"timestamp"`
	Event     string    `json:"event"`
	Hostname  string    `json:"hostname"`
	Message   string    `json:"message"`
	Error     string    `json:"error,omitempty"`
}

TimelineEvent represents a single event in the job timeline

Directories

Path Synopsis
Package client provides job client operations for NATS JetStream.
Package client provides job client operations for NATS JetStream.
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
hostname
Package hostname provides mock implementations for HostnameProvider testing.
Package hostname provides mock implementations for HostnameProvider testing.

Jump to

Keyboard shortcuts

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