common

package
v0.2.7 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2026 License: AGPL-3.0 Imports: 20 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNodeNotConfigured     = errors.New("node not configured")
	ErrNodeAlreadyConfigured = errors.New("node already configured")
)

Functions

func CastMetadata added in v0.1.9

func CastMetadata[T any](metadataPtr any) (*T, error)

func CopyFile added in v0.1.9

func CopyFile(src, dst string) error

func CreateLogFile

func CreateLogFile(filePath string, perm os.FileMode) (*os.File, error)

Create a file and all the missing directories

func ReadFileAt

func ReadFileAt(filepath string, offset int64) ([]byte, int64, error)

func RegisterJobDriver added in v0.2.5

func RegisterJobDriver(d JobDriver) error

func RegisterLoadDriver

func RegisterLoadDriver(d LoadDriver) error

func RegisterNodeDriver

func RegisterNodeDriver(d NodeDriver) error

func ResolveAgentURL added in v0.2.2

func ResolveAgentURL(nodeConfig *NodeConfig) (string, error)

func ResolveExecPath added in v0.1.8

func ResolveExecPath(execFile string, workingDir *string) (string, error)

Resolve execFile by priority: absolute path, working directory, PATH env var

func SetDeploymentError

func SetDeploymentError(repository DeploymentsRepository, deployment Deployment, msg string, args ...any) error

func SetNodeContextBuilder added in v0.2.5

func SetNodeContextBuilder(builder NodeContexBuilder)

func TailFile

func TailFile(filepath string, w io.Writer) error

func UnregisterJobDriver added in v0.2.5

func UnregisterJobDriver(id JobDriverID) error

func UnregisterLoadDriver

func UnregisterLoadDriver(id LoadDriverID) error

func UnregisterNodeDriver

func UnregisterNodeDriver(id NodeDriverID) error

func UpdateDeploymentMetadata added in v0.1.2

func UpdateDeploymentMetadata[T any](repo DeploymentsRepository, deploymentID DeploymentID, updateFn func(metadata *T) error) error

UpdateDeploymentMetadata is a generic helper that provides type-safe metadata updates. It handles the JSON marshal/unmarshal internally so callers get a typed pointer.

func UpdateGuestNodeMetadata added in v0.1.8

func UpdateGuestNodeMetadata[T any](guestNodeName string, repo NodesRepository, updateFn func(metadata *T) error) error

func UpdateSelfNodeMetadata added in v0.1.8

func UpdateSelfNodeMetadata[T any](repo NodesRepository, updateFn func(metadata *T) error) error

Types

type Capabilities added in v0.1.2

type Capabilities interface {
	ContainersEngine() bool
	ContainersNetworking() bool
	Volumes() bool
	VolumesZFS() bool
	VMM() bool
}

type ContainerState added in v0.1.8

type ContainerState struct {
	ContainerID   string  `json:"container_id"`
	CPUUsage      float64 `json:"cpu_usage"` // Important (percentage)
	CPUSystem     float64 `json:"cpu_system"`
	CPUUser       float64 `json:"cpu_user"`
	MemoryUsage   float64 `json:"mem_usage"`
	MemoryLimit   float64 `json:"mem_limit"`
	MemoryPercent float64 `json:"mem_percentage"` // Important (percentage)
}

type ContainerStates added in v0.1.8

type ContainerStates map[string]ContainerState

type Deployment

type Deployment struct {
	ID         DeploymentID
	LoadName   string
	LoadDriver LoadDriver
	Status     DeploymentStatus
	Metadata   any
}

A deployment is the object created when a load has been loaded in the cluster Notice it doesn't reference Load but contains an immutable copy because a deployment cannot be modified directly, it must be updated from the DeploymentsRepository

type DeploymentID

type DeploymentID = uuid.UUID

type DeploymentStatus

type DeploymentStatus struct {
	StatusCode DeploymentStatusCode `json:"status"`
	Reason     string               `json:"reason"`
}

type DeploymentStatusCode

type DeploymentStatusCode string
const (
	DeploymentStatusNotReady DeploymentStatusCode = "not ready"
	DeploymentStatusReady    DeploymentStatusCode = "ready"
	DeploymentStatusRunning  DeploymentStatusCode = "running"
	DeploymentStatusStopped  DeploymentStatusCode = "stopped"
	DeploymentStatusError    DeploymentStatusCode = "error"
)

type DeploymentsRepository

