api

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jun 9, 2025 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ClusterDataTTL  = 1 * time.Hour
	NodeDataTTL     = 1 * time.Hour
	VMDataTTL       = 1 * time.Hour
	ResourceDataTTL = 1 * time.Hour
)

Cache TTLs for different types of data

View Source
const (
	VMTypeQemu = "qemu"
	VMTypeLXC  = "lxc"
)

VM Types

View Source
const (
	VMStatusRunning = "running"
	VMStatusStopped = "stopped"
)

VM Status

View Source
const (
	IPTypeIPv4 = "ipv4"
	IPTypeIPv6 = "ipv6"
)

IP Types

View Source
const (
	StringTrue = "true"
	StringNA   = "N/A"
)

Common strings

View Source
const (
	PageNodes  = "Nodes"
	PageGuests = "Guests"
)

UI Pages

View Source
const (
	ActionRefresh   = "Refresh"
	ActionOpenShell = "Open Shell"
)

Menu actions

View Source
const (
	LoopbackInterface = "lo"
)

Network interface names

View Source
const (
	NodeType = "node"
)

Node types

Variables

This section is empty.

Functions

func ExampleUsage

func ExampleUsage()

ExampleUsage demonstrates how to use the reusable API package

func GetFirstNonLoopbackIP

func GetFirstNonLoopbackIP(interfaces []NetworkInterface, preferIPv4 bool) string

GetFirstNonLoopbackIP returns the first non-loopback IP address from network interfaces

Types

type AuthManager

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

AuthManager handles Proxmox API authentication with dependency injection

func NewAuthManagerWithPassword

func NewAuthManagerWithPassword(httpClient *HTTPClient, username, password string, logger interfaces.Logger) *AuthManager

NewAuthManagerWithPassword creates a new authentication manager for password auth

func NewAuthManagerWithToken

func NewAuthManagerWithToken(httpClient *HTTPClient, token string, logger interfaces.Logger) *AuthManager

NewAuthManagerWithToken creates a new authentication manager for token auth

func (*AuthManager) ClearToken

func (am *AuthManager) ClearToken()

ClearToken clears the cached authentication token

func (*AuthManager) EnsureAuthenticated

func (am *AuthManager) EnsureAuthenticated() error

EnsureAuthenticated ensures the client is authenticated

func (*AuthManager) GetValidToken

func (am *AuthManager) GetValidToken(ctx context.Context) (*AuthToken, error)

GetValidToken returns a valid authentication token, refreshing if necessary

func (*AuthManager) IsTokenAuth

func (am *AuthManager) IsTokenAuth() bool

IsTokenAuth returns true if using API token authentication

type AuthToken

type AuthToken struct {
	Ticket    string    `json:"ticket"`
	CSRFToken string    `json:"csrf_token"`
	Username  string    `json:"username"`
	ExpiresAt time.Time `json:"expires_at"`
}

AuthToken represents a Proxmox authentication token

func (*AuthToken) IsValid

func (t *AuthToken) IsValid() bool

IsValid checks if the token is still valid (not expired)

type CPUInfo

type CPUInfo struct {
	Cores   int    `json:"cores"`
	Cpus    int    `json:"cpus"`
	Model   string `json:"model"`
	Sockets int    `json:"sockets"`
}

CPUInfo contains detailed CPU information from Proxmox node status

type Client

type Client struct {
	Cluster *Cluster // Cached cluster state
	// contains filtered or unexported fields
}

Client is a Proxmox API client with dependency injection for logging and caching

func NewClient

func NewClient(config interfaces.Config, options ...ClientOption) (*Client, error)

NewClient creates a new Proxmox API client with dependency injection

func (*Client) ClearAPICache

func (c *Client) ClearAPICache()

ClearAPICache removes all API-related cached responses

func (*Client) EnrichVMs

func (c *Client) EnrichVMs(cluster *Cluster) error

EnrichVMs enriches all VMs in the cluster with detailed status information

func (*Client) FastGetClusterStatus

func (c *Client) FastGetClusterStatus(onEnrichmentComplete func()) (*Cluster, error)

FastGetClusterStatus retrieves only essential cluster status without VM enrichment for fast application startup. VM details will be loaded in the background. The onEnrichmentComplete callback is called when background VM enrichment finishes.

