osapi

package
v0.0.0-...-4c6ff51 Latest Latest
Warning

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

Go to latest
Published: Mar 8, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package osapi provides a Go SDK for the OSAPI REST API.

Create a client with New() and use the domain-specific services to interact with the API:

client := osapi.New("http://localhost:8080", "your-jwt-token")

// Get hostname
resp, err := client.Node.Hostname(ctx, "_any")

// Execute a command
resp, err := client.Node.Exec(ctx, osapi.ExecRequest{
    Command: "uptime",
    Target:  "_all",
})

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	StatusCode int
	Message    string
}

APIError is the base error type for OSAPI API errors.

func (*APIError) Error

func (e *APIError) Error() string

Error returns a formatted error string.

type Agent

type Agent struct {
	Hostname         string
	Status           string
	State            string
	Labels           map[string]string
	Architecture     string
	CPUCount         int
	Fqdn             string
	KernelVersion    string
	PackageMgr       string
	ServiceMgr       string
	LoadAverage      *LoadAverage
	Memory           *Memory
	OSInfo           *OSInfo
	PrimaryInterface string
	Interfaces       []NetworkInterface
	Routes           []Route
	Conditions       []Condition
	Timeline         []TimelineEvent
	Uptime           string
	StartedAt        time.Time
	RegisteredAt     time.Time
	Facts            map[string]any
}

Agent represents a registered OSAPI agent.

type AgentJobResponse

type AgentJobResponse struct {
	Hostname string
	Status   string
	Error    string
	Data     any
}

AgentJobResponse represents an agent's response data for a broadcast job.

type AgentList

type AgentList struct {
	Agents []Agent
	Total  int
}

AgentList is a collection of agents.

type AgentService

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

AgentService provides agent discovery and details operations.

func (*AgentService) Drain

func (s *AgentService) Drain(
	ctx context.Context,
	hostname string,
) (*Response[MessageResponse], error)

Drain initiates draining of an agent, stopping it from accepting new jobs while allowing in-flight jobs to complete.

func (*AgentService) Get

func (s *AgentService) Get(
	ctx context.Context,
	hostname string,
) (*Response[Agent], error)

Get retrieves detailed information about a specific agent by hostname.

func (*AgentService) List

func (s *AgentService) List(
	ctx context.Context,
) (*Response[AgentList], error)

List retrieves all active agents.

func (*AgentService) Undrain

func (s *AgentService) Undrain(
	ctx context.Context,
	hostname string,
) (*Response[MessageResponse], error)

Undrain resumes job acceptance on a drained agent.

type AgentState

type AgentState struct {
	Status   string
	Duration string
	Error    string
}

AgentState represents an agent's processing state for a broadcast job.

type AgentStats

type AgentStats struct {
	Total  int
	Ready  int
	Agents []AgentSummary
}

AgentStats represents agent statistics from the health endpoint.

type AgentSummary

type AgentSummary struct {
	Hostname   string
	Labels     string
	Registered string
}

AgentSummary represents a summary of an agent from the health endpoint.

type AuditEntry

type AuditEntry struct {
	ID           string
	Timestamp    time.Time
	User         string
	Roles        []string
	Method       string
	Path         string
	ResponseCode int
	DurationMs   int64
	SourceIP     string
	OperationID  string
}

AuditEntry represents a single audit log entry.

type AuditList

type AuditList struct {
	Items      []AuditEntry
	TotalItems int
}

AuditList is a paginated list of audit entries.

type AuditService

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

AuditService provides audit log operations.

func (*AuditService) Export

func (s *AuditService) Export(
	ctx context.Context,
) (*Response[AuditList], error)

Export retrieves all audit log entries for export.

func (*AuditService) Get

func (s *AuditService) Get(
	ctx context.Context,
	id string,
) (*Response[AuditEntry], error)

Get retrieves a single audit log entry by ID.

func (*AuditService) List