type DeploymentsRepository interface {
	Create(loadName string, driver LoadDriver, status DeploymentStatus, metadata any) (DeploymentID, error)
	UpdateStatus(deploymentID DeploymentID, status DeploymentStatus) error
	UpdateMetadata(deploymentID DeploymentID, updateFn func(metadata any) error) error

	GetAll() ([]Deployment, error)
	GetByLoad(loadName string) ([]Deployment, error)
	GetByLoadAndStatus(loadName string, statusCode DeploymentStatusCode) ([]Deployment, error)
	GetDeployment(deploymentID DeploymentID) (*Deployment, error)

	DeleteByLoad(loadName string) error
	DeleteDeployment(deploymentID uuid.UUID) error
}

Store interface for deployments All methods are related to the deployments of the self node

Notice all data is returned by an immutable copy because this repository might be stored in a distributed database so no memory references must be used

type Hash

type Hash [32]byte

type HashableLoadConfig

type HashableLoadConfig struct {
	Name         string       `json:"name"`
	Node         string       `json:"node"`
	DependsOn    []string     `json:"depends_on"`
	Driver       LoadDriverID `json:"driver"`
	DriverConfig any          `json:"driver_config"`
}

type Job added in v0.2.5

type Job struct {
	Name   string
	Node   *Node
	Driver JobDriver
}

func (*Job) Hash added in v0.2.5

func (j *Job) Hash() [32]byte

func (*Job) MarshalJSON added in v0.2.5

func (j *Job) MarshalJSON() ([]byte, error)

func (*Job) UnmarshalJSON added in v0.2.5

func (j *Job) UnmarshalJSON(data []byte) error

type JobConfig added in v0.2.5

type JobConfig struct {
	Name         string      `json:"name"`
	Node         string      `json:"node"`
	Driver       JobDriverID `json:"driver"`
	DriverConfig any         `json:"driver_config"`
}

type JobDriver added in v0.2.5

type JobDriver interface {
	ID() JobDriverID

	Info() JobDriverInfo

	Run(w JobResultWriter, args ...string) error

	Config() JobDriverConfig
}

func BuildJobDriver added in v0.2.5

func BuildJobDriver(d JobDriverConfig) (JobDriver, error)

type JobDriverConfig added in v0.2.5

type JobDriverConfig struct {
	Driver       JobDriverID `json:"driver"`
	DriverConfig any         `json:"driver_config,omitempty"`
}

type JobDriverError added in v0.2.5

type JobDriverError struct {
	Code     JobDriverErrorCode
	DriverID JobDriverID
	Err      error
}

func (*JobDriverError) Error added in v0.2.5

func (e *JobDriverError) Error() string

type JobDriverErrorCode added in v0.2.5

type JobDriverErrorCode string
const (
	JobDriverErrAlreadyRegistered JobDriverErrorCode = "already_registered"
	JobDriverErrNotRegistered     JobDriverErrorCode = "not_registered"
	JobDriverErrBuildFailed       JobDriverErrorCode = "build_failed"
)

type JobDriverID added in v0.2.5

type JobDriverID string

type JobDriverInfo added in v0.2.5

type JobDriverInfo struct {
	ID  JobDriverID
	New func(config any) (JobDriver, error)
}

func RegisteredJobDrivers added in v0.2.5

func RegisteredJobDrivers() []JobDriverInfo

type JobResult added in v0.2.6

type JobResult struct {
	Value *string `json:"value,omitempty"`
	Err   *string `json:"err,omitempty"`
}

type JobResultWriter added in v0.2.6

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

func NewJobResultWriter added in v0.2.6

func NewJobResultWriter(w http.ResponseWriter) JobResultWriter

func (*JobResultWriter) Write added in v0.2.6

func (j *JobResultWriter) Write(r JobResult) error

func (*JobResultWriter) WriteError added in v0.2.6

func (j *JobResultWriter) WriteError(err error) error

func (*JobResultWriter) WriteValue added in v0.2.6

func (j *JobResultWriter) WriteValue(value string) error

type Load

type Load struct {
	Name       string
	Node       *Node
	DependsOn  []*Load
	Driver     LoadDriver
	StartChain LoadChain
	StopChain  LoadChain
}

func (*Load) GetDependencies

func (l *Load) GetDependencies() []string

func (*Load) Hash

func (l *Load) Hash() [32]byte

func (*Load) MarshalJSON

func (l *Load) MarshalJSON() ([]byte, error)

func (*Load) UnmarshalJSON

func (l *Load) UnmarshalJSON(data []byte) error

func (*Load) UpdateLoadChains