func (*Client) GenerateNodeVNCURL

func (c *Client) GenerateNodeVNCURL(nodeName string) (string, error)

GenerateNodeVNCURL creates a noVNC shell URL for the given node

func (*Client) GenerateVNCURL

func (c *Client) GenerateVNCURL(vm *VM) (string, error)

GenerateVNCURL creates a noVNC console URL for the given VM

func (*Client) Get

func (c *Client) Get(path string, result *map[string]interface{}) error

Get makes a GET request to the Proxmox API with retry logic

func (*Client) GetClusterStatus

func (c *Client) GetClusterStatus() (*Cluster, error)

GetClusterStatus retrieves high-level cluster status and node list

func (*Client) GetDetailedVmInfo

func (c *Client) GetDetailedVmInfo(node, vmType string, vmid int) (*VM, error)

GetDetailedVmInfo retrieves complete information about a VM by combining status and config data

func (*Client) GetFreshClusterStatus

func (c *Client) GetFreshClusterStatus() (*Cluster, error)

GetFreshClusterStatus retrieves cluster status bypassing cache completely

func (*Client) GetGuestAgentFilesystems

func (c *Client) GetGuestAgentFilesystems(vm *VM) ([]Filesystem, error)

GetGuestAgentFilesystems retrieves filesystem information from the QEMU guest agent

func (*Client) GetGuestAgentInterfaces

func (c *Client) GetGuestAgentInterfaces(vm *VM) ([]NetworkInterface, error)

GetGuestAgentInterfaces retrieves network interface information from the QEMU guest agent

func (*Client) GetLxcInterfaces

func (c *Client) GetLxcInterfaces(vm *VM) ([]NetworkInterface, error)

GetLxcInterfaces retrieves network interface information for an LXC container.

func (*Client) GetNoRetry

func (c *Client) GetNoRetry(path string, result *map[string]interface{}) error

GetNoRetry makes a GET request to the Proxmox API without retry logic

func (*Client) GetNodeConfig

func (c *Client) GetNodeConfig(nodeName string) (map[string]interface{}, error)

GetNodeConfig retrieves configuration for a given node with caching

func (*Client) GetNodeStatus

func (c *Client) GetNodeStatus(nodeName string) (*Node, error)

GetNodeStatus retrieves real-time status for a specific node

func (*Client) GetNodeVNCShell

func (c *Client) GetNodeVNCShell(nodeName string) (*VNCProxyResponse, error)

GetNodeVNCShell creates a VNC shell connection for a node and returns connection details

func (*Client) GetVNCProxy

func (c *Client) GetVNCProxy(vm *VM) (*VNCProxyResponse, error)

GetVNCProxy creates a VNC proxy for a VM and returns connection details

func (*Client) GetVmList

func (c *Client) GetVmList(ctx context.Context) ([]map[string]interface{}, error)

GetVmList gets a list of VMs

func (*Client) GetVmStatus

func (c *Client) GetVmStatus(vm *VM) error

GetVmStatus retrieves current status metrics for a VM or LXC

func (*Client) GetWithCache

func (c *Client) GetWithCache(path string, result *map[string]interface{}, ttl time.Duration) error

GetWithCache makes a GET request to the Proxmox API with caching

func (*Client) GetWithRetry

func (c *Client) GetWithRetry(path string, result *map[string]interface{}, maxRetries int) error

GetWithRetry makes a GET request with retry logic

func (*Client) IsUsingTokenAuth

func (c *Client) IsUsingTokenAuth() bool

IsUsingTokenAuth returns true if the client is using API token authentication

func (*Client) ListNodes

func (c *Client) ListNodes() ([]Node, error)

ListNodes retrieves nodes from cached cluster data

func (*Client) Post

func (c *Client) Post(path string, data interface{}) error

Post makes a POST request to the Proxmox API

func (*Client) PostWithResponse

func (c *Client) PostWithResponse(path string, data interface{}, result *map[string]interface{}) error

PostWithResponse makes a POST request to the Proxmox API and returns the response

func (*Client) RefreshNodeData

func (c *Client) RefreshNodeData(nodeName string) (*Node, error)

RefreshNodeData refreshes data for a specific node by clearing its cache entries and fetching fresh data