func (s *AuditService) List(
	ctx context.Context,
	limit int,
	offset int,
) (*Response[AuditList], error)

List retrieves audit log entries with pagination.

type AuthError

type AuthError struct {
	APIError
}

AuthError represents authentication/authorization errors (401, 403).

func (*AuthError) Unwrap

func (e *AuthError) Unwrap() error

Unwrap returns the underlying APIError.

type Client

type Client struct {
	// Agent provides agent discovery and details operations.
	Agent *AgentService

	// Node provides node management operations (hostname, status, disk,
	// memory, load, OS, uptime, network DNS/ping, command exec/shell).
	Node *NodeService

	// Job provides job queue operations (create, get, list, delete, retry).
	Job *JobService

	// Health provides health check operations (liveness, readiness, status).
	Health *HealthService

	// Audit provides audit log operations (list, get, export).
	Audit *AuditService

	// Metrics provides Prometheus metrics access.
	Metrics *MetricsService

	// File provides file management operations (upload, list, get, delete).
	File *FileService
	// contains filtered or unexported fields
}

Client is the top-level OSAPI SDK client. Use New() to create one.

func New

func New(
	baseURL string,
	bearerToken string,
	opts ...Option,
) *Client

New creates an OSAPI SDK client.

type Collection

type Collection[T any] struct {
	Results []T
	JobID   string
}

Collection is a generic wrapper for collection responses from node queries.

type CommandResult

type CommandResult struct {
	Hostname   string
	Stdout     string
	Stderr     string
	Error      string
	ExitCode   int
	Changed    bool
	DurationMs int64
}

CommandResult represents command execution result from a single agent.

type ComponentHealth

type ComponentHealth struct {
	Status string
	Error  string
}

ComponentHealth represents a component's health.

type Condition

type Condition struct {
	Type               string
	Status             bool
	Reason             string
	LastTransitionTime time.Time
}

Condition represents a node condition evaluated agent-side.

type ConflictError

type ConflictError struct {
	APIError
}

ConflictError represents conflict errors (409).

func (*ConflictError) Unwrap

func (e *ConflictError) Unwrap() error

Unwrap returns the underlying APIError.

type ConsumerDetail

type ConsumerDetail struct {
	Name        string
	Pending     int
	AckPending  int
	Redelivered int
}

ConsumerDetail represents a single consumer's details.

type ConsumerStats

type ConsumerStats struct {
	Total     int
	Consumers []ConsumerDetail
}

ConsumerStats represents JetStream consumer statistics.

type DNSConfig

type DNSConfig struct {
	Hostname      string
	Error         string
	Servers       []string
	SearchDomains []string
}

DNSConfig represents DNS configuration from a single agent.

type DNSUpdateResult

type DNSUpdateResult struct {
	Hostname string
	Status   string
	Error    string
	Changed  bool
}

DNSUpdateResult represents DNS update result from a single agent.

type Disk

type Disk struct {
	Name  string
	Total int
	Used  int
	Free  int
}

Disk represents disk usage information.

type DiskResult

type DiskResult struct {
	Hostname string
	Error    string
	Disks    []Disk
}

DiskResult represents disk query result from a single agent.

type ExecRequest

type ExecRequest struct {
	// Command is the binary to execute (required).
	Command string

	// Args is the argument list passed to the command.
	Args []string

	// Cwd is the working directory. Empty uses the agent default.
	Cwd string

	// Timeout in seconds. Zero uses the server default (30s).
	Timeout int

	// Target specifies the host: "_any", "_all", hostname, or
	// label ("group:web").
	Target string
}

ExecRequest contains parameters for direct command execution.

type FileChanged

type FileChanged struct {
	Name    string
	Changed bool
	SHA256  string
}

FileChanged represents the result of a change detection check.

type FileDelete

type FileDelete struct {
	Name    string
	Deleted bool
}

FileDelete represents the result of a file deletion.

type FileDeployOpts