func (l *Load) UpdateLoadChains(configGraph graph.Graph[string, string], loadsMap map[string]*Load) error

type LoadChain

type LoadChain []*Load

func (LoadChain) Hash

func (chain LoadChain) Hash() Hash

Hash loads in order Order is important that's why it receives an array of loads

type LoadConfig

type LoadConfig struct {
	Name           string       `json:"name"`
	Node           string       `json:"node"`
	DependsOn      []string     `json:"depends_on"`
	Driver         LoadDriverID `json:"driver"`
	DriverConfig   any          `json:"driver_config"`
	StartChainHash string       `json:"start_chain_hash"`
	StopChainHash  string       `json:"stop_chain_hash"`
}

type LoadDriver

type LoadDriver interface {
	// GetLoadDriverID returns the unique identifier for this load driver.
	ID() LoadDriverID

	// Info returns driver description for internal factory use.
	Info() LoadDriverInfo

	// Provision validates prerequisites and creates a deployment in "provisioned" status.
	// It shall check load requirements but it won't check depending loads.
	// This is invoked within the agent and does not affect client behavior.
	//
	// Returns the deployment ID for the provisioned deployment.
	Provision(node NodeDriver, repository DeploymentsRepository, loadName string) (DeploymentID, error)

	// Deprovision removes a provisioned deployment with cleanup
	// Only operates on deployments in "provisioned" status.
	Deprovision(repository DeploymentsRepository, deployment Deployment) error

	// Start starts the load execution for a provisioned deployment.
	// This has no effect when called from the client.
	//
	// LoadDriver is responsible of the consistency of the DeploymentsRepository
	Start(repository DeploymentsRepository, deployment Deployment) error

	// Stop stops a running load execution within the agent.
	// This has no effect when called from the client.
	//
	// LoadDriver is responsible of the consistency of the DeploymentsRepository
	Stop(repository DeploymentsRepository, deployment Deployment) error

	// Kill stops immediately a running load execution within the agent.
	// This has no effect when called from the client.
	//
	// LoadDriver is responsible of the consistency of the DeploymentsRepository
	Kill(repository DeploymentsRepository, deployment Deployment) error

	// UpdateStatus update and returns current status based on internal drivers factors.
	UpdateStatus(repository DeploymentsRepository, deployment Deployment) (DeploymentStatus, error)

	// Config returns the configuration for this load driver.
	Config() LoadDriverConfig

	// Stream load stdout to writer
	StreamStdout(repository DeploymentsRepository, deployment Deployment, w io.Writer) error

	// Stream load stderr to writer
	StreamStderr(repository DeploymentsRepository, deployment Deployment, w io.Writer) error

	// Read load stdout from offset, returns bytes read and end position
	ReadStdout(repository DeploymentsRepository, deployment Deployment, offset int64) ([]byte, int64, error)

	// Read load stderr from offset, returns bytes read and end position
	ReadStderr(repository DeploymentsRepository, deployment Deployment, offset int64) ([]byte, int64, error)
}

func BuildLoadDriver

func BuildLoadDriver(d LoadDriverConfig) (LoadDriver, error)

type LoadDriverConfig

type LoadDriverConfig struct {
	Driver       LoadDriverID `json:"driver"`
	DriverConfig any          `json:"driver_config"`
}

type LoadDriverError added in v0.2.1

type LoadDriverError struct {
	Code     LoadDriverErrorCode
	DriverID LoadDriverID
	Err      error
}

func (*LoadDriverError) Error added in v0.2.1

func (e *LoadDriverError) Error() string

type LoadDriverErrorCode added in v0.2.1

type LoadDriverErrorCode string
const (
	LoadDriverErrAlreadyRegistered LoadDriverErrorCode = "already_registered"
	LoadDriverErrNotRegistered     LoadDriverErrorCode = "not_registered"
	LoadDriverErrBuildFailed       LoadDriverErrorCode = "build_failed"
)

type LoadDriverID

type LoadDriverID string

type LoadDriverInfo

type LoadDriverInfo struct {
	ID  LoadDriverID
	New func(config any) (LoadDriver, error)
}

func RegisteredLoadDrivers added in v0.2.5

func RegisteredLoadDrivers() []LoadDriverInfo

type NetworkInterface added in v0.1.10

type NetworkInterface struct {
	Name      string   `json:"name"`
	HWAddr    string   `json:"hwaddr,omitempty"`
	Addresses []string `json:"addresses,omitempty"`
}

type NewNodeDriverInfoOpts added in v0.1.2