func (*Client) RefreshVMData

func (c *Client) RefreshVMData(vm *VM, onEnrichmentComplete func(*VM)) (*VM, error)

RefreshVMData refreshes data for a specific VM by clearing its cache entries and fetching fresh data The onEnrichmentComplete callback is called after VM data has been enriched with guest agent information

func (*Client) RestartVM

func (c *Client) RestartVM(vm *VM) error

RestartVM restarts a VM or container

func (*Client) StartVM

func (c *Client) StartVM(vm *VM) error

StartVM starts a VM or container

func (*Client) StopVM

func (c *Client) StopVM(vm *VM) error

StopVM stops a VM or container

func (*Client) Version

func (c *Client) Version(ctx context.Context) (float64, error)

Version gets the Proxmox API version

type ClientOption

type ClientOption func(*ClientOptions)

ClientOption is a function that configures ClientOptions

func WithCache

func WithCache(cache interfaces.Cache) ClientOption

WithCache sets a custom cache for the client

func WithLogger

func WithLogger(logger interfaces.Logger) ClientOption

WithLogger sets a custom logger for the client

type ClientOptions

type ClientOptions struct {
	Logger interfaces.Logger
	Cache  interfaces.Cache
}

ClientOptions holds optional dependencies for the API client

type Cluster

type Cluster struct {
	Name           string          `json:"name"`
	Version        string          `json:"version"`
	Quorate        bool            `json:"quorate"`
	TotalNodes     int             `json:"total_nodes"`
	OnlineNodes    int             `json:"online"`
	TotalCPU       float64         `json:"total_cpu"`
	CPUUsage       float64         `json:"cpu_usage"`
	MemoryTotal    float64         `json:"memory_total"`
	MemoryUsed     float64         `json:"memory_used"`
	StorageTotal   int64           `json:"storage_total"`
	StorageUsed    int64           `json:"storage_used"`
	Nodes          []*Node         `json:"nodes"`
	StorageManager *StorageManager `json:"-"` // Storage manager for handling deduplication
	// contains filtered or unexported fields
}

Cluster represents aggregated Proxmox cluster metrics

type ExampleConfig

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

ExampleConfig demonstrates how to implement the Config interface

func NewExampleConfig

func NewExampleConfig(addr, user, password, realm string, insecure bool) *ExampleConfig

func (*ExampleConfig) GetAPIToken

func (c *ExampleConfig) GetAPIToken() string

func (*ExampleConfig) GetAddr

func (c *ExampleConfig) GetAddr() string

func (*ExampleConfig) GetInsecure

func (c *ExampleConfig) GetInsecure() bool

func (*ExampleConfig) GetPassword

func (c *ExampleConfig) GetPassword() string

func (*ExampleConfig) GetRealm

func (c *ExampleConfig) GetRealm() string

func (*ExampleConfig) GetTokenID

func (c *ExampleConfig) GetTokenID() string

func (*ExampleConfig) GetTokenSecret

func (c *ExampleConfig) GetTokenSecret() string

func (*ExampleConfig) GetUser

func (c *ExampleConfig) GetUser() string

func (*ExampleConfig) IsUsingTokenAuth

func (c *ExampleConfig) IsUsingTokenAuth() bool

type ExampleLogger

type ExampleLogger struct{}

ExampleLogger demonstrates how to implement the Logger interface

func (*ExampleLogger) Debug

func (l *ExampleLogger) Debug(format string, args ...interface{})

func (*ExampleLogger) Error

func (l *ExampleLogger) Error(format string, args ...interface{})

func (*ExampleLogger) Info

func (l *ExampleLogger) Info(format string, args ...interface{})

type Filesystem

type Filesystem struct {
	Name          string `json:"name"`
	Mountpoint    string `json:"mountpoint"`
	Type          string `json:"type"`
	TotalBytes    int64  `json:"total_bytes"`
	UsedBytes     int64  `json:"used_bytes"`
	Device        string `json:"device,omitempty"`
	IsRoot        bool   `json:"-"` // Determined by mountpoint ("/")
	IsSystemDrive bool   `json:"-"` // For Windows C: drive
}

Filesystem represents filesystem information from QEMU guest agent

type HTTPClient

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