type FileDeployOpts struct {
	// ObjectName is the name of the file in the Object Store (required).
	ObjectName string

	// Path is the destination path on the target filesystem (required).
	Path string

	// ContentType is "raw" or "template" (required).
	ContentType string

	// Mode is the file permission mode (e.g., "0644"). Optional.
	Mode string

	// Owner is the file owner user. Optional.
	Owner string

	// Group is the file owner group. Optional.
	Group string

	// Vars are template variables when ContentType is "template". Optional.
	Vars map[string]any

	// Target specifies the host: "_any", "_all", hostname, or
	// label ("group:web").
	Target string
}

FileDeployOpts contains parameters for file deployment.

type FileDeployResult

type FileDeployResult struct {
	JobID    string
	Hostname string
	Changed  bool
}

FileDeployResult represents the result of a file deploy operation.

type FileItem

type FileItem struct {
	Name        string
	SHA256      string
	Size        int
	ContentType string
}

FileItem represents file metadata in a list.

type FileList

type FileList struct {
	Files []FileItem
	Total int
}

FileList is a collection of files with total count.

type FileMetadata

type FileMetadata struct {
	Name        string
	SHA256      string
	Size        int
	ContentType string
}

FileMetadata represents metadata for a single file.

type FileService

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

FileService provides file management operations for the Object Store.

func (*FileService) Changed

func (s *FileService) Changed(
	ctx context.Context,
	name string,
	file io.Reader,
) (*Response[FileChanged], error)

Changed computes the SHA-256 of the provided content and compares it against the stored hash in the Object Store. Returns true if the content differs or the file does not exist yet.

func (*FileService) Delete

func (s *FileService) Delete(
	ctx context.Context,
	name string,
) (*Response[FileDelete], error)

Delete removes a file from the Object Store.

func (*FileService) Get

func (s *FileService) Get(
	ctx context.Context,
	name string,
) (*Response[FileMetadata], error)

Get retrieves metadata for a specific file in the Object Store.

func (*FileService) List

func (s *FileService) List(
	ctx context.Context,
) (*Response[FileList], error)

List retrieves all files stored in the Object Store.

func (*FileService) Upload

func (s *FileService) Upload(
	ctx context.Context,
	name string,
	contentType string,
	file io.Reader,
	opts ...UploadOption,
) (*Response[FileUpload], error)

Upload uploads a file to the Object Store via multipart/form-data. By default, it computes SHA-256 locally and compares against the stored hash to skip the upload when content is unchanged. Use WithForce to bypass this check.

type FileStatusResult

type FileStatusResult struct {
	JobID    string
	Hostname string
	Path     string
	Status   string
	SHA256   string
}

FileStatusResult represents the result of a file status check.

type FileUpload

type FileUpload struct {
	Name        string
	SHA256      string
	Size        int
	Changed     bool
	ContentType string
}

FileUpload represents a successfully uploaded file.

type HealthService

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

HealthService provides health check operations.

func (*HealthService) Liveness

func (s *HealthService) Liveness(
	ctx context.Context,
) (*Response[HealthStatus], error)

Liveness checks if the API server process is alive.

func (*HealthService) Ready

func (s *HealthService) Ready(
	ctx context.Context,
) (*Response[ReadyStatus], error)

Ready checks if the API server and its dependencies are ready to serve traffic. A 503 response is treated as success with the ServiceUnavailable flag set.

func (*HealthService) Status

func (s *HealthService) Status(
	ctx context.Context,
) (*Response[SystemStatus], error)

Status returns detailed system status including component health, NATS info, stream stats, and job queue counts. Requires authentication. A 503 response is treated as success with the ServiceUnavailable flag set.

type HealthStatus

type HealthStatus struct {
	Status string
}

HealthStatus represents a liveness check response.

type HostnameResult

type HostnameResult struct {
	Hostname string
	Error    string
	Labels   map[string]string
}

HostnameResult represents a hostname query result from a single agent.

type JobCreated

