### Complete Task Management Example Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/tasks.md Demonstrates a full workflow: starting a VM, waiting for its start task to complete, and checking the final exit status. Includes error handling for task failure or timeouts. ```java // Start VM var startResult = client.getNodes().get("pve1") .getQemu().get(100).getStatus().start(); if (startResult.isSuccessStatusCode()) { String upid = startResult.getData().asText(); System.out.println("Starting VM, task: " + upid); // Wait for completion if (client.waitForTaskToFinish("pve1", upid, 1000, 60000)) { String exitStatus = client.getExitStatusTask("pve1", upid); if ("OK".equals(exitStatus)) { System.out.println("VM started successfully"); } else { System.err.println("Task failed: " + exitStatus); } } else { System.err.println("Task timeout"); } } ``` -------------------------------- ### Example API Token Creation and Permissions (Bash) Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/authentication.md Create a user, generate an API token for them, and grant 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 ``` -------------------------------- ### Create and Configure a VM Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/README.md Example of creating a new virtual machine with specified ID, name, memory, and core count. This snippet assumes successful authentication and connection. ```java // Create and configure a VM var client = new PveClient("pve.example.com", 8006); client.login("admin@pve", "password"); var result = client.getNodes().get("pve1").getQemu().createVm( 100, // vmid "web-server", // name 4096, // memory 2 // cores ); if (result.isSuccessStatusCode()) { System.out.println("VM created successfully!"); } ``` -------------------------------- ### Get and Manage Container Configuration Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/examples.md Retrieves configuration details for a specific LXC container, including hostname, OS template, and memory. Also shows how to start a container and check its status. ```java var container = client.getNodes().get("pve1").getLxc().get(101); // Get container configuration var ctConfig = container.getConfig().vmConfig().getData(); System.out.println("Container: " + ctConfig.get("hostname").asText()); System.out.println("OS Template: " + ctConfig.get("ostemplate").asText()); System.out.println("Memory: " + ctConfig.get("memory").asInt() + " MB"); // Start container container.getStatus().start(); System.out.println("Container started"); // Get container status var data = container.getStatus().current().getData(); System.out.println("Status: " + data.get("status").asText()); System.out.println("Uptime: " + data.get("uptime").asInt() + " seconds"); ``` -------------------------------- ### Configure IDE CD-ROM Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/common-issues.md Set up an IDE device to mount an ISO image as a CD-ROM. This is commonly used for operating system installation. ```java // IDE CD-ROM var ideDisks = Map.of( 2, "local:iso/ubuntu-22.04.iso,media=cdrom" ); ``` -------------------------------- ### Configure Proxy for Enterprise Scenarios Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/api.md Set up a proxy for the API client to use in enterprise network environments. This example configures an HTTP proxy. ```java var proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.company.com", 8080)); client.setProxy(proxy); ``` -------------------------------- ### Access and Manage Nested Resources (Snapshots) Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/apistructure.md Demonstrates accessing nested resources like VM snapshots. Includes examples for creating a snapshot, accessing a specific snapshot, and deleting it. ```java // Access VM snapshots var snapshots = client.getNodes().get("pve1") .getQemu().get(100) .getSnapshot(); // Create snapshot snapshots.snapshot("backup-2024"); // Access specific snapshot var snapshot = snapshots.get("backup-2024"); snapshot.delsnapshot(); // Delete snapshot ``` -------------------------------- ### Create Linux VM with VirtIO and Cloud-Init using Java Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/common-issues.md Complete example for creating a Linux VM with VirtIO hardware and Cloud-Init for initial configuration. Ensure you have a PveClient instance and valid credentials. ```java var client = new PveClient("pve.example.com", 8006); client.login("admin@pve", "password"); // VM identifiers int vmid = 101; String vmName = "ubuntu-server"; String node = "pve1"; // Hardware resources int memory = 4096; // 4GB RAM int cores = 2; int sockets = 1; // Configure VirtIO disks var disks = Map.of( 0, "local-lvm:32,cache=writethrough,discard=on" ); // Configure network interfaces var networks = Map.of( 0, "model=virtio,bridge=vmbr0,firewall=1" ); // Cloud-init IP configuration var ipconfig = Map.of( 0, "ip=192.168.1.100/24,gw=192.168.1.1" ); // OS and boot settings String ostype = "l26"; String scsihw = "virtio-scsi-single"; String boot = "order=virtio0"; String agent = "enabled=1"; // Cloud-init credentials and network String ciuser = "admin"; String cipassword = "SecurePassword123!"; String sshkeys = "ssh-rsa AAAAB3NzaC1yc2E..."; String nameserver = "8.8.8.8 8.8.4.4"; String searchdomain = "example.com"; client.getNodes().get(node).getQemu().createVm( vmid, vmName, memory, cores, sockets, ostype, disks, // virtioN networks, // netN ipconfig, // ipconfigN scsihw, boot, agent, ciuser, cipassword, sshkeys, nameserver, searchdomain ); System.out.println("VM " + vmid + " created successfully with cloud-init!"); ``` -------------------------------- ### List All Resources on a Node Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/apistructure.md Examples of listing various resources like nodes, VMs on a specific node, and storage devices attached to a node. These operations typically return a Result object. ```java // List all nodes Result nodes = client.getNodes().index(); // List all VMs on a node Result vms = client.getNodes().get("pve1").getQemu().vmlist(); // List all storage on a node Result storage = client.getNodes().get("pve1").getStorage().index(); ``` -------------------------------- ### Define Basic SCSI Disk Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/common-issues.md Create a basic 32GB SCSI disk using the 'local-lvm' storage. This is a common starting point for VM storage. ```java // Basic SCSI disk - 32GB var disks = Map.of( 0, "local-lvm:32" ); ``` -------------------------------- ### Access and Operate on Virtual Machines Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/apistructure.md Demonstrates accessing a specific VM by its ID and performing common operations such as starting, stopping, shutting down, resetting, and retrieving its configuration. Snapshot management is also included. ```java // Access VM by VMID var vm = client.getNodes().get("pve1").getQemu().get(100); // VM operations vm.getStatus().start(); // Start VM vm.getStatus().stop(); // Stop VM vm.getStatus().shutdown(); // Shutdown VM vm.getStatus().reset(); // Reset VM // VM configuration vm.getConfig().vmConfig(); // Get config vm.getSnapshot(); // Manage snapshots ``` -------------------------------- ### Home Lab Proxmox VE API Setup Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/authentication.md Set up the Proxmox VE Java client for a home lab, disabling certificate validation for self-signed certificates and using a password for login. ```java // Simple home lab setup var client = new PveClient("192.168.1.100", 8006); client.setValidateCertificate(false); // Self-signed cert client.setTimeout(120000); // 2 minutes client.login("root@pam", System.getenv("PVE_PASSWORD")); ``` -------------------------------- ### Get and Update VM Configuration Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/api.md Retrieve and modify the configuration of a Proxmox Virtual Machine. Ensure the PveClient is initialized and authenticated before use. ```java import it.corsinvest.proxmoxve.*; var client = new PveClient("pve.example.com", 8006); client.login("admin@pve", "password"); // Get VM configuration var vm = client.getNodes().get("pve1").getQemu().get(100); var vmData = vm.getConfig().vmConfig().getData(); System.out.println("VM Name: " + vmData.get("name").asText()); System.out.println("Memory: " + vmData.get("memory").asInt() + " MB"); System.out.println("CPUs: " + vmData.get("cores").asInt()); System.out.println("OS Type: " + vmData.get("ostype").asText()); // Update VM configuration var params = Map.of( "memory", 8192, // 8GB RAM "cores", 4 // 4 CPU cores ); vm.getConfig().updateVm(params); System.out.println("VM configuration updated!"); ``` -------------------------------- ### Define Basic VirtIO Network Interface Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/common-issues.md Configure a single VirtIO network interface connected to vmbr0. This is a fundamental setup for VM networking. ```java // Basic VirtIO network var networks = Map.of( 0, "model=virtio,bridge=vmbr0" ); ``` -------------------------------- ### Access and Operate on Containers Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/apistructure.md Shows how to access a specific LXC container by its VMID and perform operations like starting, stopping, and managing snapshots. Retrieving configuration is also covered. ```java // Access container by VMID var ct = client.getNodes().get("pve1").getLxc().get(100); // Container operations ct.getStatus().start(); ct.getStatus().stop(); ct.getSnapshot(); ``` -------------------------------- ### Accessing Proxmox VE API Endpoints Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/api.md Examples demonstrating how to access various Proxmox VE API endpoints using the Java client library. These mirror the API's tree structure. ```java // API Path: /cluster/status client.getCluster().getStatus().getStatus() ``` ```java // API Path: /nodes/{node}/qemu/{vmid}/config client.getNodes().get("pve1").getQemu().get(100).getConfig().vmConfig() ``` ```java // API Path: /nodes/{node}/lxc/{vmid}/snapshot client.getNodes().get("pve1").getLxc().get(101).getSnapshot().snapshot("snap-name") ``` ```java // API Path: /nodes/{node}/storage/{storage} client.getNodes().get("pve1").getStorage().get("local").status() ``` -------------------------------- ### Avoid Hardcoding Credentials (Java) Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/authentication.md Example of what NOT to do: hardcoding credentials directly in the code is a security risk. ```java // Don't hardcode credentials client.login("root", "password123"); // Bad! ``` -------------------------------- ### Safely Perform VM Operations with Error Handling in Java Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/examples.md Provides a robust method for starting or stopping a virtual machine, including comprehensive error handling for exceptions and API response failures. Returns true on success, false otherwise. ```java public static boolean safeVmOperation(PveClient client, String node, int vmId, String operation) { try { var vm = client.getNodes().get(node).getQemu().get(vmId); Result result = switch (operation.toLowerCase()) { case "start" -> vm.getStatus().start(); case "stop" -> vm.getStatus().stop(); default -> throw new IllegalArgumentException("Unknown operation: " + operation); }; if (result.isSuccessStatusCode()) { System.out.println("VM " + vmId + " " + operation + " successful"); return true; } else { System.out.println("VM " + vmId + " " + operation + " failed: " + result.getError()); return false; } } catch (Exception ex) { System.out.println("Exception during " + operation + " on VM " + vmId + ": " + ex.getMessage()); return false; } } ``` -------------------------------- ### Get Cluster Resources Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/README.md Retrieves all resources within the Proxmox VE cluster and iterates through them to print details of QEMU virtual machines. This requires an active client connection and authentication. ```java // Get cluster resources var resources = client.getCluster().getResources().resources().getData(); for (var resource : resources) { if (resource.get("type").asText().equals("qemu")) { System.out.println("VM " + resource.get("vmid").asInt() + ": " + resource.get("name").asText() + " on " + resource.get("node").asText() + " - " + resource.get("status").asText()); } } ``` -------------------------------- ### Comprehensive Error Handling Example Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/errorhandling.md Combine checks for HTTP status, API errors, and general exceptions for robust error management. This function creates a VM and reports success or specific errors. ```java public void createVm(String nodeName, int vmid, String name) { try { var result = client.getNodes().get(nodeName).getQemu().createVm(vmid, name, 512, 1); if (result.isSuccessStatusCode()) { if (!result.responseInError()) { System.out.println("VM created successfully"); } else { System.err.println("API Error: " + result.getError()); } } else { System.err.println("HTTP Error " + result.getStatusCode() + ": " + result.getReasonPhrase()); } } catch (Exception e) { System.err.println("Unexpected error: " + e.getMessage()); e.printStackTrace(); } } ``` -------------------------------- ### Get Virtual Machine Configuration Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/examples.md Fetches and displays the configuration details for a specific virtual machine, identified by its VMID. Includes name, memory, CPU cores, and boot order. ```java // Get VM configuration var config = client.getNodes().get("pve1").getQemu().get(100) .getConfig().vmConfig().getData(); System.out.println("VM Name: " + config.get("name").asText()); System.out.println("Memory: " + config.get("memory").asInt() + " MB"); System.out.println("CPU Cores: " + config.get("cores").asInt()); System.out.println("Boot Order: " + config.get("boot").asText()); ``` -------------------------------- ### Proxmox VE Client Setup with Error Handling Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/examples.md Configures the Proxmox VE client, including disabling certificate validation for development and setting a timeout. Supports authentication via API token or username/password login. ```java public static PveClient createClient() { var client = new PveClient("pve.local", 8006); client.setValidateCertificate(false); // For development client.setTimeout(120000); // 2 minutes try { // Use API token or login String token = System.getenv("PVE_TOKEN"); if (token != null && !token.isEmpty()) { client.setApiToken(token); } else { boolean success = client.login("root@pam", "password"); if (!success) { throw new Exception("Authentication failed"); } } return client; } catch (Exception ex) { System.out.println("Failed to create client: " + ex.getMessage()); throw new RuntimeException(ex); } } ``` -------------------------------- ### Cloud/Automation Proxmox VE API Setup Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/authentication.md Configure the Proxmox VE Java client for automated deployments using an API token and verifying the connection before proceeding. It retrieves host and token from environment variables. ```java // Automated deployment script var client = new PveClient(System.getenv("PROXMOX_HOST"), 8006); client.setValidateCertificate(true); // Use API token for automation client.setApiToken(System.getenv("PROXMOX_API_TOKEN")); // Verify connection before proceeding if (!testAuthentication(client)) { System.exit(1); } ``` -------------------------------- ### Process Data with Java 8+ Streams Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/advanced.md Leverage Java 8+ streams for efficient data processing. Examples include filtering online nodes and finding specific VMs. ```java var nodes = client.getNodes().index().getData(); // Filter online nodes for (JsonNode node : nodes) { if ("online".equals(node.get("status").asText())) { System.out.println("Online node: " + node.get("node").asText()); } } // Find specific VM for (JsonNode vm : vms) { if ("web-server".equals(vm.get("name").asText())) { // Found the VM break; // or process the vm } } ``` -------------------------------- ### Perform Batch VM Operations in Java Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/examples.md Executes a specified operation (start, stop, restart) on multiple virtual machines. It first discovers the VM resources and then applies the operation, printing the success or failure status for each VM. ```java public static void batchVmOperation(PveClient client, int[] vmIds, String operation) { var resources = client.getCluster().getResources().resources().getData(); for (int vmId : vmIds) { // Find VM location JsonNode vmResource = null; for (JsonNode resource : resources) { if ("qemu".equals(resource.get("type").asText()) && resource.get("vmid").asInt() == vmId) { vmResource = resource; break; } } if (vmResource != null) { String node = vmResource.get("node").asText(); var vm = client.getNodes().get(node).getQemu().get(vmId); Result result = switch (operation.toLowerCase()) { case "start" -> vm.getStatus().start(); case "stop" -> vm.getStatus().stop(); case "restart" -> vm.getStatus().reboot(); default -> throw new IllegalArgumentException("Unknown operation: " + operation); }; boolean success = result.isSuccessStatusCode(); System.out.printf("VM %d %s: %s%n", vmId, operation, success ? "Success" : "Failed"); } } } ``` -------------------------------- ### Enterprise Proxmox VE API Setup with Proxy Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/authentication.md Configure the Proxmox VE Java client for a corporate environment, including setting up an HTTP proxy, validating certificates, and using an API token from environment variables. ```java // Corporate environment with proxy var proxy = new Proxy( Proxy.Type.HTTP, new InetSocketAddress("proxy.company.com", 8080) ); var client = new PveClient("pve.company.com", 8006); client.setProxy(proxy); client.setValidateCertificate(true); client.setTimeout(300000); // 5 minutes client.setApiToken(System.getenv("PROXMOX_API_TOKEN")); ``` -------------------------------- ### Configure Multiple Network Interfaces with Different Settings Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/common-issues.md Define multiple network interfaces with varying models, bridges, VLAN tags, and other options. This allows for complex network setups within a single VM. ```java // Multiple networks with different settings var networks = Map.of( 0, "model=virtio,bridge=vmbr0,firewall=1", 1, "model=e1000,bridge=vmbr1,rate=100", 2, "model=virtio,bridge=vmbr0,tag=200,queues=4" ); ``` -------------------------------- ### Retry Policies in Java Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/api.md Implement retry logic with exponential backoff for resilient API calls. This example shows a utility method to retry an operation up to a specified number of times. ```java // Retry logic for resilient API calls public Result retryOperation(Supplier operation, int maxRetries) { int retries = 0; while (retries < maxRetries) { var result = operation.get(); if (result.isSuccessStatusCode()) { return result; } retries++; if (retries < maxRetries) { try { Thread.sleep(1000 * (long)Math.pow(2, retries)); // Exponential backoff } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } } } return null; } // Usage var result = retryOperation( () -> client.getNodes().get("pve1").getStatus().status(), 3 ); ``` -------------------------------- ### Get VM Performance Metrics in Java Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/examples.md Retrieves and displays detailed performance metrics for a specific virtual machine, including CPU usage, memory consumption, disk I/O, network traffic, and uptime. Requires the Proxmox client, node name, and VM ID. ```java public static void getVmPerformance(PveClient client, String node, int vmId) { var data = client.getNodes().get(node).getQemu().get(vmId) .getStatus().current().getData(); System.out.println("VM " + vmId + " Performance:"); System.out.println(" Status: " + data.get("status").asText()); System.out.printf(" CPU Usage: %.2f%%%n", data.get("cpu").asDouble() * 100); System.out.printf(" Memory: %.2f GB / %.2f GB (%.1f%%)%n", data.get("mem").asLong() / (1024.0 * 1024 * 1024), data.get("maxmem").asLong() / (1024.0 * 1024 * 1024), (data.get("mem").asDouble() / data.get("maxmem").asDouble()) * 100); System.out.printf(" Disk Read: %.2f MB%n", data.get("diskread").asLong() / (1024.0 * 1024)); System.out.printf(" Disk Write: %.2f MB%n", data.get("diskwrite").asLong() / (1024.0 * 1024)); System.out.printf(" Network In: %.2f MB%n", data.get("netin").asLong() / (1024.0 * 1024)); System.out.printf(" Network Out: %.2f MB%n", data.get("netout").asLong() / (1024.0 * 1024)); System.out.println(" Uptime: " + java.time.Duration.ofSeconds(data.get("uptime").asInt())); } ``` -------------------------------- ### Control VM Status Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/api.md Get the current status of a Proxmox Virtual Machine and perform actions like starting, stopping, or restarting it. This is essential for managing VM lifecycle. ```java var vm = client.getNodes().get("pve1").getQemu().get(100); // Get current status var statusData = vm.getStatus().current().getData(); System.out.println("Current status: " + statusData.get("status").asText()); System.out.println("CPU usage: " + String.format("%.2f%%", statusData.get("cpu").asDouble() * 100)); System.out.println("Memory usage: " + String.format("%.2f%%", (statusData.get("mem").asDouble() / statusData.get("maxmem").asDouble()) * 100)); // Start VM if ("stopped".equals(statusData.get("status").asText())) { vm.getStatus().start(); System.out.println("VM started successfully!"); } // Stop VM vm.getStatus().stop(); System.out.println("VM stopped successfully!"); // Restart VM vm.getStatus().reboot(); System.out.println("VM restarted successfully!"); ``` -------------------------------- ### Avoid Disabling SSL Validation (Java) Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/authentication.md Example of what NOT to do: disabling SSL validation is insecure and should only be used for development purposes. ```java // Don't disable SSL validation in production client.setValidateCertificate(false); // Only for development! ``` -------------------------------- ### Create and Monitor VM Task Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/api.md Demonstrates creating a virtual machine and monitoring its task progress. It shows how to obtain a task ID, poll for status updates, and determine completion. ```java var createResult = client.getNodes().get("pve1").getQemu().createVm( Map.of( "vmid", 999, "name", "test-vm", "memory", 2048 ) ); if (createResult.isSuccessStatusCode()) { String taskId = createResult.getData().asText(); System.out.println("Task started: " + taskId); // Monitor task progress while (true) { var taskStatus = client.getNodes().get("pve1") .getTasks().get(taskId).getStatus().readTaskStatus(); if (taskStatus.isSuccessStatusCode()) { var status = taskStatus.getData().get("status").asText(); if ("stopped".equals(status)) { var exitStatus = taskStatus.getData().get("exitstatus").asText(); System.out.println("Task completed with status: " + exitStatus); break; } else if ("running".equals(status)) { System.out.println("Task still running..."); Thread.sleep(2000); } } } } ``` -------------------------------- ### Basic Proxmox VE API Client Usage Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/README.md Demonstrates creating a client instance, logging in, retrieving cluster status, and accessing VM configuration. Ensure you replace placeholder credentials and host information. ```java import it.corsinvest.proxmoxve.*; // Create client and authenticate var client = new PveClient("your-proxmox-host.com", 8006); if (client.login("root@pam", "your-password")) { // Get cluster status var status = client.getCluster().getStatus().getStatus().getData(); System.out.println("Cluster: " + status.get(0).get("name").asText()); // Manage VMs var vm = client.getNodes().get("pve1") .getQemu().get(100).getConfig().vmConfig() .getData(); System.out.println("VM: " + vm.get("name").asText()); } ``` -------------------------------- ### Complete VM Workflow with PVE API Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/apistructure.md This Java snippet demonstrates a full workflow: logging into PVE, retrieving a VM's configuration, creating a snapshot, and waiting for the snapshot task to finish. Ensure you have the PVE client initialized and authenticated before executing. ```java var client = new PveClient("pve.example.com", 8006); client.login("root", "password", "pam"); // Navigate to specific VM var nodeName = "pve1"; int vmid = 100; // Get VM config var config = client.getNodes() .get(nodeName) .getQemu() .get(vmid) .getConfig() .vmConfig() .getData(); System.out.println("VM Name: " + config.get("name").asText()); // Create snapshot var upid = client.getNodes() .get(nodeName) .getQemu() .get(vmid) .getSnapshot() .snapshot("backup-now") .getData() .asText(); client.waitForTaskToFinish(nodeName, upid); System.out.println("Snapshot created successfully"); ``` -------------------------------- ### Get Proxmox VE Cluster Status Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/examples.md Fetches and displays the current status of the Proxmox VE cluster, iterating through different resource types and their states. ```java // Get cluster status var status = client.getCluster().getStatus().getStatus().getData(); System.out.println("Cluster Status:"); for (JsonNode item : status) { System.out.printf(" %s: %s - %s%n", item.get("type").asText(), item.get("name").asText(), item.get("status").asText()); } ``` -------------------------------- ### Get Task UPID Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/tasks.md Initiates an operation and retrieves its unique task UPID for further tracking. This is the first step in managing long-running operations. ```java var result = client.getNodes().get("pve1") .getQemu().get(100).getStatus().start(); String upid = result.getData().asText(); System.out.println("Task UPID: " + upid); ``` -------------------------------- ### Access Result Properties and Methods Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/results.md Shows how to extract response data, check for errors, and get HTTP status information from a Result object. ```java // Get response data (JsonNode with "data", "errors", etc.) JsonNode response = result.getResponse(); // Access the data array/object JsonNode data = response.get("data"); // Check for errors boolean hasError = result.responseInError(); String errorMessage = result.getError(); // HTTP status information int statusCode = result.getStatusCode(); String reasonPhrase = result.getReasonPhrase(); boolean isSuccess = result.isSuccessStatusCode(); ``` -------------------------------- ### Configure VM IP Settings with Java Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/common-issues.md Demonstrates various ways to configure IP settings for a VM, including DHCP, static IP, multiple interfaces, and IPv6. ```java var ipconfig = Map.of( 0, "ip=dhcp" ); ``` ```java var ipconfig = Map.of( 0, "ip=192.168.1.100/24,gw=192.168.1.1" ); ``` ```java var ipconfig = Map.of( 0, "ip=192.168.1.100/24,gw=192.168.1.1", // Management 1, "ip=10.0.0.100/24", // Internal network 2, "ip=dhcp" // External network via DHCP ); ``` ```java var ipconfig = Map.of( 0, "ip=192.168.1.100/24,gw=192.168.1.1,ip6=auto" ); ``` -------------------------------- ### List All and Running Virtual Machines Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/examples.md Retrieves a list of all resources and iterates through them to identify and display information about virtual machines (QEMU). It also filters and counts the running VMs. ```java // Get all VMs in cluster var resources = client.getCluster().getResources().resources().getData(); for (JsonNode resource : resources) { if ("qemu".equals(resource.get("type").asText())) { System.out.printf("VM %d: %s on %s - %s%n", resource.get("vmid").asInt(), resource.get("name").asText(), resource.get("node").asText(), resource.get("status").asText()); } } // Filter running VMs var runningVms = new ArrayList(); for (JsonNode resource : resources) { if ("qemu".equals(resource.get("type").asText()) && "running".equals(resource.get("status").asText())) { runningVms.add(resource); } } System.out.println("Running VMs: " + runningVms.size()); ``` -------------------------------- ### Manage Virtual Machines (Qemu) Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/apistructure.md Perform operations on virtual machines, including listing all VMs on a node, retrieving their configuration, and checking their current status. ```java // List VMs on a node client.getNodes().get("pve1").getQemu().vmlist(); // Get VM configuration client.getNodes().get("pve1").getQemu().get(100).getConfig().vmConfig(); // VM status client.getNodes().get("pve1").getQemu().get(100).getStatus().current(); ``` -------------------------------- ### Configure VM Networks and Disks with Indexed Parameters Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/common-issues.md Use Map.of() to define network and disk configurations for a VM. The keys represent device indices (e.g., net0, scsi0), and values are configuration strings. This is useful for setting up multiple network interfaces or disk devices simultaneously. ```java import it.corsinvest.proxmoxve.api.*; var client = new PveClient("pve.example.com", 8006); client.login("root@pam", "password"); // Configure network interfaces var networks = Map.of( 0, "model=virtio,bridge=vmbr0,firewall=1", 1, "model=e1000,bridge=vmbr1" ); // Configure disks var disks = Map.of( 0, "local-lvm:32,cache=writethrough", 1, "local-lvm:64,iothread=1" ); client.getNodes().get("pve1").getQemu().get(100).getConfig().updateVm( networks, // netN disks // scsiN ); ``` -------------------------------- ### List and Get Node Status Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/apistructure.md Operations for listing all available nodes in the cluster and retrieving the status of a specific node. Node-specific tasks can also be accessed. ```java // List all nodes client.getNodes().index(); // Get node status client.getNodes().get("pve1").getStatus().status(); // Node tasks client.getNodes().get("pve1").getTasks().nodeTasks(); ``` -------------------------------- ### Get Cluster Status and Resources Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/apistructure.md Retrieve the overall status of the Proxmox VE cluster and its aggregated resources. Access control user indexing is also shown. ```java // Get cluster status client.getCluster().getStatus().getStatus(); // Get cluster resources client.getCluster().getResources().resources(); // Access control client.getAccess().getUsers().index(); ``` -------------------------------- ### Check VM Configuration with Java Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/common-issues.md Retrieves and prints the configuration data for a specific VM. Useful for verifying settings or diagnosing startup issues. ```java var config = client.getNodes().get("pve1").getQemu().get(100).getConfig().vmConfig().getData(); // Verify configuration is valid System.out.println(config); ``` -------------------------------- ### Manage LXC Container Operations Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/api.md Interact with Linux Containers (LXC) on Proxmox VE, including retrieving configuration, checking status, starting, and creating snapshots. This is for container-specific management. ```java // Access LXC container var container = client.getNodes().get("pve1").getLxc().get(101); // Get container configuration var ctData = container.getConfig().vmConfig().getData(); System.out.println("Container: " + ctData.get("hostname").asText()); System.out.println("OS Template: " + ctData.get("ostemplate").asText()); System.out.println("Memory: " + ctData.get("memory").asInt() + " MB"); // Container status operations var status = container.getStatus().current().getData(); System.out.println("Status: " + status.get("status").asText()); // Start container if ("stopped".equals(status.get("status").asText())) { container.getStatus().start(); System.out.println("Container started!"); } // Create container snapshot container.getSnapshot().snapshot("backup-snapshot"); System.out.println("Container snapshot created!"); ``` -------------------------------- ### Create API Token via Command Line Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/authentication.md Manage API tokens using the `pveum user token` command. Supports creation, listing, and removal. ```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 ``` -------------------------------- ### Create VM Management Role (Bash) Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/authentication.md Define a 'VMManager' role with permissions for managing virtual machines, including configuration and power operations. ```bash # VM management pveum role add VMManager -privs "VM.Audit,VM.Config.Disk,VM.Config.Memory,VM.PowerMgmt,VM.Snapshot,VM.Clone" ``` -------------------------------- ### Access and Manage Storage Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/apistructure.md Demonstrates accessing specific storage by name and performing operations such as listing its content and retrieving its status. ```java // Access storage var storage = client.getNodes().get("pve1").getStorage().get("local"); // Storage operations storage.getContent().index(); // List content storage.getStatus().read_status(); // Get status ``` -------------------------------- ### Configure EFI Disk for UEFI Boot Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/common-issues.md Set up an EFI disk with specific parameters for UEFI boot. This is required for VMs that use UEFI firmware. ```java // EFI disk for UEFI boot String efidisk = "local-lvm:1,efitype=4m,pre-enrolled-keys=0"; client.getNodes().get("pve1").getQemu().get(100).getConfig().updateVm( "ovmf", // bios efidisk // efidisk0 ); ``` -------------------------------- ### Load Configuration from Properties File (Java) Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/authentication.md Load Proxmox VE connection details from a properties file, supporting both API token and username/password authentication. ```java import java.util.Properties; import java.io.FileInputStream; // Load from properties file var config = new Properties(); config.load(new FileInputStream("config.properties")); var client = new PveClient(config.getProperty("proxmox.host"), 8006); // Use API token if available var apiToken = config.getProperty("proxmox.apiToken"); if (apiToken != null && !apiToken.isEmpty()) { client.setApiToken(apiToken); } else { // Fallback to username/password var username = config.getProperty("proxmox.username"); var password = config.getProperty("proxmox.password"); client.login(username, password); } ``` -------------------------------- ### Get Specific Storage Details Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/api.md Retrieves detailed information about a specific storage volume, including total, used, and available space in GB. This helps in managing storage consumption. ```java var storageData = client.getNodes().get("pve1").getStorage().get("local").status().getData(); System.out.println("Storage: " + storageData.get("storage").asText()); System.out.println("Type: " + storageData.get("type").asText()); System.out.printf("Total: %.2f GB%n", storageData.get("total").asLong() / (1024.0 * 1024.0 * 1024.0)); System.out.printf("Used: %.2f GB%n", storageData.get("used").asLong() / (1024.0 * 1024.0 * 1024.0)); System.out.printf("Available: %.2f GB%n", storageData.get("avail").asLong() / (1024.0 * 1024.0 * 1024.0)); ``` -------------------------------- ### Configure SCSI Disk with Advanced Options Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/common-issues.md Set up a SCSI disk with specific cache mode, IO thread enabled, and discard (TRIM) support. These options can improve performance and disk management. ```java // SCSI disk with options var disks = Map.of( 0, "local-lvm:32,cache=writethrough,iothread=1,discard=on" ); ``` -------------------------------- ### Get Storage Information for a Node Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/examples.md Retrieves and displays the storage details for a specific node, including the storage name, type, percentage used, total capacity, and available space. ```java // Get storage for a specific node var storages = client.getNodes().get("pve1").getStorage().index().getData(); System.out.println("Available Storage:"); for (JsonNode storage : storages) { double usedPercent = (storage.get("used").asDouble() / storage.get("total").asDouble()) * 100; System.out.printf(" %s (%s): %.1f%% used%n", storage.get("storage").asText(), storage.get("type").asText(), usedPercent); System.out.printf(" Total: %.2f GB%n", storage.get("total").asLong() / (1024.0 * 1024 * 1024)); System.out.printf(" Available: %.2f GB%n", storage.get("avail").asLong() / (1024.0 * 1024 * 1024)); } ``` -------------------------------- ### Configure Network Interface with VLAN and Firewall Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/common-issues.md Set up a VirtIO network interface with a specific VLAN tag and enable the firewall. This is useful for network segmentation and security. ```java // Network with VLAN and firewall var networks = Map.of( 0, "model=virtio,bridge=vmbr0,tag=100,firewall=1" ); ``` -------------------------------- ### List Storage Information with Java Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/common-issues.md Fetches and displays information about available storage pools, including their type and available space. Helps in troubleshooting disk-related issues. ```java var storages = client.getNodes().get("pve1").getStorage().index(); for (var storage : storages.getData()) { System.out.println("Storage: " + storage.get("storage").asText()); System.out.println(" Type: " + storage.get("type").asText()); System.out.println(" Available: " + storage.get("avail").asText()); } ``` -------------------------------- ### Get Cluster Status and Resources Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/api.md Retrieves and prints the status of the Proxmox cluster, its resources (nodes and VMs), and available nodes. This is useful for monitoring the overall health and resource utilization of the cluster. ```java var clusterStatus = client.getCluster().getStatus().getStatus().getData(); System.out.println("Cluster Status:"); for (JsonNode item : clusterStatus) { System.out.println(" " + item.get("type").asText() + ": " + item.get("name").asText() + " - " + item.get("status").asText()); } // Get cluster resources var resources = client.getCluster().getResources().resources().getData(); System.out.println("Cluster Resources:"); for (JsonNode resource : resources) { if ("node".equals(resource.get("type").asText())) { System.out.printf(" Node: %s - CPU: %.2f%%, Memory: %.2f%%%n", resource.get("node").asText(), resource.get("cpu").asDouble() * 100, (resource.get("mem").asDouble() / resource.get("maxmem").asDouble()) * 100); } else if ("qemu".equals(resource.get("type").asText())) { System.out.printf(" VM: %d (%s) on %s - %s%n", resource.get("vmid").asInt(), resource.get("name").asText(), resource.get("node").asText(), resource.get("status").asText()); } } // Get node information var nodes = client.getNodes().index().getData(); System.out.println("Available Nodes:"); for (JsonNode node : nodes) { System.out.println(" " + node.get("node").asText() + ": " + node.get("status").asText() + " - Uptime: " + node.get("uptime").asInt() + "s"); } ``` -------------------------------- ### Secure Configuration with Environment Variables Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/advanced.md Use environment variables for secure configuration of host and API tokens in production deployments. Includes verification of connection. ```java // Read credentials from environment var host = System.getenv("PVE_HOST"); var apiToken = System.getenv("PVE_API_TOKEN"); if (host == null || apiToken == null) { throw new IllegalStateException("Missing required environment variables"); } var client = new PveClient(host, 8006); client.setApiToken(apiToken); // Verify connection var result = client.getVersion().version(); if (!result.isSuccessStatusCode()) { throw new RuntimeException("Failed to connect to Proxmox VE"); } ``` -------------------------------- ### Create User for API Access (Bash) Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/authentication.md Create a dedicated user for API access with a secure password and a descriptive comment. ```bash # Create user for API access pveum user add api-user@pve --password "secure-password" --comment "API automation user" ``` -------------------------------- ### Access Specific Resources by ID or Name Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/apistructure.md Code snippets showing how to access specific resources like a VM by its ID, a storage by its name, or a network interface by its name. ```java // Access specific VM var vm = client.getNodes().get("pve1").getQemu().get(100); // Access specific storage var storage = client.getNodes().get("pve1").getStorage().get("local"); // Access specific network var network = client.getNodes().get("pve1").getNetwork().get("vmbr0"); ``` -------------------------------- ### Initialize Result Object Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/results.md Demonstrates how to obtain a Result object from an API call. ```java var result = client.getNodes().index(); ``` -------------------------------- ### Proxmox VE VM Power Management Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/examples.md Controls the power state of a virtual machine, including starting, stopping, and restarting. Also retrieves and displays the current operational status, CPU usage, and memory utilization. ```java var vm = client.getNodes().get("pve1").getQemu().get(100); // Start VM vm.getStatus().start(); System.out.println("VM started successfully"); // Stop VM vm.getStatus().stop(); System.out.println("VM stopped successfully"); // Restart VM vm.getStatus().reboot(); System.out.println("VM restarted successfully"); // Get current status var data = vm.getStatus().current().getData(); System.out.println("VM Status: " + data.get("status").asText()); System.out.printf("CPU Usage: %.2f%%%n", data.get("cpu").asDouble() * 100); System.out.printf("Memory: %.2f%%%n", (data.get("mem").asDouble() / data.get("maxmem").asDouble()) * 100); ``` -------------------------------- ### Discover All VMs in Cluster Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/README.md Fetches all resources from the Proxmox VE cluster and filters for QEMU virtual machines, then prints their ID, name, node, and status. This is useful for inventory and monitoring. ```java // Get all VMs in cluster var resources = client.getCluster().getResources().resources().getData(); for (var resource : resources) { if (resource.get("type").asText().equals("qemu")) { var node = resource.get("node").asText(); var vmid = resource.get("vmid").asInt(); var name = resource.get("name").asText(); var status = resource.get("status").asText(); System.out.println("VM " + vmid + " (" + name + ") on " + node + " - " + status); } } ``` -------------------------------- ### Proxy Configuration in Java Source: https://github.com/corsinvest/cv4pve-api-java/blob/master/docs/api.md Configure corporate proxy settings for the PveClient, including setting the proxy host, port, and authentication credentials if required. ```java // Corporate proxy setup var proxy = new Proxy( Proxy.Type.HTTP, new InetSocketAddress("proxy.company.com", 8080) ); // Proxy authentication if required Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { if (getRequestorType() == RequestorType.PROXY) { return new PasswordAuthentication("proxyuser", "proxypass".toCharArray()); } return null; } }); var client = new PveClient("pve.company.com", 8006); client.setProxy(proxy); ```