HTTPClient wraps http.Client with Proxmox-specific functionality and dependency injection

func NewHTTPClient

func NewHTTPClient(httpClient *http.Client, baseURL string, logger interfaces.Logger) *HTTPClient

NewHTTPClient creates a new Proxmox HTTP client with dependency injection

func (*HTTPClient) Delete

func (hc *HTTPClient) Delete(ctx context.Context, path string, result *map[string]interface{}) error

Delete performs a DELETE request to the Proxmox API

func (*HTTPClient) Get

func (hc *HTTPClient) Get(ctx context.Context, path string, result *map[string]interface{}) error

Get performs a GET request to the Proxmox API

func (*HTTPClient) GetWithRetry

func (hc *HTTPClient) GetWithRetry(ctx context.Context, path string, result *map[string]interface{}, maxRetries int) error

GetWithRetry performs a GET request with retry logic

func (*HTTPClient) Post

func (hc *HTTPClient) Post(ctx context.Context, path string, data interface{}, result *map[string]interface{}) error

Post performs a POST request to the Proxmox API

func (*HTTPClient) Put

func (hc *HTTPClient) Put(ctx context.Context, path string, data interface{}, result *map[string]interface{}) error

Put performs a PUT request to the Proxmox API

func (*HTTPClient) SetAPIToken

func (hc *HTTPClient) SetAPIToken(token string)

SetAPIToken sets the API token for authentication

func (*HTTPClient) SetAuthManager

func (hc *HTTPClient) SetAuthManager(authManager *AuthManager)

SetAuthManager sets the auth manager for the HTTP client

type IPAddress

type IPAddress struct {
	Address string `json:"ip-address"`
	Type    string `json:"ip-address-type"` // ipv4 or ipv6
	Prefix  int    `json:"prefix"`
}

IPAddress represents an IP address from QEMU guest agent

type NetworkInterface

type NetworkInterface struct {
	Name        string                     `json:"name"`
	MACAddress  string                     `json:"hardware-address"`
	IPAddresses []IPAddress                `json:"ip-addresses"`
	Statistics  NetworkInterfaceStatistics `json:"statistics"`
	IsLoopback  bool                       `json:"-"` // Determined by name (lo)
}

NetworkInterface represents a network interface from QEMU guest agent

type NetworkInterfaceStatistics

type NetworkInterfaceStatistics struct {
	RxBytes   int64 `json:"rx-bytes"`
	RxDropped int64 `json:"rx-dropped"`
	RxErrors  int64 `json:"rx-errs"`
	RxPackets int64 `json:"rx-packets"`
	TxBytes   int64 `json:"tx-bytes"`
	TxDropped int64 `json:"tx-dropped"`
	TxErrors  int64 `json:"tx-errs"`
	TxPackets int64 `json:"tx-packets"`
}

NetworkInterfaceStatistics represents network interface statistics from QEMU guest agent

type Node

type Node struct {
	ID            string   `json:"id"`
	Name          string   `json:"name"`
	IP            string   `json:"ip"`
	CPUCount      float64  `json:"cpus"`
	CPUUsage      float64  `json:"cpu"`
	MemoryTotal   float64  `json:"memory_total"`
	MemoryUsed    float64  `json:"memory_used"`
	TotalStorage  int64    `json:"rootfs_total"`
	UsedStorage   int64    `json:"rootfs_used"`
	Uptime        int64    `json:"uptime"`
	Version       string   `json:"pveversion"`
	KernelVersion string   `json:"kversion"`
	Online        bool     `json:"-"`
	CGroupMode    int      `json:"cgroup_mode,omitempty"`
	Level         string   `json:"level,omitempty"`
	Storage       *Storage `json:"storage,omitempty"`
	VMs           []*VM    `json:"vms,omitempty"`
	CPUInfo       *CPUInfo `json:"cpuinfo,omitempty"`
	LoadAvg       []string `json:"loadavg,omitempty"`
	// contains filtered or unexported fields
}

Node represents a Proxmox cluster node

type Storage