type NewNodeDriverInfoOpts func(i *NodeDriverInfo) error

func WithGuestMode added in v0.2.5

func WithGuestMode() NewNodeDriverInfoOpts

type Node

type Node struct {
	Name       string
	Url        string
	CloudInit  *cloudinit.CloudInit
	Registries []RegistryConfig
	Driver     NodeDriver
}

func (*Node) Hash

func (n *Node) Hash() [32]byte

func (*Node) MarshalJSON

func (n *Node) MarshalJSON() ([]byte, error)

func (*Node) UnmarshalJSON

func (n *Node) UnmarshalJSON(data []byte) error

type NodeConfig

type NodeConfig struct {
	Name         string               `json:"name"`
	Url          string               `json:"url"`
	CloudInit    *cloudinit.CloudInit `json:"cloud_init,omitempty"`
	Driver       NodeDriverID         `json:"driver,omitempty"`
	DriverConfig *any                 `json:"driver_config,omitempty"`
	Registries   []RegistryConfig     `json:"registries,omitempty"`
}

type NodeContexBuilder added in v0.2.5

type NodeContexBuilder func(nodeName string) NodeContext

type NodeContext added in v0.2.5

type NodeContext struct {
	Repository   NodesRepository // Only available when agent is running
	Capabilities Capabilities
	NodeName     string
	RunMode      RunMode
}

func NewNodeContext added in v0.2.5

func NewNodeContext(nodeName string) NodeContext

type NodeDriver

type NodeDriver interface {
	// ID returns the unique identifier for this node driver.
	ID() NodeDriverID

	// Info returns driver description for internal factory use.
	Info() (NodeDriverInfo, error)

	// Config returns the configuration for this node driver.
	Config() NodeDriverConfig

	// PowerOn starts the node
	PowerOn(cloudInit *cloudinit.CloudInit) error

	// PowerOff stops the node immediately
	PowerOff() error

	// Shutdown stops the node
	Shutdown(message string, time uint32) error

	// Restart restarts the node
	// Message will be shown to users before shutdown on the time
	// offset specified
	Restart(message string, time uint32) error

	// State returns current node state (e.g. cpu, mem, etc...)
	State() (NodeState, error)

	// UpdateStatus update and returns current status based on internal drivers factors
	//
	// nodeName as nil for self-node
	UpdateStatus() (NodeStatus, error)
}

func BuildNodeDriver

func BuildNodeDriver(ctx NodeContext, d NodeDriverConfig) (NodeDriver, error)

type NodeDriverBuilder added in v0.1.2

type NodeDriverBuilder func(ctx NodeContext, config *any) (NodeDriver, error)

type NodeDriverConfig

type NodeDriverConfig struct {
	Driver       NodeDriverID `json:"driver"`
	DriverConfig *any         `json:"driver_config"`
}

func (NodeDriverConfig) Equal added in v0.2.5

func (d NodeDriverConfig) Equal(other NodeDriverConfig) bool

Equal compares two NodeDriverConfig by normalizing both DriverConfig values through JSON, since one side may hold a concrete driver struct and the other a map[string]any decoded from JSON.

type NodeDriverID

type NodeDriverID string

type NodeDriverInfo

type NodeDriverInfo struct {
	ID        NodeDriverID
	New       NodeDriverBuilder
	GuestMode bool
}

func NewNodeDriverInfo added in v0.1.2

func NewNodeDriverInfo(id NodeDriverID, builder NodeDriverBuilder, opts ...NewNodeDriverInfoOpts) (NodeDriverInfo, error)

func RegisteredNodeDrivers added in v0.2.5

func RegisteredNodeDrivers() []NodeDriverInfo

type NodeEntry

type NodeEntry struct {
	NodeName   string
	NodeDriver NodeDriver
	Registries []RegistryConfig
	Metadata   any
}

type NodeState added in v0.1.8