type JobCreated struct {
	JobID     string
	Status    string
	Revision  int64
	Timestamp string
}

JobCreated represents a newly created job response.

type JobDetail

type JobDetail struct {
	ID          string
	Status      string
	Hostname    string
	Created     string
	UpdatedAt   string
	Error       string
	Operation   map[string]any
	Result      any
	AgentStates map[string]AgentState
	Responses   map[string]AgentJobResponse
	Timeline    []TimelineEvent
}

JobDetail represents a job's full details.

type JobList

type JobList struct {
	Items        []JobDetail
	TotalItems   int
	StatusCounts map[string]int
}

JobList is a paginated list of jobs.

type JobService

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

JobService provides job queue operations.

func (*JobService) Create

func (s *JobService) Create(
	ctx context.Context,
	operation map[string]interface{},
	target string,
) (*Response[JobCreated], error)

Create creates a new job with the given operation and target.

func (*JobService) Delete

func (s *JobService) Delete(
	ctx context.Context,
	id string,
) error

Delete deletes a job by ID.

func (*JobService) Get

func (s *JobService) Get(
	ctx context.Context,
	id string,
) (*Response[JobDetail], error)

Get retrieves a job by ID.

func (*JobService) List

func (s *JobService) List(
	ctx context.Context,
	params ListParams,
) (*Response[JobList], error)

List retrieves jobs, optionally filtered by status.

func (*JobService) QueueStats

func (s *JobService) QueueStats(
	ctx context.Context,
) (*Response[QueueStats], error)

QueueStats retrieves job queue statistics.

func (*JobService) Retry

func (s *JobService) Retry(
	ctx context.Context,
	id string,
	target string,
) (*Response[JobCreated], error)

Retry retries a failed job by ID, optionally on a different target.

type JobStats

type JobStats struct {
	Total       int
	Completed   int
	Failed      int
	Processing  int
	Unprocessed int
	Dlq         int
}

JobStats represents job queue statistics from the health endpoint.

type KVBucketInfo

type KVBucketInfo struct {
	Name  string
	Keys  int
	Bytes int
}

KVBucketInfo represents a KV bucket's info.

type ListParams

type ListParams struct {
	// Status filters by job status (e.g., "pending", "completed").
	Status string

	// Limit is the maximum number of results. Zero uses server default.
	Limit int

	// Offset is the number of results to skip. Zero starts from the
	// beginning.
	Offset int
}

ListParams contains optional filters for listing jobs.

type LoadAverage

type LoadAverage struct {
	OneMin     float32
	FiveMin    float32
	FifteenMin float32
}

LoadAverage represents system load averages.

type LoadResult

type LoadResult struct {
	Hostname    string
	Error       string
	LoadAverage *LoadAverage
}

LoadResult represents load average query result from a single agent.

type Memory

type Memory struct {
	Total int
	Used  int
	Free  int
}

Memory represents memory usage information.

type MemoryResult

type MemoryResult struct {
	Hostname string
	Error    string
	Memory   *Memory
}

MemoryResult represents memory query result from a single agent.

type MessageResponse

type MessageResponse struct {
	Message string
}

MessageResponse represents a simple message response from the API.

type MetricsService

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

MetricsService provides Prometheus metrics access.

func (*MetricsService) Get

func (s *MetricsService) Get(
	ctx context.Context,
) (string, error)

Get fetches the raw Prometheus metrics text from the /metrics endpoint.

type NATSInfo

type NATSInfo struct {
	URL     string
	Version string
}

NATSInfo represents NATS connection info.

type NetworkInterface

type NetworkInterface struct {
	Name   string
	Family string
	IPv4   string
	IPv6   string
	MAC    string
}

NetworkInterface represents a network interface on an agent.

type NodeService

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

NodeService provides node management operations.

func (*NodeService) Disk

func (s *NodeService) Disk(
	ctx context.Context,
	target string,
) (*Response[Collection[DiskResult]], error)

Disk retrieves disk usage information from the target host.