type Storage struct {
	ID         string `json:"id"`         // Full ID like "storage/saturn/bigdiggus-ssd"
	Name       string `json:"storage"`    // Storage name like "bigdiggus-ssd"
	Content    string `json:"content"`    // Content types: "vztmpl,snippets,iso,rootdir,images"
	Disk       int64  `json:"disk"`       // Used space in bytes
	MaxDisk    int64  `json:"maxdisk"`    // Total space in bytes
	Node       string `json:"node"`       // Node name
	Plugintype string `json:"plugintype"` // Storage type: nfs, dir, lvmthin, zfspool, etc.
	Status     string `json:"status"`     // Status: available, etc.
	Shared     int    `json:"shared"`     // Whether storage is shared across nodes (1/0 from API)
	Type       string `json:"type"`       // Always "storage" from API
}

Storage represents a Proxmox storage resource

func (*Storage) GetTotalGB

func (s *Storage) GetTotalGB() float64

GetTotalGB returns total space in GB

func (*Storage) GetUsageGB

func (s *Storage) GetUsageGB() float64

GetUsageGB returns used space in GB

func (*Storage) GetUsagePercent

func (s *Storage) GetUsagePercent() float64

GetUsagePercent returns the storage usage as a percentage

func (*Storage) IsShared

func (s *Storage) IsShared() bool

IsShared returns true if this storage is shared across multiple nodes

type StorageManager

type StorageManager struct {
	// AllStorages contains all storage entries (including duplicates for shared storage)
	AllStorages []*Storage

	// UniqueStorages contains deduplicated storage entries
	// For shared storage, only one entry is kept
	// For local storage, all entries are kept since they're unique per node
	UniqueStorages []*Storage

	// SharedStorages contains only shared storage entries (deduplicated)
	SharedStorages []*Storage

	// LocalStorages contains only local storage entries (per node)
	LocalStorages []*Storage
}

StorageManager handles storage aggregation and deduplication

func NewStorageManager

func NewStorageManager() *StorageManager

NewStorageManager creates a new storage manager

func (*StorageManager) AddStorage

func (sm *StorageManager) AddStorage(storage *Storage)

AddStorage adds a storage entry and handles deduplication

func (*StorageManager) GetTotalCapacity

func (sm *StorageManager) GetTotalCapacity() int64

GetTotalCapacity returns total capacity across all unique storages

func (*StorageManager) GetTotalUsage

func (sm *StorageManager) GetTotalUsage() int64

GetTotalUsage returns total used space across all unique storages

type VM

type VM struct {
	ID        int     `json:"id"`
	Name      string  `json:"name"`
	Node      string  `json:"node"`
	Type      string  `json:"type"`
	Status    string  `json:"status"`
	IP        string  `json:"ip,omitempty"`
	CPU       float64 `json:"cpu,omitempty"`
	Mem       int64   `json:"mem,omitempty"`
	MaxMem    int64   `json:"maxmem,omitempty"`
	Disk      int64   `json:"disk,omitempty"`
	MaxDisk   int64   `json:"maxdisk,omitempty"`
	Uptime    int64   `json:"uptime,omitempty"`
	DiskRead  int64   `json:"diskread,omitempty"`
	DiskWrite int64   `json:"diskwrite,omitempty"`
	NetIn     int64   `json:"netin,omitempty"`
	NetOut    int64   `json:"netout,omitempty"`
	HAState   string  `json:"hastate,omitempty"`
	Lock      string  `json:"lock,omitempty"`
	Tags      string  `json:"tags,omitempty"`
	Template  bool    `json:"template,omitempty"`
	Pool      string  `json:"pool,omitempty"`

	// Guest agent related fields
	AgentEnabled   bool               `json:"agent_enabled,omitempty"`
	AgentRunning   bool               `json:"agent_running,omitempty"`
	NetInterfaces  []NetworkInterface `json:"net_interfaces,omitempty"`
	Filesystems    []Filesystem       `json:"filesystems,omitempty"`
	ConfiguredMACs map[string]bool    `json:"-"` // Stores MACs from VM config (net0, net1, etc.)

	Enriched bool `json:"-"`
	// contains filtered or unexported fields
}

VM represents a Proxmox VM or container

type VNCProxyResponse

type VNCProxyResponse struct {
	Ticket string `json:"ticket"`
	Port   string `json:"port"`
	User   string `json:"user"`
	Cert   string `json:"cert"`
}

VNCProxyResponse represents the response from a VNC proxy request

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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