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.
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 CPUInfo
- type Client
- func (c *Client) ClearAPICache()
- func (c *Client) CreateSnapshot(vm *VM, name string, options *SnapshotOptions) error
- func (c *Client) Delete(path 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) GetBaseURL() string
- 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) GetNodeVNCShell(nodeName string) (*VNCProxyResponse, error)
- func (c *Client) GetNodeVNCShellWithWebSocket(nodeName string) (*VNCProxyResponse, error)
- func (c *Client) GetSnapshots(vm *VM) ([]Snapshot, 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) 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) 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)
- type ClientOption
- type ClientOptions
- type Cluster
- type ClusterTask
- type ConfiguredNetwork
- 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 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 Snapshot
- type SnapshotOptions
- type Storage
- type StorageDevice
- type StorageManager
- 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 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) CreateSnapshot ¶
func (c *Client) CreateSnapshot(vm *VM, name string, options *SnapshotOptions) error
CreateSnapshot creates a new snapshot for a VM or container.
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) GetBaseURL ¶
GetBaseURL returns the base URL of the Proxmox API.
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) 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) 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) 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 immediately after initiating the migration, and the actual progress can be monitored via 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
}
err := client.MigrateVM(vm, options)
Parameters:
- vm: The VM or container to migrate
- options: Migration configuration options
Returns 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) 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.
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 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"`
}
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 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 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"`
// contains filtered or unexported fields
}
Node represents a Proxmox cluster node.
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 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
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. |