func (*NodeService) Exec

Exec executes a command directly without a shell interpreter.

func (*NodeService) FileDeploy

func (s *NodeService) FileDeploy(
	ctx context.Context,
	req FileDeployOpts,
) (*Response[FileDeployResult], error)

FileDeploy deploys a file from the Object Store to the target host.

func (*NodeService) FileStatus

func (s *NodeService) FileStatus(
	ctx context.Context,
	target string,
	path string,
) (*Response[FileStatusResult], error)

FileStatus checks the deployment status of a file on the target host.

func (*NodeService) GetDNS

func (s *NodeService) GetDNS(
	ctx context.Context,
	target string,
	interfaceName string,
) (*Response[Collection[DNSConfig]], error)

GetDNS retrieves DNS configuration for a network interface on the target host.

func (*NodeService) Hostname

func (s *NodeService) Hostname(
	ctx context.Context,
	target string,
) (*Response[Collection[HostnameResult]], error)

Hostname retrieves the hostname from the target host.

func (*NodeService) Load

func (s *NodeService) Load(
	ctx context.Context,
	target string,
) (*Response[Collection[LoadResult]], error)

Load retrieves load average information from the target host.

func (*NodeService) Memory

func (s *NodeService) Memory(
	ctx context.Context,
	target string,
) (*Response[Collection[MemoryResult]], error)

Memory retrieves memory usage information from the target host.

func (*NodeService) OS

func (s *NodeService) OS(
	ctx context.Context,
	target string,
) (*Response[Collection[OSInfoResult]], error)

OS retrieves operating system information from the target host.

func (*NodeService) Ping

func (s *NodeService) Ping(
	ctx context.Context,
	target string,
	address string,
) (*Response[Collection[PingResult]], error)

Ping sends an ICMP ping to the specified address from the target host.

func (*NodeService) Shell

Shell executes a command through /bin/sh -c with shell features (pipes, redirects, variable expansion).

func (*NodeService) Status

func (s *NodeService) Status(
	ctx context.Context,
	target string,
) (*Response[Collection[NodeStatus]], error)

Status retrieves node status (OS info, disk, memory, load) from the target host.

func (*NodeService) UpdateDNS

func (s *NodeService) UpdateDNS(
	ctx context.Context,
	target string,
	interfaceName string,
	servers []string,
	searchDomains []string,
) (*Response[Collection[DNSUpdateResult]], error)

UpdateDNS updates DNS configuration for a network interface on the target host.

func (*NodeService) Uptime

func (s *NodeService) Uptime(
	ctx context.Context,
	target string,
) (*Response[Collection[UptimeResult]], error)

Uptime retrieves uptime information from the target host.

type NodeStatus

type NodeStatus struct {
	Hostname    string
	Uptime      string
	Error       string
	Disks       []Disk
	LoadAverage *LoadAverage
	Memory      *Memory
	OSInfo      *OSInfo
}

NodeStatus represents full node status from a single agent.

type NotFoundError

type NotFoundError struct {
	APIError
}

NotFoundError represents resource not found errors (404).

func (*NotFoundError) Unwrap

func (e *NotFoundError) Unwrap() error

Unwrap returns the underlying APIError.

type OSInfo

type OSInfo struct {
	Distribution string
	Version      string
}

OSInfo represents operating system information.

type OSInfoResult

type OSInfoResult struct {
	Hostname string
	Error    string
	OSInfo   *OSInfo
}

OSInfoResult represents OS info query result from a single agent.

type ObjectStoreInfo

type ObjectStoreInfo struct {
	Name string
	Size int
}

ObjectStoreInfo represents an Object Store bucket's info.

type Option

type Option func(*Client)

Option configures the Client.

func WithHTTPTransport

func WithHTTPTransport(
	transport http.RoundTripper,
) Option

WithHTTPTransport sets a custom base HTTP transport.

func WithLogger

func WithLogger(
	logger *slog.Logger,
) Option

