├── .npmignore ├── .vscode └── settings.json ├── .gitignore ├── .prettierrc ├── .prettierignore ├── 3rd-party-licenses.md ├── .editorconfig ├── tsconfig.json ├── .github ├── workflows │ ├── build.yml │ ├── code-quality.yml │ └── npm-publish.yml └── ISSUE_TEMPLATE │ └── bug_report.yml ├── package.json ├── test.js ├── docs ├── apistructure.md ├── results.md ├── authentication.md ├── common-issues.md ├── errorhandling.md ├── tasks.md ├── advanced.md └── examples.md ├── README.md └── LICENSE /.npmignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | .project 3 | .settings/ 4 | .classpath 5 | node_modules/ -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "java.configuration.updateBuildConfiguration": "automatic" 3 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | .project 3 | .settings/ 4 | .classpath 5 | node_modules/ 6 | dist/ 7 | .claude -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "semi": true, 3 | "singleQuote": false, 4 | "tabWidth": 2, 5 | "trailingComma": "es5", 6 | "printWidth": 100, 7 | "arrowParens": "always", 8 | "endOfLine": "lf" 9 | } 10 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | # Dependencies 2 | node_modules/ 3 | 4 | # Build outputs 5 | dist/ 6 | *.d.ts 7 | 8 | # Logs 9 | *.log 10 | npm-debug.log* 11 | 12 | # OS files 13 | .DS_Store 14 | Thumbs.db 15 | 16 | # IDE 17 | .vscode/ 18 | .idea/ 19 | -------------------------------------------------------------------------------- /3rd-party-licenses.md: -------------------------------------------------------------------------------- 1 | # License overview of included 3rd party libraries 2 | 3 | The project is licensed under the terms of the [LICENSE](LICENSE) 4 | 5 | However, includes several third-party Open-Source libraries, which are licensed under their own respective Open-Source licenses. 6 | 7 | ## Libraries directly included 8 | 9 | [debug](https://github.com/debug-js/debug) 10 | License: MIT 11 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig is awesome: https://EditorConfig.org 2 | 3 | # top-most EditorConfig file 4 | root = true 5 | 6 | # All files 7 | [*] 8 | charset = utf-8 9 | end_of_line = lf 10 | insert_final_newline = true 11 | trim_trailing_whitespace = true 12 | 13 | # JavaScript files 14 | [*.js] 15 | indent_style = space 16 | indent_size = 2 17 | 18 | # JSON files 19 | [*.json] 20 | indent_style = space 21 | indent_size = 2 22 | 23 | # Markdown files 24 | [*.md] 25 | indent_style = space 26 | indent_size = 2 27 | trim_trailing_whitespace = false 28 | 29 | # YAML files 30 | [*.{yml,yaml}] 31 | indent_style = space 32 | indent_size = 2 33 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | // Change this to match your project 3 | "include": ["src/*"], 4 | "compilerOptions": { 5 | // Tells TypeScript to read JS files, as 6 | // normally they are ignored as source files 7 | "allowJs": true, 8 | // Generate d.ts files 9 | "declaration": true, 10 | // This compiler run should 11 | // only output d.ts files 12 | "emitDeclarationOnly": true, 13 | // Types should go into this directory. 14 | // Removing this would place the .d.ts files 15 | // next to the .js files 16 | "outDir": "dist", 17 | // go to js file when using IDE functions like 18 | // "Go to Definition" in VSCode 19 | "declarationMap": true, 20 | "composite": true, 21 | "target": "ES2020" 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | push: 5 | branches: [ "main", "dev" ] 6 | pull_request: 7 | branches: [ "main", "dev" ] 8 | workflow_dispatch: 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | strategy: 14 | matrix: 15 | node-version: [18.x, 20.x, 22.x] 16 | 17 | steps: 18 | - uses: actions/checkout@v4 19 | 20 | - name: Use Node.js ${{ matrix.node-version }} 21 | uses: actions/setup-node@v4 22 | with: 23 | node-version: ${{ matrix.node-version }} 24 | cache: 'npm' 25 | 26 | - name: Install dependencies 27 | run: npm ci 28 | 29 | - name: Build the project 30 | run: npm run prepare 31 | 32 | - name: Run type checking 33 | run: npx tsc --noEmit -------------------------------------------------------------------------------- /.github/workflows/code-quality.yml: -------------------------------------------------------------------------------- 1 | name: Code Quality 2 | 3 | on: 4 | push: 5 | branches: [ "main", "dev" ] 6 | pull_request: 7 | branches: [ "main", "dev" ] 8 | workflow_dispatch: 9 | 10 | jobs: 11 | code-quality: 12 | runs-on: ubuntu-latest 13 | strategy: 14 | matrix: 15 | node-version: [18.x, 20.x, 22.x] 16 | 17 | steps: 18 | - uses: actions/checkout@v4 19 | 20 | - name: Use Node.js ${{ matrix.node-version }} 21 | uses: actions/setup-node@v4 22 | with: 23 | node-version: ${{ matrix.node-version }} 24 | cache: 'npm' 25 | 26 | - name: Install dependencies 27 | run: npm ci 28 | 29 | - name: Check code formatting 30 | run: npm run format:check 31 | 32 | - name: Run type checking 33 | run: npx tsc --noEmit 34 | 35 | - name: Run security audit 36 | run: npm audit --audit-level moderate -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@corsinvest/cv4pve-api-javascript", 3 | "version": "9.1.0", 4 | "description": "Proxmox VE Client API JavaScript", 5 | "main": "./src/index.js", 6 | "types": "./dist/src/index.d.ts", 7 | "keywords": [ 8 | "Proxmox VE", 9 | "Api", 10 | "Proxmox", 11 | "Corsinvest", 12 | "pve" 13 | ], 14 | "scripts": { 15 | "prepare": "npx tsc", 16 | "test": "echo \"Error: no test specified\" && exit 1", 17 | "format": "prettier --write \"src/**/*.js\"", 18 | "format:check": "prettier --check \"src/**/*.js\"" 19 | }, 20 | "repository": { 21 | "type": "git", 22 | "url": "git+https://github.com/Corsinvest/cv4pve-api-javascript.git" 23 | }, 24 | "author": "Daniele Corsini ", 25 | "license": "GPLv3", 26 | "bugs": { 27 | "url": "https://github.com/Corsinvest/cv4pve-api-javascript/issues" 28 | }, 29 | "files": [ 30 | "src", 31 | "dist", 32 | "LICENSE", 33 | "README.md" 34 | ], 35 | "homepage": "https://github.com/Corsinvest/cv4pve-api-javascript#readme", 36 | "devDependencies": { 37 | "prettier": "^3.0.0", 38 | "typescript": "^5.3.3" 39 | }, 40 | "dependencies": { 41 | "debug": "^4.3.5" 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | const pve = require('./src'); 2 | 3 | console.log(pve); 4 | 5 | async function foo() { 6 | const client = new pve.PveClient('192.168.0.2', 8006); 7 | //client.logEnabled = true; 8 | //client.apiToken = ''; 9 | 10 | const login = await client.login('root', process.env.PVE_PASSWORD, process.env.PVE_REALM, process.env.PVE_OTP); 11 | if (login) { 12 | console.log((await client.get('/version')).response); 13 | console.log((await client.version.version()).response); 14 | 15 | console.log((await client.get('/nodes')).response); 16 | console.log((await client.nodes.index()).response); 17 | 18 | let result = await client.nodes.get("cc01").qemu.get(1006).agent.exec.exec(["powershell", "-command", "echo", "test"]); 19 | console.log(result.response); 20 | 21 | // console.log((await client.get('/nodes/cv-pve01/qemu')).response); 22 | // console.log((await client.nodes.get('cv-pve01').qemu.vmlist(0)).response); 23 | 24 | // console.log((await client.get('/nodes/cv-pve01/qemu/103/config/')).response); 25 | // console.log((await client.nodes.get('cv-pve01').qemu.get(103).config.vmConfig()).response); 26 | 27 | // console.log((await client.get('/nodes/cv-pve01/qemu/103/snapshot/')).response); 28 | // console.log((await client.nodes.get('cv-pve01').qemu.get(103).snapshot.snapshotList()).response); 29 | } 30 | } 31 | 32 | foo(); -------------------------------------------------------------------------------- /.github/workflows/npm-publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish 2 | 3 | on: 4 | push: 5 | tags: 6 | - 'v*' 7 | 8 | env: 9 | NODE_VERSION: '20.x' 10 | 11 | jobs: 12 | publish: 13 | runs-on: ubuntu-latest 14 | 15 | permissions: 16 | contents: write 17 | id-token: write 18 | 19 | steps: 20 | - name: Checkout 21 | uses: actions/checkout@v4 22 | with: 23 | fetch-depth: 0 24 | 25 | - name: Setup Node.js 26 | uses: actions/setup-node@v4 27 | with: 28 | node-version: ${{ env.NODE_VERSION }} 29 | registry-url: 'https://registry.npmjs.org/' 30 | cache: 'npm' 31 | scope: '@corsinvest' 32 | 33 | - name: Update npm to latest 34 | run: npm install -g npm@latest 35 | 36 | - name: Install dependencies 37 | run: npm ci 38 | 39 | - name: Validate version 40 | id: version 41 | run: | 42 | # Extract version from package.json 43 | PROJECT_VERSION=$(node -p "require('./package.json').version") 44 | echo "Project version: $PROJECT_VERSION" 45 | # Extract version from tag 46 | TAG_VERSION=${GITHUB_REF#refs/tags/v} 47 | echo "Tag version: $TAG_VERSION" 48 | # Validate they match 49 | if [ "$PROJECT_VERSION" != "$TAG_VERSION" ]; then 50 | echo "❌ ERROR: Version mismatch!" 51 | echo "   package.json: $PROJECT_VERSION" 52 | echo "   Git tag: v$TAG_VERSION" 53 | exit 1 54 | fi 55 | echo "✅ Version validated: $PROJECT_VERSION" 56 | echo "version=$PROJECT_VERSION" >> $GITHUB_OUTPUT 57 | 58 | - name: Build package 59 | run: npm run prepare 60 | 61 | - name: Create release 62 | uses: softprops/action-gh-release@v2 63 | with: 64 | name: Release v${{ steps.version.outputs.version }} 65 | draft: false 66 | prerelease: false 67 | generate_release_notes: true 68 | 69 | - name: Publish to npm 70 | run: npm publish --access public --provenance 71 | env: 72 | NODE_AUTH_TOKEN: '' 73 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.yml: -------------------------------------------------------------------------------- 1 | name: Bug Report 2 | description: File a bug report 3 | labels: [needs investigation] 4 | body: 5 | - type: markdown 6 | attributes: 7 | value: | 8 | Thanks for taking the time to fill out this bug report. Note that this template is only for bug reports. 9 | - type: textarea 10 | id: what-happened 11 | attributes: 12 | label: What happened? 13 | description: Please describe the issue briefly. You can use log, screenshots, gifs or videos to further explain your problem. 14 | placeholder: Describe your issue! 15 | validations: 16 | required: true 17 | - type: textarea 18 | id: expected-behavior 19 | attributes: 20 | label: Expected behavior 21 | description: Please provide a clear and concise description of what you expected to happen. 22 | placeholder: Describe the expected behavior! 23 | validations: 24 | required: true 25 | - type: textarea 26 | id: logs 27 | attributes: 28 | label: Relevant log output 29 | description: Please copy and paste any relevant log output. This will be automatically formatted into code, so no need for backticks. 30 | render: shell 31 | 32 | - type: input 33 | id: proxmox-ve-version 34 | attributes: 35 | label: Proxmox VE Version 36 | description: Proxmox VE Version 37 | placeholder: 5.X.X 38 | validations: 39 | required: true 40 | 41 | - type: input 42 | id: bug-version 43 | attributes: 44 | label: Version (bug) 45 | description: With which version are you experiencing the issue? 46 | placeholder: 1.X.X 47 | validations: 48 | required: true 49 | - type: input 50 | id: working-version 51 | attributes: 52 | label: Version (working) 53 | description: Did it work on a previous version? If so, which version? 54 | placeholder: 1.X.X 55 | - type: dropdown 56 | id: os 57 | attributes: 58 | label: On what operating system are you experiencing the issue? 59 | description: You don't have to test it on every os. 60 | multiple: true 61 | options: 62 | - Windows 63 | - Mac OSX 64 | - Linux 65 | - Other 66 | validations: 67 | required: true 68 | 69 | - type: checkboxes 70 | id: pr 71 | attributes: 72 | label: Pull Request 73 | description: Are you interested in implementing a fix via a Pull Request? That would be the fastest way to resolve your issue. We appreciate every contribution! 74 | options: 75 | - label: I would like to do a Pull Request 76 | -------------------------------------------------------------------------------- /docs/apistructure.md: -------------------------------------------------------------------------------- 1 | # API Structure Guide 2 | 3 | Understanding the hierarchical structure of the Proxmox VE API and how it maps to the JavaScript client. 4 | 5 | ## Tree Structure 6 | 7 | The API follows the exact structure of the [Proxmox VE API](https://pve.proxmox.com/pve-docs/api-viewer/): 8 | 9 | ```javascript 10 | // API Path: /cluster/status 11 | await client.cluster.status.status(); 12 | 13 | // API Path: /nodes/{node}/qemu/{vmid}/config 14 | await client.nodes.get("pve1").qemu.get(100).config.vmConfig(); 15 | 16 | // API Path: /nodes/{node}/lxc/{vmid}/snapshot 17 | await client.nodes.get("pve1").lxc.get(101).snapshot.snapshot("snap-name"); 18 | 19 | // API Path: /nodes/{node}/storage/{storage} 20 | await client.nodes.get("pve1").storage.get("local").status(); 21 | ``` 22 | 23 | ## HTTP Method Mapping 24 | 25 | | HTTP Method | JavaScript Method | Purpose | Example | 26 | |-------------|------------------|---------|---------| 27 | | `GET` | `await resource.get()` | Retrieve information | `await vm.config.vmConfig()` | 28 | | `POST` | `await resource.create(parameters)` | Create resources | `await vm.snapshot.snapshot("snap-name", "description")` | 29 | | `PUT` | `await resource.set(parameters)` | Update resources | `await vm.config.updateVm({memory: 4096})` | 30 | | `DELETE` | `await resource.delete()` | Remove resources | `await vm.deleteVm()` | 31 | 32 | ## Common Endpoints 33 | 34 | ### **Cluster Level** 35 | ```javascript 36 | await client.cluster.status.status(); // GET /cluster/status 37 | await client.cluster.resources.resources(); // GET /cluster/resources 38 | await client.version.version(); // GET /version 39 | ``` 40 | 41 | ### **Node Level** 42 | ```javascript 43 | await client.nodes.index(); // GET /nodes 44 | await client.nodes.get("pve1").status.status(); // GET /nodes/pve1/status 45 | await client.nodes.get("pve1").storage.index(); // GET /nodes/pve1/storage 46 | ``` 47 | 48 | ### **VM Operations** 49 | ```javascript 50 | await client.nodes.get("pve1").qemu.get(100).config.vmConfig(); // GET config 51 | await client.nodes.get("pve1").qemu.get(100).status.current.vmStatus(); // GET status 52 | await client.nodes.get("pve1").qemu.get(100).status.start.vmStart(); // POST start 53 | await client.nodes.get("pve1").qemu.get(100).snapshot.snapshotList(); // GET snapshots 54 | ``` 55 | 56 | ### **Container Operations** 57 | ```javascript 58 | await client.nodes.get("pve1").lxc.get(101).config.vmConfig(); // GET config 59 | await client.nodes.get("pve1").lxc.get(101).status.current.vmStatus(); // GET status 60 | await client.nodes.get("pve1").lxc.get(101).status.start.vmStart(); // POST start 61 | ``` 62 | 63 | ## Parameters and Indexers 64 | 65 | ### **Numeric Indexers** 66 | ```javascript 67 | client.nodes.get("pve1").qemu.get(100) // VM ID 100 68 | client.nodes.get("pve1").lxc.get(101) // Container ID 101 69 | ``` 70 | 71 | ### **String Indexers** 72 | ```javascript 73 | client.nodes.get("pve1") // Node name 74 | client.nodes.get("pve1").storage.get("local") // Storage name 75 | client.nodes.get("pve1").qemu.get(100).snapshot.get("snap1") // Snapshot name 76 | ``` 77 | 78 | ### **Method Parameters** 79 | ```javascript 80 | // Parameters as objects 81 | await vm.config.updateVm({memory: 4096, cores: 2}); 82 | 83 | // Positional parameters 84 | await vm.snapshot.snapshot("backup", "Description here"); 85 | ``` 86 | -------------------------------------------------------------------------------- /docs/results.md: -------------------------------------------------------------------------------- 1 | # Result Handling Guide 2 | 3 | Understanding how to work with API responses and the Result class. 4 | 5 | ## Result Class 6 | 7 | Every API call returns a Result object: 8 | 9 | ```javascript 10 | { 11 | // Response data from Proxmox VE 12 | response: { 13 | data: {}, // The actual API response data 14 | /* for JSON responses, this contains the Proxmox VE response object */ 15 | }, 16 | 17 | // HTTP response information 18 | isSuccessStatusCode: true, // Whether the request was successful (statusCode === 200) 19 | statusCode: 200, // HTTP status code 20 | reasonPhrase: "", // HTTP status message 21 | 22 | // Request information 23 | requestResource: "", // The API endpoint called 24 | requestParameters: {}, // Parameters sent 25 | methodType: "", // HTTP method used 26 | responseType: "", // "json" or "png" 27 | 28 | // Utility properties 29 | responseInError: false // Whether there's an error in the response 30 | } 31 | ``` 32 | 33 | ## Checking Success 34 | 35 | ```javascript 36 | const result = await client.nodes.get("pve1").qemu.get(100).config.vmConfig(); 37 | 38 | if (result.isSuccessStatusCode) { 39 | // Success - process the data 40 | console.log(`VM Name: ${result.response.data.name}`); 41 | } 42 | ``` 43 | 44 | ## Accessing Response Data 45 | 46 | ### **Direct Access** 47 | ```javascript 48 | const result = await vm.config.vmConfig(); 49 | const data = result.response.data; 50 | console.log(`VM Name: ${data.name}`); 51 | console.log(`Memory: ${data.memory}`); 52 | console.log(`Cores: ${data.cores}`); 53 | ``` 54 | 55 | ### **Iterating Through Response** 56 | ```javascript 57 | const result = await vm.config.vmConfig(); 58 | if (result.isSuccessStatusCode) { 59 | const data = result.response.data; 60 | for (const [key, value] of Object.entries(data)) { 61 | console.log(`${key}: ${value}`); 62 | } 63 | } 64 | ``` 65 | 66 | ## Error Handling 67 | 68 | ### **Basic Error Checking** 69 | ```javascript 70 | const result = await vm.status.start.vmStart(); 71 | 72 | if (!result.isSuccessStatusCode) { 73 | console.log(`Failed to start VM: ${result.reasonPhrase}`); 74 | console.log(`HTTP Status: ${result.statusCode}`); 75 | } 76 | ``` 77 | 78 | ### **Detailed Error Information** 79 | ```javascript 80 | const result = await vm.config.updateVm({memory: 999999}); // Invalid value 81 | 82 | if (!result.isSuccessStatusCode) { 83 | console.log("Proxmox VE returned an error:"); 84 | console.log(result.reasonPhrase); 85 | 86 | // Check specific status codes 87 | switch (result.statusCode) { 88 | case 401: 89 | console.log("Authentication failed"); 90 | break; 91 | case 403: 92 | console.log("Permission denied"); 93 | break; 94 | case 400: 95 | console.log("Invalid request parameters"); 96 | break; 97 | case 500: 98 | console.log("Server error"); 99 | break; 100 | } 101 | } 102 | ``` 103 | 104 | ## Working with Different Response Types 105 | 106 | ### **List Responses** 107 | ```javascript 108 | const result = await client.cluster.resources.resources(); 109 | if (result.isSuccessStatusCode) { 110 | for (const resource of result.response.data) { 111 | console.log(`${resource.type}: ${resource.id}`); 112 | } 113 | } 114 | ``` 115 | 116 | ### **Task Responses** 117 | ```javascript 118 | // Operations that return task IDs 119 | const result = await vm.snapshot.snapshot("backup-snapshot"); 120 | if (result.isSuccessStatusCode) { 121 | const taskId = result.response.data; 122 | console.log(`Task started: ${taskId}`); 123 | 124 | // Monitor task progress... 125 | } 126 | ``` 127 | 128 | ### **Image Responses** 129 | ```javascript 130 | // Change response type for charts 131 | client.responseType = "png"; 132 | const chartResult = await client.nodes.get("pve1").rrd.rrd({ds: "cpu", timeframe: "day"}); 133 | 134 | if (chartResult.isSuccessStatusCode) { 135 | const base64Image = chartResult.response; // Base64 encoded image with data URI prefix 136 | console.log(``); 137 | } 138 | 139 | // Switch back to JSON 140 | client.responseType = "json"; 141 | ``` 142 | 143 | ## Best Practices 144 | 145 | ### **Always Check Success** 146 | ```javascript 147 | // Good practice 148 | const result = await vm.status.start.vmStart(); 149 | if (result.isSuccessStatusCode) { 150 | console.log("VM started successfully"); 151 | } else { 152 | console.log(`Failed to start VM: ${result.reasonPhrase}`); 153 | } 154 | 155 | // Don't ignore errors 156 | await vm.status.start.vmStart(); // Missing error handling 157 | ``` 158 | 159 | ### **Handle Null Values** 160 | ```javascript 161 | const result = await vm.config.vmConfig(); 162 | const data = result.response.data; 163 | 164 | // Safe access with optional chaining 165 | const vmName = data?.name || "Unnamed VM"; 166 | const description = data?.description || "No description"; 167 | 168 | console.log(`VM: ${vmName} - ${description}`); 169 | ``` 170 | 171 | ### **Error Handling with Try-Catch** 172 | ```javascript 173 | try { 174 | const result = await vm.status.start.vmStart(); 175 | if (result.isSuccessStatusCode) { 176 | console.log("VM started successfully"); 177 | } else { 178 | console.log(`API error: ${result.reasonPhrase}`); 179 | } 180 | } catch (error) { 181 | console.log(`Connection error: ${error.message}`); 182 | } 183 | ``` 184 | 185 | ## Response Error Detection 186 | 187 | ### **Check for Errors in Response** 188 | ```javascript 189 | const result = await vm.config.updateVm({memory: 2048}); 190 | 191 | // Check if response contains errors 192 | if (result.responseInError) { 193 | console.log("Response contains errors:"); 194 | console.log(result.response.errors); 195 | } 196 | ``` 197 | 198 | ## Logging Results 199 | 200 | ### **Debug Information** 201 | ```javascript 202 | // Enable logging to see full request/response details 203 | client.logEnabled = true; 204 | 205 | const result = await vm.config.vmConfig(); 206 | 207 | // The result object has a toString() method 208 | console.log(result.toString()); 209 | ``` 210 | -------------------------------------------------------------------------------- /docs/authentication.md: -------------------------------------------------------------------------------- 1 | # Authentication Guide 2 | 3 | This guide covers all authentication methods available for connecting to Proxmox VE. 4 | 5 | ## Authentication Methods 6 | 7 | ### **API Token (Recommended)** 8 | 9 | API tokens are the most secure method for automation and applications. 10 | 11 | ```javascript 12 | const { PveClient } = require("@corsinvest/cv4pve-api-javascript"); 13 | 14 | const client = new PveClient("pve.example.com"); 15 | 16 | // Set API token (no login() call needed) 17 | client.apiToken = "user@realm!tokenid=uuid"; 18 | 19 | // Ready to use 20 | const version = await client.version.version(); 21 | ``` 22 | 23 | **Format:** `USER@REALM!TOKENID=UUID` 24 | 25 | **Example:** `automation@pve!api-token=12345678-1234-1234-1234-123456789abc` 26 | 27 | ### **Username/Password** 28 | 29 | Traditional authentication with username and password. 30 | 31 | ```javascript 32 | const { PveClient } = require("@corsinvest/cv4pve-api-javascript"); 33 | 34 | const client = new PveClient("pve.example.com"); 35 | 36 | // Basic login (defaults to PAM realm) 37 | const success = await client.login("root", "password"); 38 | 39 | // Login with specific realm 40 | const success = await client.login("admin", "password", "pve"); 41 | 42 | // Login with PAM realm explicitly 43 | const success = await client.login("user", "password", "pam"); 44 | ``` 45 | 46 | ### **Two-Factor Authentication (2FA)** 47 | 48 | For accounts with Two-Factor Authentication enabled. 49 | 50 | ```javascript 51 | const { PveClient } = require("@corsinvest/cv4pve-api-javascript"); 52 | 53 | const client = new PveClient("pve.example.com"); 54 | 55 | // Login with TOTP/OTP code 56 | const success = await client.login("admin", "password", "pve", "123456"); 57 | 58 | // The fourth parameter is the 6-digit code from your authenticator app 59 | ``` 60 | 61 | --- 62 | 63 | ## Creating API Tokens 64 | 65 | ### **Via Proxmox VE Web Interface** 66 | 67 | 1. **Login** to Proxmox VE web interface 68 | 2. **Navigate** to Datacenter → Permissions → API Tokens 69 | 3. **Click** "Add" button 70 | 4. **Configure** token: 71 | - **User:** Select user (e.g., `root@pam`) 72 | - **Token ID:** Choose name (e.g., `api-automation`) 73 | - **Privilege Separation:** Uncheck for full user permissions 74 | - **Comment:** Optional description 75 | 5. **Click** "Add" and **copy the token** (you won't see it again!) 76 | 77 | ### **Via Command Line** 78 | 79 | ```bash 80 | # Create API token 81 | pveum user token add root@pam api-automation --privsep=0 82 | 83 | # List tokens 84 | pveum user token list root@pam 85 | 86 | # Remove token 87 | pveum user token remove root@pam api-automation 88 | ``` 89 | 90 | ### **Example Token Creation** 91 | 92 | ```bash 93 | # Create token for automation user 94 | pveum user add automation@pve --password "secure-password" 95 | pveum user token add automation@pve api-token --privsep=0 --comment "API automation" 96 | 97 | # Grant necessary permissions 98 | pveum aclmod / -user automation@pve -role Administrator 99 | ``` 100 | 101 | --- 102 | 103 | ## Security Best Practices 104 | 105 | ### **DO's** 106 | 107 | ```javascript 108 | // Use API tokens for automation 109 | client.apiToken = process.env.PROXMOX_API_TOKEN; 110 | 111 | // Store credentials securely 112 | const username = process.env.PROXMOX_USER; 113 | const password = process.env.PROXMOX_PASS; 114 | 115 | // Use specific user accounts (not root) 116 | await client.login("automation", password, "pve"); 117 | ``` 118 | 119 | ### **DON'Ts** 120 | 121 | ```javascript 122 | // Don't hardcode credentials 123 | await client.login("root", "password123"); // Bad! 124 | 125 | // Don't use overly permissive tokens 126 | // Create tokens with minimal required permissions 127 | ``` 128 | 129 | --- 130 | 131 | ## Permission Management 132 | 133 | ### **Creating Dedicated Users** 134 | 135 | ```bash 136 | # Create user for API access 137 | pveum user add api-user@pve --password "secure-password" --comment "API automation user" 138 | 139 | # Create custom role with specific permissions 140 | pveum role add ApiUser -privs "VM.Audit,VM.Config.Disk,VM.Config.Memory,VM.PowerMgmt,VM.Snapshot" 141 | 142 | # Assign role to user 143 | pveum aclmod / -user api-user@pve -role ApiUser 144 | ``` 145 | 146 | ### **Common Permission Sets** 147 | 148 | ```bash 149 | # Read-only access 150 | pveum role add ReadOnly -privs "VM.Audit,Datastore.Audit,Sys.Audit" 151 | 152 | # VM management 153 | pveum role add VMManager -privs "VM.Audit,VM.Config.Disk,VM.Config.Memory,VM.PowerMgmt,VM.Snapshot,VM.Clone" 154 | 155 | # Full administrator (use with caution) 156 | pveum aclmod / -user user@pve -role Administrator 157 | ``` 158 | 159 | --- 160 | 161 | ## Environment Configuration 162 | 163 | ### **Environment Variables** 164 | 165 | ```bash 166 | # Set environment variables 167 | export PROXMOX_HOST="pve.example.com" 168 | export PROXMOX_API_TOKEN="user@pve!token=uuid" 169 | 170 | # Or for username/password 171 | export PROXMOX_USER="admin@pve" 172 | export PROXMOX_PASS="secure-password" 173 | ``` 174 | 175 | ### **Application Configuration** 176 | 177 | ```javascript 178 | const { PveClient } = require("@corsinvest/cv4pve-api-javascript"); 179 | 180 | // Load configuration from environment 181 | const config = { 182 | host: process.env.PROXMOX_HOST, 183 | apiToken: process.env.PROXMOX_API_TOKEN, 184 | timeout: parseInt(process.env.PROXMOX_TIMEOUT || '30000') 185 | }; 186 | 187 | const client = new PveClient(config.host); 188 | 189 | // Use API token if available 190 | if (config.apiToken) { 191 | client.apiToken = config.apiToken; 192 | } else { 193 | // Fallback to username/password 194 | const username = process.env.PROXMOX_USER; 195 | const password = process.env.PROXMOX_PASS; 196 | await client.login(username, password); 197 | } 198 | ``` 199 | 200 | ### **Configuration File Example** 201 | 202 | ```json 203 | { 204 | "proxmox": { 205 | "host": "pve.example.com", 206 | "apiToken": "user@pve!token=uuid", 207 | "timeout": 30000 208 | } 209 | } 210 | ``` 211 | 212 | --- 213 | 214 | ## Troubleshooting Authentication 215 | 216 | ### **Common Issues** 217 | 218 | #### **"Authentication Failed"** 219 | ```javascript 220 | // Check credentials 221 | try { 222 | const success = await client.login("user", "password", "pam"); 223 | if (!success) { 224 | console.log("Invalid credentials"); 225 | } 226 | } catch (error) { 227 | console.log(`Login error: ${error.message}`); 228 | } 229 | ``` 230 | 231 | #### **"Permission Denied"** 232 | ```bash 233 | # Check user permissions 234 | pveum user list 235 | pveum aclmod / -user user@pve -role Administrator 236 | ``` 237 | 238 | #### **"Invalid API Token"** 239 | ```javascript 240 | // Verify token format 241 | client.apiToken = "user@realm!tokenid=uuid"; // Correct format 242 | 243 | // Check if token exists 244 | // Token format: USER@REALM!TOKENID=SECRET 245 | ``` 246 | 247 | ### **Testing Authentication** 248 | 249 | ```javascript 250 | async function testAuthentication(client) { 251 | try { 252 | const version = await client.version.version(); 253 | if (version.isSuccessStatusCode) { 254 | console.log("Authentication successful"); 255 | console.log(`Connected to Proxmox VE ${version.response.data.version}`); 256 | return true; 257 | } else { 258 | console.log(`Authentication failed: ${version.reasonPhrase}`); 259 | return false; 260 | } 261 | } catch (error) { 262 | console.log(`Connection error: ${error.message}`); 263 | return false; 264 | } 265 | } 266 | ``` 267 | 268 | --- 269 | 270 | ## Authentication Examples 271 | 272 | ### **Enterprise Setup** 273 | 274 | ```javascript 275 | // Corporate environment 276 | const { PveClient } = require("@corsinvest/cv4pve-api-javascript"); 277 | 278 | const client = new PveClient("pve.company.com"); 279 | client.timeout = 300000; // 5 minutes in milliseconds 280 | 281 | client.apiToken = process.env.PROXMOX_API_TOKEN; 282 | ``` 283 | 284 | ### **Home Lab Setup** 285 | 286 | ```javascript 287 | // Simple home lab setup 288 | const { PveClient } = require("@corsinvest/cv4pve-api-javascript"); 289 | 290 | const client = new PveClient("192.168.1.100"); 291 | client.timeout = 120000; // 2 minutes in milliseconds 292 | 293 | await client.login("root", process.env.PVE_PASSWORD, "pam"); 294 | ``` 295 | 296 | ### **Cloud/Automation Setup** 297 | 298 | ```javascript 299 | // Automated deployment script 300 | const { PveClient } = require("@corsinvest/cv4pve-api-javascript"); 301 | 302 | const client = new PveClient(process.env.PROXMOX_HOST); 303 | 304 | // Use API token for automation 305 | client.apiToken = process.env.PROXMOX_API_TOKEN; 306 | 307 | // Verify connection before proceeding 308 | if (!(await testAuthentication(client))) { 309 | process.exit(1); 310 | } 311 | ``` 312 | -------------------------------------------------------------------------------- /docs/common-issues.md: -------------------------------------------------------------------------------- 1 | # Common Issues and Solutions 2 | 3 | This guide covers common issues, configuration patterns, and solutions when working with the Proxmox VE API in JavaScript/Node.js. 4 | 5 | --- 6 | 7 | ## Indexed Parameters 8 | 9 | Many VM/CT configuration methods use indexed parameters represented as objects where the key is the index and the value is the configuration string. 10 | 11 | ### Understanding Indexed Parameters 12 | 13 | Proxmox VE uses indexed parameters for devices that can have multiple instances. In the JavaScript API, indexed parameters are passed as objects with numeric keys and string values. 14 | 15 | **Common Parameters:** 16 | - **netN** - Network interfaces 17 | - **scsiN** / **virtioN** / **sataN** / **ideN** - Disk devices 18 | - **ipconfigN** - Cloud-init network configuration 19 | - **hostpciN** / **usbN** - Hardware passthrough 20 | - **mpN** - LXC mount points (containers only) 21 | 22 | > **Note:** Proxmox VE supports many other indexed parameters. All use the same object pattern. For a complete list, refer to the [Proxmox VE API Documentation](https://pve.proxmox.com/pve-docs/api-viewer/). 23 | 24 | ### Basic Usage 25 | 26 | ```javascript 27 | const { PveClient } = require("@corsinvest/cv4pve-api-javascript"); 28 | 29 | const client = new PveClient("pve.example.com"); 30 | await client.login("root", "password", "pam"); 31 | 32 | // Configure network interfaces (indexed as net0, net1, etc.) 33 | const networks = { 34 | 0: "model=virtio,bridge=vmbr0,firewall=1", 35 | 1: "model=e1000,bridge=vmbr1" 36 | }; 37 | 38 | // Configure disks (indexed as scsi0, scsi1, etc.) 39 | const disks = { 40 | 0: "local-lvm:32,cache=writethrough", 41 | 1: "local-lvm:64,iothread=1" 42 | }; 43 | 44 | // Note: The actual method parameters may vary - check API documentation 45 | await client.nodes.get("pve1").qemu.get(100).config.updateVm({ 46 | net0: networks[0], 47 | net1: networks[1], 48 | scsi0: disks[0], 49 | scsi1: disks[1] 50 | }); 51 | ``` 52 | 53 | --- 54 | 55 | ## Network Configuration (netN) 56 | 57 | ### Network Interface Syntax 58 | 59 | Format: `model=,bridge=[,option=value,...]` 60 | 61 | ### Common Parameters 62 | 63 | | Parameter | Description | Example Values | 64 | |-----------|-------------|----------------| 65 | | model | Network card model | virtio, e1000, rtl8139, vmxnet3 | 66 | | bridge | Bridge to connect to | vmbr0, vmbr1 | 67 | | firewall | Enable firewall | 0, 1 | 68 | | link_down | Disconnect interface | 0, 1 | 69 | | macaddr | MAC address | A2:B3:C4:D5:E6:F7 | 70 | | mtu | MTU size | 1500, 9000 | 71 | | queues | Number of queues | 1, 2, 4, 8 | 72 | | rate | Rate limit (MB/s) | 10, 100 | 73 | | tag | VLAN tag | 100, 200 | 74 | | trunks | VLAN trunks | 10;20;30 | 75 | 76 | ### Examples 77 | 78 | ```javascript 79 | // Basic VirtIO network 80 | await vm.config.updateVm({ 81 | net0: "model=virtio,bridge=vmbr0" 82 | }); 83 | 84 | // Network with VLAN and firewall 85 | await vm.config.updateVm({ 86 | net0: "model=virtio,bridge=vmbr0,tag=100,firewall=1" 87 | }); 88 | 89 | // Multiple networks with different settings 90 | await vm.config.updateVm({ 91 | net0: "model=virtio,bridge=vmbr0,firewall=1", 92 | net1: "model=e1000,bridge=vmbr1,rate=100", 93 | net2: "model=virtio,bridge=vmbr0,tag=200,queues=4" 94 | }); 95 | ``` 96 | 97 | --- 98 | 99 | ## Disk Configuration 100 | 101 | ### Disk Syntax 102 | 103 | Format: `:[,option=value,...]` 104 | 105 | Or for existing volumes: `:[,option=value,...]` 106 | 107 | ### Storage Types 108 | 109 | - **scsiN** - SCSI disks (0-30), most common, supports all features 110 | - **virtioN** - VirtIO disks (0-15), high performance 111 | - **sataN** - SATA disks (0-5), legacy compatibility 112 | - **ideN** - IDE disks (0-3), legacy, often used for CD-ROM 113 | - **efidisk0** - EFI disk for UEFI boot 114 | 115 | ### Common Disk Parameters 116 | 117 | | Parameter | Description | Example Values | 118 | |-----------|-------------|----------------| 119 | | cache | Cache mode | none, writethrough, writeback, directsync, unsafe | 120 | | discard | Enable TRIM/discard | on, ignore | 121 | | iothread | Enable IO thread | 0, 1 | 122 | | ssd | SSD emulation | 0, 1 | 123 | | backup | Include in backup | 0, 1 | 124 | | replicate | Enable replication | 0, 1 | 125 | | media | Media type | disk, cdrom | 126 | | size | Disk size | 32G, 100G, 1T | 127 | 128 | ### SCSI Disk Examples 129 | 130 | ```javascript 131 | // Basic SCSI disk - 32GB 132 | await vm.config.updateVm({ 133 | scsi0: "local-lvm:32" 134 | }); 135 | 136 | // SCSI disk with options 137 | await vm.config.updateVm({ 138 | scsi0: "local-lvm:32,cache=writethrough,iothread=1,discard=on" 139 | }); 140 | 141 | // Multiple SCSI disks 142 | await vm.config.updateVm({ 143 | scsi0: "local-lvm:32,cache=writethrough,iothread=1", // OS disk 144 | scsi1: "local-lvm:100,cache=none,iothread=1,discard=on", // Data disk 145 | scsi2: "local-lvm:200,backup=0" // Temp disk, no backup 146 | }); 147 | ``` 148 | 149 | ### VirtIO Disk Examples 150 | 151 | ```javascript 152 | // VirtIO disks for maximum performance 153 | await vm.config.updateVm({ 154 | virtio0: "local-lvm:32,cache=writethrough,discard=on", 155 | virtio1: "ceph-storage:100,cache=none,iothread=1" 156 | }); 157 | ``` 158 | 159 | ### SATA/IDE Examples 160 | 161 | ```javascript 162 | // SATA disk 163 | await vm.config.updateVm({ 164 | sata0: "local-lvm:32" 165 | }); 166 | 167 | // IDE CD-ROM 168 | await vm.config.updateVm({ 169 | ide2: "local:iso/ubuntu-22.04.iso,media=cdrom" 170 | }); 171 | ``` 172 | 173 | ### EFI Disk 174 | 175 | ```javascript 176 | // EFI disk for UEFI boot 177 | await client.nodes.get("pve1").qemu.get(100).config.updateVm({ 178 | bios: "ovmf", 179 | efidisk0: "local-lvm:1,efitype=4m,pre-enrolled-keys=0" 180 | }); 181 | ``` 182 | 183 | --- 184 | 185 | ## Cloud-Init Configuration (ipconfigN) 186 | 187 | ### IP Configuration Syntax 188 | 189 | Format: `ip=
,gw=[,option=value,...]` 190 | 191 | ### Examples 192 | 193 | ```javascript 194 | // DHCP on all interfaces 195 | await vm.config.updateVm({ 196 | ipconfig0: "ip=dhcp" 197 | }); 198 | 199 | // Static IP configuration 200 | await vm.config.updateVm({ 201 | ipconfig0: "ip=192.168.1.100/24,gw=192.168.1.1" 202 | }); 203 | 204 | // Multiple interfaces with different configs 205 | await vm.config.updateVm({ 206 | ipconfig0: "ip=192.168.1.100/24,gw=192.168.1.1", // Management 207 | ipconfig1: "ip=10.0.0.100/24", // Internal network 208 | ipconfig2: "ip=dhcp" // External network via DHCP 209 | }); 210 | 211 | // IPv6 with auto-configuration 212 | await vm.config.updateVm({ 213 | ipconfig0: "ip=192.168.1.100/24,gw=192.168.1.1,ip6=auto" 214 | }); 215 | ``` 216 | 217 | --- 218 | 219 | ## Complete Example 220 | 221 | ### Linux VM with VirtIO and Cloud-Init 222 | 223 | ```javascript 224 | const client = new PveClient("pve.example.com"); 225 | await client.login("admin", "password", "pve"); 226 | 227 | // VM identifiers 228 | const vmid = 101; 229 | const vmName = "ubuntu-server"; 230 | const node = "pve1"; 231 | 232 | // Hardware resources 233 | const memory = 4096; // 4GB RAM 234 | const cores = 2; 235 | const sockets = 1; 236 | 237 | // Create VM with full configuration 238 | const result = await client.nodes.get(node).qemu.createVm({ 239 | vmid: vmid, 240 | name: vmName, 241 | memory: memory, 242 | cores: cores, 243 | sockets: sockets, 244 | ostype: "l26", 245 | scsihw: "virtio-scsi-single", 246 | boot: "order=virtio0", 247 | agent: "enabled=1", 248 | virtio0: "local-lvm:32,cache=writethrough,discard=on", 249 | net0: "model=virtio,bridge=vmbr0,firewall=1", 250 | ipconfig0: "ip=192.168.1.100/24,gw=192.168.1.1", 251 | ciuser: "admin", 252 | cipassword: "SecurePassword123!", 253 | sshkeys: "ssh-rsa AAAAB3NzaC1yc2E...", 254 | nameserver: "8.8.8.8 8.8.4.4", 255 | searchdomain: "example.com" 256 | }); 257 | 258 | console.log(`VM ${vmid} created successfully with cloud-init!`); 259 | ``` 260 | 261 | --- 262 | 263 | ## Common Troubleshooting 264 | 265 | ### VM Won't Start 266 | 267 | **Check configuration:** 268 | ```javascript 269 | const result = await client.nodes.get("pve1").qemu.get(100).config.vmConfig(); 270 | console.log(result.response.data); 271 | ``` 272 | 273 | **Common issues:** 274 | - Missing boot disk: Verify `boot` parameter points to valid disk 275 | - Invalid network bridge: Check bridge exists on node 276 | - Insufficient resources: Verify memory/CPU allocation 277 | 278 | ### Disk Not Found 279 | 280 | Verify storage exists and has space: 281 | ```javascript 282 | const storages = await client.nodes.get("pve1").storage.index(); 283 | for (const storage of storages.response.data) { 284 | console.log(`Storage: ${storage.storage}`); 285 | console.log(` Type: ${storage.type}`); 286 | console.log(` Available: ${storage.avail}`); 287 | } 288 | ``` 289 | 290 | ### Network Issues 291 | 292 | Verify bridge configuration: 293 | ```javascript 294 | const networks = await client.nodes.get("pve1").network.index(); 295 | for (const net of networks.response.data) { 296 | if (net.type === "bridge") { 297 | console.log(`Bridge: ${net.iface}`); 298 | } 299 | } 300 | ``` 301 | 302 | --- 303 | 304 | For more details on specific parameters and options, refer to the [Proxmox VE API Documentation](https://pve.proxmox.com/pve-docs/api-viewer/). 305 | -------------------------------------------------------------------------------- /docs/errorhandling.md: -------------------------------------------------------------------------------- 1 | # Error Handling Guide 2 | 3 | Comprehensive guide to handling errors and exceptions when working with the Proxmox VE API in JavaScript/Node.js. 4 | 5 | ## Types of Errors 6 | 7 | ### **Network Errors** 8 | ```javascript 9 | try { 10 | const client = new PveClient("invalid-host.local"); 11 | const result = await client.version.version(); 12 | } catch (error) { 13 | if (error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED' || error.code === 'EHOSTUNREACH') { 14 | console.log(`Network error: ${error.message}`); 15 | // Handle: DNS resolution, connection refused, network unreachable 16 | } else if (error.message.includes('timeout') || error.code === 'ETIMEDOUT') { 17 | console.log(`Request timeout: ${error.message}`); 18 | // Handle: Request took too long 19 | } else { 20 | console.log(`Request error: ${error.message}`); 21 | } 22 | } 23 | ``` 24 | 25 | ### **Authentication Errors** 26 | ```javascript 27 | try { 28 | const client = new PveClient("pve.local"); 29 | const success = await client.login("user", "wrong-password", "pam"); 30 | 31 | if (!success) { 32 | console.log("Authentication failed - check credentials"); 33 | } 34 | } catch (error) { 35 | console.log(`Authentication error: ${error.message}`); 36 | } 37 | ``` 38 | 39 | ### **API Response Errors** 40 | ```javascript 41 | const result = await client.nodes.get("pve1").qemu.get(999).config.vmConfig(); 42 | 43 | if (!result.isSuccessStatusCode) { 44 | switch (result.statusCode) { 45 | case 404: 46 | console.log("VM not found"); 47 | break; 48 | case 403: 49 | console.log("Permission denied"); 50 | break; 51 | case 400: 52 | console.log(`Bad request: ${result.reasonPhrase}`); 53 | break; 54 | default: 55 | console.log(`API error: ${result.statusCode} - ${result.reasonPhrase}`); 56 | break; 57 | } 58 | } 59 | ``` 60 | 61 | ## Error Handling Patterns 62 | 63 | ### **Basic Pattern** 64 | ```javascript 65 | async function safeVmOperation(client, node, vmId) { 66 | try { 67 | const result = await client.nodes.get(node).qemu.get(vmId).status.start.vmStart(); 68 | 69 | if (result.isSuccessStatusCode) { 70 | console.log(`VM ${vmId} started successfully`); 71 | return true; 72 | } else { 73 | console.log(`Failed to start VM ${vmId}: ${result.reasonPhrase}`); 74 | return false; 75 | } 76 | } catch (error) { 77 | console.log(`Exception starting VM ${vmId}: ${error.message}`); 78 | return false; 79 | } 80 | } 81 | ``` 82 | 83 | ### **Centralized Error Handler** 84 | ```javascript 85 | class ErrorHandler { 86 | static async safeApiCall(apiCall, operation = "API call") { 87 | try { 88 | const result = await apiCall(); 89 | 90 | if (!result.isSuccessStatusCode) { 91 | this.logApiError(result, operation); 92 | } 93 | 94 | return result; 95 | } catch (error) { 96 | if (error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED' || error.code === 'EHOSTUNREACH') { 97 | console.log(`Network error during ${operation}: ${error.message}`); 98 | } else if (error.message.includes('timeout') || error.code === 'ETIMEDOUT') { 99 | console.log(`Timeout during ${operation}: ${error.message}`); 100 | } else { 101 | console.log(`Unexpected error during ${operation}: ${error.message}`); 102 | } 103 | throw error; 104 | } 105 | } 106 | 107 | static logApiError(result, operation) { 108 | console.log(`${operation} failed:`); 109 | console.log(` Status: ${result.statusCode} - ${result.reasonPhrase}`); 110 | 111 | if (result.response.errors) { 112 | console.log(` Details: ${result.response.errors}`); 113 | } 114 | } 115 | } 116 | 117 | // Usage 118 | const result = await ErrorHandler.safeApiCall( 119 | () => client.nodes.get("pve1").qemu.get(100).status.start.vmStart(), 120 | "Starting VM 100" 121 | ); 122 | ``` 123 | 124 | ### **Retry Logic** 125 | ```javascript 126 | async function withRetry(operation, maxRetries = 3, operationName = "operation") { 127 | for (let attempt = 1; attempt <= maxRetries; attempt++) { 128 | try { 129 | const result = await operation(); 130 | 131 | if (result.isSuccessStatusCode) { 132 | return result; 133 | } 134 | 135 | // Don't retry client errors (4xx), only server errors (5xx) 136 | if (result.statusCode < 500) { 137 | console.log(`${operationName} failed with client error: ${result.statusCode}`); 138 | return result; 139 | } 140 | 141 | if (attempt < maxRetries) { 142 | console.log(`Warning: ${operationName} failed (attempt ${attempt}/${maxRetries}), retrying...`); 143 | const delay = Math.pow(2, attempt) * 1000; // Exponential backoff in milliseconds 144 | await new Promise(resolve => setTimeout(resolve, delay)); 145 | } 146 | } catch (error) { 147 | if (attempt < maxRetries) { 148 | console.log(`Warning: ${operationName} threw exception (attempt ${attempt}/${maxRetries}): ${error.message}`); 149 | const delay = Math.pow(2, attempt) * 1000; 150 | await new Promise(resolve => setTimeout(resolve, delay)); 151 | } else { 152 | // Final attempt - re-throw the error 153 | throw error; 154 | } 155 | } 156 | } 157 | 158 | // Final attempt without catching exceptions 159 | return await operation(); 160 | } 161 | 162 | // Usage 163 | const result = await withRetry( 164 | () => client.nodes.get("pve1").qemu.get(100).config.vmConfig(), 165 | 3, 166 | "Get VM config" 167 | ); 168 | ``` 169 | 170 | ## Common Error Scenarios 171 | 172 | ### **Permission Issues** 173 | ```javascript 174 | function handlePermissionError(result) { 175 | if (result.statusCode === 403) { 176 | console.log("Permission denied. Check:"); 177 | console.log(" - User has required permissions"); 178 | console.log(" - API token has correct privileges"); 179 | console.log(" - Resource exists and user has access"); 180 | } 181 | } 182 | ``` 183 | 184 | ### **Resource Not Found** 185 | ```javascript 186 | async function vmExists(client, node, vmId) { 187 | try { 188 | const result = await client.nodes.get(node).qemu.get(vmId).config.vmConfig(); 189 | return result.isSuccessStatusCode; 190 | } catch (error) { 191 | return false; // Network error, can't determine 192 | } 193 | } 194 | 195 | // Usage 196 | if (!(await vmExists(client, "pve1", 100))) { 197 | console.log("VM 100 does not exist on node pve1"); 198 | return; 199 | } 200 | ``` 201 | 202 | ### **Timeout Handling** 203 | ```javascript 204 | const client = new PveClient("pve.local"); 205 | client.timeout = 300000; // Increase timeout for long operations (5 minutes in milliseconds) 206 | 207 | try { 208 | const result = await client.nodes.get("pve1").qemu.get(100).clone.cloneVm({newid: 101}); 209 | } catch (error) { 210 | if (error.message.includes('timeout')) { 211 | console.log("Operation timed out - try increasing client timeout"); 212 | } else { 213 | console.log("Operation failed:", error.message); 214 | } 215 | } 216 | ``` 217 | 218 | ## Best Practices 219 | 220 | ### **Defensive Programming** 221 | ```javascript 222 | // Always validate input 223 | async function getVmConfig(client, node, vmId) { 224 | if (!node || typeof node !== 'string') { 225 | throw new Error("Node name must be a non-empty string"); 226 | } 227 | 228 | if (typeof vmId !== 'number' || vmId <= 0) { 229 | throw new Error("VM ID must be a positive number"); 230 | } 231 | 232 | return await client.nodes.get(node).qemu.get(vmId).config.vmConfig(); 233 | } 234 | 235 | // Check for null responses 236 | const result = await client.cluster.resources.resources(); 237 | if (result.isSuccessStatusCode && result.response.data) { 238 | for (const resource of result.response.data) { 239 | // Process resource 240 | } 241 | } 242 | ``` 243 | 244 | ### **Graceful Degradation** 245 | ```javascript 246 | async function getClusterStatus(client) { 247 | try { 248 | const result = await client.cluster.status.status(); 249 | if (result.isSuccessStatusCode) { 250 | return parseClusterStatus(result.response.data); 251 | } 252 | } catch (error) { 253 | console.log(`Warning: Could not get cluster status: ${error.message}`); 254 | } 255 | 256 | // Return fallback status 257 | return { status: "unknown", lastUpdate: new Date() }; 258 | } 259 | ``` 260 | 261 | ### **Detailed Logging** 262 | ```javascript 263 | async function loggedApiCall(apiCall, operation) { 264 | console.log(`Starting: ${operation}`); 265 | const startTime = Date.now(); 266 | 267 | try { 268 | const result = await apiCall(); 269 | const duration = Date.now() - startTime; 270 | 271 | if (result.isSuccessStatusCode) { 272 | console.log(`${operation} completed in ${duration}ms`); 273 | } else { 274 | console.log(`${operation} failed after ${duration}ms: ${result.reasonPhrase}`); 275 | } 276 | 277 | return result; 278 | } catch (error) { 279 | const duration = Date.now() - startTime; 280 | console.log(`${operation} threw exception after ${duration}ms: ${error.message}`); 281 | throw error; 282 | } 283 | } 284 | ``` 285 | -------------------------------------------------------------------------------- /docs/tasks.md: -------------------------------------------------------------------------------- 1 | # Task Management Guide 2 | 3 | Understanding and managing long-running operations in Proxmox VE. 4 | 5 | ## Understanding Tasks 6 | 7 | Many Proxmox VE operations are asynchronous and return a task ID instead of immediate results: 8 | 9 | ```javascript 10 | // Operations that return task IDs 11 | const result = await client.nodes.get("pve1").qemu.get(100).clone.cloneVm({newid: 101}); 12 | const taskId = result.response.data; // Returns: "UPID:pve1:..." 13 | console.log(`Task started: ${taskId}`); 14 | ``` 15 | 16 | ## Task Status 17 | 18 | ### **Checking Task Status** 19 | ```javascript 20 | async function getTaskStatus(client, node, taskId) { 21 | const result = await client.nodes.get(node).tasks.get(taskId).status.readTaskStatus(); 22 | const data = result.response.data; 23 | return { 24 | status: data.status, // "running", "stopped" 25 | exitStatus: data.exitstatus, // "OK" if successful 26 | startTime: data.starttime, 27 | endTime: data.endtime, 28 | progress: data.pct ? parseFloat(data.pct) : null, 29 | log: data.log 30 | }; 31 | } 32 | ``` 33 | 34 | ### **Waiting for Completion** 35 | ```javascript 36 | async function waitForTaskCompletion( 37 | client, 38 | node, 39 | taskId, 40 | timeout = 1800000, // 30 minutes in milliseconds 41 | progressCallback = null 42 | ) { 43 | const startTime = Date.now(); 44 | let lastStatus = ""; 45 | 46 | while (Date.now() - startTime < timeout) { 47 | const statusResult = await client.nodes.get(node).tasks.get(taskId).status.readTaskStatus(); 48 | const data = statusResult.response.data; 49 | const currentStatus = data.status; 50 | 51 | // Report progress if status changed 52 | if (currentStatus !== lastStatus && progressCallback) { 53 | progressCallback(`Task ${taskId}: ${currentStatus}`); 54 | lastStatus = currentStatus; 55 | } 56 | 57 | // Check if task completed 58 | if (currentStatus === "stopped") { 59 | const exitStatus = data.exitstatus; 60 | const success = exitStatus === "OK"; 61 | 62 | if (progressCallback) { 63 | progressCallback(`Task ${taskId} ${success ? "completed" : "failed"}: ${exitStatus}`); 64 | } 65 | return success; 66 | } 67 | 68 | await new Promise(resolve => setTimeout(resolve, 2000)); // Check every 2 seconds 69 | } 70 | 71 | throw new Error(`Task ${taskId} did not complete within timeout`); 72 | } 73 | ``` 74 | 75 | ## Common Task Operations 76 | 77 | ### **VM Clone with Progress** 78 | ```javascript 79 | async function cloneVmWithProgress( 80 | client, 81 | node, 82 | sourceVmId, 83 | targetVmId, 84 | newName 85 | ) { 86 | console.log(`Cloning VM ${sourceVmId} to ${targetVmId}...`); 87 | 88 | // Start clone operation 89 | const cloneResult = await client.nodes.get(node).qemu.get(sourceVmId).clone.cloneVm({ 90 | newid: targetVmId, 91 | name: newName 92 | }); 93 | const taskId = cloneResult.response.data; 94 | 95 | // Wait for completion with progress reporting 96 | const progressCallback = (status) => console.log(`Status: ${status}`); 97 | 98 | try { 99 | const success = await waitForTaskCompletion(client, node, taskId, 3600000, progressCallback); // 60 minutes 100 | 101 | if (success) { 102 | console.log(`VM cloned successfully: ${sourceVmId} → ${targetVmId}`); 103 | } else { 104 | console.log(`VM clone failed`); 105 | } 106 | 107 | return success; 108 | } catch (error) { 109 | console.log(`Timeout: Clone operation timed out: ${error.message}`); 110 | return false; 111 | } 112 | } 113 | ``` 114 | 115 | ### **Container Creation** 116 | ```javascript 117 | async function createContainer( 118 | client, 119 | node, 120 | vmId, 121 | template, 122 | config 123 | ) { 124 | // Start container creation 125 | const createResult = await client.nodes.get(node).lxc.createVm({ 126 | vmid: vmId, 127 | ostemplate: template, 128 | hostname: config.hostname, 129 | memory: config.memory, 130 | rootfs: config.rootfs 131 | }); 132 | const taskId = createResult.response.data; 133 | console.log(`Creating container ${vmId} (Task: ${taskId})`); 134 | 135 | return await waitForTaskCompletion(client, node, taskId, 600000); // 10 minutes 136 | } 137 | ``` 138 | 139 | ## Monitoring Multiple Tasks 140 | 141 | ### **Parallel Task Monitoring** 142 | ```javascript 143 | async function monitorMultipleTasks( 144 | client, 145 | tasks // Map: {taskId: node} 146 | ) { 147 | const results = {}; 148 | const activeTasks = {...tasks}; // Clone the object 149 | 150 | console.log(`Monitoring ${Object.keys(activeTasks).length} tasks...`); 151 | 152 | while (Object.keys(activeTasks).length > 0) { 153 | const completedTasks = []; 154 | 155 | // Check each active task 156 | for (const [taskId, node] of Object.entries(activeTasks)) { 157 | try { 158 | const statusResult = await client.nodes.get(node).tasks.get(taskId).status.readTaskStatus(); 159 | 160 | if (statusResult.response.data.status === "stopped") { 161 | const success = statusResult.response.data.exitstatus === "OK"; 162 | results[taskId] = success; 163 | completedTasks.push(taskId); 164 | 165 | console.log(`Task ${taskId}: ${statusResult.response.data.exitstatus} (${success ? "Success" : "Failed"})`); 166 | } 167 | } catch (error) { 168 | console.log(`Error checking task ${taskId}: ${error.message}`); 169 | results[taskId] = false; 170 | completedTasks.push(taskId); 171 | } 172 | } 173 | 174 | // Remove completed tasks 175 | for (const taskId of completedTasks) { 176 | delete activeTasks[taskId]; 177 | } 178 | 179 | if (Object.keys(activeTasks).length > 0) { 180 | await new Promise(resolve => setTimeout(resolve, 3000)); // Check every 3 seconds 181 | } 182 | } 183 | 184 | return results; 185 | } 186 | ``` 187 | 188 | ## Task Utilities 189 | 190 | ### **Task History** 191 | ```javascript 192 | async function getRecentTasks(client, node, limit = 10) { 193 | const result = await client.nodes.get(node).tasks.nodeTasks({limit: limit}); 194 | const tasks = []; 195 | 196 | for (const task of result.response.data) { 197 | tasks.push({ 198 | id: task.upid, 199 | type: task.type, 200 | status: task.status, 201 | exitStatus: task.exitstatus, 202 | startTime: new Date(task.starttime * 1000), // Convert Unix timestamp 203 | endTime: task.endtime ? new Date(task.endtime * 1000) : null, 204 | user: task.user, 205 | node: task.node 206 | }); 207 | } 208 | 209 | return tasks.sort((a, b) => b.startTime - a.startTime); 210 | } 211 | ``` 212 | 213 | ### **Task Cleanup** 214 | ```javascript 215 | async function stopTask(client, node, taskId) { 216 | await client.nodes.get(node).tasks.get(taskId).delete(); 217 | console.log(`Task ${taskId} stopped`); 218 | } 219 | ``` 220 | 221 | ## Best Practices 222 | 223 | ### **Timeout Management** 224 | ```javascript 225 | // Set appropriate timeouts for different operations 226 | const timeouts = { 227 | clone: 7200000, // 2 hours in milliseconds 228 | backup: 14400000, // 4 hours in milliseconds 229 | snapshot: 600000, // 10 minutes 230 | start: 300000, // 5 minutes 231 | stop: 300000, // 5 minutes 232 | create: 1800000 // 30 minutes 233 | }; 234 | 235 | const timeout = timeouts[operationType] || 1800000; // Default to 30 minutes 236 | await waitForTaskCompletion(client, node, taskId, timeout); 237 | ``` 238 | 239 | ### **Error Recovery** 240 | ```javascript 241 | async function robustTaskWait(client, node, taskId) { 242 | const maxRetries = 3; 243 | 244 | for (let attempt = 1; attempt <= maxRetries; attempt++) { 245 | try { 246 | return await waitForTaskCompletion(client, node, taskId); 247 | } catch (error) { 248 | if (attempt < maxRetries && 249 | (error.code === 'ECONNRESET' || error.code === 'ECONNREFUSED' || error.message.includes('timeout'))) { 250 | console.log(`Warning: Network error checking task (attempt ${attempt}): ${error.message}`); 251 | await new Promise(resolve => setTimeout(resolve, 5000)); // Wait 5 seconds 252 | } else if (attempt === maxRetries) { 253 | throw error; // Re-throw on final attempt 254 | } 255 | } 256 | } 257 | 258 | // Final attempt (should not be reached due to throw above, but for safety) 259 | return await waitForTaskCompletion(client, node, taskId); 260 | } 261 | ``` 262 | 263 | ### **Batch Operations with Tasks** 264 | ```javascript 265 | async function bulkVmClone( 266 | client, 267 | node, 268 | sourceVmId, 269 | targetVmIds 270 | ) { 271 | const tasks = {}; // taskId -> targetVmId 272 | const results = {}; 273 | 274 | // Start all clone operations 275 | for (const targetVmId of targetVmIds) { 276 | try { 277 | const cloneResult = await client.nodes.get(node).qemu.get(sourceVmId).clone.cloneVm({newid: targetVmId}); 278 | 279 | if (cloneResult.isSuccessStatusCode) { 280 | const taskId = cloneResult.response.data; 281 | tasks[taskId] = targetVmId; 282 | console.log(`Started clone to VM ${targetVmId} (Task: ${taskId})`); 283 | } else { 284 | console.log(`Failed to start clone to VM ${targetVmId}: ${cloneResult.reasonPhrase}`); 285 | results[targetVmId] = false; 286 | } 287 | } catch (error) { 288 | console.log(`Exception starting clone to VM ${targetVmId}: ${error.message}`); 289 | results[targetVmId] = false; 290 | } 291 | } 292 | 293 | // Monitor all tasks 294 | const taskResults = await monitorMultipleTasks( 295 | client, 296 | Object.keys(tasks).reduce((obj, taskId) => { 297 | obj[taskId] = node; 298 | return obj; 299 | }, {}) 300 | ); 301 | 302 | // Map task results back to VM IDs 303 | for (const [taskId, success] of Object.entries(taskResults)) { 304 | if (tasks[taskId] !== undefined) { 305 | results[tasks[taskId]] = success; 306 | } 307 | } 308 | 309 | return results; 310 | } 311 | ``` 312 | -------------------------------------------------------------------------------- /docs/advanced.md: -------------------------------------------------------------------------------- 1 | # Advanced Usage Guide 2 | 3 | This guide covers complex scenarios, best practices, and advanced patterns for experienced developers. 4 | 5 | ## Enterprise Configuration 6 | 7 | ### **Client Setup** 8 | 9 | ```javascript 10 | const { PveClient } = require("@corsinvest/cv4pve-api-javascript"); 11 | 12 | const client = new PveClient("pve.company.com"); 13 | client.apiToken = process.env.PROXMOX_API_TOKEN; 14 | client.timeout = 600000; // 10 minutes in milliseconds 15 | ``` 16 | 17 | ### **Resilient Operations** 18 | 19 | ```javascript 20 | // Retry policy with exponential backoff 21 | async function withRetry(operation, maxRetries = 3) { 22 | for (let attempt = 1; attempt <= maxRetries; attempt++) { 23 | try { 24 | return await operation(); 25 | } catch (error) { 26 | if (attempt < maxRetries && isRetriableError(error)) { 27 | const delay = Math.pow(2, attempt) * 1000; 28 | console.log(`Attempt ${attempt} failed, retrying in ${delay/1000}s: ${error.message}`); 29 | await new Promise(resolve => setTimeout(resolve, delay)); 30 | } else if (attempt === maxRetries) { 31 | throw error; // Re-throw on final attempt 32 | } 33 | } 34 | } 35 | } 36 | 37 | function isRetriableError(error) { 38 | // Network errors that can be retried 39 | return error.code === 'ECONNRESET' || error.code === 'ECONNREFUSED' || 40 | error.code === 'EHOSTUNREACH' || error.message.includes('timeout'); 41 | } 42 | 43 | // Usage 44 | const result = await withRetry(async () => 45 | await client.nodes.get("pve1").qemu.get(100).status.start.vmStart() 46 | ); 47 | ``` 48 | 49 | --- 50 | 51 | ## Task and Resource Management 52 | 53 | ### **Long-Running Operations** 54 | 55 | ```javascript 56 | // Complete task management with progress 57 | async function executeWithProgress(client, operation, node, description) { 58 | console.log(`Starting: ${description}`); 59 | 60 | const result = await operation(); 61 | if (!result.isSuccessStatusCode) { 62 | console.log(`Failed to start ${description}: ${result.reasonPhrase}`); 63 | return false; 64 | } 65 | 66 | const taskId = result.response.data; 67 | return await waitForTaskCompletion(client, node, taskId, description); 68 | } 69 | 70 | async function waitForTaskCompletion(client, node, taskId, description) { 71 | const timeout = 30 * 60 * 1000; // 30 minutes in milliseconds 72 | const start = Date.now(); 73 | 74 | while (Date.now() - start < timeout) { 75 | const status = await client.nodes.get(node).tasks.get(taskId).status.readTaskStatus(); 76 | 77 | if (status.response.data.status === "stopped") { 78 | const success = status.response.data.exitstatus === "OK"; 79 | console.log(`${description}: ${status.response.data.exitstatus} (${success ? "Success" : "Failed"})`); 80 | return success; 81 | } 82 | 83 | await new Promise(resolve => setTimeout(resolve, 2000)); 84 | } 85 | 86 | console.log(`Timeout: ${description} timed out`); 87 | return false; 88 | } 89 | ``` 90 | 91 | ### **Bulk Operations** 92 | 93 | ```javascript 94 | // Perform operations on multiple VMs with concurrency control 95 | async function bulkVmOperation(client, vmIds, operation, operationName) { 96 | // Get all resources to find VM locations 97 | const resources = await client.cluster.resources.resources(); 98 | const vmLocations = {}; 99 | 100 | for (const resource of resources.response.data) { 101 | if (resource.type === "qemu" && vmIds.includes(resource.vmid)) { 102 | vmLocations[resource.vmid] = resource.node; 103 | } 104 | } 105 | 106 | // Create a semaphore to limit concurrent operations 107 | const maxConcurrent = 5; 108 | const results = {}; 109 | 110 | // Process in batches 111 | for (let i = 0; i < vmIds.length; i += maxConcurrent) { 112 | const batch = vmIds.slice(i, i + maxConcurrent); 113 | const batchPromises = batch.map(async vmId => { 114 | if (!vmLocations[vmId]) { 115 | console.log(`VM ${vmId} not found`); 116 | results[vmId] = false; 117 | return; 118 | } 119 | 120 | const node = vmLocations[vmId]; 121 | try { 122 | await operation(client, node, vmId); 123 | console.log(`VM ${vmId} ${operationName}: Success`); 124 | results[vmId] = true; 125 | } catch (error) { 126 | console.log(`VM ${vmId} ${operationName}: Failed - ${error.message}`); 127 | results[vmId] = false; 128 | } 129 | }); 130 | 131 | await Promise.all(batchPromises); 132 | } 133 | 134 | return results; 135 | } 136 | 137 | // Usage examples 138 | const startResults = await bulkVmOperation( 139 | client, 140 | [100, 101, 102], 141 | async (c, node, vmId) => await c.nodes.get(node).qemu.get(vmId).status.start.vmStart(), 142 | "start" 143 | ); 144 | ``` 145 | 146 | --- 147 | 148 | ## Monitoring and Health Checks 149 | 150 | ### **Cluster Health Assessment** 151 | 152 | ```javascript 153 | class ClusterHealthMonitor { 154 | constructor(client) { 155 | this.client = client; 156 | } 157 | 158 | async getHealthReport() { 159 | const resources = await this.client.cluster.resources.resources(); 160 | const data = resources.response.data; 161 | 162 | const nodes = data.filter(r => r.type === "node"); 163 | const vms = data.filter(r => r.type === "qemu"); 164 | const containers = data.filter(r => r.type === "lxc"); 165 | 166 | // Calculate averages - handle potential division by zero 167 | const avgCpuUsage = nodes.length > 0 ? nodes.reduce((sum, n) => sum + (n.cpu || 0), 0) / nodes.length : 0; 168 | const avgMemoryUsage = nodes.length > 0 ? nodes.reduce((sum, n) => sum + ((n.mem || 0) / (n.maxmem || 1)), 0) / nodes.length : 0; 169 | 170 | return { 171 | timestamp: new Date(), 172 | nodes: { 173 | total: nodes.length, 174 | online: nodes.filter(n => n.status === "online").length, 175 | averageCpuUsage: avgCpuUsage, 176 | averageMemoryUsage: avgMemoryUsage 177 | }, 178 | virtualMachines: { 179 | total: vms.length, 180 | running: vms.filter(v => v.status === "running").length, 181 | stopped: vms.filter(v => v.status === "stopped").length, 182 | highCpuUsage: vms.filter(v => (v.cpu || 0) > 0.8).length 183 | }, 184 | containers: { 185 | total: containers.length, 186 | running: containers.filter(c => c.status === "running").length, 187 | stopped: containers.filter(c => c.status === "stopped").length 188 | } 189 | }; 190 | } 191 | 192 | async checkAlerts() { 193 | const alerts = []; 194 | const resources = await this.client.cluster.resources.resources(); 195 | const data = resources.response.data; 196 | 197 | // Check for offline nodes 198 | const offlineNodes = data.filter(r => r.type === "node" && r.status !== "online"); 199 | for (const node of offlineNodes) { 200 | alerts.push({ 201 | severity: "critical", 202 | message: `Node ${node.node} is offline`, 203 | resource: node.node 204 | }); 205 | } 206 | 207 | // Check for high resource usage 208 | const highCpuNodes = data.filter(r => r.type === "node" && (r.cpu || 0) > 0.9); 209 | for (const node of highCpuNodes) { 210 | alerts.push({ 211 | severity: "warning", 212 | message: `Node ${node.node} has high CPU usage: ${(node.cpu * 100).toFixed(1)}%`, 213 | resource: node.node 214 | }); 215 | } 216 | 217 | return alerts; 218 | } 219 | } 220 | 221 | // Usage 222 | const monitor = new ClusterHealthMonitor(client); 223 | const health = await monitor.getHealthReport(); 224 | const alerts = await monitor.checkAlerts(); 225 | 226 | console.log(`Cluster Health: ${health.nodes.online}/${health.nodes.total} nodes online`); 227 | console.log(`VMs: ${health.virtualMachines.running}/${health.virtualMachines.total} running`); 228 | 229 | for (const alert of alerts.filter(a => a.severity === "critical")) { 230 | console.log(`CRITICAL: ${alert.message}`); 231 | } 232 | ``` 233 | 234 | --- 235 | 236 | ## Architecture Patterns 237 | 238 | ### **Repository Pattern** 239 | 240 | ```javascript 241 | class ProxmoxRepository { 242 | constructor(client) { 243 | this.client = client; 244 | } 245 | 246 | async getVmsAsync(nodeFilter = null) { 247 | console.log(`Getting VMs for node filter: ${nodeFilter}`); 248 | 249 | const resources = await this.client.cluster.resources.resources(); 250 | let vms = resources.response.data.filter(r => r.type === "qemu"); 251 | 252 | if (nodeFilter) { 253 | vms = vms.filter(vm => vm.node.toLowerCase() === nodeFilter.toLowerCase()); 254 | } 255 | 256 | return vms; 257 | } 258 | 259 | async getVmConfigAsync(node, vmId) { 260 | console.log(`Getting config for VM ${vmId} on node ${node}`); 261 | 262 | const result = await this.client.nodes.get(node).qemu.get(vmId).config.vmConfig(); 263 | return result.response.data; 264 | } 265 | 266 | async startVmAsync(node, vmId) { 267 | console.log(`Starting VM ${vmId} on node ${node}`); 268 | 269 | await this.client.nodes.get(node).qemu.get(vmId).status.start.vmStart(); 270 | console.log(`Successfully started VM ${vmId}`); 271 | } 272 | 273 | async createSnapshotAsync(node, vmId, name, description = null) { 274 | console.log(`Creating snapshot ${name} for VM ${vmId} on node ${node}`); 275 | 276 | await this.client.nodes.get(node).qemu.get(vmId).snapshot.snapshot(name, description); 277 | } 278 | } 279 | ``` 280 | 281 | --- 282 | 283 | ## Error Handling and Logging 284 | 285 | ### **Centralized Error Management** 286 | 287 | ```javascript 288 | class ProxmoxOperations { 289 | static async safeExecute(operation, operationName, logger = console) { 290 | try { 291 | logger.log(`Executing: ${operationName}`); 292 | const startTime = Date.now(); 293 | 294 | const result = await operation(); 295 | const duration = Date.now() - startTime; 296 | 297 | logger.log(`${operationName} completed in ${duration}ms`); 298 | 299 | return result; 300 | } catch (error) { 301 | if (error.code === 'ECONNRESET' || error.code === 'ECONNREFUSED') { 302 | logger.error(`Network error during ${operationName}: ${error.message}`); 303 | throw error; 304 | } else if (error.message.includes('timeout')) { 305 | logger.error(`Timeout during ${operationName}: ${error.message}`); 306 | throw error; 307 | } else { 308 | logger.error(`Unexpected error during ${operationName}: ${error.message}`); 309 | throw error; 310 | } 311 | } 312 | } 313 | } 314 | 315 | // Usage 316 | const result = await ProxmoxOperations.safeExecute( 317 | async () => await client.nodes.get("pve1").qemu.get(100).status.start.vmStart(), 318 | "Start VM 100", 319 | console 320 | ); 321 | ``` 322 | 323 | --- 324 | 325 | ## Best Practices Summary 326 | 327 | ### **Performance** 328 | - Use appropriate timeout settings 329 | - Implement retry policies for resilience 330 | - Limit concurrent operations to avoid overloading the API 331 | - Cache frequently accessed data 332 | 333 | ### **Security** 334 | - Always use API tokens in production 335 | - Store credentials securely (environment variables) 336 | - Implement proper audit logging 337 | 338 | ### **Architecture** 339 | - Use repository pattern for testability 340 | - Implement centralized error handling 341 | - Separate concerns with proper abstractions 342 | 343 | ### **Monitoring** 344 | - Log all operations with appropriate levels 345 | - Implement health checks and alerting 346 | - Monitor task completion and failures 347 | - Track performance metrics 348 | -------------------------------------------------------------------------------- /docs/examples.md: -------------------------------------------------------------------------------- 1 | # Basic Examples 2 | 3 | This guide provides common usage patterns and practical examples for getting started with the Proxmox VE API. 4 | 5 | ## Getting Started 6 | 7 | ### **Basic Connection** 8 | 9 | ```javascript 10 | const { PveClient } = require("@corsinvest/cv4pve-api-javascript"); 11 | 12 | // Create client and authenticate 13 | const client = new PveClient("pve.example.com"); 14 | client.apiToken = "user@pve!token=uuid"; 15 | 16 | // Test connection 17 | const version = await client.version.version(); 18 | console.log(`Connected to Proxmox VE ${version.response.data.version}`); 19 | ``` 20 | 21 | ### **Client Setup with Error Handling** 22 | 23 | ```javascript 24 | async function createClient() { 25 | const client = new PveClient("pve.local"); 26 | client.timeout = 120000; // 2 minutes in milliseconds 27 | 28 | try { 29 | // Use API token or login 30 | if (process.env.PVE_TOKEN) { 31 | client.apiToken = process.env.PVE_TOKEN; 32 | } else { 33 | const success = await client.login("root", "password", "pam"); 34 | if (!success) { 35 | throw new Error("Authentication failed"); 36 | } 37 | } 38 | 39 | return client; 40 | } catch (error) { 41 | console.log(`Failed to create client: ${error.message}`); 42 | throw error; 43 | } 44 | } 45 | ``` 46 | 47 | --- 48 | 49 | ## Virtual Machine Operations 50 | 51 | ### **List Virtual Machines** 52 | 53 | ```javascript 54 | // Get all VMs in cluster 55 | const resources = await client.cluster.resources.resources(); 56 | for (const resource of resources.response.data) { 57 | if (resource.type === "qemu") { 58 | console.log(`VM ${resource.vmid}: ${resource.name} on ${resource.node} - ${resource.status}`); 59 | } 60 | } 61 | ``` 62 | 63 | ### **Get VM Configuration** 64 | 65 | ```javascript 66 | // Get VM configuration 67 | const vmConfig = await client.nodes.get("pve1").qemu.get(100).config.vmConfig(); 68 | const config = vmConfig.response.data; 69 | console.log(`VM Name: ${config.name}`); 70 | console.log(`Memory: ${config.memory} MB`); 71 | console.log(`CPU Cores: ${config.cores}`); 72 | console.log(`Boot Order: ${config.boot}`); 73 | ``` 74 | 75 | ### **VM Power Management** 76 | 77 | ```javascript 78 | const vm = client.nodes.get("pve1").qemu.get(100); 79 | 80 | // Start VM 81 | await vm.status.start.vmStart(); 82 | console.log("VM started successfully"); 83 | 84 | // Stop VM 85 | await vm.status.stop.vmStop(); 86 | console.log("VM stopped successfully"); 87 | 88 | // Restart VM 89 | await vm.status.reboot.vmReboot(); 90 | console.log("VM restarted successfully"); 91 | 92 | // Get current status 93 | const status = await vm.status.current.vmStatus(); 94 | console.log(`VM Status: ${status.response.data.status}`); 95 | console.log(`CPU Usage: ${(status.response.data.cpu * 100).toFixed(2)}%`); 96 | console.log(`Memory: ${(status.response.data.mem / status.response.data.maxmem * 100).toFixed(2)}%`); 97 | ``` 98 | 99 | ### **Snapshot Management** 100 | 101 | ```javascript 102 | const vm = client.nodes.get("pve1").qemu.get(100); 103 | 104 | // Create snapshot 105 | await vm.snapshot.snapshot("backup-2024", "Pre-update backup"); 106 | console.log("Snapshot created successfully"); 107 | 108 | // List snapshots 109 | const snapshots = await vm.snapshot.snapshotList(); 110 | console.log("Available snapshots:"); 111 | for (const snapshot of snapshots.response.data) { 112 | console.log(` - ${snapshot.name}: ${snapshot.description} (${snapshot.snaptime})`); 113 | } 114 | 115 | // Restore snapshot 116 | await vm.snapshot.get("backup-2024").rollback.rollbackVm(); 117 | console.log("Snapshot restored successfully"); 118 | 119 | // Delete snapshot 120 | await vm.snapshot.get("backup-2024").delSnapshot(); 121 | console.log("Snapshot deleted successfully"); 122 | ``` 123 | 124 | --- 125 | 126 | ## Container Operations 127 | 128 | ### **List Containers** 129 | 130 | ```javascript 131 | // Get all containers 132 | const resources = await client.cluster.resources.resources(); 133 | for (const resource of resources.response.data) { 134 | if (resource.type === "lxc") { 135 | console.log(`CT ${resource.vmid}: ${resource.name} on ${resource.node} - ${resource.status}`); 136 | } 137 | } 138 | ``` 139 | 140 | ### **Container Management** 141 | 142 | ```javascript 143 | const container = client.nodes.get("pve1").lxc.get(101); 144 | 145 | // Get container configuration 146 | const config = await container.config.vmConfig(); 147 | const ctConfig = config.response.data; 148 | console.log(`Container: ${ctConfig.hostname}`); 149 | console.log(`OS Template: ${ctConfig.ostemplate}`); 150 | console.log(`Memory: ${ctConfig.memory} MB`); 151 | 152 | // Start container 153 | await container.status.start.vmStart(); 154 | console.log("Container started"); 155 | 156 | // Get container status 157 | const status = await container.status.current.vmStatus(); 158 | console.log(`Status: ${status.response.data.status}`); 159 | console.log(`Uptime: ${status.response.data.uptime} seconds`); 160 | ``` 161 | 162 | --- 163 | 164 | ## Cluster Operations 165 | 166 | ### **Cluster Status** 167 | 168 | ```javascript 169 | // Get cluster status 170 | const clusterStatus = await client.cluster.status.status(); 171 | console.log("Cluster Status:"); 172 | for (const item of clusterStatus.response.data) { 173 | console.log(` ${item.type}: ${item.name} - ${item.status}`); 174 | } 175 | ``` 176 | 177 | ### **Node Information** 178 | 179 | ```javascript 180 | // Get all nodes 181 | const nodes = await client.nodes.index(); 182 | console.log("Available Nodes:"); 183 | for (const node of nodes.response.data) { 184 | console.log(` ${node.node}: ${node.status}`); 185 | console.log(` CPU: ${(node.cpu * 100).toFixed(2)}%`); 186 | console.log(` Memory: ${(node.mem / node.maxmem * 100).toFixed(2)}%`); 187 | console.log(` Uptime: ${Math.floor(node.uptime / 3600)}h ${Math.floor((node.uptime % 3600) / 60)}m`); 188 | } 189 | ``` 190 | 191 | ### **Storage Information** 192 | 193 | ```javascript 194 | // Get storage for a specific node 195 | const storages = await client.nodes.get("pve1").storage.index(); 196 | console.log("Available Storage:"); 197 | for (const storage of storages.response.data) { 198 | const usedPercent = storage.used / storage.total * 100; 199 | console.log(` ${storage.storage} (${storage.type}): ${usedPercent.toFixed(1)}% used`); 200 | console.log(` Total: ${(storage.total / (1024*1024*1024)).toFixed(2)} GB`); 201 | console.log(` Available: ${(storage.avail / (1024*1024*1024)).toFixed(2)} GB`); 202 | } 203 | ``` 204 | 205 | --- 206 | 207 | ## Common Patterns 208 | 209 | ### **Resource Monitoring** 210 | 211 | ```javascript 212 | async function monitorResources(client) { 213 | while (true) { 214 | const resources = await client.cluster.resources.resources(); 215 | 216 | console.clear(); // Note: This may not work in all environments 217 | console.log(`Proxmox VE Resource Monitor - ${new Date().toLocaleTimeString()}`); 218 | console.log("=".repeat(50)); 219 | 220 | // Group by type 221 | const nodes = resources.response.data.filter(r => r.type === "node"); 222 | const vms = resources.response.data.filter(r => r.type === "qemu"); 223 | const containers = resources.response.data.filter(r => r.type === "lxc"); 224 | 225 | console.log(`Nodes: ${nodes.length}`); 226 | for (const node of nodes) { 227 | console.log(` ${node.node}: CPU ${(node.cpu * 100).toFixed(1)}%, Memory ${((node.mem / node.maxmem) * 100).toFixed(1)}%`); 228 | } 229 | 230 | console.log(`\nVMs: ${vms.length} (${vms.filter(v => v.status === "running").length} running)`); 231 | console.log(`Containers: ${containers.length} (${containers.filter(c => c.status === "running").length} running)`); 232 | 233 | await new Promise(resolve => setTimeout(resolve, 5000)); // Update every 5 seconds 234 | } 235 | } 236 | ``` 237 | 238 | ### **Batch Operations** 239 | 240 | ```javascript 241 | async function batchVmOperation(client, vmIds, operation) { 242 | const results = []; 243 | 244 | for (const vmId of vmIds) { 245 | // Find VM location 246 | const resources = await client.cluster.resources.resources(); 247 | const vm = resources.response.data.find(r => r.type === "qemu" && r.vmid === vmId); 248 | 249 | if (vm) { 250 | const vmInstance = client.nodes.get(vm.node).qemu.get(vmId); 251 | 252 | let task; 253 | switch (operation.toLowerCase()) { 254 | case "start": 255 | task = vmInstance.status.start.vmStart(); 256 | break; 257 | case "stop": 258 | task = vmInstance.status.stop.vmStop(); 259 | break; 260 | case "restart": 261 | task = vmInstance.status.reboot.vmReboot(); 262 | break; 263 | default: 264 | throw new Error(`Unknown operation: ${operation}`); 265 | } 266 | 267 | await task; 268 | results.push({ vmId, success: true }); 269 | } 270 | } 271 | 272 | for (const result of results) { 273 | console.log(`VM ${result.vmId} ${operation}: ${result.success ? "Success" : "Failed"}`); 274 | } 275 | } 276 | ``` 277 | 278 | ### **Performance Monitoring** 279 | 280 | ```javascript 281 | async function getVmPerformance(client, node, vmId) { 282 | const vm = client.nodes.get(node).qemu.get(vmId); 283 | 284 | // Get current status 285 | const status = await vm.status.current.vmStatus(); 286 | const data = status.response.data; 287 | 288 | console.log(`VM ${vmId} Performance:`); 289 | console.log(` Status: ${data.status}`); 290 | console.log(` CPU Usage: ${(data.cpu * 100).toFixed(2)}%`); 291 | console.log(` Memory: ${formatBytes(data.mem)} / ${formatBytes(data.maxmem)} (${((data.mem / data.maxmem) * 100).toFixed(1)}%)`); 292 | console.log(` Disk Read: ${formatBytes(data.diskread)}`); 293 | console.log(` Disk Write: ${formatBytes(data.diskwrite)}`); 294 | console.log(` Network In: ${formatBytes(data.netin)}`); 295 | console.log(` Network Out: ${formatBytes(data.netout)}`); 296 | console.log(` Uptime: ${Math.floor(data.uptime / 60)}m ${data.uptime % 60}s`); 297 | } 298 | 299 | function formatBytes(bytes) { 300 | if (bytes === 0) return '0 Bytes'; 301 | const k = 1024; 302 | const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; 303 | const i = Math.floor(Math.log(bytes) / Math.log(k)); 304 | return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; 305 | } 306 | ``` 307 | 308 | --- 309 | 310 | ## Best Practices 311 | 312 | ### **Error Handling** 313 | 314 | ```javascript 315 | async function safeVmOperation(client, node, vmId, operation) { 316 | try { 317 | const vm = client.nodes.get(node).qemu.get(vmId); 318 | 319 | let result; 320 | switch (operation.toLowerCase()) { 321 | case "start": 322 | result = await vm.status.start.vmStart(); 323 | break; 324 | case "stop": 325 | result = await vm.status.stop.vmStop(); 326 | break; 327 | default: 328 | throw new Error(`Unknown operation: ${operation}`); 329 | } 330 | 331 | if (result.isSuccessStatusCode) { 332 | console.log(`VM ${vmId} ${operation} successful`); 333 | return true; 334 | } else { 335 | console.log(`VM ${vmId} ${operation} failed: ${result.reasonPhrase}`); 336 | return false; 337 | } 338 | } catch (error) { 339 | console.log(`Exception during ${operation} on VM ${vmId}: ${error.message}`); 340 | return false; 341 | } 342 | } 343 | ``` 344 | 345 | ### **Resource Discovery** 346 | 347 | ```javascript 348 | async function findVm(client, vmName) { 349 | const resources = await client.cluster.resources.resources(); 350 | const vm = resources.response.data.find(r => 351 | r.type === "qemu" && 352 | r.name && 353 | r.name.toLowerCase() === vmName.toLowerCase() 354 | ); 355 | 356 | return vm ? { node: vm.node, vmId: vm.vmid } : null; 357 | } 358 | 359 | // Usage 360 | const vmLocation = await findVm(client, "web-server"); 361 | if (vmLocation) { 362 | const { node, vmId } = vmLocation; 363 | const vm = client.nodes.get(node).qemu.get(vmId); 364 | // ... work with VM 365 | } 366 | ``` 367 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cv4pve-api-javascript 2 | 3 | ``` 4 | ______ _ __ 5 | / ____/___ __________(_)___ _ _____ _____/ /_ 6 | / / / __ \/ ___/ ___/ / __ \ | / / _ \/ ___/ __/ 7 | / /___/ /_/ / / (__ ) / / / / |/ / __(__ ) /_ 8 | \____/\____/_/ /____/_/_/ /_/|___/\___/____/\__/ 9 | 10 | Proxmox VE API Client for JavaScript/Node.js (Made in Italy) 11 | ``` 12 | 13 | [![License](https://img.shields.io/github/license/Corsinvest/cv4pve-api-javascript.svg?style=flat-square)](LICENSE) 14 | [![npm](https://img.shields.io/npm/v/@corsinvest/cv4pve-api-javascript?style=flat-square&logo=npm)](https://www.npmjs.com/package/@corsinvest/cv4pve-api-javascript) 15 | [![npm](https://img.shields.io/npm/dt/@corsinvest/cv4pve-api-javascript?style=flat-square&logo=npm)](https://www.npmjs.com/package/@corsinvest/cv4pve-api-javascript) 16 | 17 | 18 | --- 19 | 20 | ## Quick Start 21 | 22 | ```bash 23 | # Install the package 24 | npm install @corsinvest/cv4pve-api-javascript 25 | ``` 26 | 27 | ```javascript 28 | const { PveClient } = require("@corsinvest/cv4pve-api-javascript"); 29 | 30 | async function main() { 31 | const client = new PveClient("your-proxmox-host.com"); 32 | if (await client.login("root", "your-password")) { 33 | // Get cluster status 34 | const status = await client.cluster.status.status(); 35 | console.log(`Cluster: ${status.response.data[0].name}`); 36 | 37 | // Manage VMs 38 | const vm = await client.nodes.get("pve1").qemu.get(100).config.vmConfig(); 39 | console.log(`VM: ${vm.response.data.name}`); 40 | } 41 | } 42 | 43 | main(); 44 | ``` 45 | 46 | --- 47 | 48 | ## Key Features 49 | 50 | ### Developer Experience 51 | - **Async/Await** throughout the library 52 | - **Promise-based** API for modern JavaScript 53 | - **JSDoc comments** for IntelliSense support 54 | - **Auto-generated** from official API docs 55 | - **Tree structure** matching Proxmox VE API 56 | 57 | ### Core Functionality 58 | - **Full API coverage** for Proxmox VE 59 | - **VM/CT management** (create, configure, snapshot) 60 | - **Cluster operations** (status, resources, HA) 61 | - **Storage management** (local, shared, backup) 62 | - **Network configuration** (bridges, VLANs, SDN) 63 | 64 | ### Enterprise Ready 65 | - **API token** authentication (Proxmox VE 6.2+) 66 | - **Two-factor** authentication support 67 | - **Configurable timeouts** and retry logic 68 | - **Response type** switching (JSON, PNG) 69 | 70 | --- 71 | 72 | ## Documentation 73 | 74 | ### Getting Started 75 | 76 | - **[Authentication](./docs/authentication.md)** - API tokens and security 77 | - **[Basic Examples](./docs/examples.md)** - Common usage patterns 78 | - **[Advanced Usage](./docs/advanced.md)** - Complex scenarios and best practices 79 | - **[Common Issues](./docs/common-issues.md)** - Configuration patterns and troubleshooting 80 | 81 | ### API Reference 82 | 83 | - **[API Structure](./docs/apistructure.md)** - Understanding the tree structure 84 | - **[Result Handling](./docs/results.md)** - Working with responses 85 | - **[Error Handling](./docs/errorhandling.md)** - Exception management 86 | - **[Task Management](./docs/tasks.md)** - Long-running operations 87 | 88 | --- 89 | 90 | ## API Structure 91 | 92 | The library follows the exact structure of the [Proxmox VE API](https://pve.proxmox.com/pve-docs/api-viewer/): 93 | 94 | ```javascript 95 | // API Path: /cluster/status 96 | client.cluster.status.status() 97 | 98 | // API Path: /nodes/{node}/qemu/{vmid}/config 99 | client.nodes.get("pve1").qemu.get(100).config.vmConfig() 100 | 101 | // API Path: /nodes/{node}/lxc/{vmid}/snapshot 102 | client.nodes.get("pve1").lxc.get(101).snapshot.snapshot("snap-name") 103 | 104 | // API Path: /nodes/{node}/storage/{storage} 105 | client.nodes.get("pve1").storage.get("local").status() 106 | ``` 107 | 108 | ### HTTP Method Mapping 109 | 110 | | HTTP Method | JavaScript Method | Purpose | Example | 111 | |-------------|------------------|---------|---------| 112 | | `GET` | `await resource.get()` | Retrieve information | `await vm.config.vmConfig()` | 113 | | `POST` | `await resource.create(parameters)` | Create resources | `await vm.snapshot.snapshot("snap-name", "description")` | 114 | | `PUT` | `await resource.set(parameters)` | Update resources | `await vm.config.updateVm({memory: 4096})` | 115 | | `DELETE` | `await resource.delete()` | Remove resources | `await vm.deleteVm()` | 116 | 117 | > **Note:** Some endpoints also have specific method names like `vmConfig()`, `snapshot()`, etc. that map to the appropriate HTTP verbs. 118 | 119 | --- 120 | 121 | ## Authentication 122 | 123 | ### Username/Password Authentication 124 | 125 | ```javascript 126 | const { PveClient } = require("@corsinvest/cv4pve-api-javascript"); 127 | 128 | const client = new PveClient("pve.example.com"); 129 | 130 | // Basic login (defaults to PAM realm) 131 | const success = await client.login("root", "password"); 132 | 133 | // Login with specific realm 134 | const success = await client.login("admin", "password", "pve"); 135 | 136 | // Two-factor authentication 137 | const success = await client.login("root", "password", "pam", "123456"); 138 | ``` 139 | 140 | ### API Token Authentication (Recommended) 141 | 142 | ```javascript 143 | const { PveClient } = require("@corsinvest/cv4pve-api-javascript"); 144 | 145 | const client = new PveClient("pve.example.com"); 146 | 147 | // Set API token (Proxmox VE 6.2+) 148 | client.apiToken = "user@realm!tokenid=uuid"; 149 | 150 | // No login() call needed with API tokens 151 | const version = await client.version.version(); 152 | ``` 153 | 154 | ### Configuration 155 | 156 | ```javascript 157 | // Create client with custom port 158 | const client = new PveClient("pve.example.com", 8006); 159 | 160 | // Configure timeout (default: 30000ms = 30 seconds) 161 | client.timeout = 300000; // 5 minutes in milliseconds 162 | 163 | // Response type: "json" or "png" (for charts) 164 | client.responseType = "json"; 165 | 166 | // Enable debug logging 167 | client.logEnabled = true; 168 | ``` 169 | 170 | --- 171 | 172 | ## Working with Results 173 | 174 | Every API call returns a Result object containing comprehensive response information: 175 | 176 | ```javascript 177 | const result = await client.nodes.get("pve1").qemu.get(100).config.vmConfig(); 178 | 179 | // Check success 180 | if (result.isSuccessStatusCode) { 181 | // Access response data directly 182 | console.log(`VM Name: ${result.response.data.name}`); 183 | console.log(`Memory: ${result.response.data.memory}`); 184 | console.log(`Cores: ${result.response.data.cores}`); 185 | 186 | // Iterate through response data 187 | for (const [key, value] of Object.entries(result.response.data)) { 188 | console.log(`${key}: ${value}`); 189 | } 190 | } else { 191 | // Handle errors 192 | console.error(`Error: ${result.reasonPhrase}`); 193 | console.error(`Status: ${result.statusCode} - ${result.reasonPhrase}`); 194 | } 195 | ``` 196 | 197 | ### Result Properties 198 | 199 | ```javascript 200 | // Result object structure: 201 | { 202 | // Response data from Proxmox VE (JSON parsed or base64 image) 203 | response: { 204 | data: {}, // The actual API response data 205 | /* for JSON responses */ 206 | }, 207 | 208 | // HTTP response information 209 | isSuccessStatusCode: true, // Whether the request was successful (statusCode === 200) 210 | statusCode: 200, // HTTP status code 211 | reasonPhrase: "", // HTTP status message 212 | 213 | // Request information 214 | requestResource: "", // The API endpoint called 215 | requestParameters: {}, // Parameters sent 216 | methodType: "", // HTTP method used 217 | responseType: "", // "json" or "png" 218 | 219 | // Utility properties 220 | responseInError: false // Whether there's an error in the response 221 | } 222 | ``` 223 | 224 | --- 225 | 226 | ## Examples 227 | 228 | ### Virtual Machine Management 229 | 230 | ```javascript 231 | const { PveClient } = require("@corsinvest/cv4pve-api-javascript"); 232 | 233 | const client = new PveClient("pve.example.com"); 234 | await client.login("admin", "password", "pve"); 235 | 236 | // Get VM configuration 237 | const vm = client.nodes.get("pve1").qemu.get(100); 238 | const config = await vm.config.vmConfig(); 239 | 240 | const vmData = config.response.data; 241 | console.log(`VM Name: ${vmData.name}`); 242 | console.log(`Memory: ${vmData.memory} MB`); 243 | console.log(`CPUs: ${vmData.cores}`); 244 | 245 | // Update VM configuration 246 | const updateResult = await vm.config.updateVm({ 247 | memory: 8192, // 8GB RAM 248 | cores: 4 // 4 CPU cores 249 | }); 250 | 251 | console.log("VM configuration updated!"); 252 | 253 | // VM Status Management 254 | const status = await vm.status.current.vmStatus(); 255 | console.log(`Current status: ${status.response.data.status}`); 256 | 257 | // Start VM 258 | if (status.response.data.status === "stopped") { 259 | await vm.status.start.vmStart(); 260 | console.log("VM started successfully!"); 261 | } 262 | ``` 263 | 264 | ### Snapshot Management 265 | 266 | ```javascript 267 | const vm = client.nodes.get("pve1").qemu.get(100); 268 | 269 | // Create snapshot 270 | await vm.snapshot.snapshot("backup-before-update", "Pre-update backup"); 271 | console.log("Snapshot created successfully!"); 272 | 273 | // List snapshots 274 | const snapshots = await vm.snapshot.snapshotList(); 275 | console.log("Available snapshots:"); 276 | for (const snap of snapshots.response.data) { 277 | console.log(` - ${snap.name}: ${snap.description}`); 278 | } 279 | 280 | // Delete snapshot 281 | await vm.snapshot.get("backup-before-update").delSnapshot(); 282 | console.log("Snapshot deleted successfully!"); 283 | ``` 284 | 285 | ### Cluster Operations 286 | 287 | ```javascript 288 | // Get cluster status 289 | const clusterStatus = await client.cluster.status.status(); 290 | console.log("Cluster Status:"); 291 | for (const item of clusterStatus.response.data) { 292 | console.log(` ${item.type}: ${item.name} - ${item.status}`); 293 | } 294 | 295 | // Get cluster resources 296 | const resources = await client.cluster.resources.resources(); 297 | console.log("Cluster Resources:"); 298 | for (const resource of resources.response.data) { 299 | if (resource.type === "node") { 300 | console.log(` Node: ${resource.node} - CPU: ${(resource.cpu * 100).toFixed(2)}%`); 301 | } else if (resource.type === "qemu") { 302 | console.log(` VM: ${resource.vmid} (${resource.name}) - ${resource.status}`); 303 | } 304 | } 305 | ``` 306 | 307 | --- 308 | 309 | ## Task Management 310 | 311 | Long-running operations return task IDs that must be monitored: 312 | 313 | ```javascript 314 | // Create VM (returns task ID) 315 | const createResult = await client.nodes.get("pve1").qemu.createVm({ 316 | vmid: 999, 317 | name: "test-vm", 318 | memory: 2048 319 | }); 320 | 321 | const taskId = createResult.response.data; 322 | console.log(`Task started: ${taskId}`); 323 | 324 | // Monitor task progress 325 | while (true) { 326 | const taskStatus = await client.nodes.get("pve1").tasks.get(taskId).status.readTaskStatus(); 327 | const status = taskStatus.response.data.status; 328 | 329 | if (status === "stopped") { 330 | const exitStatus = taskStatus.response.data.exitstatus; 331 | console.log(`Task completed with status: ${exitStatus}`); 332 | break; 333 | } else if (status === "running") { 334 | console.log("Task still running..."); 335 | await new Promise(resolve => setTimeout(resolve, 2000)); 336 | } 337 | } 338 | ``` 339 | 340 | --- 341 | 342 | ## Error Handling 343 | 344 | ```javascript 345 | try { 346 | const result = await client.nodes.get("pve1").qemu.get(100).status.start.vmStart(); 347 | 348 | if (result.isSuccessStatusCode) { 349 | console.log("VM started successfully"); 350 | } else { 351 | console.error(`API error: ${result.statusCode} - ${result.reasonPhrase}`); 352 | } 353 | } catch (error) { 354 | // Network errors, timeouts, etc. 355 | if (error.code === 'ECONNREFUSED') { 356 | console.error("Cannot connect to Proxmox VE server"); 357 | } else if (error.message.includes('timeout')) { 358 | console.error("Request timed out"); 359 | } else { 360 | console.error(`Unexpected error: ${error.message}`); 361 | } 362 | } 363 | ``` 364 | 365 | --- 366 | 367 | ## Best Practices 368 | 369 | ### Recommended Patterns 370 | 371 | ```javascript 372 | // 1. Always check isSuccessStatusCode 373 | const result = await client.cluster.status.status(); 374 | if (result.isSuccessStatusCode) { 375 | // Process successful response 376 | processClusterStatus(result.response.data); 377 | } else { 378 | // Handle error appropriately 379 | console.error(`API call failed: ${result.reasonPhrase}`); 380 | } 381 | 382 | // 2. Use API tokens for automation 383 | const client = new PveClient("pve.cluster.com"); 384 | client.apiToken = process.env.PROXMOX_API_TOKEN; 385 | 386 | // 3. Configure timeouts for long operations 387 | client.timeout = 900000; // 15 minutes in milliseconds 388 | 389 | // 4. Use environment variables for credentials 390 | const success = await client.login( 391 | process.env.PROXMOX_USER, 392 | process.env.PROXMOX_PASS 393 | ); 394 | ``` 395 | 396 | ### Common Pitfalls to Avoid 397 | 398 | ```javascript 399 | // Don't ignore error handling 400 | const result = await client.nodes.get("pve1").qemu.get(100).status.start.vmStart(); 401 | // Missing: if (!result.isSuccessStatusCode) { ... } 402 | 403 | // Don't hardcode credentials 404 | await client.login("root", "password123"); // Bad! 405 | // Better: Use environment variables or secure storage 406 | 407 | // Don't assume response properties exist 408 | console.log(result.response.data.nonexistent); // May be undefined 409 | // Better: Check if property exists or use optional chaining 410 | const name = result.response.data?.name || "Unnamed"; 411 | ``` 412 | 413 | --- 414 | 415 | ## Support 416 | 417 | Professional support and consulting available through [Corsinvest](https://www.corsinvest.it/cv4pve). 418 | 419 | --- 420 | 421 | Part of [cv4pve](https://www.corsinvest.it/cv4pve) suite | Made with ❤️ in Italy by [Corsinvest](https://www.corsinvest.it) 422 | 423 | Copyright © Corsinvest Srl -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------