Documentation
¶
Overview ¶
Package api provides a comprehensive client library for the Proxmox Virtual Environment API.
This package implements a clean, testable client for interacting with Proxmox VE clusters, including authentication, resource management, and monitoring capabilities. It supports both password-based and API token authentication methods.
Key Features:
- Clean Architecture with dependency injection
- Comprehensive authentication support (password + API tokens)
- Built-in caching with configurable TTL
- Structured logging with configurable levels
- Robust error handling and retry logic
- Full support for VMs, containers, nodes, and cluster operations
- Thread-safe operations with proper concurrency handling
Basic Usage:
// Create configuration
config := &Config{
Addr: "https://pve.example.com:8006",
User: "root",
Password: "password",
Realm: "pam",
}
// Create client with optional logger and cache
client, err := NewClient(config, WithLogger(logger), WithCache(cache))
if err != nil {
log.Fatal(err)
}
// Use the client
vms, err := client.GetVmList(context.Background())
if err != nil {
log.Fatal(err)
}
Authentication:
The package supports two authentication methods:
1. Password Authentication (username/password):
- Automatically handles ticket-based authentication
- Manages CSRF tokens for write operations
- Handles token refresh and expiration
2. API Token Authentication:
- Uses Proxmox API tokens for stateless authentication
- No session management required
- Recommended for automated/service accounts
Thread Safety:
All client operations are thread-safe and can be used concurrently from multiple goroutines. Internal state is protected with appropriate synchronization primitives.
Package api provides Proxmox API client functionality.
Package api provides Proxmox API client functionality.
Package api provides Proxmox API client functionality.
Index ¶
- Constants
- func ExampleUsage()
- func FormatBytes(bytes int64) string
- func FormatUptime(seconds int64) string
- func GetFirstNonLoopbackIP(interfaces []NetworkInterface, preferIPv4 bool) string
- func ParseVMID(input interface{}) (int, error)
- func SafeBoolValue(value interface{}) bool
- func SafeFloatValue(value interface{}) float64
- func SafeStringValue(value interface{}) string
- type AuthManager
- type AuthToken
- type Backup
- type BackupOptions
- type CPUInfo
- type Client
- func (c *Client) BaseHostname() string
- func (c *Client) ClearAPICache()
- func (c *Client) CreateBackup(vm *VM, options BackupOptions) (string, error)
- func (c *Client) CreateSnapshot(vm *VM, name string, options *SnapshotOptions) error
- func (c *Client) Delete(path string) error
- func (c *Client) DeleteBackup(vm *VM, volID string) error
- func (c *Client) DeleteSnapshot(vm *VM, snapshotName string) error
- func (c *Client) DeleteVM(vm *VM) error
- func (c *Client) DeleteVMWithOptions(vm *VM, options *DeleteVMOptions) error
- func (c *Client) EnrichVMs(cluster *Cluster) error
- func (c *Client) ExecGuestAgentCommand(vm *VM, command []string) (int, error)
- func (c *Client) ExecuteGuestAgentCommand(ctx context.Context, vm *VM, command []string, timeout time.Duration) (stdout, stderr string, exitCode int, err error)
- func (c *Client) FastGetClusterStatus(onEnrichmentComplete func()) (*Cluster, error)
- func (c *Client) GenerateNodeVNCURL(nodeName string) (string, error)
- func (c *Client) GenerateVNCURL(vm *VM) (string, error)
- func (c *Client) Get(path string, result *map[string]interface{}) error
- func (c *Client) GetAuthToken() string
- func (c *Client) GetBackups(vm *VM) ([]Backup, error)
- func (c *Client) GetBaseURL() string
- func (c *Client) GetCache() interfaces.Cache
- func (c *Client) GetClusterStatus() (*Cluster, error)
- func (c *Client) GetClusterTasks() ([]*ClusterTask, error)
- func (c *Client) GetDetailedVmInfo(node, vmType string, vmid int) (*VM, error)
- func (c *Client) GetFreshClusterStatus() (*Cluster, error)
- func (c *Client) GetGuestAgentExecStatus(vm *VM, pid int) (*GuestAgentExecStatus, error)
- func (c *Client) GetGuestAgentFilesystems(vm *VM) ([]Filesystem, error)
- func (c *Client) GetGuestAgentInterfaces(vm *VM) ([]NetworkInterface, error)
- func (c *Client) GetLxcInterfaces(vm *VM) ([]NetworkInterface, error)
- func (c *Client) GetNoRetry(path string, result *map[string]interface{}) error
- func (c *Client) GetNodeConfig(nodeName string) (map[string]interface{}, error)
- func (c *Client) GetNodeStatus(nodeName string) (*Node, error)
- func (c *Client) GetNodeStorages(nodeName string) ([]*Storage, error)
- func (c *Client) GetNodeVNCShell(nodeName string) (*VNCProxyResponse, error)
- func (c *Client) GetNodeVNCShellWithWebSocket(nodeName string) (*VNCProxyResponse, error)
- func (c *Client) GetSnapshots(vm *VM) ([]Snapshot, error)
- func (c *Client) GetTaskStatus(node, upid string) (*TaskStatus, error)
- func (c *Client) GetVMConfig(vm *VM) (*VMConfig, error)
- func (c *Client) GetVNCProxy(vm *VM) (*VNCProxyResponse, error)
- func (c *Client) GetVNCProxyWithWebSocket(vm *VM) (*VNCProxyResponse, error)
- func (c *Client) GetVmList(ctx context.Context) ([]map[string]interface{}, error)
- func (c *Client) GetVmStatus(vm *VM) error
- func (c *Client) GetWithCache(path string, result *map[string]interface{}, ttl time.Duration) error
- func (c *Client) GetWithRetry(path string, result *map[string]interface{}, maxRetries int) error
- func (c *Client) IsUsingTokenAuth() bool
- func (c *Client) ListNodes() ([]Node, error)
- func (c *Client) MigrateVM(vm *VM, options *MigrationOptions) (string, error)
- func (c *Client) Post(path string, data interface{}) error
- func (c *Client) PostWithResponse(path string, data interface{}, result *map[string]interface{}) error
- func (c *Client) RefreshNodeData(nodeName string) (*Node, error)
- func (c *Client) RefreshVMData(vm *VM, onEnrichmentComplete func(*VM)) (*VM, error)
- func (c *Client) ResetVM(vm *VM) error
- func (c *Client) ResizeVMStorage(vm *VM, disk string, size string) error
- func (c *Client) RestartVM(vm *VM) error
- func (c *Client) RestoreBackup(vm *VM, volID string) (string, error)
- func (c *Client) RollbackToSnapshot(vm *VM, snapshotName string) error
- func (c *Client) ShutdownVM(vm *VM) error
- func (c *Client) StartVM(vm *VM) error
- func (c *Client) StopVM(vm *VM) error
- func (c *Client) UpdateVMConfig(vm *VM, config *VMConfig) error
- func (c *Client) UpdateVMResources(vm *VM, cores int, memory int64) error
- func (c *Client) Version(ctx context.Context) (float64, error)
- func (c *Client) WaitForTaskCompletion(upid string, operationName string, maxWait time.Duration) error
- type ClientOption
- type ClientOptions
- type Cluster
- type ClusterTask
- type ConfiguredNetwork
- type ConnectionSummary
- type DeleteVMOptions
- type ExampleConfig
- func (c *ExampleConfig) GetAPIToken() string
- func (c *ExampleConfig) GetAddr() string
- func (c *ExampleConfig) GetInsecure() bool
- func (c *ExampleConfig) GetPassword() string
- func (c *ExampleConfig) GetRealm() string
- func (c *ExampleConfig) GetTokenID() string
- func (c *ExampleConfig) GetTokenSecret() string
- func (c *ExampleConfig) GetUser() string
- func (c *ExampleConfig) IsUsingTokenAuth() bool
- type ExampleLogger
- type Filesystem
- type GroupClientManager
- func (m *GroupClientManager) Close()
- func (m *GroupClientManager) ExecuteOnAllProfiles(ctx context.Context, operation ProfileOperation) []ProfileResult
- func (m *GroupClientManager) ExecuteOnProfile(ctx context.Context, profileName string, operation ProfileOperation) (interface{}, error)
- func (m *GroupClientManager) FindNodeByNameInGroup(ctx context.Context, nodeName string) (*Node, string, error)
- func (m *GroupClientManager) FindVMByIDInGroup(ctx context.Context, vmID int) (*VM, string, error)
- func (m *GroupClientManager) GetAllClients() []*ProfileClient
- func (m *GroupClientManager) GetClient(profileName string) (*ProfileClient, bool)
- func (m *GroupClientManager) GetConnectedClients() []*ProfileClient
- func (m *GroupClientManager) GetConnectionSummary() ConnectionSummary
- func (m *GroupClientManager) GetGroupClusterResources(ctx context.Context, fresh bool) ([]*Node, []*VM, error)
- func (m *GroupClientManager) GetGroupData(ctx context.Context, operation ProfileOperation, ...) (interface{}, error)
- func (m *GroupClientManager) GetGroupName() string
- func (m *GroupClientManager) GetGroupNodes(ctx context.Context) ([]*Node, error)
- func (m *GroupClientManager) GetGroupTasks(ctx context.Context) ([]*ClusterTask, error)
- func (m *GroupClientManager) GetGroupVMs(ctx context.Context) ([]*VM, error)
- func (m *GroupClientManager) GetNodeFromGroup(ctx context.Context, profileName string, nodeName string) (*Node, error)
- func (m *GroupClientManager) GetVMFromGroup(ctx context.Context, profileName string, nodeName string, vmType string, ...) (*VM, error)
- func (m *GroupClientManager) Initialize(ctx context.Context, profiles []ProfileEntry) error
- func (m *GroupClientManager) RefreshAllFailedProfiles(ctx context.Context, profileConfigs map[string]interfaces.Config) map[string]error
- func (m *GroupClientManager) RefreshProfileConnection(ctx context.Context, profileName string, profileConfig interfaces.Config) error
- type GuestAgentExecRequest
- type GuestAgentExecResponse
- type GuestAgentExecStatus
- type HTTPClient
- func (hc *HTTPClient) Delete(ctx context.Context, path string, result *map[string]interface{}) error
- func (hc *HTTPClient) Get(ctx context.Context, path string, result *map[string]interface{}) error
- func (hc *HTTPClient) GetWithRetry(ctx context.Context, path string, result *map[string]interface{}, ...) error
- func (hc *HTTPClient) Post(ctx context.Context, path string, data interface{}, ...) error
- func (hc *HTTPClient) Put(ctx context.Context, path string, data interface{}, ...) error
- func (hc *HTTPClient) SetAPIToken(token string)
- func (hc *HTTPClient) SetAuthManager(authManager *AuthManager)
- type IPAddress
- type MigrationOptions
- type NetworkInterface
- type NetworkInterfaceStatistics
- type Node
- type ProfileClient
- type ProfileConnectionStatus
- type ProfileEntry
- type ProfileOperation
- type ProfileResult
- type Snapshot
- type SnapshotOptions
- type Storage
- type StorageDevice
- type StorageManager
- type TaskStatus
- type VM
- type VMConfig
- type VNCProxyResponse
Constants ¶
const ( ClusterDataTTL = 1 * time.Hour NodeDataTTL = 1 * time.Hour VMDataTTL = 1 * time.Hour ResourceDataTTL = 1 * time.Hour )
Cache TTLs for different types of data.
const ( DefaultAPITimeout = 30 * time.Second DefaultRetryCount = 3 DefaultMaxAttempts = DefaultRetryCount // Alias for clarity )
Default API request timeout and retry configuration.
const ( VMTypeQemu = "qemu" VMTypeLXC = "lxc" )
VM Types.
const ( VMStatusRunning = "running" VMStatusStopped = "stopped" )
VM Status.
const ( IPTypeIPv4 = "ipv4" IPTypeIPv6 = "ipv6" )
IP Types.
const ( StringTrue = "true" StringNA = "N/A" )
Common strings.
const ( HTTPMethodPOST = "POST" HTTPMethodPUT = "PUT" HTTPMethodDELETE = "DELETE" )
HTTP Methods.
const ( PageNodes = "Nodes" PageGuests = "Guests" PageTasks = "Tasks" )
UI Pages.
const ( ActionRefresh = "Refresh" ActionOpenShell = "Open Shell" ActionMigrate = "Migrate" )
Menu actions.
const (
EndpointAccessTicket = "/access/ticket"
)
API Endpoints.
const (
LoopbackInterface = "lo"
)
Network interface names.
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 FormatBytes ¶
FormatBytes converts a byte count into a human-readable string with appropriate units.
This function formats byte values using binary units (1024-based) and provides a consistent, human-readable representation. The function automatically selects the most appropriate unit (B, KB, MB, GB, TB) based on the input size.
Formatting rules:
- Values in bytes are shown as integers (e.g., "42 B")
- Larger values are shown with one decimal place (e.g., "1.5 GB")
- Zero bytes returns "0 B"
- Uses binary units (1024 bytes = 1 KB)
Parameters:
- bytes: The number of bytes to format
Returns a formatted string with value and unit.
Example usage:
fmt.Println(FormatBytes(0)) // "0 B" fmt.Println(FormatBytes(1024)) // "1.0 KB" fmt.Println(FormatBytes(1536)) // "1.5 KB" fmt.Println(FormatBytes(1073741824)) // "1.0 GB"
func FormatUptime ¶
FormatUptime converts seconds into a human-readable uptime string.
This function formats duration values (in seconds) into a natural language representation showing days, hours, minutes, and seconds as appropriate. Only non-zero units are included in the output.
Formatting rules:
- Shows only relevant units (omits zero values)
- Uses natural language (e.g., "2 days, 3 hours, 15 minutes, 30 seconds")
- Handles singular and plural forms correctly
- Zero seconds returns "0 seconds"
Parameters:
- seconds: The duration in seconds to format
Returns a formatted uptime string.
Example usage:
fmt.Println(FormatUptime(0)) // "0 seconds" fmt.Println(FormatUptime(65)) // "1 minute, 5 seconds" fmt.Println(FormatUptime(3661)) // "1 hour, 1 minute, 1 second" fmt.Println(FormatUptime(90061)) // "1 day, 1 hour, 1 minute, 1 second"
func GetFirstNonLoopbackIP ¶
func GetFirstNonLoopbackIP(interfaces []NetworkInterface, preferIPv4 bool) string
GetFirstNonLoopbackIP returns the first non-loopback IP address from network interfaces.
func ParseVMID ¶
ParseVMID extracts and validates a VM ID from various input types.
This function handles the common scenario where VM IDs can come from different sources (JSON APIs, user input, etc.) in various formats. It safely converts the input to a valid integer VM ID.
Supported input types:
- int: Direct integer value
- float64: Floating-point number (common from JSON)
- string: Numeric string representation
- Other types: Return error
Validation rules:
- Must be a positive integer
- Zero is considered invalid
- Negative numbers are invalid
Parameters:
- input: The value to parse as a VM ID
Returns the VM ID as an integer, or an error if invalid.
Example usage:
vmid, err := ParseVMID(123) // Returns 123, nil
vmid, err := ParseVMID(123.0) // Returns 123, nil
vmid, err := ParseVMID("123") // Returns 123, nil
vmid, err := ParseVMID("invalid") // Returns 0, error
vmid, err := ParseVMID(-1) // Returns 0, error
func SafeBoolValue ¶
func SafeBoolValue(value interface{}) bool
SafeBoolValue safely converts various types to boolean representation.
This function provides a safe way to convert interface{} values to boolean, handling multiple representations commonly found in APIs and configuration. It follows common conventions for truthy/falsy values.
Conversion rules:
- bool: Returns as-is
- string: "true", "1" → true; "false", "0" → false (case-insensitive)
- int, float64: 0 → false; non-zero → true
- Other types: Returns false
Parameters:
- value: The value to convert to boolean
Returns a boolean representation of the value.
Example usage:
b := SafeBoolValue(true) // true
b := SafeBoolValue("true") // true
b := SafeBoolValue("1") // true
b := SafeBoolValue(1) // true
b := SafeBoolValue(0) // false
b := SafeBoolValue("false") // false
func SafeFloatValue ¶
func SafeFloatValue(value interface{}) float64
SafeFloatValue safely converts various types to float64 representation.
This function provides a safe way to convert interface{} values to float64, handling multiple numeric types and string representations. It never panics and returns 0.0 for non-convertible values.
Supported conversions:
- float64: Returns as-is
- int, int64: Converts to float64
- string: Attempts to parse as float64
- Other types: Returns 0.0
Parameters:
- value: The value to convert to float64
Returns a float64 representation of the value, or 0.0 if not convertible.
Example usage:
f := SafeFloatValue(123.45) // 123.45
f := SafeFloatValue(123) // 123.0
f := SafeFloatValue("123.45") // 123.45
f := SafeFloatValue("invalid") // 0.0
func SafeStringValue ¶
func SafeStringValue(value interface{}) string
SafeStringValue safely converts various types to string representation.
This function provides a safe way to convert interface{} values to strings, handling multiple common types that can appear in JSON or API responses. It never panics and always returns a string value.
Supported conversions:
- string: Returns as-is
- int, int64, float64: Converts to string representation
- bool: Returns "true" or "false"
- nil: Returns empty string
- Other types: Returns fmt.Sprintf("%v", value)
Parameters:
- value: The value to convert to string
Returns a string representation of the value.
Example usage:
str := SafeStringValue("hello") // "hello"
str := SafeStringValue(123) // "123"
str := SafeStringValue(true) // "true"
str := SafeStringValue(nil) // ""
Types ¶
type AuthManager ¶
type AuthManager struct {
// contains filtered or unexported fields
}
AuthManager handles Proxmox API authentication with support for both password-based and API token authentication methods.
The manager automatically handles:
- Token caching and refresh for password authentication
- CSRF token management for write operations
- Thread-safe access to authentication state
- Automatic re-authentication when tokens expire
For password authentication, the manager maintains an internal authentication token that is refreshed as needed. For API token authentication, the manager simply configures the HTTP client with the provided token.
All methods are safe for concurrent use from multiple goroutines.
func NewAuthManagerWithPassword ¶
func NewAuthManagerWithPassword(httpClient *HTTPClient, username, password string, logger interfaces.Logger) *AuthManager
NewAuthManagerWithPassword creates a new authentication manager for password-based authentication.
This method sets up the manager to use username/password authentication with automatic ticket management. The manager will authenticate with Proxmox and cache the resulting authentication ticket for subsequent requests.
Parameters:
- httpClient: HTTP client configured for the Proxmox server
- username: Proxmox username (without realm, e.g., "root")
- password: User password
- logger: Logger for debugging and error reporting
Example usage:
authManager := NewAuthManagerWithPassword(httpClient, "root", "password", logger)
err := authManager.EnsureAuthenticated()
if err != nil {
log.Fatal("Authentication failed:", err)
}
func NewAuthManagerWithToken ¶
func NewAuthManagerWithToken(httpClient *HTTPClient, token string, logger interfaces.Logger) *AuthManager
NewAuthManagerWithToken creates a new authentication manager for API token authentication.
This method sets up the manager to use Proxmox API tokens for stateless authentication. API tokens don't require session management and are recommended for automated systems and service accounts.
Parameters:
- httpClient: HTTP client configured for the Proxmox server
- token: Complete API token string in Proxmox format (PVEAPIToken=USER@REALM!TOKENID=SECRET)
- logger: Logger for debugging and error reporting
Example usage:
token := "PVEAPIToken=root@pam!mytoken=12345678-1234-1234-1234-123456789abc"
authManager := NewAuthManagerWithToken(httpClient, token, logger)
err := authManager.EnsureAuthenticated()
if err != nil {
log.Fatal("Authentication failed:", err)
}
func (*AuthManager) ClearToken ¶
func (am *AuthManager) ClearToken()
ClearToken clears the cached authentication token, forcing re-authentication on next use.
This method is useful when you know the current token is invalid (e.g., after receiving 401 responses) or when you want to force a fresh authentication. The method is thread-safe and can be called from multiple goroutines.
After calling this method, the next API request will trigger re-authentication.
Example usage:
// Clear token after receiving 401 error
if isUnauthorizedError(err) {
authManager.ClearToken()
// Next request will re-authenticate
}
func (*AuthManager) EnsureAuthenticated ¶
func (am *AuthManager) EnsureAuthenticated() error
EnsureAuthenticated ensures the client is properly authenticated and ready for API calls.
For API token authentication, this method configures the HTTP client with the token. For password authentication, this method performs the initial authentication if needed.
This method should be called before making any API requests to ensure proper authentication state. It's safe to call multiple times.
Returns an error if authentication fails or if the configuration is invalid.
func (*AuthManager) GetValidToken ¶
func (am *AuthManager) GetValidToken(ctx context.Context) (*AuthToken, error)
GetValidToken returns a valid authentication token, refreshing if necessary.
For API token authentication, this method returns a dummy AuthToken containing the API token string. For password authentication, this method returns the cached token if valid, or performs re-authentication if the token is expired or missing.
This method is thread-safe and handles concurrent access properly. Multiple goroutines can call this method simultaneously without issues.
Parameters:
- ctx: Context for cancellation and timeout control
Returns the authentication token or an error if authentication fails.
Example usage:
token, err := authManager.GetValidToken(ctx)
if err != nil {
return fmt.Errorf("authentication failed: %w", err)
}
// Use token for API requests
func (*AuthManager) IsTokenAuth ¶
func (am *AuthManager) IsTokenAuth() bool
IsTokenAuth returns true if the authentication manager is configured for API token authentication.
This method helps distinguish between password-based and token-based authentication modes, which can be useful for conditional logic or debugging.
Returns true for API token authentication, false for password authentication.
Example usage:
if authManager.IsTokenAuth() {
log.Println("Using API token authentication")
} else {
log.Println("Using password authentication")
}
type AuthToken ¶
type AuthToken struct {
Ticket string `json:"ticket"` // Authentication ticket for session-based auth
CSRFToken string `json:"csrf_token"` // CSRF prevention token for write operations
Username string `json:"username"` // Authenticated username
ExpiresAt time.Time `json:"expires_at"` // Token expiration time
}
AuthToken represents a Proxmox authentication token containing session information.
This structure holds the authentication ticket, CSRF prevention token, and expiration information returned by the Proxmox API during password-based authentication. The token is used for subsequent API requests until it expires.
For API token authentication, this structure is used as a container but the actual API token string is used directly in Authorization headers.
func (*AuthToken) IsValid ¶
IsValid checks if the authentication token is still valid and not expired.
Returns true if the token exists, has a non-empty ticket, and the current time is before the expiration time. This method is safe to call on nil tokens.
Example usage:
if token != nil && token.IsValid() {
// Use existing token
} else {
// Need to re-authenticate
}
type Backup ¶ added in v1.0.15
type Backup struct {
VolID string `json:"volid"` // Volume ID (e.g., "local:backup/vzdump-qemu-100-....vma.zst")
Name string `json:"name,omitempty"` // Derived name
Date time.Time `json:"date"` // Backup timestamp
Size int64 `json:"size"` // Size in bytes
Format string `json:"format"` // Format (vma, tar, etc.)
Notes string `json:"notes"` // Notes/Description
VMID int `json:"vmid"` // VM ID
Storage string `json:"storage"` // Storage name
Content string `json:"content"` // Content type (backup)
Verification string `json:"verification"` // Verification status
}
Backup represents a Proxmox backup (vzdump) file.
type BackupOptions ¶ added in v1.0.15
type BackupOptions struct {
Mode string // "snapshot", "suspend", "stop"
Compression string // "zstd", "gzip", "lzo"
Notes string // Description
Storage string // Target storage
Remove bool // Remove old backups (prune)
Notification string // "auto", "always", "never"
}
BackupOptions contains options for creating backups.
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) BaseHostname ¶ added in v1.0.14
BaseHostname returns the hostname component of the configured API base URL. Falls back to the raw baseURL string if parsing fails.
func (*Client) ClearAPICache ¶
func (c *Client) ClearAPICache()
ClearAPICache removes all API-related cached responses.
func (*Client) CreateBackup ¶ added in v1.0.15
func (c *Client) CreateBackup(vm *VM, options BackupOptions) (string, error)
CreateBackup creates a new backup for the VM. It returns the UPID of the backup task.
func (*Client) CreateSnapshot ¶
func (c *Client) CreateSnapshot(vm *VM, name string, options *SnapshotOptions) error
CreateSnapshot creates a new snapshot for a VM or container.
func (*Client) DeleteBackup ¶ added in v1.0.15
DeleteBackup deletes a backup volume.
func (*Client) DeleteSnapshot ¶
DeleteSnapshot deletes a snapshot from a VM or container.
func (*Client) DeleteVM ¶
DeleteVM permanently deletes a VM or container WARNING: This operation is irreversible and will destroy all VM data including disks.
func (*Client) DeleteVMWithOptions ¶
func (c *Client) DeleteVMWithOptions(vm *VM, options *DeleteVMOptions) error
DeleteVMWithOptions permanently deletes a VM or container with specific options WARNING: This operation is irreversible and will destroy all VM data including disks.
func (*Client) EnrichVMs ¶
EnrichVMs enriches all VMs in the cluster with detailed status information.
func (*Client) ExecGuestAgentCommand ¶ added in v1.0.9
ExecGuestAgentCommand starts command execution via QEMU guest agent. Returns the PID of the started process.
func (*Client) ExecuteGuestAgentCommand ¶ added in v1.0.9
func (c *Client) ExecuteGuestAgentCommand(ctx context.Context, vm *VM, command []string, timeout time.Duration) (stdout, stderr string, exitCode int, err error)
ExecuteGuestAgentCommand executes a command via QEMU guest agent and waits for completion. This is a convenience wrapper around ExecGuestAgentCommand and GetGuestAgentExecStatus.
func (*Client) FastGetClusterStatus ¶
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 ¶
GenerateNodeVNCURL creates a noVNC shell URL for the given node.
func (*Client) GenerateVNCURL ¶
GenerateVNCURL creates a noVNC console URL for the given VM.
func (*Client) GetAuthToken ¶
GetAuthToken returns the authentication token for API requests.
func (*Client) GetBackups ¶ added in v1.0.15
GetBackups retrieves all backups for a VM across all available storages.
func (*Client) GetBaseURL ¶
GetBaseURL returns the base URL of the Proxmox API.
func (*Client) GetCache ¶ added in v1.0.14
func (c *Client) GetCache() interfaces.Cache
GetCache returns the cache instance used by this client. This is useful for sharing cache instances across multiple clients in group mode.
func (*Client) GetClusterStatus ¶
GetClusterStatus retrieves high-level cluster status and node list.
func (*Client) GetClusterTasks ¶
func (c *Client) GetClusterTasks() ([]*ClusterTask, error)
GetClusterTasks retrieves recent cluster tasks.
func (*Client) GetDetailedVmInfo ¶
GetDetailedVmInfo retrieves complete information about a VM by combining status and config data (cached).
func (*Client) GetFreshClusterStatus ¶
GetFreshClusterStatus retrieves cluster status bypassing cache completely.
func (*Client) GetGuestAgentExecStatus ¶ added in v1.0.9
func (c *Client) GetGuestAgentExecStatus(vm *VM, pid int) (*GuestAgentExecStatus, error)
GetGuestAgentExecStatus retrieves the status of a command executed via guest agent.
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 ¶
GetNoRetry makes a GET request to the Proxmox API without retry logic but with timeout.
func (*Client) GetNodeConfig ¶
GetNodeConfig retrieves configuration for a given node with caching.
func (*Client) GetNodeStatus ¶
GetNodeStatus retrieves real-time status for a specific node.
func (*Client) GetNodeStorages ¶ added in v1.0.15
GetNodeStorages retrieves all storages available on 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) GetNodeVNCShellWithWebSocket ¶
func (c *Client) GetNodeVNCShellWithWebSocket(nodeName string) (*VNCProxyResponse, error)
GetNodeVNCShellWithWebSocket creates a VNC shell connection for a node with WebSocket support and one-time password.
func (*Client) GetSnapshots ¶
GetSnapshots retrieves all snapshots for a VM or container.
func (*Client) GetTaskStatus ¶ added in v1.0.15
func (c *Client) GetTaskStatus(node, upid string) (*TaskStatus, error)
GetTaskStatus retrieves the status of a specific task.
func (*Client) GetVMConfig ¶
GetVMConfig fetches the configuration for a VM or container.
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) GetVNCProxyWithWebSocket ¶
func (c *Client) GetVNCProxyWithWebSocket(vm *VM) (*VNCProxyResponse, error)
GetVNCProxyWithWebSocket creates a VNC proxy for a VM with WebSocket support and one-time password.
func (*Client) GetVmStatus ¶
GetVmStatus retrieves current status metrics for a VM or LXC.
func (*Client) GetWithCache ¶
GetWithCache makes a GET request to the Proxmox API with caching.
func (*Client) GetWithRetry ¶
GetWithRetry makes a GET request with retry logic and timeout.
func (*Client) IsUsingTokenAuth ¶
IsUsingTokenAuth returns true if the client is using API token authentication.
func (*Client) MigrateVM ¶
func (c *Client) MigrateVM(vm *VM, options *MigrationOptions) (string, error)
MigrateVM migrates a VM or container to another node using the Proxmox API.
The migration process supports both QEMU VMs and LXC containers with different options and behaviors:
For QEMU VMs:
- Online migration (live migration) is supported for running VMs
- Offline migration requires the VM to be stopped first
- Supports bandwidth limiting and migration network specification
For LXC containers:
- Migration type can be "secure" (default) or "insecure"
- Online migration is supported for running containers
- Supports bandwidth limiting
The function performs validation to ensure:
- Target node is specified and exists in the cluster
- Target node is different from the source node
- Target node is online and available
Migration is an asynchronous operation. The function returns a task UPID that can be monitored via the WaitForTaskCompletion method or the cluster tasks API.
Example usage:
options := &api.MigrationOptions{
Target: "node2",
Online: &[]bool{true}[0], // Enable online migration
BandwidthLimit: 1000, // Limit to 1000 KB/s
}
upid, err := client.MigrateVM(vm, options)
if err != nil {
return err
}
// Wait for migration to complete (migrations can take several minutes)
err = client.WaitForTaskCompletion(upid, "VM migration", 10*time.Minute)
Parameters:
- vm: The VM or container to migrate
- options: Migration configuration options
Returns the task UPID and an error if the migration cannot be initiated.
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 with timeout.
func (*Client) RefreshNodeData ¶
RefreshNodeData refreshes data for a specific node by clearing its cache entries and fetching fresh data.
func (*Client) RefreshVMData ¶
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) ResetVM ¶
ResetVM performs a hard reset (like pressing the reset button). Only supported for QEMU VMs. Not applicable to LXC.
func (*Client) ResizeVMStorage ¶
ResizeVMStorage resizes a disk for a VM or container.
func (*Client) RestartVM ¶
RestartVM restarts a VM or container
Both QEMU VMs and LXC containers use the `/status/reboot` endpoint according to the official Proxmox VE API documentation.
Parameters:
- vm: The VM or container to restart
Returns an error if the restart operation fails.
func (*Client) RestoreBackup ¶ added in v1.0.15
RestoreBackup restores a backup to the VM. If the VM exists, it will be overwritten.
func (*Client) RollbackToSnapshot ¶
RollbackToSnapshot rolls back a VM or container to a specific snapshot.
func (*Client) ShutdownVM ¶
ShutdownVM requests a graceful shutdown via the guest OS. For both QEMU and LXC, Proxmox exposes `/status/shutdown`. The guest tools/agent should be installed for reliable behavior.
func (*Client) UpdateVMConfig ¶
UpdateVMConfig updates the configuration for a VM or container. For LXC: uses PUT (synchronous, no task ID) For QEMU: uses POST (asynchronous, returns task ID).
func (*Client) UpdateVMResources ¶
UpdateVMResources updates CPU and memory for a VM or container.
func (*Client) WaitForTaskCompletion ¶ added in v1.0.12
func (c *Client) WaitForTaskCompletion(upid string, operationName string, maxWait time.Duration) error
WaitForTaskCompletion polls for task completion and returns an error if the task failed. This is a public wrapper that allows specifying a custom timeout.
Proxmox task completion is determined by checking the EndTime field:
- If EndTime > 0, the task has finished
- If Status == "OK", the task succeeded
- If Status != "OK", the task failed and Status contains the error message
Parameters:
- upid: The Proxmox task UPID to monitor
- operationName: A human-readable name for the operation (used in error messages)
- maxWait: Maximum time to wait for the task to complete
Returns an error if the task fails or times out.
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 grouped Proxmox cluster metrics.
type ClusterTask ¶
type ClusterTask struct {
ID string `json:"id"`
Node string `json:"node"`
Type string `json:"type"`
Status string `json:"status"`
User string `json:"user"`
TokenID string `json:"tokenid,omitempty"`
UPID string `json:"upid"`
Saved string `json:"saved"`
StartTime int64 `json:"starttime"`
EndTime int64 `json:"endtime"`
// Group cluster support
// SourceProfile is the profile name this task came from in group cluster mode.
SourceProfile string `json:"source_profile,omitempty"`
}
ClusterTask represents a cluster task from the Proxmox API.
type ConfiguredNetwork ¶
type ConfiguredNetwork struct {
Interface string `json:"interface"` // Interface identifier (net0, net1, etc.)
Model string `json:"model"` // Network model (QEMU) or interface name (LXC)
MACAddr string `json:"mac_address"` // Hardware MAC address
Bridge string `json:"bridge"` // Bridge name (vmbr0, vmbr1, etc.)
VLAN string `json:"vlan,omitempty"` // VLAN tag if configured
Rate string `json:"rate,omitempty"` // Rate limiting (e.g., "1000" for 1000 MB/s)
IP string `json:"ip,omitempty"` // Static IP configuration or "dhcp"
Gateway string `json:"gateway,omitempty"` // Gateway IP (LXC containers)
Firewall bool `json:"firewall,omitempty"` // Whether firewall is enabled for this interface
}
ConfiguredNetwork represents a network interface configuration from VM config endpoint.
This struct contains the network configuration as defined in the VM's configuration, which may differ from the runtime network information available through the guest agent. It includes both the network model/type and bridge configuration details.
For QEMU VMs, the Model field typically contains values like "virtio", "e1000", "rtl8139". For LXC containers, the Model field contains the interface name like "eth0", "eth1".
Example QEMU network config: "virtio=AA:BB:CC:DD:EE:FF,bridge=vmbr0,tag=100,firewall=1" Example LXC network config: "name=eth0,hwaddr=AA:BB:CC:DD:EE:FF,bridge=vmbr0,ip=dhcp".
type ConnectionSummary ¶ added in v1.0.14
type ConnectionSummary struct {
GroupName string
TotalProfiles int
ConnectedCount int
ErrorCount int
ProfileStatus map[string]string // profile name -> status description
}
ConnectionSummary represents the connection status of the group.
type DeleteVMOptions ¶
type DeleteVMOptions struct {
// Force deletion even if VM is running
Force bool `json:"force,omitempty"`
// Skip lock checking
SkipLock bool `json:"skiplock,omitempty"`
// Destroy unreferenced disks owned by guest
DestroyUnreferencedDisks bool `json:"destroy-unreferenced-disks,omitempty"`
// Remove VMID from configurations (backup, replication jobs, HA)
Purge bool `json:"purge,omitempty"`
}
DeleteVMOptions contains options for deleting a VM.
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 GroupClientManager ¶ added in v1.0.14
type GroupClientManager struct {
// contains filtered or unexported fields
}
GroupClientManager manages multiple Proxmox API clients for group cluster mode. It provides concurrent access to multiple profiles and groups their data.
func NewGroupClientManager ¶ added in v1.0.14
func NewGroupClientManager( groupName string, logger interfaces.Logger, cache interfaces.Cache, ) *GroupClientManager
NewGroupClientManager creates a new group client manager.
func (*GroupClientManager) Close ¶ added in v1.0.14
func (m *GroupClientManager) Close()
Close disconnects all clients and cleans up resources.
func (*GroupClientManager) ExecuteOnAllProfiles ¶ added in v1.0.14
func (m *GroupClientManager) ExecuteOnAllProfiles( ctx context.Context, operation ProfileOperation, ) []ProfileResult
ExecuteOnAllProfiles executes an operation concurrently on all connected profiles. Returns a slice of ProfileResult, one for each profile attempted. This method does not fail if some profiles fail; it collects all results.
func (*GroupClientManager) ExecuteOnProfile ¶ added in v1.0.14
func (m *GroupClientManager) ExecuteOnProfile( ctx context.Context, profileName string, operation ProfileOperation, ) (interface{}, error)
ExecuteOnProfile executes an operation on a specific profile by name. Returns the operation data and error.
func (*GroupClientManager) FindNodeByNameInGroup ¶ added in v1.0.14
func (m *GroupClientManager) FindNodeByNameInGroup(ctx context.Context, nodeName string) (*Node, string, error)
FindNodeByNameInGroup searches for a node with the given name across all profiles. Returns the node and its source profile name, or an error if not found.
func (*GroupClientManager) FindVMByIDInGroup ¶ added in v1.0.14
FindVMByIDInGroup searches for a VM with the given ID across all profiles. Returns the VM and its source profile name, or an error if not found. Note: VM IDs should be unique within a profile, but may overlap across profiles.
func (*GroupClientManager) GetAllClients ¶ added in v1.0.14
func (m *GroupClientManager) GetAllClients() []*ProfileClient
GetAllClients returns all clients regardless of status.
func (*GroupClientManager) GetClient ¶ added in v1.0.14
func (m *GroupClientManager) GetClient(profileName string) (*ProfileClient, bool)
GetClient returns the client for a specific profile by name.
func (*GroupClientManager) GetConnectedClients ¶ added in v1.0.14
func (m *GroupClientManager) GetConnectedClients() []*ProfileClient
GetConnectedClients returns all currently connected profile clients.
func (*GroupClientManager) GetConnectionSummary ¶ added in v1.0.14
func (m *GroupClientManager) GetConnectionSummary() ConnectionSummary
GetConnectionSummary returns a summary of connection statuses.
func (*GroupClientManager) GetGroupClusterResources ¶ added in v1.0.14
func (m *GroupClientManager) GetGroupClusterResources(ctx context.Context, fresh bool) ([]*Node, []*VM, error)
GetGroupClusterResources retrieves cluster resources from all profiles in the group. This provides a unified view of all resources across all connected profiles. fresh flag bypasses caches when true.
func (*GroupClientManager) GetGroupData ¶ added in v1.0.14
func (m *GroupClientManager) GetGroupData( ctx context.Context, operation ProfileOperation, groupFunc func(results []ProfileResult) (interface{}, error), ) (interface{}, error)
GetGroupData is a helper for executing an operation and grouping results. It executes the operation on all connected profiles and returns combined results. The groupFunc receives all successful results and should combine them.
func (*GroupClientManager) GetGroupName ¶ added in v1.0.14
func (m *GroupClientManager) GetGroupName() string
GetGroupName returns the name of this group.
func (*GroupClientManager) GetGroupNodes ¶ added in v1.0.14
func (m *GroupClientManager) GetGroupNodes(ctx context.Context) ([]*Node, error)
GetGroupNodes retrieves nodes from all connected profiles in the group. Each node's SourceProfile field is set to identify which profile it came from. Returns a combined list of all nodes across all profiles.
func (*GroupClientManager) GetGroupTasks ¶ added in v1.0.14
func (m *GroupClientManager) GetGroupTasks(ctx context.Context) ([]*ClusterTask, error)
GetGroupTasks retrieves tasks from all connected profiles in the group. Each task's SourceProfile field is set to identify which profile it came from. Returns a combined list of all tasks across all profiles.
func (*GroupClientManager) GetGroupVMs ¶ added in v1.0.14
func (m *GroupClientManager) GetGroupVMs(ctx context.Context) ([]*VM, error)
GetGroupVMs retrieves VMs from all connected profiles in the group. Each VM's SourceProfile field is set to identify which profile it came from. Returns a combined list of all VMs across all profiles.
func (*GroupClientManager) GetNodeFromGroup ¶ added in v1.0.14
func (m *GroupClientManager) GetNodeFromGroup( ctx context.Context, profileName string, nodeName string, ) (*Node, error)
GetNodeFromGroup retrieves a specific node from a specific profile. This is useful when you need to perform operations on a node and need to ensure you're using the correct profile's client.
func (*GroupClientManager) GetVMFromGroup ¶ added in v1.0.14
func (m *GroupClientManager) GetVMFromGroup( ctx context.Context, profileName string, nodeName string, vmType string, vmID int, ) (*VM, error)
GetVMFromGroup retrieves detailed VM information from a specific profile. This is useful when you need to perform operations on a VM and need to ensure you're using the correct profile's client.
func (*GroupClientManager) Initialize ¶ added in v1.0.14
func (m *GroupClientManager) Initialize(ctx context.Context, profiles []ProfileEntry) error
Initialize creates and connects clients for all profiles in the group. Returns an error only if ALL connections fail; partial failures are logged.
func (*GroupClientManager) RefreshAllFailedProfiles ¶ added in v1.0.14
func (m *GroupClientManager) RefreshAllFailedProfiles( ctx context.Context, profileConfigs map[string]interfaces.Config, ) map[string]error
RefreshAllFailedProfiles attempts to reconnect all profiles with error status. Returns a map of profile names to their reconnection results (nil on success, error on failure).
func (*GroupClientManager) RefreshProfileConnection ¶ added in v1.0.14
func (m *GroupClientManager) RefreshProfileConnection( ctx context.Context, profileName string, profileConfig interfaces.Config, ) error
RefreshProfileConnection attempts to reconnect a failed profile. This is useful for recovering from transient network errors.
type GuestAgentExecRequest ¶ added in v1.0.9
type GuestAgentExecRequest struct {
Command []string `json:"command"` // Command and arguments as array
}
GuestAgentExecRequest represents a request to execute a command via QEMU guest agent.
type GuestAgentExecResponse ¶ added in v1.0.9
type GuestAgentExecResponse struct {
PID int `json:"pid"` // Process ID of the started command
}
GuestAgentExecResponse represents the response from starting a command execution.
type GuestAgentExecStatus ¶ added in v1.0.9
type GuestAgentExecStatus struct {
Exited int `json:"exited"` // Whether the process has exited (0 or 1)
ExitCode *int `json:"exitcode"` // Exit code (only if exited)
OutData string `json:"out-data"` // Stdout data (base64 encoded by Proxmox)
ErrData string `json:"err-data"` // Stderr data (base64 encoded by Proxmox)
Signal *int `json:"signal"` // Signal number if process was terminated
OutTrunc bool `json:"out-truncated"` // Whether stdout was truncated
ErrTrunc bool `json:"err-truncated"` // Whether stderr was truncated
}
GuestAgentExecStatus represents the status and output of an executed command.
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) 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 MigrationOptions ¶
type MigrationOptions struct {
// Target specifies the destination node name for the migration.
// This field is required and must be a valid, online node in the cluster
// that is different from the source node.
Target string `json:"target"`
// Online controls whether to perform online (live) migration for QEMU VMs.
// If nil, defaults to true for running QEMU VMs and false for stopped ones.
// Online migration allows the QEMU VM to continue running during migration,
// while offline migration requires stopping the VM first.
// NOTE: This parameter is ignored for LXC containers as they don't support live migration.
Online *bool `json:"online,omitempty"`
// Force enables forced migration, bypassing locks and some safety checks.
// Use with caution as this can potentially cause data corruption if the
// VM/container is in an inconsistent state.
Force bool `json:"force,omitempty"`
// MigrationNetwork specifies the network interface to use for migration traffic.
// This is useful in clusters with multiple networks to control which network
// carries the migration data. If empty, uses the default migration network.
MigrationNetwork string `json:"migration_network,omitempty"`
// MigrationType specifies the migration method for LXC containers.
// NOTE: This parameter is not supported by the current Proxmox API for LXC containers.
// LXC migration is always a "restart" style operation by default.
// This field is kept for potential future compatibility but is not sent to the API.
// This option is ignored for QEMU VMs.
MigrationType string `json:"migration_type,omitempty"`
// BandwidthLimit sets the maximum bandwidth for migration in KB/s.
// This helps control network usage during migration to avoid impacting
// other services. A value of 0 means no limit.
BandwidthLimit int `json:"bwlimit,omitempty"`
// TargetStorage specifies the target storage for offline migrations.
// This allows migrating VM disks to different storage on the target node.
// Only applicable for offline migrations.
TargetStorage string `json:"targetstorage,omitempty"`
// Delete controls whether to remove the VM/container from the source node
// after successful migration. When false (default), the VM/container
// configuration remains on the source node but in a stopped state.
Delete bool `json:"delete,omitempty"`
}
MigrationOptions contains configuration options for migrating a VM or container.
This struct provides comprehensive control over the migration process, supporting both QEMU VMs and LXC containers with their specific requirements.
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"`
// Group cluster support
// SourceProfile is the profile name this node came from in group cluster mode.
// Empty for non-group mode. Used to track which Proxmox cluster a node belongs to
// when viewing multiple clusters together.
SourceProfile string `json:"source_profile,omitempty"`
// contains filtered or unexported fields
}
Node represents a Proxmox cluster node.
type ProfileClient ¶ added in v1.0.14
type ProfileClient struct {
Client *Client
ProfileName string // The profile name from config
Status ProfileConnectionStatus
LastErr error
// contains filtered or unexported fields
}
ProfileClient wraps an API client with its profile information. This represents a single Proxmox connection within a group cluster.
func (*ProfileClient) GetStatus ¶ added in v1.0.14
func (pc *ProfileClient) GetStatus() (ProfileConnectionStatus, error)
GetStatus safely retrieves the profile's connection status.
func (*ProfileClient) SetStatus ¶ added in v1.0.14
func (pc *ProfileClient) SetStatus(status ProfileConnectionStatus, err error)
SetStatus safely updates the profile's connection status.
type ProfileConnectionStatus ¶ added in v1.0.14
type ProfileConnectionStatus int
ProfileConnectionStatus represents the connection state of a profile.
const ( // ProfileStatusUnknown indicates the profile connection status is unknown. ProfileStatusUnknown ProfileConnectionStatus = iota // ProfileStatusConnected indicates the profile is successfully connected. ProfileStatusConnected // ProfileStatusDisconnected indicates the profile is disconnected. ProfileStatusDisconnected // ProfileStatusError indicates the profile connection has an error. ProfileStatusError )
func (ProfileConnectionStatus) String ¶ added in v1.0.14
func (s ProfileConnectionStatus) String() string
String returns the string representation of the connection status.
type ProfileEntry ¶ added in v1.0.14
type ProfileEntry struct {
Name string
Config interfaces.Config
}
ProfileEntry represents a profile to be added to the group manager. This is a simple struct to pass profile information without importing config package, used in group management.
type ProfileOperation ¶ added in v1.0.14
ProfileOperation is a function that performs an operation on a single client. It receives the profile name, client, and returns optional data and an error.
type ProfileResult ¶ added in v1.0.14
type ProfileResult struct {
ProfileName string
Success bool
Error error
Data interface{} // Optional data returned from the operation
}
ProfileResult represents the result of an operation on a single profile.
type Snapshot ¶
type Snapshot struct {
Name string `json:"name"` // Snapshot name
Description string `json:"description"` // Snapshot description
SnapTime time.Time `json:"snaptime"` // Creation timestamp (from API)
Parent string `json:"parent"` // Parent snapshot name (if any)
VMState bool `json:"vmstate"` // Whether VM state is included (QEMU only)
}
Snapshot represents a Proxmox VM or container snapshot.
type SnapshotOptions ¶
type SnapshotOptions struct {
// Description for the snapshot
Description string `json:"description,omitempty"`
// Whether to include VM state (memory dump) - QEMU only
VMState bool `json:"vmstate,omitempty"`
}
SnapshotOptions contains options for creating snapshots.
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.
Type string `json:"type"` // Always "storage" from API
}
Storage represents a Proxmox storage resource.
func (*Storage) GetTotalGB ¶
GetTotalGB returns total space in GB.
func (*Storage) GetUsageGB ¶
GetUsageGB returns used space in GB.
func (*Storage) GetUsagePercent ¶
GetUsagePercent returns the storage usage as a percentage.
type StorageDevice ¶
type StorageDevice struct {
Device string `json:"device"` // Device identifier (scsi0, ide0, virtio0, rootfs, mp0, etc.)
Storage string `json:"storage"` // Storage pool name or device path
Size string `json:"size,omitempty"` // Size specification (e.g., "32G", "500G")
Format string `json:"format,omitempty"` // Storage format (raw, qcow2, vmdk, etc.)
Cache string `json:"cache,omitempty"` // Cache mode (none, writethrough, writeback, etc.)
IOThread bool `json:"iothread,omitempty"` // Whether to use dedicated I/O thread
SSD bool `json:"ssd,omitempty"` // Whether device is SSD (affects scheduler)
Discard string `json:"discard,omitempty"` // Discard mode (on, ignore) for TRIM support
Serial string `json:"serial,omitempty"` // Custom serial number
Backup bool `json:"backup"` // Whether device is included in backups (default: true)
Replicate bool `json:"replicate,omitempty"` // Whether device participates in replication
Media string `json:"media,omitempty"` // Media type (e.g., "cdrom")
}
StorageDevice represents a storage device configuration from VM config endpoint.
This struct contains detailed storage configuration including the storage backend, performance settings, and device-specific options. The configuration varies between QEMU VMs and LXC containers.
For QEMU VMs, devices include SCSI, IDE, VirtIO, SATA, and EFI disk devices. For LXC containers, devices include rootfs and mount points (mp0, mp1, etc.).
Example QEMU storage: "local-lvm:vm-100-disk-0,size=32G,cache=writeback,iothread=1" Example LXC storage: "local-lvm:vm-101-disk-0,size=8G" (rootfs) Example direct device: "/dev/disk/by-id/ata-SAMSUNG-SSD,size=500G,ssd=1,discard=on".
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 []*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 TaskStatus ¶ added in v1.0.15
type TaskStatus struct {
Status string `json:"status"`
ExitStatus string `json:"exitstatus"`
Node string `json:"node"`
UPID string `json:"upid"`
StartTime int64 `json:"starttime"`
EndTime int64 `json:"endtime"`
Type string `json:"type"`
User string `json:"user"`
ID string `json:"id"`
PStart int64 `json:"pstart"`
}
TaskStatus represents the status of a task.
type VM ¶
type VM struct {
// Basic identification and status
ID int `json:"id"` // VM ID (unique within cluster)
Name string `json:"name"` // VM name
Node string `json:"node"` // Proxmox node hosting this VM
Type string `json:"type"` // VM type: "qemu" or "lxc"
Status string `json:"status"` // Current status: "running", "stopped", etc.
IP string `json:"ip,omitempty"` // Primary IP address (from config or guest agent)
// Runtime resource usage metrics
CPU float64 `json:"cpu,omitempty"` // CPU usage as percentage (0.0-1.0)
Mem int64 `json:"mem,omitempty"` // Current memory usage in bytes
MaxMem int64 `json:"maxmem,omitempty"` // Maximum memory allocation in bytes
Disk int64 `json:"disk,omitempty"` // Current disk usage in bytes
MaxDisk int64 `json:"maxdisk,omitempty"` // Maximum disk allocation in bytes
Uptime int64 `json:"uptime,omitempty"` // Uptime in seconds
DiskRead int64 `json:"diskread,omitempty"` // Total disk read bytes
DiskWrite int64 `json:"diskwrite,omitempty"` // Total disk write bytes
NetIn int64 `json:"netin,omitempty"` // Total network input bytes
NetOut int64 `json:"netout,omitempty"` // Total network output bytes
// Administrative and cluster information
HAState string `json:"hastate,omitempty"` // High availability state
Lock string `json:"lock,omitempty"` // Lock status if VM is locked
Tags string `json:"tags,omitempty"` // Comma-separated tags
Template bool `json:"template,omitempty"` // Whether this is a template
Pool string `json:"pool,omitempty"` // Resource pool assignment
// Guest agent related fields (QEMU VMs only)
AgentEnabled bool `json:"agent_enabled,omitempty"` // Whether guest agent is enabled
AgentRunning bool `json:"agent_running,omitempty"` // Whether guest agent is responding
NetInterfaces []NetworkInterface `json:"net_interfaces,omitempty"` // Network interfaces from guest agent
Filesystems []Filesystem `json:"filesystems,omitempty"` // Filesystem information from guest agent
ConfiguredMACs map[string]bool `json:"-"` // MAC addresses from VM config (internal use)
// Configuration details from config endpoint
ConfiguredNetworks []ConfiguredNetwork `json:"configured_networks,omitempty"` // Network interface configuration
StorageDevices []StorageDevice `json:"storage_devices,omitempty"` // Storage device configuration
BootOrder string `json:"boot_order,omitempty"` // Boot device order
CPUCores int `json:"cpu_cores,omitempty"` // Number of CPU cores
CPUSockets int `json:"cpu_sockets,omitempty"` // Number of CPU sockets
Architecture string `json:"architecture,omitempty"` // CPU architecture (amd64, arm64, etc.)
OSType string `json:"ostype,omitempty"` // Operating system type
Description string `json:"description,omitempty"` // VM description
OnBoot bool `json:"onboot,omitempty"` // Whether VM starts automatically
// Group cluster support
// SourceProfile is the profile name this VM came from in group cluster mode.
// Empty for non-group mode. Used to track which Proxmox cluster a VM belongs to
// when viewing multiple clusters together.
SourceProfile string `json:"source_profile,omitempty"`
Enriched bool `json:"-"` // Whether VM has been enriched with detailed information
// contains filtered or unexported fields
}
VM represents a Proxmox VM or container with comprehensive configuration and runtime information.
This struct contains both runtime metrics (CPU usage, memory, network I/O) and detailed configuration information parsed from the VM's config endpoint. The configuration details include network interfaces, storage devices, CPU settings, and other system configuration.
The struct is populated through multiple API calls:
- Basic VM information from cluster resources
- Runtime metrics from status/current endpoint
- Configuration details from config endpoint
- Guest agent information (for QEMU VMs with agent enabled)
Example usage:
vm, err := client.GetDetailedVmInfo("node1", "qemu", 100)
if err != nil {
return err
}
// Access runtime information
fmt.Printf("VM %s is %s, CPU: %.1f%%, Memory: %s\n",
vm.Name, vm.Status, vm.CPU*100, utils.FormatBytes(vm.Mem))
// Access configuration details
for _, net := range vm.ConfiguredNetworks {
fmt.Printf("Interface %s: %s on bridge %s\n",
net.Interface, net.MACAddr, net.Bridge)
}
type VMConfig ¶
type VMConfig struct {
// Common fields (match Proxmox API)
Name string `json:"name,omitempty"` // VM name (QEMU) or hostname (LXC)
Hostname string `json:"hostname,omitempty"` // LXC hostname (alternative to name)
Cores int `json:"cores,omitempty"`
Sockets int `json:"sockets,omitempty"`
Memory int64 `json:"memory,omitempty"` // in bytes
Description string `json:"description,omitempty"`
OnBoot *bool `json:"onboot,omitempty"`
// QEMU-specific
CPUType string `json:"cpu,omitempty"`
MaxMem int64 `json:"maxmem,omitempty"`
BootOrder string `json:"boot,omitempty"`
// LXC-specific
Swap int64 `json:"swap,omitempty"`
// Storage (for resizing, etc.)
Disks map[string]int64 `json:"disks,omitempty"` // disk name -> size in bytes
}
VMConfig represents editable configuration for both QEMU and LXC guests.
type VNCProxyResponse ¶
type VNCProxyResponse struct {
Ticket string `json:"ticket"`
Port string `json:"port"`
User string `json:"user"`
Cert string `json:"cert"`
Password string `json:"password,omitempty"` // One-time password for WebSocket connections
}
VNCProxyResponse represents the response from a VNC proxy request.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package interfaces defines the core interfaces used throughout the pvetui application.
|
Package interfaces defines the core interfaces used throughout the pvetui application. |
|
Package testutils provides testing utilities, mocks, and helper functions for the pvetui API package.
|
Package testutils provides testing utilities, mocks, and helper functions for the pvetui API package. |