mirror of
https://github.com/Dvorinka/Containr.git
synced 2026-06-03 20:12:58 +00:00
overhaul
This commit is contained in:
@@ -0,0 +1,334 @@
|
||||
package proxmox
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Client represents a Proxmox API client
|
||||
type Client struct {
|
||||
baseURL string
|
||||
username string
|
||||
password string
|
||||
tokenID string
|
||||
token string
|
||||
httpClient *http.Client
|
||||
ticket string
|
||||
csrfToken string
|
||||
}
|
||||
|
||||
// NewClient creates a new Proxmox API client
|
||||
func NewClient(baseURL, username, password string) *Client {
|
||||
return &Client{
|
||||
baseURL: strings.TrimSuffix(baseURL, "/"),
|
||||
username: username,
|
||||
password: password,
|
||||
httpClient: &http.Client{
|
||||
Timeout: 30 * time.Second,
|
||||
Transport: &http.Transport{
|
||||
TLSClientConfig: &tls.Config{
|
||||
InsecureSkipVerify: true, // Proxmox typically uses self-signed certs
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// NewClientWithToken creates a new Proxmox API client using API token
|
||||
func NewClientWithToken(baseURL, tokenID, token string) *Client {
|
||||
return &Client{
|
||||
baseURL: strings.TrimSuffix(baseURL, "/"),
|
||||
tokenID: tokenID,
|
||||
token: token,
|
||||
httpClient: &http.Client{
|
||||
Timeout: 30 * time.Second,
|
||||
Transport: &http.Transport{
|
||||
TLSClientConfig: &tls.Config{
|
||||
InsecureSkipVerify: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Login authenticates with Proxmox and stores session tokens
|
||||
func (c *Client) Login() error {
|
||||
data := url.Values{}
|
||||
data.Set("username", c.username)
|
||||
data.Set("password", c.password)
|
||||
|
||||
resp, err := c.httpClient.PostForm(c.baseURL+"/api2/json/access/ticket", data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to login: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("login failed with status: %s", resp.Status)
|
||||
}
|
||||
|
||||
var result struct {
|
||||
Data struct {
|
||||
Ticket string `json:"ticket"`
|
||||
CSRFPreventionToken string `json:"CSRFPreventionToken"`
|
||||
Username string `json:"username"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
return fmt.Errorf("failed to decode login response: %w", err)
|
||||
}
|
||||
|
||||
c.ticket = result.Data.Ticket
|
||||
c.csrfToken = result.Data.CSRFPreventionToken
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// makeRequest makes an authenticated request to Proxmox API
|
||||
func (c *Client) makeRequest(method, path string, body io.Reader) (*http.Response, error) {
|
||||
req, err := http.NewRequest(method, c.baseURL+path, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Use token authentication if available
|
||||
if c.tokenID != "" && c.token != "" {
|
||||
req.Header.Set("Authorization", "PVEAPIToken="+c.tokenID+"="+c.token)
|
||||
} else {
|
||||
// Use session ticket authentication
|
||||
if c.ticket == "" {
|
||||
if err := c.Login(); err != nil {
|
||||
return nil, fmt.Errorf("failed to authenticate: %w", err)
|
||||
}
|
||||
}
|
||||
req.AddCookie(&http.Cookie{
|
||||
Name: "PVEAuthCookie",
|
||||
Value: c.ticket,
|
||||
})
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
// Add CSRF token for state-changing requests
|
||||
if method != "GET" && method != "HEAD" && c.csrfToken != "" {
|
||||
req.Header.Set("CSRFPreventionToken", c.csrfToken)
|
||||
}
|
||||
|
||||
return c.httpClient.Do(req)
|
||||
}
|
||||
|
||||
// GetNodes retrieves all nodes in the Proxmox cluster
|
||||
func (c *Client) GetNodes() ([]Node, error) {
|
||||
resp, err := c.makeRequest("GET", "/api2/json/nodes", nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var result struct {
|
||||
Data []Node `json:"data"`
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
return nil, fmt.Errorf("failed to decode nodes response: %w", err)
|
||||
}
|
||||
|
||||
return result.Data, nil
|
||||
}
|
||||
|
||||
// GetVMs retrieves all VMs/LXCs on a specific node
|
||||
func (c *Client) GetVMs(node string) ([]VM, error) {
|
||||
resp, err := c.makeRequest("GET", fmt.Sprintf("/api2/json/nodes/%s/qemu", node), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var result struct {
|
||||
Data []VM `json:"data"`
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
return nil, fmt.Errorf("failed to decode VMs response: %w", err)
|
||||
}
|
||||
|
||||
return result.Data, nil
|
||||
}
|
||||
|
||||
// GetContainers retrieves all LXC containers on a specific node
|
||||
func (c *Client) GetContainers(node string) ([]Container, error) {
|
||||
resp, err := c.makeRequest("GET", fmt.Sprintf("/api2/json/nodes/%s/lxc", node), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var result struct {
|
||||
Data []Container `json:"data"`
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
return nil, fmt.Errorf("failed to decode containers response: %w", err)
|
||||
}
|
||||
|
||||
return result.Data, nil
|
||||
}
|
||||
|
||||
// CreateVM creates a new VM on the specified node
|
||||
func (c *Client) CreateVM(node string, config VMConfig) (string, error) {
|
||||
data := url.Values{}
|
||||
|
||||
// Basic VM configuration
|
||||
data.Set("vmid", fmt.Sprintf("%d", config.VMID))
|
||||
data.Set("name", config.Name)
|
||||
data.Set("memory", fmt.Sprintf("%d", config.Memory))
|
||||
data.Set("cores", fmt.Sprintf("%d", config.Cores))
|
||||
|
||||
if config.Template != "" {
|
||||
data.Set("template", config.Template)
|
||||
}
|
||||
|
||||
if config.Storage != "" {
|
||||
data.Set("scsi0", fmt.Sprintf("%s:%d", config.Storage, config.DiskSize))
|
||||
}
|
||||
|
||||
if config.NetworkBridge != "" {
|
||||
data.Set("net0", fmt.Sprintf("model=virtio,bridge=%s", config.NetworkBridge))
|
||||
}
|
||||
|
||||
resp, err := c.makeRequest("POST", fmt.Sprintf("/api2/json/nodes/%s/qemu", node), strings.NewReader(data.Encode()))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return "", fmt.Errorf("failed to create VM: %s - %s", resp.Status, string(body))
|
||||
}
|
||||
|
||||
var result struct {
|
||||
Data string `json:"data"`
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
return "", fmt.Errorf("failed to decode create VM response: %w", err)
|
||||
}
|
||||
|
||||
return result.Data, nil
|
||||
}
|
||||
|
||||
// CreateContainer creates a new LXC container on the specified node
|
||||
func (c *Client) CreateContainer(node string, config ContainerConfig) (string, error) {
|
||||
data := url.Values{}
|
||||
|
||||
// Basic container configuration
|
||||
data.Set("vmid", fmt.Sprintf("%d", config.VMID))
|
||||
data.Set("hostname", config.Hostname)
|
||||
data.Set("memory", fmt.Sprintf("%d", config.Memory))
|
||||
data.Set("cores", fmt.Sprintf("%d", config.Cores))
|
||||
|
||||
if config.Template != "" {
|
||||
data.Set("ostemplate", config.Template)
|
||||
}
|
||||
|
||||
if config.Storage != "" {
|
||||
data.Set("rootfs", fmt.Sprintf("%s:%d", config.Storage, config.DiskSize))
|
||||
}
|
||||
|
||||
if config.NetworkBridge != "" {
|
||||
data.Set("net0", fmt.Sprintf("name=eth0,bridge=%s", config.NetworkBridge))
|
||||
}
|
||||
|
||||
resp, err := c.makeRequest("POST", fmt.Sprintf("/api2/json/nodes/%s/lxc", node), strings.NewReader(data.Encode()))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return "", fmt.Errorf("failed to create container: %s - %s", resp.Status, string(body))
|
||||
}
|
||||
|
||||
var result struct {
|
||||
Data string `json:"data"`
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
return "", fmt.Errorf("failed to decode create container response: %w", err)
|
||||
}
|
||||
|
||||
return result.Data, nil
|
||||
}
|
||||
|
||||
// StartVM starts a VM
|
||||
func (c *Client) StartVM(node string, vmid int) error {
|
||||
resp, err := c.makeRequest("POST", fmt.Sprintf("/api2/json/nodes/%s/qemu/%d/status/start", node, vmid), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("failed to start VM: %s", resp.Status)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// StopVM stops a VM
|
||||
func (c *Client) StopVM(node string, vmid int) error {
|
||||
resp, err := c.makeRequest("POST", fmt.Sprintf("/api2/json/nodes/%s/qemu/%d/status/stop", node, vmid), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("failed to stop VM: %s", resp.Status)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteVM deletes a VM
|
||||
func (c *Client) DeleteVM(node string, vmid int) error {
|
||||
resp, err := c.makeRequest("DELETE", fmt.Sprintf("/api2/json/nodes/%s/qemu/%d", node, vmid), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("failed to delete VM: %s", resp.Status)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetVMStatus retrieves the status of a VM
|
||||
func (c *Client) GetVMStatus(node string, vmid int) (*VMStatus, error) {
|
||||
resp, err := c.makeRequest("GET", fmt.Sprintf("/api2/json/nodes/%s/qemu/%d/status/current", node, vmid), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var result struct {
|
||||
Data VMStatus `json:"data"`
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
return nil, fmt.Errorf("failed to decode VM status response: %w", err)
|
||||
}
|
||||
|
||||
return &result.Data, nil
|
||||
}
|
||||
@@ -0,0 +1,456 @@
|
||||
package proxmox
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Service manages Proxmox operations
|
||||
type Service struct {
|
||||
client *Client
|
||||
nodeCache map[string]*NodeStats
|
||||
cacheMu sync.RWMutex
|
||||
config Config
|
||||
}
|
||||
|
||||
// Config holds Proxmox configuration
|
||||
type Config struct {
|
||||
BaseURL string `json:"base_url"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
TokenID string `json:"token_id"`
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
// NewService creates a new Proxmox service
|
||||
func NewService(config Config) *Service {
|
||||
var client *Client
|
||||
|
||||
if config.TokenID != "" && config.Token != "" {
|
||||
client = NewClientWithToken(config.BaseURL, config.TokenID, config.Token)
|
||||
} else {
|
||||
client = NewClient(config.BaseURL, config.Username, config.Password)
|
||||
}
|
||||
|
||||
return &Service{
|
||||
client: client,
|
||||
nodeCache: make(map[string]*NodeStats),
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
// GetClusterStatus returns the overall cluster status
|
||||
func (s *Service) GetClusterStatus() (*ClusterInfo, error) {
|
||||
// This would require additional API endpoints for cluster info
|
||||
// For now, return basic cluster information
|
||||
nodes, err := s.client.GetNodes()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get cluster nodes: %w", err)
|
||||
}
|
||||
|
||||
activeNodes := 0
|
||||
for _, node := range nodes {
|
||||
if node.Status == "online" {
|
||||
activeNodes++
|
||||
}
|
||||
}
|
||||
|
||||
return &ClusterInfo{
|
||||
Name: "containr-cluster",
|
||||
Version: "7.x", // This should be dynamically retrieved
|
||||
Nodes: len(nodes),
|
||||
Quorate: activeNodes > 0,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetAllNodes returns all nodes with their current status
|
||||
func (s *Service) GetAllNodes() ([]Node, error) {
|
||||
return s.client.GetNodes()
|
||||
}
|
||||
|
||||
// GetNodeStats returns detailed statistics for a specific node
|
||||
func (s *Service) GetNodeStats(nodeName string) (*NodeStats, error) {
|
||||
s.cacheMu.RLock()
|
||||
if stats, exists := s.nodeCache[nodeName]; exists {
|
||||
s.cacheMu.RUnlock()
|
||||
return stats, nil
|
||||
}
|
||||
s.cacheMu.RUnlock()
|
||||
|
||||
// Fetch fresh data
|
||||
nodes, err := s.client.GetNodes()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get nodes: %w", err)
|
||||
}
|
||||
|
||||
var targetNode *Node
|
||||
for _, node := range nodes {
|
||||
if node.Node == nodeName {
|
||||
targetNode = &node
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if targetNode == nil {
|
||||
return nil, fmt.Errorf("node %s not found", nodeName)
|
||||
}
|
||||
|
||||
stats := &NodeStats{
|
||||
Node: targetNode.Node,
|
||||
Status: targetNode.Status,
|
||||
CPU: targetNode.CPU,
|
||||
MemoryTotal: targetNode.MaxMemory,
|
||||
MemoryUsed: targetNode.MemoryUsed,
|
||||
MemoryFree: targetNode.MaxMemory - targetNode.MemoryUsed,
|
||||
DiskTotal: targetNode.MaxDisk,
|
||||
DiskUsed: targetNode.DiskUsed,
|
||||
DiskFree: targetNode.MaxDisk - targetNode.DiskUsed,
|
||||
Uptime: targetNode.Uptime,
|
||||
LastUpdate: time.Now(),
|
||||
}
|
||||
|
||||
// Update cache
|
||||
s.cacheMu.Lock()
|
||||
s.nodeCache[nodeName] = stats
|
||||
s.cacheMu.Unlock()
|
||||
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
// GetAllVMs returns all VMs across all nodes
|
||||
func (s *Service) GetAllVMs() ([]VM, error) {
|
||||
nodes, err := s.client.GetNodes()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get nodes: %w", err)
|
||||
}
|
||||
|
||||
var allVMs []VM
|
||||
for _, node := range nodes {
|
||||
if node.Status == "online" {
|
||||
vms, err := s.client.GetVMs(node.Node)
|
||||
if err != nil {
|
||||
log.Printf("Failed to get VMs for node %s: %v", node.Node, err)
|
||||
continue
|
||||
}
|
||||
allVMs = append(allVMs, vms...)
|
||||
}
|
||||
}
|
||||
|
||||
return allVMs, nil
|
||||
}
|
||||
|
||||
// GetAllContainers returns all containers across all nodes
|
||||
func (s *Service) GetAllContainers() ([]Container, error) {
|
||||
nodes, err := s.client.GetNodes()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get nodes: %w", err)
|
||||
}
|
||||
|
||||
var allContainers []Container
|
||||
for _, node := range nodes {
|
||||
if node.Status == "online" {
|
||||
containers, err := s.client.GetContainers(node.Node)
|
||||
if err != nil {
|
||||
log.Printf("Failed to get containers for node %s: %v", node.Node, err)
|
||||
continue
|
||||
}
|
||||
allContainers = append(allContainers, containers...)
|
||||
}
|
||||
}
|
||||
|
||||
return allContainers, nil
|
||||
}
|
||||
|
||||
// CreateServiceVM creates a new VM optimized for running services
|
||||
func (s *Service) CreateServiceVM(nodeName string, config ServiceVMConfig) (*VM, error) {
|
||||
// Find the next available VMID
|
||||
vmid, err := s.getNextAvailableVMID(nodeName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get next VMID: %w", err)
|
||||
}
|
||||
|
||||
vmConfig := VMConfig{
|
||||
VMID: vmid,
|
||||
Name: config.Name,
|
||||
Memory: config.Memory,
|
||||
Cores: config.Cores,
|
||||
DiskSize: config.DiskSize,
|
||||
Storage: config.Storage,
|
||||
NetworkBridge: config.NetworkBridge,
|
||||
Template: config.Template,
|
||||
}
|
||||
|
||||
taskID, err := s.client.CreateVM(nodeName, vmConfig)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create VM: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("VM creation started with task ID: %s", taskID)
|
||||
|
||||
// Wait for VM to be created and get its status
|
||||
time.Sleep(5 * time.Second) // Give Proxmox time to process
|
||||
|
||||
vms, err := s.client.GetVMs(nodeName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get VM status after creation: %w", err)
|
||||
}
|
||||
|
||||
for _, vm := range vms {
|
||||
if vm.VMID == vmid {
|
||||
return &vm, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("VM %d not found after creation", vmid)
|
||||
}
|
||||
|
||||
// CreateServiceContainer creates a new LXC container optimized for running services
|
||||
func (s *Service) CreateServiceContainer(nodeName string, config ServiceContainerConfig) (*Container, error) {
|
||||
// Find the next available VMID
|
||||
vmid, err := s.getNextAvailableVMID(nodeName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get next VMID: %w", err)
|
||||
}
|
||||
|
||||
containerConfig := ContainerConfig{
|
||||
VMID: vmid,
|
||||
Hostname: config.Hostname,
|
||||
Memory: config.Memory,
|
||||
Cores: config.Cores,
|
||||
DiskSize: config.DiskSize,
|
||||
Storage: config.Storage,
|
||||
NetworkBridge: config.NetworkBridge,
|
||||
Template: config.Template,
|
||||
}
|
||||
|
||||
taskID, err := s.client.CreateContainer(nodeName, containerConfig)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create container: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("Container creation started with task ID: %s", taskID)
|
||||
|
||||
// Wait for container to be created and get its status
|
||||
time.Sleep(5 * time.Second) // Give Proxmox time to process
|
||||
|
||||
containers, err := s.client.GetContainers(nodeName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get container status after creation: %w", err)
|
||||
}
|
||||
|
||||
for _, container := range containers {
|
||||
if container.VMID == vmid {
|
||||
return &container, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("Container %d not found after creation", vmid)
|
||||
}
|
||||
|
||||
// StartInstance starts a VM or container
|
||||
func (s *Service) StartInstance(nodeName string, vmid int, instanceType string) error {
|
||||
switch instanceType {
|
||||
case "qemu":
|
||||
return s.client.StartVM(nodeName, vmid)
|
||||
case "lxc":
|
||||
// Implement container start
|
||||
return fmt.Errorf("container start not yet implemented")
|
||||
default:
|
||||
return fmt.Errorf("unknown instance type: %s", instanceType)
|
||||
}
|
||||
}
|
||||
|
||||
// StopInstance stops a VM or container
|
||||
func (s *Service) StopInstance(nodeName string, vmid int, instanceType string) error {
|
||||
switch instanceType {
|
||||
case "qemu":
|
||||
return s.client.StopVM(nodeName, vmid)
|
||||
case "lxc":
|
||||
// Implement container stop
|
||||
return fmt.Errorf("container stop not yet implemented")
|
||||
default:
|
||||
return fmt.Errorf("unknown instance type: %s", instanceType)
|
||||
}
|
||||
}
|
||||
|
||||
// DeleteInstance deletes a VM or container
|
||||
func (s *Service) DeleteInstance(nodeName string, vmid int, instanceType string) error {
|
||||
switch instanceType {
|
||||
case "qemu":
|
||||
return s.client.DeleteVM(nodeName, vmid)
|
||||
case "lxc":
|
||||
// Implement container delete
|
||||
return fmt.Errorf("container delete not yet implemented")
|
||||
default:
|
||||
return fmt.Errorf("unknown instance type: %s", instanceType)
|
||||
}
|
||||
}
|
||||
|
||||
// GetInstanceStatus returns the status of a VM or container
|
||||
func (s *Service) GetInstanceStatus(nodeName string, vmid int, instanceType string) (interface{}, error) {
|
||||
switch instanceType {
|
||||
case "qemu":
|
||||
return s.client.GetVMStatus(nodeName, vmid)
|
||||
case "lxc":
|
||||
// Implement container status
|
||||
return nil, fmt.Errorf("container status not yet implemented")
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown instance type: %s", instanceType)
|
||||
}
|
||||
}
|
||||
|
||||
// getNextAvailableVMID finds the next available VM ID on the specified node
|
||||
func (s *Service) getNextAvailableVMID(nodeName string) (int, error) {
|
||||
vms, err := s.client.GetVMs(nodeName)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
containers, err := s.client.GetContainers(nodeName)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
usedIDs := make(map[int]bool)
|
||||
for _, vm := range vms {
|
||||
usedIDs[vm.VMID] = true
|
||||
}
|
||||
for _, container := range containers {
|
||||
usedIDs[container.VMID] = true
|
||||
}
|
||||
|
||||
// Start from 1000 and find the first available ID
|
||||
for vmid := 1000; vmid < 9999; vmid++ {
|
||||
if !usedIDs[vmid] {
|
||||
return vmid, nil
|
||||
}
|
||||
}
|
||||
|
||||
return 0, fmt.Errorf("no available VM IDs found")
|
||||
}
|
||||
|
||||
// ServiceVMConfig represents configuration for creating a service VM
|
||||
type ServiceVMConfig struct {
|
||||
Name string `json:"name"`
|
||||
Memory int `json:"memory"`
|
||||
Cores int `json:"cores"`
|
||||
DiskSize int `json:"disk_size"` // in GB
|
||||
Storage string `json:"storage"`
|
||||
NetworkBridge string `json:"network_bridge"`
|
||||
Template string `json:"template"`
|
||||
}
|
||||
|
||||
// ServiceContainerConfig represents configuration for creating a service container
|
||||
type ServiceContainerConfig struct {
|
||||
Hostname string `json:"hostname"`
|
||||
Memory int `json:"memory"`
|
||||
Cores int `json:"cores"`
|
||||
DiskSize int `json:"disk_size"` // in GB
|
||||
Storage string `json:"storage"`
|
||||
NetworkBridge string `json:"network_bridge"`
|
||||
Template string `json:"template"`
|
||||
}
|
||||
|
||||
// GetResourceUsage returns resource usage across the cluster
|
||||
func (s *Service) GetResourceUsage() (map[string]interface{}, error) {
|
||||
nodes, err := s.client.GetNodes()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get nodes: %w", err)
|
||||
}
|
||||
|
||||
var totalCPU, usedCPU float64
|
||||
var totalMemory, usedMemory, totalDisk, usedDisk int64
|
||||
var onlineNodes int
|
||||
|
||||
for _, node := range nodes {
|
||||
if node.Status == "online" {
|
||||
onlineNodes++
|
||||
totalCPU += 1.0 // Assuming 1 CPU per node for simplicity
|
||||
usedCPU += node.CPU
|
||||
totalMemory += int64(node.MaxMemory)
|
||||
usedMemory += int64(node.MemoryUsed)
|
||||
totalDisk += int64(node.MaxDisk)
|
||||
usedDisk += int64(node.DiskUsed)
|
||||
}
|
||||
}
|
||||
|
||||
return map[string]interface{}{
|
||||
"total_nodes": len(nodes),
|
||||
"online_nodes": onlineNodes,
|
||||
"cpu_usage": map[string]interface{}{
|
||||
"total": totalCPU,
|
||||
"used": usedCPU,
|
||||
"free": totalCPU - usedCPU,
|
||||
},
|
||||
"memory_usage": map[string]interface{}{
|
||||
"total": totalMemory,
|
||||
"used": usedMemory,
|
||||
"free": totalMemory - usedMemory,
|
||||
},
|
||||
"disk_usage": map[string]interface{}{
|
||||
"total": totalDisk,
|
||||
"used": usedDisk,
|
||||
"free": totalDisk - usedDisk,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ValidateConnection tests the connection to Proxmox
|
||||
func (s *Service) ValidateConnection() error {
|
||||
_, err := s.client.GetNodes()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to connect to Proxmox: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetAvailableTemplates returns a list of available VM and container templates
|
||||
func (s *Service) GetAvailableTemplates(nodeName string) (map[string]interface{}, error) {
|
||||
vms, err := s.client.GetVMs(nodeName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get VMs: %w", err)
|
||||
}
|
||||
|
||||
containers, err := s.client.GetContainers(nodeName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get containers: %w", err)
|
||||
}
|
||||
|
||||
var vmTemplates []VMTemplate
|
||||
for _, vm := range vms {
|
||||
if vm.Template {
|
||||
vmTemplates = append(vmTemplates, VMTemplate{
|
||||
VMID: vm.VMID,
|
||||
Name: vm.Name,
|
||||
Node: vm.Node,
|
||||
Storage: "local", // This should be dynamically retrieved
|
||||
CPU: 2, // Default values
|
||||
Memory: 2048,
|
||||
DiskSize: 20,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var containerTemplates []ContainerTemplate
|
||||
for _, container := range containers {
|
||||
if container.Template {
|
||||
containerTemplates = append(containerTemplates, ContainerTemplate{
|
||||
VMID: container.VMID,
|
||||
Name: container.Name,
|
||||
Node: container.Node,
|
||||
Storage: "local", // This should be dynamically retrieved
|
||||
CPU: 1,
|
||||
Memory: 512,
|
||||
DiskSize: 8,
|
||||
OSTemplate: "ubuntu-22.04-standard", // Default template
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return map[string]interface{}{
|
||||
"vm_templates": vmTemplates,
|
||||
"container_templates": containerTemplates,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
package proxmox
|
||||
|
||||
import "time"
|
||||
|
||||
// Node represents a Proxmox cluster node
|
||||
type Node struct {
|
||||
Node string `json:"node"`
|
||||
Status string `json:"status"`
|
||||
CPU float64 `json:"cpu"`
|
||||
Memory int `json:"-"`
|
||||
MemoryUsed int `json:"mem"`
|
||||
MaxMemory int `json:"maxmem"`
|
||||
Disk int `json:"disk"`
|
||||
DiskUsed int `json:"diskused"`
|
||||
MaxDisk int `json:"maxdisk"`
|
||||
Uptime int `json:"uptime"`
|
||||
Level string `json:"level"`
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
// VM represents a virtual machine in Proxmox
|
||||
type VM struct {
|
||||
VMID int `json:"vmid"`
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
CPU float64 `json:"cpu"`
|
||||
Memory int `json:"mem"`
|
||||
MemoryUsed int `json:"maxmem"`
|
||||
Disk int `json:"disk"`
|
||||
DiskUsed int `json:"maxdisk"`
|
||||
Uptime int `json:"uptime"`
|
||||
Template bool `json:"template"`
|
||||
Node string `json:"node"`
|
||||
Type string `json:"type"`
|
||||
NetIn int64 `json:"netin"`
|
||||
NetOut int64 `json:"netout"`
|
||||
DiskRead int64 `json:"diskread"`
|
||||
DiskWrite int64 `json:"diskwrite"`
|
||||
CPUUsage float64 `json:"cpuusage"`
|
||||
}
|
||||
|
||||
// Container represents an LXC container in Proxmox
|
||||
type Container struct {
|
||||
VMID int `json:"vmid"`
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
CPU float64 `json:"cpu"`
|
||||
Memory int `json:"mem"`
|
||||
MemoryUsed int `json:"maxmem"`
|
||||
Disk int `json:"disk"`
|
||||
DiskUsed int `json:"maxdisk"`
|
||||
Uptime int `json:"uptime"`
|
||||
Template bool `json:"template"`
|
||||
Node string `json:"node"`
|
||||
Type string `json:"type"`
|
||||
NetIn int64 `json:"netin"`
|
||||
NetOut int64 `json:"netout"`
|
||||
DiskRead int64 `json:"diskread"`
|
||||
DiskWrite int64 `json:"diskwrite"`
|
||||
CPUUsage float64 `json:"cpuusage"`
|
||||
}
|
||||
|
||||
// VMConfig represents the configuration for creating a VM
|
||||
type VMConfig struct {
|
||||
VMID int `json:"vmid"`
|
||||
Name string `json:"name"`
|
||||
Memory int `json:"memory"`
|
||||
Cores int `json:"cores"`
|
||||
DiskSize int `json:"disk_size"` // in GB
|
||||
Storage string `json:"storage"`
|
||||
NetworkBridge string `json:"network_bridge"`
|
||||
Template string `json:"template,omitempty"`
|
||||
}
|
||||
|
||||
// ContainerConfig represents the configuration for creating an LXC container
|
||||
type ContainerConfig struct {
|
||||
VMID int `json:"vmid"`
|
||||
Hostname string `json:"hostname"`
|
||||
Memory int `json:"memory"`
|
||||
Cores int `json:"cores"`
|
||||
DiskSize int `json:"disk_size"` // in GB
|
||||
Storage string `json:"storage"`
|
||||
NetworkBridge string `json:"network_bridge"`
|
||||
Template string `json:"template"`
|
||||
}
|
||||
|
||||
// VMStatus represents the current status of a VM
|
||||
type VMStatus struct {
|
||||
VMID int `json:"vmid"`
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
CPU float64 `json:"cpu"`
|
||||
Memory int `json:"mem"`
|
||||
MemoryUsed int `json:"maxmem"`
|
||||
Disk int `json:"disk"`
|
||||
DiskUsed int `json:"maxdisk"`
|
||||
Uptime int `json:"uptime"`
|
||||
Lock string `json:"lock,omitempty"`
|
||||
HA bool `json:"ha"`
|
||||
QMPStatus string `json:"qmpstatus"`
|
||||
Spice bool `json:"spice"`
|
||||
Template bool `json:"template"`
|
||||
Agent bool `json:"agent"`
|
||||
}
|
||||
|
||||
// ContainerStatus represents the current status of a container
|
||||
type ContainerStatus struct {
|
||||
VMID int `json:"vmid"`
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
CPU float64 `json:"cpu"`
|
||||
Memory int `json:"mem"`
|
||||
MemoryUsed int `json:"maxmem"`
|
||||
Disk int `json:"disk"`
|
||||
DiskUsed int `json:"maxdisk"`
|
||||
Uptime int `json:"uptime"`
|
||||
Lock string `json:"lock,omitempty"`
|
||||
HA bool `json:"ha"`
|
||||
Template bool `json:"template"`
|
||||
}
|
||||
|
||||
// NodeStats represents detailed statistics for a node
|
||||
type NodeStats struct {
|
||||
Node string `json:"node"`
|
||||
Status string `json:"status"`
|
||||
CPU float64 `json:"cpu"`
|
||||
MemoryTotal int `json:"memory_total"`
|
||||
MemoryUsed int `json:"memory_used"`
|
||||
MemoryFree int `json:"memory_free"`
|
||||
DiskTotal int `json:"disk_total"`
|
||||
DiskUsed int `json:"disk_used"`
|
||||
DiskFree int `json:"disk_free"`
|
||||
Uptime int `json:"uptime"`
|
||||
LoadAverage []float64 `json:"load_average"`
|
||||
NetworkIn int64 `json:"network_in"`
|
||||
NetworkOut int64 `json:"network_out"`
|
||||
LastUpdate time.Time `json:"last_update"`
|
||||
}
|
||||
|
||||
// VMTemplate represents a VM template that can be cloned
|
||||
type VMTemplate struct {
|
||||
VMID int `json:"vmid"`
|
||||
Name string `json:"name"`
|
||||
Node string `json:"node"`
|
||||
Storage string `json:"storage"`
|
||||
Size int `json:"size"`
|
||||
CPU int `json:"cpu"`
|
||||
Memory int `json:"memory"`
|
||||
DiskSize int `json:"disk_size"`
|
||||
}
|
||||
|
||||
// ContainerTemplate represents an LXC template that can be cloned
|
||||
type ContainerTemplate struct {
|
||||
VMID int `json:"vmid"`
|
||||
Name string `json:"name"`
|
||||
Node string `json:"node"`
|
||||
Storage string `json:"storage"`
|
||||
Size int `json:"size"`
|
||||
CPU int `json:"cpu"`
|
||||
Memory int `json:"memory"`
|
||||
DiskSize int `json:"disk_size"`
|
||||
OSTemplate string `json:"os_template"`
|
||||
}
|
||||
|
||||
// StorageInfo represents storage information on a node
|
||||
type StorageInfo struct {
|
||||
Storage string `json:"storage"`
|
||||
Node string `json:"node"`
|
||||
Type string `json:"type"`
|
||||
Total int `json:"total"`
|
||||
Used int `json:"used"`
|
||||
Available int `json:"avail"`
|
||||
Shared bool `json:"shared"`
|
||||
Content string `json:"content"`
|
||||
Active bool `json:"active"`
|
||||
Enabled bool `json:"enabled"`
|
||||
ReadOnly bool `json:"read_only"`
|
||||
}
|
||||
|
||||
// NetworkInfo represents network interface information
|
||||
type NetworkInfo struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Active bool `json:"active"`
|
||||
MACAddress string `json:"mac"`
|
||||
Bridge string `json:"bridge"`
|
||||
IP string `json:"ip"`
|
||||
CIDR string `json:"cidr"`
|
||||
Gateway string `json:"gateway"`
|
||||
DNS string `json:"dns"`
|
||||
}
|
||||
|
||||
// TaskInfo represents a task running on Proxmox
|
||||
type TaskInfo struct {
|
||||
UPID string `json:"upid"`
|
||||
Node string `json:"node"`
|
||||
Type string `json:"type"`
|
||||
Status string `json:"status"`
|
||||
User string `json:"user"`
|
||||
StartTime time.Time `json:"starttime"`
|
||||
EndTime time.Time `json:"endtime"`
|
||||
Duration string `json:"duration"`
|
||||
PID int `json:"pid"`
|
||||
}
|
||||
|
||||
// ClusterInfo represents cluster information
|
||||
type ClusterInfo struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
Nodes int `json:"nodes"`
|
||||
Quorate bool `json:"quorate"`
|
||||
Links int `json:"links"`
|
||||
Messages string `json:"messages"`
|
||||
}
|
||||
|
||||
// Resource represents a generic resource in Proxmox
|
||||
type Resource struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Node string `json:"node"`
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
Level string `json:"level"`
|
||||
}
|
||||
|
||||
// Pool represents a resource pool
|
||||
type Pool struct {
|
||||
PoolID string `json:"poolid"`
|
||||
Name string `json:"name"`
|
||||
Comment string `json:"comment,omitempty"`
|
||||
}
|
||||
|
||||
// User represents a Proxmox user
|
||||
type User struct {
|
||||
UserID string `json:"userid"`
|
||||
Realm string `json:"realm"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Email string `json:"email,omitempty"`
|
||||
FirstName string `json:"firstname,omitempty"`
|
||||
LastName string `json:"lastname,omitempty"`
|
||||
Groups []string `json:"groups,omitempty"`
|
||||
Comment string `json:"comment,omitempty"`
|
||||
Expire int `json:"expire,omitempty"`
|
||||
LastLogin int64 `json:"last_login,omitempty"`
|
||||
}
|
||||
|
||||
// Role represents a Proxmox user role
|
||||
type Role struct {
|
||||
RoleID string `json:"roleid"`
|
||||
Privs []string `json:"privs,omitempty"`
|
||||
Special bool `json:"special,omitempty"`
|
||||
}
|
||||
|
||||
// Permission represents a permission in Proxmox
|
||||
type Permission struct {
|
||||
Path string `json:"path"`
|
||||
Role string `json:"role"`
|
||||
User string `json:"user,omitempty"`
|
||||
Group string `json:"group,omitempty"`
|
||||
Realm string `json:"realm,omitempty"`
|
||||
}
|
||||
Reference in New Issue
Block a user