WithLogger sets a custom logger. Defaults to slog.Default().

type PingResult

type PingResult struct {
	Hostname        string
	Error           string
	PacketsSent     int
	PacketsReceived int
	PacketLoss      float64
	MinRtt          string
	AvgRtt          string
	MaxRtt          string
}

PingResult represents ping result from a single agent.

type QueueStats

type QueueStats struct {
	TotalJobs    int
	DlqCount     int
	StatusCounts map[string]int
}

QueueStats represents job queue statistics.

type ReadyStatus

type ReadyStatus struct {
	Status             string
	Error              string
	ServiceUnavailable bool
}

ReadyStatus represents a readiness check response.

type Response

type Response[T any] struct {
	Data T
	// contains filtered or unexported fields
}

Response wraps a domain type with raw JSON for CLI --json mode.

func NewResponse

func NewResponse[T any](
	data T,
	rawJSON []byte,
) *Response[T]

NewResponse creates a Response with the given data and raw JSON body.

func (*Response[T]) RawJSON

func (r *Response[T]) RawJSON() []byte

RawJSON returns the raw HTTP response body.

type Route

type Route struct {
	Destination string
	Gateway     string
	Interface   string
	Mask        string
	Flags       string
	Metric      int
}

Route represents a network routing table entry.

type ServerError

type ServerError struct {
	APIError
}

ServerError represents internal server errors (500).

func (*ServerError) Unwrap

func (e *ServerError) Unwrap() error

Unwrap returns the underlying APIError.

type ShellRequest

type ShellRequest struct {
	// Command is the shell command string passed to /bin/sh -c (required).
	Command string

	// Cwd is the working directory. Empty uses the agent default.
	Cwd string

	// Timeout in seconds. Zero uses the server default (30s).
	Timeout int

	// Target specifies the host: "_any", "_all", hostname, or
	// label ("group:web").
	Target string
}

ShellRequest contains parameters for shell command execution.

type StreamInfo

type StreamInfo struct {
	Name      string
	Messages  int
	Bytes     int
	Consumers int
}

StreamInfo represents a JetStream stream's info.

type SystemStatus

type SystemStatus struct {
	Status             string
	Version            string
	Uptime             string
	ServiceUnavailable bool
	Components         map[string]ComponentHealth
	NATS               *NATSInfo
	Agents             *AgentStats
	Jobs               *JobStats
	Consumers          *ConsumerStats
	Streams            []StreamInfo
	KVBuckets          []KVBucketInfo
	ObjectStores       []ObjectStoreInfo
}

SystemStatus represents detailed system status.

type TimelineEvent

type TimelineEvent struct {
	Timestamp string
	Event     string
	Hostname  string
	Message   string
	Error     string
}

TimelineEvent represents a lifecycle event. Used by both job timelines and agent state transition history.

type UnexpectedStatusError

type UnexpectedStatusError struct {
	APIError
}

UnexpectedStatusError represents unexpected HTTP status codes.

func (*UnexpectedStatusError) Unwrap

func (e *UnexpectedStatusError) Unwrap() error

Unwrap returns the underlying APIError.

type UploadOption

type UploadOption func(*uploadOptions)

UploadOption configures Upload behavior.

func WithForce

func WithForce() UploadOption

WithForce bypasses both SDK-side pre-check and server-side digest check. The file is always uploaded and changed is always true.

type UptimeResult

type UptimeResult struct {
	Hostname string
	Uptime   string
	Error    string
}

UptimeResult represents uptime query result from a single agent.

type ValidationError

type ValidationError struct {
	APIError
}

ValidationError represents validation errors (400).

func (*ValidationError) Unwrap

func (e *ValidationError) Unwrap() error

Unwrap returns the underlying APIError.

Directories

Path Synopsis
Package gen provides primitives to interact with the openapi HTTP API.
Package gen provides primitives to interact with the openapi HTTP API.

Jump to

Keyboard shortcuts

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