type NodeState struct {
	NumCPU          int     `json:"ncpu"`
	UserCPU         uint64  `json:"cpu_user"`
	IdleCPU         uint64  `json:"cpu_idle"`
	SystemCPU       uint64  `json:"cpu_system"`
	TotalCPU        uint64  `json:"cpu_total"`
	UsageCPUPercent float64 `json:"cpu_usage_percentage"` // Important

	TotalMem       uint64  `json:"mem_total"`
	UsedMem        uint64  `json:"mem_used"`
	FreeMem        uint64  `json:"mem_free"`
	FreeMemPercent float64 `json:"mem_free_percentage"` // Important

	FreeStorage uint64 `json:"free_storage"`

	// Swap memory information
	SwapTotal uint64 `json:"swap_total"` // Total available swap memory in bytes
	SwapUsed  uint64 `json:"swap_used"`  // Total used swap memory in bytes
	SwapFree  uint64 `json:"swap_free"`  // Total free swap memory in bytes

	// CPU load average
	CpuLoadAvg float32 `json:"cpu_load_avg"` // CPU load average (from 0 to 1)

	// Process counts
	ProcTotalCount    uint32 `json:"proc_total_count"`    // Number of active processes
	ProcSleepingCount uint32 `json:"proc_sleeping_count"` // Number of sleeping processes
	ProcRunningCount  uint32 `json:"proc_running_count"`  // Number of running processes
	ProcZombieCount   uint32 `json:"proc_zombie_count"`   // Number of zombie processes
	ProcStoppedCount  uint32 `json:"proc_stopped_count"`  // Number of stopped processes
	ProcIdleCount     uint32 `json:"proc_idle_count"`     // Number of idle processes
	ProcThreadsCount  uint32 `json:"proc_threads_count"`  // Number of threads

	Containers []ContainerState `json:"containers,omitempty"`

	NetworkInterfaces []NetworkInterface `json:"network_interfaces,omitempty"`
}

func NewNodeState added in v0.2.0

func NewNodeState() NodeState

type NodeStatus

type NodeStatus struct {
	StatusCode NodeStatusCode `json:"status"`
	Reason     string         `json:"reason"`
}

type NodeStatusCode added in v0.1.2

type NodeStatusCode string
const (
	NodeStatusOffline NodeStatusCode = "offline"
	NodeStatusOnline  NodeStatusCode = "online"
	NodeStatusReady   NodeStatusCode = "ready"
	NodeStatusError   NodeStatusCode = "error"
)

type NodesRepository

type NodesRepository interface {
	// SetSelf creates or updates the node for the caller
	SetSelf(nodeName string, driver NodeDriver, registries []RegistryConfig) error

	// GetSelf return nodeentry for the caller node
	GetSelf() (NodeEntry, error)

	// DeleteSelf caller node from repository
	DeleteSelf() error

	// Update self node metadata
	UpdateSelfMetadata(updateFn func(metadataPtr any) error) error

	// Retrieve node entry by agent ID
	GetByAgentId(agentId string) (NodeEntry, error)

	// SetGuestNode creates or update the guest node entry for the caller host node
	SetGuestNode(guestNodeName string, guestDriver NodeDriver) error

	// GetGuestNode returns a guest node of the caller host node
	GetGuestNode(guestNodeName string) (NodeEntry, error)

	// GetAllGuestNodes returns all guest nodes of the self node
	GetAllGuestNodes() ([]NodeEntry, error)

	// DeleteGuestNode deletes the guest node entry for the caller host node
	DeleteGuestNode(guestNodeName string, guestDriver NodeDriver) error

	// Update guest node metadata
	UpdateGuestMetadata(guestNodeName string, updateFn func(metadataPtr any) error) error
}

Store interface for nodes

Notice all data is returned by an immutable copy because this repository might be stored in a distributed database so no memory references must be used

type RegistryAuth added in v0.2.7

type RegistryAuth struct {
	Username string `json:"username,omitempty"`
	Password string `json:"password,omitempty"`
	Token    string `json:"token,omitempty"`
}

RegistryAuth holds authentication credentials for a container registry. Token OR Username/Password should be set, not both.

type RegistryConfig added in v0.2.7

type RegistryConfig struct {
	Host     string       `json:"host"` // Registry host (e.g., "ghcr.io", "docker.io", "registry.example.com:5000")
	Auth     RegistryAuth `json:"auth"`
	Insecure bool         `json:"insecure,omitempty"` // Allow HTTP instead of HTTPS

	// Skip verification of the registry's TLS certificate.
	SkipTLSVerify bool `json:"skip_tls_verify,omitempty"`

	// Path to a PEM bundle with additional CAs trusted for this registry.
	CAFile string `json:"ca_file,omitempty"`
}

RegistryConfig holds configuration for a container registry.

func FindRegistryConfig added in v0.2.7

func FindRegistryConfig(registries []RegistryConfig, host string) *RegistryConfig

FindRegistryConfig returns the registry configuration for a given host, or nil when the host is not configured.

type RunMode added in v0.2.5

type RunMode int
const (
	ClientMode RunMode = iota
	AgentMode
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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