### API Path Examples Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/README.md Examples demonstrating how the library's JavaScript methods map to Proxmox VE API paths. ```javascript // API Path: /cluster/status client.cluster.status.status() ``` ```javascript // API Path: /nodes/{node}/qemu/{vmid}/config client.nodes.get("pve1").qemu.get(100).config.vmConfig() ``` ```javascript // API Path: /nodes/{node}/lxc/{vmid}/snapshot client.nodes.get("pve1").lxc.get(101).snapshot.snapshot("snap-name") ``` ```javascript // API Path: /nodes/{node}/storage/{storage} client.nodes.get("pve1").storage.get("local").status() ``` -------------------------------- ### Example Token Creation and Permission Grant Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/authentication.md This example demonstrates creating a user, generating an API token for them, and then granting necessary permissions using `pveum` commands. ```bash # Create token for automation user pveum user add automation@pve --password "secure-password" pveum user token add automation@pve api-token --privsep=0 --comment "API automation" # Grant necessary permissions pveum aclmod / -user automation@pve -role Administrator ``` -------------------------------- ### Proxmox VE Configuration File Example Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/authentication.md Example of a configuration file for Proxmox VE API client, specifying host, API token, and timeout. ```json { "proxmox": { "host": "pve.example.com", "apiToken": "user@pve!token=uuid", "timeout": 30000 } } ``` -------------------------------- ### API Path Examples Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/apistructure.md Illustrates how different API paths map to JavaScript client method calls for various Proxmox VE resources. ```javascript // API Path: /cluster/status await client.cluster.status.status(); ``` ```javascript // API Path: /nodes/{node}/qemu/{vmid}/config await client.nodes.get("pve1").qemu.get(100).config.vmConfig(); ``` ```javascript // API Path: /nodes/{node}/lxc/{vmid}/snapshot await client.nodes.get("pve1").lxc.get(101).snapshot.snapshot("snap-name"); ``` ```javascript // API Path: /nodes/{node}/storage/{storage} await client.nodes.get("pve1").storage.get("local").status(); ``` -------------------------------- ### Manage VM Snapshots Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/README.md Provides examples for creating, listing, and deleting VM snapshots using the API. ```javascript const vm = client.nodes.get("pve1").qemu.get(100); // Create snapshot await vm.snapshot.snapshot("backup-before-update", "Pre-update backup"); console.log("Snapshot created successfully!"); // List snapshots const snapshots = await vm.snapshot.snapshotList(); console.log("Available snapshots:"); for (const snap of snapshots.response.data) { console.log(` - ${snap.name}: ${snap.description}`); } // Delete snapshot await vm.snapshot.get("backup-before-update").delSnapshot(); console.log("Snapshot deleted successfully!"); ``` -------------------------------- ### Install cv4pve-api-javascript Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/README.md Install the package using npm. This is the first step to using the Proxmox VE API client. ```bash npm install @corsinvest/cv4pve-api-javascript ``` -------------------------------- ### Home Lab Proxmox VE API Client Setup Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/authentication.md Sets up the PveClient for a home lab, configuring the host and logging in with root credentials using an environment variable for the password. ```javascript // Simple home lab setup const { PveClient } = require("@corsinvest/cv4pve-api-javascript"); const client = new PveClient("192.168.1.100"); client.timeout = 120000; // 2 minutes in milliseconds await client.login("root", process.env.PVE_PASSWORD, "pam"); ``` -------------------------------- ### API Path Examples Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/apistructure.md Illustrates how different API paths are accessed using the JavaScript client, demonstrating the mapping between API endpoints and client methods. ```APIDOC ## API Path Examples ### Description Examples showing the mapping between Proxmox VE API paths and their corresponding JavaScript client calls. ### Code Examples ```javascript // API Path: /cluster/status await client.cluster.status.status(); // API Path: /nodes/{node}/qemu/{vmid}/config await client.nodes.get("pve1").qemu.get(100).config.vmConfig(); // API Path: /nodes/{node}/lxc/{vmid}/snapshot await client.nodes.get("pve1").lxc.get(101).snapshot.snapshot("snap-name"); // API Path: /nodes/{node}/storage/{storage} await client.nodes.get("pve1").storage.get("local").status(); ``` ``` -------------------------------- ### Container Operations API Calls Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/apistructure.md Examples for managing Proxmox VE LXC containers, including configuration, status, and starting operations. ```javascript await client.nodes.get("pve1").lxc.get(101).config.vmConfig(); // GET config ``` ```javascript await client.nodes.get("pve1").lxc.get(101).status.current.vmStatus(); // GET status ``` ```javascript await client.nodes.get("pve1").lxc.get(101).status.start.vmStart(); // POST start ``` -------------------------------- ### Common Endpoints: Container Operations Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/apistructure.md Provides examples for using the JavaScript client to perform operations on Proxmox VE Containers (LXC), such as getting configuration, status, and starting a container. ```APIDOC ## Container Operations ### Description Examples of JavaScript client calls for performing various operations on Proxmox VE LXC Containers. ### Code Examples ```javascript await client.nodes.get("pve1").lxc.get(101).config.vmConfig(); // GET config await client.nodes.get("pve1").lxc.get(101).status.current.vmStatus(); // GET status await client.nodes.get("pve1").lxc.get(101).status.start.vmStart(); // POST start ``` ``` -------------------------------- ### Enterprise Proxmox VE API Client Setup Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/authentication.md Sets up the PveClient for a corporate environment, configuring the host and API token from environment variables. ```javascript // Corporate environment const { PveClient } = require("@corsinvest/cv4pve-api-javascript"); const client = new PveClient("pve.company.com"); client.timeout = 300000; // 5 minutes in milliseconds client.apiToken = process.env.PROXMOX_API_TOKEN; ``` -------------------------------- ### Quick Start: Connect and Get Cluster Status Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/README.md Connect to your Proxmox VE host and log in using username and password. Then, retrieve the cluster status. Ensure you replace placeholders with your actual host, username, and password. ```javascript const { PveClient } = require("@corsinvest/cv4pve-api-javascript"); async function main() { const client = new PveClient("your-proxmox-host.com"); if (await client.login("root", "your-password")) { // Get cluster status const status = await client.cluster.status.status(); console.log(`Cluster: ${status.response.data[0].name}`); // Manage VMs const vm = await client.nodes.get("pve1").qemu.get(100).config.vmConfig(); console.log(`VM: ${vm.response.data.name}`); } } main(); ``` -------------------------------- ### Cloud/Automation Proxmox VE API Client Setup Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/authentication.md Sets up the PveClient for cloud or automation scripts, using environment variables for host and API token, and verifying the connection. ```javascript // Automated deployment script const { PveClient } = require("@corsinvest/cv4pve-api-javascript"); const client = new PveClient(process.env.PROXMOX_HOST); // Use API token for automation client.apiToken = process.env.PROXMOX_API_TOKEN; // Verify connection before proceeding if (!(await testAuthentication(client))) { process.exit(1); } ``` -------------------------------- ### Safely Perform VM Operations with Error Handling Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/examples.md Use this function to safely start or stop a VM, catching and logging any exceptions. It returns true on success and false on failure. ```javascript async function safeVmOperation(client, node, vmId, operation) { try { const vm = client.nodes.get(node).qemu.get(vmId); let result; switch (operation.toLowerCase()) { case "start": result = await vm.status.start.vmStart(); break; case "stop": result = await vm.status.stop.vmStop(); break; default: throw new Error(`Unknown operation: ${operation}`); } if (result.isSuccessStatusCode) { console.log(`VM ${vmId} ${operation} successful`); return true; } console.log(`VM ${vmId} ${operation} failed: ${result.reasonPhrase}`); return false; } catch (error) { console.log(`Exception during ${operation} on VM ${vmId}: ${error.message}`); return false; } } ``` -------------------------------- ### Client Setup with Error Handling Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/examples.md Sets up the Proxmox VE API client with a configurable timeout and handles authentication using either an API token from environment variables or direct login credentials. Includes error handling for authentication failures. ```javascript async function createClient() { const client = new PveClient("pve.local"); client.timeout = 120000; // 2 minutes in milliseconds try { // Use API token or login if (process.env.PVE_TOKEN) { client.apiToken = process.env.PVE_TOKEN; } else { const success = await client.login("root", "password", "pam"); if (!success) { throw new Error("Authentication failed"); } } return client; } catch (error) { console.log(`Failed to create client: ${error.message}`); throw error; } } ``` -------------------------------- ### Configure IDE CD-ROM Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/common-issues.md Attaches an ISO image as a CD-ROM drive using the IDE interface. This is typically used for operating system installation. ```javascript // IDE CD-ROM await vm.config.updateVm({ ide2: "local:iso/ubuntu-22.04.iso,media=cdrom" }); ``` -------------------------------- ### Avoid Hardcoding Credentials Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/authentication.md This example shows a 'Don't' scenario, highlighting the risk of hardcoding credentials directly into your code. Always use secure methods like environment variables. ```javascript // Don't hardcode credentials await client.login("root", "password123"); // Bad! ``` -------------------------------- ### HTTP Method Mapping Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/apistructure.md Details the correspondence between standard HTTP methods (GET, POST, PUT, DELETE) and their equivalent methods in the JavaScript client, along with their purposes and examples. ```APIDOC ## HTTP Method Mapping ### Description This table outlines how common HTTP methods are translated into JavaScript client methods for interacting with the Proxmox VE API. ### Method Mapping Table | HTTP Method | JavaScript Method | Purpose | Example | |-------------|------------------|---------|---------| | `GET` | `await resource.get()` | Retrieve information | `await vm.config.vmConfig()` | | `POST` | `await resource.create(parameters)` | Create resources | `await vm.snapshot.snapshot("snap-name", "description")` | | `PUT` | `await resource.set(parameters)` | Update resources | `await vm.config.updateVm({memory: 4096})` | | `DELETE` | `await resource.delete()` | Remove resources | `await vm.deleteVm()` | ``` -------------------------------- ### Configure Client Timeout Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/errorhandling.md Adjust the client's timeout setting to accommodate long-running operations. This example increases the timeout to 5 minutes. ```javascript const client = new PveClient("pve.local"); client.timeout = 300000; // Increase timeout for long operations (5 minutes in milliseconds) try { const result = await client.nodes.get("pve1").qemu.get(100).clone.cloneVm({newid: 101}); } catch (error) { if (error.message.includes('timeout')) { console.log("Operation timed out - try increasing client timeout"); } else { console.log("Operation failed:", error.message); } } ``` -------------------------------- ### Configure Multiple Networks Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/common-issues.md Sets up multiple network interfaces with different models, bridges, and specific options like VLAN tags and queue counts. This allows for complex network setups. ```javascript // Multiple networks with different settings await vm.config.updateVm({ net0: "model=virtio,bridge=vmbr0,firewall=1", net1: "model=e1000,bridge=vmbr1,rate=100", net2: "model=virtio,bridge=vmbr0,tag=200,queues=4" }); ``` -------------------------------- ### Node Level API Calls Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/apistructure.md Examples for interacting with specific nodes, including retrieving node lists and status. ```javascript await client.nodes.index(); // GET /nodes ``` ```javascript await client.nodes.get("pve1").status.status(); // GET /nodes/pve1/status ``` ```javascript await client.nodes.get("pve1").storage.index(); // GET /nodes/pve1/storage ``` -------------------------------- ### List Network Bridges Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/common-issues.md Fetches network configuration and lists all configured network bridges on a Proxmox VE node. Essential for verifying network setup. ```javascript const networks = await client.nodes.get("pve1").network.index(); for (const net of networks.response.data) { if (net.type === "bridge") { console.log(`Bridge: ${net.iface}`); } } ``` -------------------------------- ### Cluster Level API Calls Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/apistructure.md Examples of common API calls for managing cluster-wide resources and information. ```javascript await client.cluster.status.status(); // GET /cluster/status ``` ```javascript await client.cluster.resources.resources(); // GET /cluster/resources ``` ```javascript await client.version.version(); // GET /version ``` -------------------------------- ### Get Virtual Machine Configuration Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/examples.md Fetches the configuration details for a specific virtual machine identified by its node and VMID. Displays properties like name, memory, CPU cores, and boot order. ```javascript // Get VM configuration const vmConfig = await client.nodes.get("pve1").qemu.get(100).config.vmConfig(); const config = vmConfig.response.data; console.log(`VM Name: ${config.name}`); console.log(`Memory: ${config.memory} MB`); console.log(`CPU Cores: ${config.cores}`); console.log(`Boot Order: ${config.boot}`); ``` -------------------------------- ### Proxmox Repository Pattern Implementation Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/advanced.md Implement the repository pattern to abstract data access for Proxmox resources. This class provides methods for retrieving VM lists, VM configurations, starting VMs, and creating snapshots. ```javascript class ProxmoxRepository { constructor(client) { this.client = client; } async getVmsAsync(nodeFilter = null) { console.log(`Getting VMs for node filter: ${nodeFilter}`); const resources = await this.client.cluster.resources.resources(); let vms = resources.response.data.filter(r => r.type === "qemu"); if (nodeFilter) { vms = vms.filter(vm => vm.node.toLowerCase() === nodeFilter.toLowerCase()); } return vms; } async getVmConfigAsync(node, vmId) { console.log(`Getting config for VM ${vmId} on node ${node}`); const result = await this.client.nodes.get(node).qemu.get(vmId).config.vmConfig(); return result.response.data; } async startVmAsync(node, vmId) { console.log(`Starting VM ${vmId} on node ${node}`); await this.client.nodes.get(node).qemu.get(vmId).status.start.vmStart(); console.log(`Successfully started VM ${vmId}`); } async createSnapshotAsync(node, vmId, name, description = null) { console.log(`Creating snapshot ${name} for VM ${vmId} on node ${node}`); await this.client.nodes.get(node).qemu.get(vmId).snapshot.snapshot(name, description); } } ``` -------------------------------- ### Validate Input Parameters Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/errorhandling.md Implement input validation for function arguments to prevent errors. This example checks for valid node names and VM IDs before making an API call. ```javascript // Always validate input async function getVmConfig(client, node, vmId) { if (!node || typeof node !== 'string') { throw new Error("Node name must be a non-empty string"); } if (typeof vmId !== 'number' || vmId <= 0) { throw new Error("VM ID must be a positive number"); } return await client.nodes.get(node).qemu.get(vmId).config.vmConfig(); } ``` -------------------------------- ### Virtual Machine Power Management Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/examples.md Provides functions to control the power state of a virtual machine, including starting, stopping, and restarting. Also retrieves the current status and resource utilization (CPU, memory). ```javascript const vm = client.nodes.get("pve1").qemu.get(100); // Start VM await vm.status.start.vmStart(); console.log("VM started successfully"); // Stop VM await vm.status.stop.vmStop(); console.log("VM stopped successfully"); // Restart VM await vm.status.reboot.vmReboot(); console.log("VM restarted successfully"); // Get current status const status = await vm.status.current.vmStatus(); console.log(`VM Status: ${status.response.data.status}`); console.log(`CPU Usage: ${(status.response.data.cpu * 100).toFixed(2)}%`); console.log(`Memory: ${(status.response.data.mem / status.response.data.maxmem * 100).toFixed(2)}%`); ``` -------------------------------- ### Configure API Client with API Token Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/README.md For automated processes, use API tokens for authentication. Assign the token to the `apiToken` property of the client instance. Ensure the token is securely stored, for example, in environment variables. ```javascript // 2. Use API tokens for automation const client = new PveClient("pve.cluster.com"); client.apiToken = process.env.PROXMOX_API_TOKEN; ``` -------------------------------- ### Common Endpoints: VM Operations Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/apistructure.md Shows JavaScript client usage for common Virtual Machine (VM) operations, including retrieving configuration, status, starting a VM, and managing snapshots. ```APIDOC ## VM Operations ### Description Examples of JavaScript client calls for performing various operations on Proxmox VE Virtual Machines (VMs). ### Code Examples ```javascript await client.nodes.get("pve1").qemu.get(100).config.vmConfig(); // GET config await client.nodes.get("pve1").qemu.get(100).status.current.vmStatus(); // GET status await client.nodes.get("pve1").qemu.get(100).status.start.vmStart(); // POST start await client.nodes.get("pve1").qemu.get(100).snapshot.snapshotList(); // GET snapshots ``` ``` -------------------------------- ### Get Storage Information for a Node Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/examples.md Fetches and displays storage details for a specific Proxmox VE node, including total capacity, available space, and usage percentage. Requires the node name and an initialized client. ```javascript // Get storage for a specific node const storages = await client.nodes.get("pve1").storage.index(); console.log("Available Storage:"); for (const storage of storages.response.data) { const usedPercent = storage.used / storage.total * 100; console.log(` ${storage.storage} (${storage.type}): ${usedPercent.toFixed(1)}% used`); console.log(` Total: ${(storage.total / (1024*1024*1024)).toFixed(2)} GB`); console.log(` Available: ${(storage.avail / (1024*1024*1024)).toFixed(2)} GB`); } ``` -------------------------------- ### Perform Batch Operations on VMs Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/examples.md Executes a specified operation (start, stop, restart) on a list of virtual machine IDs within the Proxmox VE cluster. It first finds the VM's node and then initiates the operation. ```javascript async function batchVmOperation(client, vmIds, operation) { const results = []; for (const vmId of vmIds) { // Find VM location const resources = await client.cluster.resources.resources(); const vm = resources.response.data.find(r => r.type === "qemu" && r.vmid === vmId); if (vm) { const vmInstance = client.nodes.get(vm.node).qemu.get(vmId); let task; switch (operation.toLowerCase()) { case "start": task = vmInstance.status.start.vmStart(); break; case "stop": task = vmInstance.status.stop.vmStop(); break; case "restart": task = vmInstance.status.reboot.vmReboot(); break; default: throw new Error(`Unknown operation: ${operation}`); } await task; results.push({ vmId, success: true }); } } for (const result of results) { console.log(`VM ${result.vmId} ${operation}: ${result.success ? "Success" : "Failed"}`); } } ``` -------------------------------- ### Get VM Performance Metrics Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/examples.md Retrieves and displays detailed performance metrics for a specific virtual machine, including CPU usage, memory, disk I/O, network traffic, and uptime. Requires the node name, VM ID, and a helper function `formatBytes`. ```javascript async function getVmPerformance(client, node, vmId) { const vm = client.nodes.get(node).qemu.get(vmId); // Get current status const status = await vm.status.current.vmStatus(); const data = status.response.data; console.log(`VM ${vmId} Performance:`); console.log(` Status: ${data.status}`); console.log(` CPU Usage: ${(data.cpu * 100).toFixed(2)}%`); console.log(` Memory: ${formatBytes(data.mem)} / ${formatBytes(data.maxmem)} (${((data.mem / data.maxmem) * 100).toFixed(1)}%)`); console.log(` Disk Read: ${formatBytes(data.diskread)}`); console.log(` Disk Write: ${formatBytes(data.diskwrite)}`); console.log(` Network In: ${formatBytes(data.netin)}`); console.log(` Network Out: ${formatBytes(data.netout)}`); console.log(` Uptime: ${Math.floor(data.uptime / 60)}m ${data.uptime % 60}s`); } function formatBytes(bytes) { if (bytes === 0) return '0 Bytes'; const k = 1024; const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; } ``` -------------------------------- ### Manage Virtual Machines Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/README.md Demonstrates logging in, retrieving VM configuration, updating VM settings, and managing VM status (start/stop). ```javascript const { PveClient } = require("@corsinvest/cv4pve-api-javascript"); const client = new PveClient("pve.example.com"); await client.login("admin", "password", "pve"); // Get VM configuration const vm = client.nodes.get("pve1").qemu.get(100); const config = await vm.config.vmConfig(); const vmData = config.response.data; console.log(`VM Name: ${vmData.name}`); console.log(`Memory: ${vmData.memory} MB`); console.log(`CPUs: ${vmData.cores}`); // Update VM configuration const updateResult = await vm.config.updateVm({ memory: 8192, // 8GB RAM cores: 4 // 4 CPU cores }); console.log("VM configuration updated!"); // VM Status Management const status = await vm.status.current.vmStatus(); console.log(`Current status: ${status.response.data.status}`); // Start VM if (status.response.data.status === "stopped") { await vm.status.start.vmStart(); console.log("VM started successfully!"); } ``` -------------------------------- ### Start an Operation and Get Task ID Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/tasks.md Initiates an asynchronous operation and retrieves the task ID for subsequent status checks. The task ID is typically found in the 'data' field of the response. ```javascript const result = await client.nodes.get("pve1").qemu.get(100).clone.cloneVm({newid: 101}); const taskId = result.response.data; // Returns: "UPID:pve1:..." console.log(`Task started: ${taskId}`); ``` -------------------------------- ### Create Linux VM with VirtIO and Cloud-Init Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/common-issues.md Creates a Linux VM with specified hardware resources, VirtIO drivers, and Cloud-Init configuration for network, user, and SSH keys. Ensure the PVE client is logged in before execution. ```javascript const client = new PveClient("pve.example.com"); await client.login("admin", "password", "pve"); // VM identifiers const vmid = 101; const vmName = "ubuntu-server"; const node = "pve1"; // Hardware resources const memory = 4096; // 4GB RAM const cores = 2; const sockets = 1; // Create VM with full configuration const result = await client.nodes.get(node).qemu.createVm({ vmid: vmid, name: vmName, memory: memory, cores: cores, sockets: sockets, ostype: "l26", scsihw: "virtio-scsi-single", boot: "order=virtio0", agent: "enabled=1", virtio0: "local-lvm:32,cache=writethrough,discard=on", net0: "model=virtio,bridge=vmbr0,firewall=1", ipconfig0: "ip=192.168.1.100/24,gw=192.168.1.1", ciuser: "admin", cipassword: "SecurePassword123!", sshkeys: "ssh-rsa AAAAB3NzaC1yc2E...", nameserver: "8.8.8.8 8.8.4.4", searchdomain: "example.com" }); console.log(`VM ${vmid} created successfully with cloud-init!`); ``` -------------------------------- ### Get Recent Tasks History Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/tasks.md Retrieves a list of recent tasks for a given node, with an optional limit. It converts Unix timestamps to JavaScript Date objects and sorts tasks by start time. ```javascript async function getRecentTasks(client, node, limit = 10) { const result = await client.nodes.get(node).tasks.nodeTasks({limit: limit}); const tasks = []; for (const task of result.response.data) { tasks.push({ id: task.upid, type: task.type, status: task.status, exitStatus: task.exitstatus, startTime: new Date(task.starttime * 1000), // Convert Unix timestamp endTime: task.endtime ? new Date(task.endtime * 1000) : null, user: task.user, node: task.node }); } return tasks.sort((a, b) => b.startTime - a.startTime); } ``` -------------------------------- ### Initialize and Login to PVE Client Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/common-issues.md Initializes the PVE client and logs in using provided credentials. Ensure you have the correct hostname and authentication method. ```javascript const { PveClient } = require("@corsinvest/cv4pve-api-javascript"); const client = new PveClient("pve.example.com"); await client.login("root", "password", "pam"); ``` -------------------------------- ### Initialize PVE Client Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/advanced.md Sets up the Proxmox Virtual Environment client with a specific hostname, API token, and request timeout. Ensure the PROXMOX_API_TOKEN environment variable is set. ```javascript const { PveClient } = require("@corsinvest/cv4pve-api-javascript"); const client = new PveClient("pve.company.com"); client.apiToken = process.env.PROXMOX_API_TOKEN; client.timeout = 600000; // 10 minutes in milliseconds ``` -------------------------------- ### Configure PveClient with Environment Variables Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/authentication.md This JavaScript code snippet demonstrates how to initialize the `PveClient` by reading configuration from environment variables, supporting both API token and username/password authentication. ```javascript const { PveClient } = require("@corsinvest/cv4pve-api-javascript"); // Load configuration from environment const config = { host: process.env.PROXMOX_HOST, apiToken: process.env.PROXMOX_API_TOKEN, timeout: parseInt(process.env.PROXMOX_TIMEOUT || '30000') }; const client = new PveClient(config.host); // Use API token if available if (config.apiToken) { client.apiToken = config.apiToken; } else { // Fallback to username/password const username = process.env.PROXMOX_USER; const password = process.env.PROXMOX_PASS; await client.login(username, password); } ``` -------------------------------- ### List All Virtual Machines Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/examples.md Retrieves a list of all resources in the cluster and filters them to display information about virtual machines (QEMU). Shows VM ID, name, node, and status. ```javascript // Get all VMs in cluster const resources = await client.cluster.resources.resources(); for (const resource of resources.response.data) { if (resource.type === "qemu") { console.log(`VM ${resource.vmid}: ${resource.name} on ${resource.node} - ${resource.status}`); } } ``` -------------------------------- ### Initialize and Authenticate with Username/Password Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/authentication.md This method uses traditional username and password for authentication. You can specify the realm or let it default to PAM. ```javascript const { PveClient } = require("@corsinvest/cv4pve-api-javascript"); const client = new PveClient("pve.example.com"); // Basic login (defaults to PAM realm) const success = await client.login("root", "password"); // Login with specific realm const success = await client.login("admin", "password", "pve"); // Login with PAM realm explicitly const success = await client.login("user", "password", "pam"); ``` -------------------------------- ### Configure Basic SCSI Disk Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/common-issues.md Creates a basic SCSI disk attached to the 'local-lvm' storage with a specified size. Ensure the storage pool is available. ```javascript // Basic SCSI disk - 32GB await vm.config.updateVm({ scsi0: "local-lvm:32" }); ``` -------------------------------- ### Create API Token via Command Line Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/authentication.md Use the `pveum` command-line tool to manage API tokens. This includes adding, listing, and removing tokens for specific users. ```bash # Create API token pveum user token add root@pam api-automation --privsep=0 # List tokens pveum user token list root@pam # Remove token pveum user token remove root@pam api-automation ``` -------------------------------- ### Retrieve VM Configuration Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/common-issues.md Fetches the configuration of a specific virtual machine. Useful for troubleshooting startup issues. ```javascript const result = await client.nodes.get("pve1").qemu.get(100).config.vmConfig(); console.log(result.response.data); ``` -------------------------------- ### Common Endpoints: Cluster Level Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/apistructure.md Provides examples of JavaScript client calls for accessing cluster-level API endpoints, such as retrieving cluster status and resources. ```APIDOC ## Cluster Level Endpoints ### Description Examples for interacting with cluster-wide API endpoints using the JavaScript client. ### Code Examples ```javascript await client.cluster.status.status(); // GET /cluster/status await client.cluster.resources.resources(); // GET /cluster/resources await client.version.version(); // GET /version ``` ``` -------------------------------- ### Log API Call Details Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/errorhandling.md Log the start, duration, and outcome (success or failure) of API calls. This is useful for debugging and monitoring API usage. ```javascript async function loggedApiCall(apiCall, operation) { console.log(`Starting: ${operation}`); const startTime = Date.now(); try { const result = await apiCall(); const duration = Date.now() - startTime; if (result.isSuccessStatusCode) { console.log(`${operation} completed in ${duration}ms`); } else { console.log(`${operation} failed after ${duration}ms: ${result.reasonPhrase}`); } return result; } catch (error) { const duration = Date.now() - startTime; console.log(`${operation} threw exception after ${duration}ms: ${error.message}`); throw error; } } ``` -------------------------------- ### Configure EFI Disk for UEFI Boot Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/common-issues.md Sets up an EFI disk and configures the VM to use UEFI boot (OVMF firmware). This is required for modern operating systems that support UEFI. ```javascript // EFI disk for UEFI boot await client.nodes.get("pve1").qemu.get(100).config.updateVm({ bios: "ovmf", efidisk0: "local-lvm:1,efitype=4m,pre-enrolled-keys=0" }); ``` -------------------------------- ### Configure VM IP Address with Cloud-Init Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/common-issues.md Use `ipconfigN` to set IP addresses for virtual machine interfaces. Supports DHCP, static IPv4, and IPv6 auto-configuration. ```javascript await vm.config.updateVm({ ipconfig0: "ip=dhcp" }); ``` ```javascript await vm.config.updateVm({ ipconfig0: "ip=192.168.1.100/24,gw=192.168.1.1" }); ``` ```javascript await vm.config.updateVm({ ipconfig0: "ip=192.168.1.100/24,gw=192.168.1.1", // Management ipconfig1: "ip=10.0.0.100/24", // Internal network ipconfig2: "ip=dhcp" // External network via DHCP }); ``` ```javascript await vm.config.updateVm({ ipconfig0: "ip=192.168.1.100/24,gw=192.168.1.1,ip6=auto" }); ``` -------------------------------- ### Get Cluster Status Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/examples.md Retrieves the overall status of the Proxmox VE cluster, iterating through different resource types (e.g., nodes, storage) and displaying their names and current status. ```javascript // Get cluster status const clusterStatus = await client.cluster.status.status(); console.log("Cluster Status:"); for (const item of clusterStatus.response.data) { console.log(` ${item.type}: ${item.name} - ${item.status}`); } ``` -------------------------------- ### Initialize and Authenticate with API Token Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/authentication.md Use this method for secure automation. Set the `apiToken` property directly; no `login()` call is required. ```javascript const { PveClient } = require("@corsinvest/cv4pve-api-javascript"); const client = new PveClient("pve.example.com"); // Set API token (no login() call needed) client.apiToken = "user@realm!tokenid=uuid"; // Ready to use const version = await client.version.version(); ``` -------------------------------- ### Get All Nodes Information Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/examples.md Retrieves and displays information about all nodes in the Proxmox VE cluster, including their status, CPU usage, memory usage, and uptime. Ensure the client is initialized before calling. ```javascript // Get all nodes const nodes = await client.nodes.index(); console.log("Available Nodes:"); for (const node of nodes.response.data) { console.log(` ${node.node}: ${node.status}`); console.log(` CPU: ${(node.cpu * 100).toFixed(2)}%`); console.log(` Memory: ${(node.mem / node.maxmem * 100).toFixed(2)}%`); console.log(` Uptime: ${Math.floor(node.uptime / 3600)}h ${Math.floor((node.uptime % 3600) / 60)}m`); } ``` -------------------------------- ### Method Parameters: Object vs. Positional Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/apistructure.md Illustrates two ways to pass parameters to methods: as an object for configuration updates or as positional arguments for actions like creating snapshots. ```javascript // Parameters as objects await vm.config.updateVm({memory: 4096, cores: 2}); ``` ```javascript // Positional parameters await vm.snapshot.snapshot("backup", "Description here"); ``` -------------------------------- ### Configure PVE Client Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/README.md Instantiate and configure the PVE client with custom settings like port, timeout, response type, and debug logging. ```javascript // Create client with custom port const client = new PveClient("pve.example.com", 8006); // Configure timeout (default: 30000ms = 30 seconds) client.timeout = 300000; // 5 minutes in milliseconds // Response type: "json" or "png" (for charts) client.responseType = "json"; // Enable debug logging client.logEnabled = true; ``` -------------------------------- ### Configure Basic VirtIO Network Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/common-issues.md Sets up a basic VirtIO network interface connected to a specified bridge. Ensure the bridge exists on your Proxmox VE node. ```javascript // Basic VirtIO network await vm.config.updateVm({ net0: "model=virtio,bridge=vmbr0" }); ``` -------------------------------- ### String Indexers for Resource Names Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/apistructure.md Demonstrates using string identifiers for nodes, storage, and snapshots to access specific resources. ```javascript client.nodes.get("pve1") // Node name ``` ```javascript client.nodes.get("pve1").storage.get("local") // Storage name ``` ```javascript client.nodes.get("pve1").qemu.get(100).snapshot.get("snap1") // Snapshot name ``` -------------------------------- ### Container Management Operations Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/examples.md Performs various management operations on an LXC container, including retrieving its configuration (hostname, OS template, memory), starting the container, and checking its current status and uptime. ```javascript const container = client.nodes.get("pve1").lxc.get(101); // Get container configuration const config = await container.config.vmConfig(); const ctConfig = config.response.data; console.log(`Container: ${ctConfig.hostname}`); console.log(`OS Template: ${ctConfig.ostemplate}`); console.log(`Memory: ${ctConfig.memory} MB`); // Start container await container.status.start.vmStart(); console.log("Container started"); // Get container status const status = await container.status.current.vmStatus(); console.log(`Status: ${status.response.data.status}`); console.log(`Uptime: ${status.response.data.uptime} seconds`); ``` -------------------------------- ### Clone VM with Progress Reporting Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/tasks.md Clones a virtual machine in Proxmox VE and monitors its progress using `waitForTaskCompletion`. Logs status updates to the console and indicates success or failure. ```javascript async function cloneVmWithProgress( client, node, sourceVmId, targetVmId, newName ) { console.log(`Cloning VM ${sourceVmId} to ${targetVmId}...`); // Start clone operation const cloneResult = await client.nodes.get(node).qemu.get(sourceVmId).clone.cloneVm({ newid: targetVmId, name: newName }); const taskId = cloneResult.response.data; // Wait for completion with progress reporting const progressCallback = (status) => console.log(`Status: ${status}`); try { const success = await waitForTaskCompletion(client, node, taskId, 3600000, progressCallback); // 60 minutes if (success) { console.log(`VM cloned successfully: ${sourceVmId} → ${targetVmId}`); } else { console.log(`VM clone failed`); } return success; } catch (error) { console.log(`Timeout: Clone operation timed out: ${error.message}`); return false; } } ``` -------------------------------- ### Provide Fallback Status on Error Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/errorhandling.md Implement graceful degradation by returning a fallback status object if an API call to get cluster status fails. This ensures the application can still provide some information. ```javascript async function getClusterStatus(client) { try { const result = await client.cluster.status.status(); if (result.isSuccessStatusCode) { return parseClusterStatus(result.response.data); } } catch (error) { console.log(`Warning: Could not get cluster status: ${error.message}`); } // Return fallback status return { status: "unknown", lastUpdate: new Date() }; } ``` -------------------------------- ### Configure VirtIO Disks Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/common-issues.md Sets up VirtIO disks for high performance, specifying storage, size, cache mode, and IO thread. VirtIO is generally recommended for modern VMs. ```javascript // VirtIO disks for maximum performance await vm.config.updateVm({ virtio0: "local-lvm:32,cache=writethrough,discard=on", virtio1: "ceph-storage:100,cache=none,iothread=1" }); ``` -------------------------------- ### Create User for API Access Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/authentication.md Use `pveum` to create a dedicated user account for API access. This allows for granular permission management and improves security. ```bash # Create user for API access pveum user add api-user@pve --password "secure-password" --comment "API automation user" ``` -------------------------------- ### Batch VM Cloning with Task Monitoring Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/tasks.md Initiates multiple VM clone operations concurrently and monitors their progress. Requires a `monitorMultipleTasks` function to be defined elsewhere. ```javascript async function bulkVmClone( client, node, sourceVmId, targetVmIds ) { const tasks = {}; // taskId -> targetVmId const results = {}; // Start all clone operations for (const targetVmId of targetVmIds) { try { const cloneResult = await client.nodes.get(node).qemu.get(sourceVmId).clone.cloneVm({newid: targetVmId}); if (cloneResult.isSuccessStatusCode) { const taskId = cloneResult.response.data; tasks[taskId] = targetVmId; console.log(`Started clone to VM ${targetVmId} (Task: ${taskId})`); } else { console.log(`Failed to start clone to VM ${targetVmId}: ${cloneResult.reasonPhrase}`); results[targetVmId] = false; } } catch (error) { console.log(`Exception starting clone to VM ${targetVmId}: ${error.message}`); results[targetVmId] = false; } } // Monitor all tasks const taskResults = await monitorMultipleTasks( client, Object.keys(tasks).reduce((obj, taskId) => { obj[taskId] = node; return obj; }, {}) ); // Map task results back to VM IDs for (const [taskId, success] of Object.entries(taskResults)) { if (tasks[taskId] !== undefined) { results[tasks[taskId]] = success; } } return results; } ``` -------------------------------- ### Manage Long-Running Tasks with Progress Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/advanced.md Executes an operation and waits for its completion, providing status updates. This function is suitable for asynchronous tasks like starting or stopping virtual machines. It includes a timeout to prevent indefinite waiting. ```javascript // Complete task management with progress async function executeWithProgress(client, operation, node, description) { console.log(`Starting: ${description}`); const result = await operation(); if (!result.isSuccessStatusCode) { console.log(`Failed to start ${description}: ${result.reasonPhrase}`); return false; } const taskId = result.response.data; return await waitForTaskCompletion(client, node, taskId, description); } async function waitForTaskCompletion(client, node, taskId, description) { const timeout = 30 * 60 * 1000; // 30 minutes in milliseconds const start = Date.now(); while (Date.now() - start < timeout) { const status = await client.nodes.get(node).tasks.get(taskId).status.readTaskStatus(); if (status.response.data.status === "stopped") { const success = status.response.data.exitstatus === "OK"; console.log(`${description}: ${status.response.data.exitstatus} (${success ? "Success" : "Failed"})`); return success; } await new Promise(resolve => setTimeout(resolve, 2000)); } console.log(`Timeout: ${description} timed out`); return false; } ``` -------------------------------- ### Set Proxmox VE Host and API Token Environment Variables Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/authentication.md Configure your environment by setting `PROXMOX_HOST` and `PROXMOX_API_TOKEN` variables. This is useful for applications that need to connect to Proxmox VE. ```bash # Set environment variables export PROXMOX_HOST="pve.example.com" export PROXMOX_API_TOKEN="user@pve!token=uuid" ``` -------------------------------- ### Basic PVE API Error Handling Pattern Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/errorhandling.md A fundamental pattern for safely executing API operations and handling both exceptions and non-successful HTTP status codes. This function attempts to start a VM and logs success or failure messages. ```javascript async function safeVmOperation(client, node, vmId) { try { const result = await client.nodes.get(node).qemu.get(vmId).status.start.vmStart(); if (result.isSuccessStatusCode) { console.log(`VM ${vmId} started successfully`); return true; } else { console.log(`Failed to start VM ${vmId}: ${result.reasonPhrase}`); return false; } } catch (error) { console.log(`Exception starting VM ${vmId}: ${error.message}`); return false; } } ``` -------------------------------- ### Configure VM Network and Disk Parameters Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/common-issues.md Updates a virtual machine's configuration with indexed network and disk parameters. Refer to the API documentation for specific parameter availability and syntax. ```javascript // Configure network interfaces (indexed as net0, net1, etc.) const networks = { 0: "model=virtio,bridge=vmbr0,firewall=1", 1: "model=e1000,bridge=vmbr1" }; // Configure disks (indexed as scsi0, scsi1, etc.) const disks = { 0: "local-lvm:32,cache=writethrough", 1: "local-lvm:64,iothread=1" }; // Note: The actual method parameters may vary - check API documentation await client.nodes.get("pve1").qemu.get(100).config.updateVm({ net0: networks[0], net1: networks[1], scsi0: disks[0], scsi1: disks[1] }); ``` -------------------------------- ### Check User Permissions with pveum Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/authentication.md Verify user permissions in Proxmox VE using the pveum command-line tool. Ensure the user has the necessary roles. ```bash # Check user permissions pveum user list pveum aclmod / -user user@pve -role Administrator ``` -------------------------------- ### Handle API Response Errors Source: https://github.com/corsinvest/cv4pve-api-javascript/blob/main/docs/errorhandling.md Process API responses to identify and handle specific HTTP status codes like 404 (Not Found), 403 (Permission Denied), or 400 (Bad Request). This example checks the `isSuccessStatusCode` property of the result. ```javascript const result = await client.nodes.get("pve1").qemu.get(999).config.vmConfig(); if (!result.isSuccessStatusCode) { switch (result.statusCode) { case 404: console.log("VM not found"); break; case 403: console.log("Permission denied"); break; case 400: console.log(`Bad request: ${result.reasonPhrase}`); break; default: console.log(`API error: ${result.statusCode} - ${result.reasonPhrase}`); break; } } ```