more docs

This commit is contained in:
Michel Roegl-Brunner 2025-10-10 11:36:32 +02:00
parent 7b71096991
commit ba90d60bf9
6 changed files with 2420 additions and 0 deletions

View File

@ -33,6 +33,15 @@ Comprehensive error handling and signal management for Proxmox Community Scripts
- Practical usage examples
- Integration with other components
### 📁 [api.func/](./api.func/)
Proxmox API integration and diagnostic reporting functionality for Community Scripts.
**Contents:**
- Visual execution flowcharts
- Complete function reference
- Practical usage examples
- Integration with other components
## Other Documentation
Additional miscellaneous documentation may be added here as the project grows.

View File

@ -0,0 +1,342 @@
# api.func Execution Flowchart
## Main API Communication Flow
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ API Communication Initialization │
│ Entry point when api.func functions are called by installation scripts │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Prerequisites Check │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ Prerequisites Validation │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Check curl │ │ Check │ │ Check │ │ │
│ │ │ Availability │ │ Diagnostics │ │ Random UUID │ │ │
│ │ │ │ │ Setting │ │ │ │
│ │ │ • command -v │ │ • DIAGNOSTICS │ │ • RANDOM_UUID │ │
│ │ │ curl │ │ = "yes" │ │ not empty │ │
│ │ │ • Return if │ │ • Return if │ │ • Return if │ │
│ │ │ not found │ │ disabled │ │ not set │ │
│ │ │ │ │ │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Data Collection │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ System Information Gathering │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Get PVE │ │ Collect │ │ Prepare JSON │ │ │
│ │ │ Version │ │ Environment │ │ Payload │ │
│ │ │ │ │ Variables │ │ │ │
│ │ │ • pveversion │ │ • CT_TYPE │ │ • Create JSON │ │
│ │ │ command │ │ • DISK_SIZE │ │ structure │ │
│ │ │ • Parse version │ │ • CORE_COUNT │ │ • Include all │ │
│ │ │ • Extract │ │ • RAM_SIZE │ │ variables │ │
│ │ │ major.minor │ │ • var_os │ │ • Format for API │ │
│ │ │ │ │ • var_version │ │ │ │
│ │ │ │ │ • NSAPP │ │ │ │
│ │ │ │ │ • METHOD │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ API Request Execution │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ HTTP Request Processing │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Prepare │ │ Execute │ │ Handle │ │ │
│ │ │ Request │ │ HTTP Request │ │ Response │ │
│ │ │ │ │ │ │ │ │
│ │ │ • Set API URL │ │ • curl -s -w │ │ • Capture HTTP │ │
│ │ │ • Set headers │ │ "%{http_code}" │ │ status code │ │
│ │ │ • Set payload │ │ • POST request │ │ • Store response │ │
│ │ │ • Content-Type │ │ • JSON data │ │ • Handle errors │ │
│ │ │ application/ │ │ • Follow │ │ gracefully │ │
│ │ │ json │ │ redirects │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
```
## LXC API Reporting Flow
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ POST_TO_API() Flow │
│ Send LXC container installation data to API │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ LXC Data Preparation │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ LXC-Specific Data Collection │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Set LXC │ │ Include LXC │ │ Set Status │ │ │
│ │ │ Type │ │ Variables │ │ Information │ │
│ │ │ │ │ │ │ │ │
│ │ │ • ct_type: 1 │ │ • DISK_SIZE │ │ • status: │ │
│ │ │ • type: "lxc" │ │ • CORE_COUNT │ │ "installing" │ │
│ │ │ • Include all │ │ • RAM_SIZE │ │ • Include all │ │
│ │ │ LXC data │ │ • var_os │ │ tracking data │ │
│ │ │ │ │ • var_version │ │ │ │
│ │ │ │ │ • DISABLEIP6 │ │ │ │
│ │ │ │ │ • NSAPP │ │ │ │
│ │ │ │ │ • METHOD │ │ │ │
│ │ │ │ │ • pve_version │ │ │ │
│ │ │ │ │ • random_id │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ JSON Payload Creation │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ JSON Structure Generation │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Create JSON │ │ Validate │ │ Format for │ │ │
│ │ │ Structure │ │ Data │ │ API Request │ │
│ │ │ │ │ │ │ │ │
│ │ │ • Use heredoc │ │ • Check all │ │ • Ensure proper │ │
│ │ │ syntax │ │ variables │ │ JSON format │ │
│ │ │ • Include all │ │ are set │ │ • Escape special │ │
│ │ │ required │ │ • Validate │ │ characters │ │
│ │ │ fields │ │ data types │ │ • Set content │ │
│ │ │ • Format │ │ • Handle │ │ type │ │
│ │ │ properly │ │ missing │ │ │ │
│ │ │ │ │ values │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
```
## VM API Reporting Flow
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ POST_TO_API_VM() Flow │
│ Send VM installation data to API │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ VM Data Preparation │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ VM-Specific Data Collection │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Check │ │ Set VM │ │ Process Disk │ │ │
│ │ │ Diagnostics │ │ Type │ │ Size │ │
│ │ │ File │ │ │ │ │ │
│ │ │ │ │ • ct_type: 2 │ │ • Remove 'G' │ │
│ │ │ • Check file │ │ • type: "vm" │ │ suffix │ │
│ │ │ existence │ │ • Include all │ │ • Convert to │ │
│ │ │ • Read │ │ VM data │ │ numeric value │ │
│ │ │ DIAGNOSTICS │ │ │ │ • Store in │ │
│ │ │ setting │ │ │ │ DISK_SIZE_API │ │
│ │ │ • Parse value │ │ │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ VM JSON Payload Creation │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ VM-Specific JSON Structure │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Include VM │ │ Set VM │ │ Format VM │ │ │
│ │ │ Variables │ │ Status │ │ Data for API │ │
│ │ │ │ │ │ │ │ │
│ │ │ • DISK_SIZE_API │ │ • status: │ │ • Ensure proper │ │
│ │ │ • CORE_COUNT │ │ "installing" │ │ JSON format │ │
│ │ │ • RAM_SIZE │ │ • Include all │ │ • Handle VM- │ │
│ │ │ • var_os │ │ tracking │ │ specific data │ │
│ │ │ • var_version │ │ information │ │ • Set appropriate │ │
│ │ │ • NSAPP │ │ │ │ content type │ │
│ │ │ • METHOD │ │ │ │ │ │
│ │ │ • pve_version │ │ │ │ │ │
│ │ │ • random_id │ │ │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
```
## Status Update Flow
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ POST_UPDATE_TO_API() Flow │
│ Send installation completion status to API │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Update Prevention Check │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ Duplicate Update Prevention │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Check │ │ Set Flag │ │ Return Early │ │ │
│ │ │ POST_UPDATE_ │ │ if First │ │ if Already │ │
│ │ │ DONE │ │ Update │ │ Updated │ │
│ │ │ │ │ │ │ │ │
│ │ │ • Check if │ │ • Set │ │ • Return 0 │ │
│ │ │ already │ │ POST_UPDATE_ │ │ • Skip API call │ │
│ │ │ updated │ │ DONE=true │ │ • Prevent │ │
│ │ │ • Prevent │ │ • Continue │ │ duplicate │ │
│ │ │ duplicate │ │ with update │ │ requests │ │
│ │ │ requests │ │ │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Status and Error Processing │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ Status Determination │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Determine │ │ Get Error │ │ Prepare Status │ │ │
│ │ │ Status │ │ Description │ │ Data │ │
│ │ │ │ │ │ │ │ │
│ │ │ • status: │ │ • Call │ │ • Include status │ │
│ │ │ "success" or │ │ get_error_ │ │ • Include error │ │
│ │ │ "failed" │ │ description() │ │ description │ │
│ │ │ • Set exit │ │ • Get human- │ │ • Include random │ │
│ │ │ code based │ │ readable │ │ ID for tracking │ │
│ │ │ on status │ │ error message │ │ │ │
│ │ │ • Default to │ │ • Handle │ │ │ │
│ │ │ error if │ │ unknown │ │ │ │
│ │ │ not set │ │ errors │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Status Update API Request │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ Status Update Payload Creation │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Create │ │ Send Status │ │ Mark Update │ │ │
│ │ │ Status JSON │ │ Update │ │ Complete │ │
│ │ │ │ │ │ │ │ │
│ │ │ • Include │ │ • POST to │ │ • Set │ │
│ │ │ status │ │ updatestatus │ │ POST_UPDATE_ │ │
│ │ │ • Include │ │ endpoint │ │ DONE=true │ │
│ │ │ error │ │ • Include JSON │ │ • Prevent further │ │
│ │ │ description │ │ payload │ │ updates │ │
│ │ │ • Include │ │ • Handle │ │ • Complete │ │
│ │ │ random_id │ │ response │ │ process │ │
│ │ │ │ │ gracefully │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
```
## Error Description Flow
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ GET_ERROR_DESCRIPTION() Flow │
│ Convert numeric exit codes to human-readable explanations │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Error Code Classification │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ Error Code Categories │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ General │ │ Network │ │ LXC-Specific │ │ │
│ │ │ System │ │ Errors │ │ Errors │ │
│ │ │ Errors │ │ │ │ │ │
│ │ │ │ │ • 18: Connection│ │ • 100-101: LXC │ │
│ │ │ • 0-9: Basic │ │ failed │ │ install errors │ │
│ │ │ errors │ │ • 22: Invalid │ │ • 200-209: LXC │ │
│ │ │ • 126-128: │ │ argument │ │ creation errors │ │
│ │ │ Command │ │ • 28: No space │ │ │ │
│ │ │ errors │ │ • 35: Timeout │ │ │ │
│ │ │ • 129-143: │ │ • 56: TLS error │ │ │ │
│ │ │ Signal │ │ • 60: SSL cert │ │ │ │
│ │ │ errors │ │ error │ │ │ │
│ │ │ • 152: Resource │ │ │ │ │ │
│ │ │ limit │ │ │ │ │ │
│ │ │ • 255: Unknown │ │ │ │ │ │
│ │ │ critical │ │ │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Error Message Return │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ Error Message Formatting │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Match Error │ │ Return │ │ Default Case │ │ │
│ │ │ Code │ │ Description │ │ │ │
│ │ │ │ │ │ │ │ │
│ │ │ • Use case │ │ • Return │ │ • Return "Unknown │ │
│ │ │ statement │ │ human- │ │ error code │ │
│ │ │ • Match │ │ readable │ │ (exit_code)" │ │
│ │ │ specific │ │ message │ │ • Handle │ │
│ │ │ codes │ │ • Include │ │ unrecognized │ │
│ │ │ • Handle │ │ context │ │ codes │ │
│ │ │ ranges │ │ information │ │ • Provide fallback │ │
│ │ │ │ │ │ │ message │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
```
## Integration Points
### With Installation Scripts
- **build.func**: Sends LXC installation data
- **vm-core.func**: Sends VM installation data
- **install.func**: Reports installation status
- **alpine-install.func**: Reports Alpine installation data
### With Error Handling
- **error_handler.func**: Provides error explanations
- **core.func**: Uses error descriptions in silent execution
- **Diagnostic reporting**: Tracks error patterns
### External Dependencies
- **curl**: HTTP client for API communication
- **Community Scripts API**: External API endpoint
- **Network connectivity**: Required for API communication

View File

@ -0,0 +1,433 @@
# api.func Functions Reference
## Overview
This document provides a comprehensive alphabetical reference of all functions in `api.func`, including parameters, dependencies, usage examples, and error handling.
## Function Categories
### Error Description Functions
#### `get_error_description()`
**Purpose**: Convert numeric exit codes to human-readable explanations
**Parameters**:
- `$1` - Exit code to explain
**Returns**: Human-readable error explanation string
**Side Effects**: None
**Dependencies**: None
**Environment Variables Used**: None
**Supported Exit Codes**:
- **General System**: 0-9, 18, 22, 28, 35, 56, 60, 125-128, 129-143, 152, 255
- **LXC-Specific**: 100-101, 200-209
- **Docker**: 125
**Usage Example**:
```bash
error_msg=$(get_error_description 127)
echo "Error 127: $error_msg"
# Output: Error 127: Command not found: Incorrect path or missing dependency.
```
**Error Code Examples**:
```bash
get_error_description 0 # " " (space)
get_error_description 1 # "General error: An unspecified error occurred."
get_error_description 127 # "Command not found: Incorrect path or missing dependency."
get_error_description 200 # "LXC creation failed."
get_error_description 255 # "Unknown critical error, often due to missing permissions or broken scripts."
```
### API Communication Functions
#### `post_to_api()`
**Purpose**: Send LXC container installation data to community-scripts.org API
**Parameters**: None (uses environment variables)
**Returns**: None
**Side Effects**:
- Sends HTTP POST request to API
- Stores response in RESPONSE variable
- Requires curl command and network connectivity
**Dependencies**: `curl` command
**Environment Variables Used**: `DIAGNOSTICS`, `RANDOM_UUID`, `CT_TYPE`, `DISK_SIZE`, `CORE_COUNT`, `RAM_SIZE`, `var_os`, `var_version`, `DISABLEIP6`, `NSAPP`, `METHOD`
**Prerequisites**:
- `curl` command must be available
- `DIAGNOSTICS` must be set to "yes"
- `RANDOM_UUID` must be set and not empty
**API Endpoint**: `http://api.community-scripts.org/dev/upload`
**JSON Payload Structure**:
```json
{
"ct_type": 1,
"type": "lxc",
"disk_size": 8,
"core_count": 2,
"ram_size": 2048,
"os_type": "debian",
"os_version": "12",
"disableip6": "true",
"nsapp": "plex",
"method": "install",
"pve_version": "8.0",
"status": "installing",
"random_id": "uuid-string"
}
```
**Usage Example**:
```bash
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
export CT_TYPE=1
export DISK_SIZE=8
export CORE_COUNT=2
export RAM_SIZE=2048
export var_os="debian"
export var_version="12"
export NSAPP="plex"
export METHOD="install"
post_to_api
```
#### `post_to_api_vm()`
**Purpose**: Send VM installation data to community-scripts.org API
**Parameters**: None (uses environment variables)
**Returns**: None
**Side Effects**:
- Sends HTTP POST request to API
- Stores response in RESPONSE variable
- Requires curl command and network connectivity
**Dependencies**: `curl` command, diagnostics file
**Environment Variables Used**: `DIAGNOSTICS`, `RANDOM_UUID`, `DISK_SIZE`, `CORE_COUNT`, `RAM_SIZE`, `var_os`, `var_version`, `NSAPP`, `METHOD`
**Prerequisites**:
- `/usr/local/community-scripts/diagnostics` file must exist
- `DIAGNOSTICS` must be set to "yes" in diagnostics file
- `curl` command must be available
- `RANDOM_UUID` must be set and not empty
**API Endpoint**: `http://api.community-scripts.org/dev/upload`
**JSON Payload Structure**:
```json
{
"ct_type": 2,
"type": "vm",
"disk_size": 8,
"core_count": 2,
"ram_size": 2048,
"os_type": "debian",
"os_version": "12",
"disableip6": "",
"nsapp": "plex",
"method": "install",
"pve_version": "8.0",
"status": "installing",
"random_id": "uuid-string"
}
```
**Usage Example**:
```bash
# Create diagnostics file
echo "DIAGNOSTICS=yes" > /usr/local/community-scripts/diagnostics
export RANDOM_UUID="$(uuidgen)"
export DISK_SIZE="8G"
export CORE_COUNT=2
export RAM_SIZE=2048
export var_os="debian"
export var_version="12"
export NSAPP="plex"
export METHOD="install"
post_to_api_vm
```
#### `post_update_to_api()`
**Purpose**: Send installation completion status to community-scripts.org API
**Parameters**:
- `$1` - Status ("success" or "failed", default: "failed")
- `$2` - Exit code (default: 1)
**Returns**: None
**Side Effects**:
- Sends HTTP POST request to API
- Sets POST_UPDATE_DONE=true to prevent duplicates
- Stores response in RESPONSE variable
**Dependencies**: `curl` command, `get_error_description()`
**Environment Variables Used**: `DIAGNOSTICS`, `RANDOM_UUID`
**Prerequisites**:
- `curl` command must be available
- `DIAGNOSTICS` must be set to "yes"
- `RANDOM_UUID` must be set and not empty
- POST_UPDATE_DONE must be false (prevents duplicates)
**API Endpoint**: `http://api.community-scripts.org/dev/upload/updatestatus`
**JSON Payload Structure**:
```json
{
"status": "success",
"error": "Error description from get_error_description()",
"random_id": "uuid-string"
}
```
**Usage Example**:
```bash
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
# Report successful installation
post_update_to_api "success" 0
# Report failed installation
post_update_to_api "failed" 127
```
## Function Call Hierarchy
### API Communication Flow
```
post_to_api()
├── Check curl availability
├── Check DIAGNOSTICS setting
├── Check RANDOM_UUID
├── Get PVE version
├── Create JSON payload
└── Send HTTP POST request
post_to_api_vm()
├── Check diagnostics file
├── Check curl availability
├── Check DIAGNOSTICS setting
├── Check RANDOM_UUID
├── Process disk size
├── Get PVE version
├── Create JSON payload
└── Send HTTP POST request
post_update_to_api()
├── Check POST_UPDATE_DONE flag
├── Check curl availability
├── Check DIAGNOSTICS setting
├── Check RANDOM_UUID
├── Determine status and exit code
├── Get error description
├── Create JSON payload
├── Send HTTP POST request
└── Set POST_UPDATE_DONE=true
```
### Error Description Flow
```
get_error_description()
├── Match exit code
├── Return appropriate description
└── Handle unknown codes
```
## Error Code Reference
### General System Errors
| Code | Description |
|------|-------------|
| 0 | (space) |
| 1 | General error: An unspecified error occurred. |
| 2 | Incorrect shell usage or invalid command arguments. |
| 3 | Unexecuted function or invalid shell condition. |
| 4 | Error opening a file or invalid path. |
| 5 | I/O error: An input/output failure occurred. |
| 6 | No such device or address. |
| 7 | Insufficient memory or resource exhaustion. |
| 8 | Non-executable file or invalid file format. |
| 9 | Failed child process execution. |
| 18 | Connection to a remote server failed. |
| 22 | Invalid argument or faulty network connection. |
| 28 | No space left on device. |
| 35 | Timeout while establishing a connection. |
| 56 | Faulty TLS connection. |
| 60 | SSL certificate error. |
### Command Execution Errors
| Code | Description |
|------|-------------|
| 125 | Docker error: Container could not start. |
| 126 | Command not executable: Incorrect permissions or missing dependencies. |
| 127 | Command not found: Incorrect path or missing dependency. |
| 128 | Invalid exit signal, e.g., incorrect Git command. |
### Signal Errors
| Code | Description |
|------|-------------|
| 129 | Signal 1 (SIGHUP): Process terminated due to hangup. |
| 130 | Signal 2 (SIGINT): Manual termination via Ctrl+C. |
| 132 | Signal 4 (SIGILL): Illegal machine instruction. |
| 133 | Signal 5 (SIGTRAP): Debugging error or invalid breakpoint signal. |
| 134 | Signal 6 (SIGABRT): Program aborted itself. |
| 135 | Signal 7 (SIGBUS): Memory error, invalid memory address. |
| 137 | Signal 9 (SIGKILL): Process forcibly terminated (OOM-killer or 'kill -9'). |
| 139 | Signal 11 (SIGSEGV): Segmentation fault, possibly due to invalid pointer access. |
| 141 | Signal 13 (SIGPIPE): Pipe closed unexpectedly. |
| 143 | Signal 15 (SIGTERM): Process terminated normally. |
| 152 | Signal 24 (SIGXCPU): CPU time limit exceeded. |
### LXC-Specific Errors
| Code | Description |
|------|-------------|
| 100 | LXC install error: Unexpected error in create_lxc.sh. |
| 101 | LXC install error: No network connection detected. |
| 200 | LXC creation failed. |
| 201 | LXC error: Invalid Storage class. |
| 202 | User aborted menu in create_lxc.sh. |
| 203 | CTID not set in create_lxc.sh. |
| 204 | PCT_OSTYPE not set in create_lxc.sh. |
| 205 | CTID cannot be less than 100 in create_lxc.sh. |
| 206 | CTID already in use in create_lxc.sh. |
| 207 | Template not found in create_lxc.sh. |
| 208 | Error downloading template in create_lxc.sh. |
| 209 | Container creation failed, but template is intact in create_lxc.sh. |
### Other Errors
| Code | Description |
|------|-------------|
| 255 | Unknown critical error, often due to missing permissions or broken scripts. |
| * | Unknown error code (exit_code). |
## Environment Variable Dependencies
### Required Variables
- **`DIAGNOSTICS`**: Enable/disable diagnostic reporting ("yes"/"no")
- **`RANDOM_UUID`**: Unique identifier for tracking
### Optional Variables
- **`CT_TYPE`**: Container type (1 for LXC, 2 for VM)
- **`DISK_SIZE`**: Disk size in GB (or GB with 'G' suffix for VM)
- **`CORE_COUNT`**: Number of CPU cores
- **`RAM_SIZE`**: RAM size in MB
- **`var_os`**: Operating system type
- **`var_version`**: OS version
- **`DISABLEIP6`**: IPv6 disable setting
- **`NSAPP`**: Namespace application name
- **`METHOD`**: Installation method
### Internal Variables
- **`POST_UPDATE_DONE`**: Prevents duplicate status updates
- **`API_URL`**: Community scripts API endpoint
- **`JSON_PAYLOAD`**: API request payload
- **`RESPONSE`**: API response
- **`DISK_SIZE_API`**: Processed disk size for VM API
## Error Handling Patterns
### API Communication Errors
- All API functions handle curl failures gracefully
- Network errors don't block installation process
- Missing prerequisites cause early return
- Duplicate updates are prevented
### Error Description Errors
- Unknown error codes return generic message
- All error codes are handled with case statement
- Fallback message includes the actual error code
### Prerequisites Validation
- Check curl availability before API calls
- Validate DIAGNOSTICS setting
- Ensure RANDOM_UUID is set
- Check for duplicate updates
## Integration Examples
### With build.func
```bash
#!/usr/bin/env bash
source core.func
source api.func
source build.func
# Set up API reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
# Report installation start
post_to_api
# Container creation...
# ... build.func code ...
# Report completion
if [[ $? -eq 0 ]]; then
post_update_to_api "success" 0
else
post_update_to_api "failed" $?
fi
```
### With vm-core.func
```bash
#!/usr/bin/env bash
source core.func
source api.func
source vm-core.func
# Set up API reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
# Report VM installation start
post_to_api_vm
# VM creation...
# ... vm-core.func code ...
# Report completion
post_update_to_api "success" 0
```
### With error_handler.func
```bash
#!/usr/bin/env bash
source core.func
source error_handler.func
source api.func
# Use error descriptions
error_code=127
error_msg=$(get_error_description $error_code)
echo "Error $error_code: $error_msg"
# Report error to API
post_update_to_api "failed" $error_code
```
## Best Practices
### API Usage
1. Always check prerequisites before API calls
2. Use unique identifiers for tracking
3. Handle API failures gracefully
4. Don't block installation on API failures
### Error Reporting
1. Use appropriate error codes
2. Provide meaningful error descriptions
3. Report both success and failure cases
4. Prevent duplicate status updates
### Diagnostic Reporting
1. Respect user privacy settings
2. Only send data when diagnostics enabled
3. Use anonymous tracking identifiers
4. Include relevant system information
### Error Handling
1. Handle unknown error codes gracefully
2. Provide fallback error messages
3. Include error code in unknown error messages
4. Use consistent error message format

View File

@ -0,0 +1,643 @@
# api.func Integration Guide
## Overview
This document describes how `api.func` integrates with other components in the Proxmox Community Scripts project, including dependencies, data flow, and API surface.
## Dependencies
### External Dependencies
#### Required Commands
- **`curl`**: HTTP client for API communication
- **`uuidgen`**: Generate unique identifiers (optional, can use other methods)
#### Optional Commands
- **None**: No other external command dependencies
### Internal Dependencies
#### Environment Variables from Other Scripts
- **build.func**: Provides container creation variables
- **vm-core.func**: Provides VM creation variables
- **core.func**: Provides system information variables
- **Installation scripts**: Provide application-specific variables
## Integration Points
### With build.func
#### LXC Container Reporting
```bash
# build.func uses api.func for container reporting
source core.func
source api.func
source build.func
# Set up API reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
# Container creation with API reporting
create_container() {
# Set container parameters
export CT_TYPE=1
export DISK_SIZE="$var_disk"
export CORE_COUNT="$var_cpu"
export RAM_SIZE="$var_ram"
export var_os="$var_os"
export var_version="$var_version"
export NSAPP="$APP"
export METHOD="install"
# Report installation start
post_to_api
# Container creation using build.func
# ... build.func container creation logic ...
# Report completion
if [[ $? -eq 0 ]]; then
post_update_to_api "success" 0
else
post_update_to_api "failed" $?
fi
}
```
#### Error Reporting Integration
```bash
# build.func uses api.func for error reporting
handle_container_error() {
local exit_code=$1
local error_msg=$(get_error_description $exit_code)
echo "Container creation failed: $error_msg"
post_update_to_api "failed" $exit_code
}
```
### With vm-core.func
#### VM Installation Reporting
```bash
# vm-core.func uses api.func for VM reporting
source core.func
source api.func
source vm-core.func
# Set up VM API reporting
mkdir -p /usr/local/community-scripts
echo "DIAGNOSTICS=yes" > /usr/local/community-scripts/diagnostics
export RANDOM_UUID="$(uuidgen)"
# VM creation with API reporting
create_vm() {
# Set VM parameters
export DISK_SIZE="${var_disk}G"
export CORE_COUNT="$var_cpu"
export RAM_SIZE="$var_ram"
export var_os="$var_os"
export var_version="$var_version"
export NSAPP="$APP"
export METHOD="install"
# Report VM installation start
post_to_api_vm
# VM creation using vm-core.func
# ... vm-core.func VM creation logic ...
# Report completion
post_update_to_api "success" 0
}
```
### With core.func
#### System Information Integration
```bash
# core.func provides system information for api.func
source core.func
source api.func
# Get system information for API reporting
get_system_info_for_api() {
# Get PVE version using core.func utilities
local pve_version=$(pveversion | awk -F'[/ ]' '{print $2}')
# Set API parameters
export var_os="$var_os"
export var_version="$var_version"
# Use core.func error handling with api.func reporting
if silent apt-get update; then
post_update_to_api "success" 0
else
post_update_to_api "failed" $?
fi
}
```
### With error_handler.func
#### Error Description Integration
```bash
# error_handler.func uses api.func for error descriptions
source core.func
source error_handler.func
source api.func
# Enhanced error handler with API reporting
enhanced_error_handler() {
local exit_code=${1:-$?}
local command=${2:-${BASH_COMMAND:-unknown}}
# Get error description from api.func
local error_msg=$(get_error_description $exit_code)
# Display error information
echo "Error $exit_code: $error_msg"
echo "Command: $command"
# Report error to API
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
post_update_to_api "failed" $exit_code
# Use standard error handler
error_handler $exit_code $command
}
```
### With install.func
#### Installation Process Reporting
```bash
# install.func uses api.func for installation reporting
source core.func
source api.func
source install.func
# Installation with API reporting
install_package_with_reporting() {
local package="$1"
# Set up API reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
export NSAPP="$package"
export METHOD="install"
# Report installation start
post_to_api
# Package installation using install.func
if install_package "$package"; then
echo "$package installed successfully"
post_update_to_api "success" 0
return 0
else
local exit_code=$?
local error_msg=$(get_error_description $exit_code)
echo "$package installation failed: $error_msg"
post_update_to_api "failed" $exit_code
return $exit_code
fi
}
```
### With alpine-install.func
#### Alpine Installation Reporting
```bash
# alpine-install.func uses api.func for Alpine reporting
source core.func
source api.func
source alpine-install.func
# Alpine installation with API reporting
install_alpine_with_reporting() {
local app="$1"
# Set up API reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
export NSAPP="$app"
export METHOD="install"
export var_os="alpine"
# Report Alpine installation start
post_to_api
# Alpine installation using alpine-install.func
if install_alpine_app "$app"; then
echo "Alpine $app installed successfully"
post_update_to_api "success" 0
return 0
else
local exit_code=$?
local error_msg=$(get_error_description $exit_code)
echo "Alpine $app installation failed: $error_msg"
post_update_to_api "failed" $exit_code
return $exit_code
fi
}
```
### With alpine-tools.func
#### Alpine Tools Reporting
```bash
# alpine-tools.func uses api.func for Alpine tools reporting
source core.func
source api.func
source alpine-tools.func
# Alpine tools with API reporting
run_alpine_tool_with_reporting() {
local tool="$1"
# Set up API reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
export NSAPP="alpine-tools"
export METHOD="tool"
# Report tool execution start
post_to_api
# Run Alpine tool using alpine-tools.func
if run_alpine_tool "$tool"; then
echo "Alpine tool $tool executed successfully"
post_update_to_api "success" 0
return 0
else
local exit_code=$?
local error_msg=$(get_error_description $exit_code)
echo "Alpine tool $tool failed: $error_msg"
post_update_to_api "failed" $exit_code
return $exit_code
fi
}
```
### With passthrough.func
#### Hardware Passthrough Reporting
```bash
# passthrough.func uses api.func for hardware reporting
source core.func
source api.func
source passthrough.func
# Hardware passthrough with API reporting
configure_passthrough_with_reporting() {
local hardware_type="$1"
# Set up API reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
export NSAPP="passthrough"
export METHOD="hardware"
# Report passthrough configuration start
post_to_api
# Configure passthrough using passthrough.func
if configure_passthrough "$hardware_type"; then
echo "Hardware passthrough configured successfully"
post_update_to_api "success" 0
return 0
else
local exit_code=$?
local error_msg=$(get_error_description $exit_code)
echo "Hardware passthrough failed: $error_msg"
post_update_to_api "failed" $exit_code
return $exit_code
fi
}
```
### With tools.func
#### Maintenance Operations Reporting
```bash
# tools.func uses api.func for maintenance reporting
source core.func
source api.func
source tools.func
# Maintenance operations with API reporting
run_maintenance_with_reporting() {
local operation="$1"
# Set up API reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
export NSAPP="maintenance"
export METHOD="tool"
# Report maintenance start
post_to_api
# Run maintenance using tools.func
if run_maintenance_operation "$operation"; then
echo "Maintenance operation $operation completed successfully"
post_update_to_api "success" 0
return 0
else
local exit_code=$?
local error_msg=$(get_error_description $exit_code)
echo "Maintenance operation $operation failed: $error_msg"
post_update_to_api "failed" $exit_code
return $exit_code
fi
}
```
## Data Flow
### Input Data
#### Environment Variables from Other Scripts
- **`CT_TYPE`**: Container type (1 for LXC, 2 for VM)
- **`DISK_SIZE`**: Disk size in GB
- **`CORE_COUNT`**: Number of CPU cores
- **`RAM_SIZE`**: RAM size in MB
- **`var_os`**: Operating system type
- **`var_version`**: OS version
- **`DISABLEIP6`**: IPv6 disable setting
- **`NSAPP`**: Namespace application name
- **`METHOD`**: Installation method
- **`DIAGNOSTICS`**: Enable/disable diagnostic reporting
- **`RANDOM_UUID`**: Unique identifier for tracking
#### Function Parameters
- **Exit codes**: Passed to `get_error_description()` and `post_update_to_api()`
- **Status information**: Passed to `post_update_to_api()`
- **API endpoints**: Hardcoded in functions
#### System Information
- **PVE version**: Retrieved from `pveversion` command
- **Disk size processing**: Processed for VM API (removes 'G' suffix)
- **Error codes**: Retrieved from command exit codes
### Processing Data
#### API Request Preparation
- **JSON payload creation**: Format data for API consumption
- **Data validation**: Ensure required fields are present
- **Error handling**: Handle missing or invalid data
- **Content type setting**: Set appropriate HTTP headers
#### Error Processing
- **Error code mapping**: Map numeric codes to descriptions
- **Error message formatting**: Format error descriptions
- **Unknown error handling**: Handle unrecognized error codes
- **Fallback messages**: Provide default error messages
#### API Communication
- **HTTP request preparation**: Prepare curl commands
- **Response handling**: Capture HTTP response codes
- **Error handling**: Handle network and API errors
- **Duplicate prevention**: Prevent duplicate status updates
### Output Data
#### API Communication
- **HTTP requests**: Sent to community-scripts.org API
- **Response codes**: Captured from API responses
- **Error information**: Reported to API
- **Status updates**: Sent to API
#### Error Information
- **Error descriptions**: Human-readable error messages
- **Error codes**: Mapped to descriptions
- **Context information**: Error context and details
- **Fallback messages**: Default error messages
#### System State
- **POST_UPDATE_DONE**: Prevents duplicate updates
- **RESPONSE**: Stores API response
- **JSON_PAYLOAD**: Stores formatted API data
- **API_URL**: Stores API endpoint
## API Surface
### Public Functions
#### Error Description
- **`get_error_description()`**: Convert exit codes to explanations
- **Parameters**: Exit code to explain
- **Returns**: Human-readable explanation string
- **Usage**: Called by other functions and scripts
#### API Communication
- **`post_to_api()`**: Send LXC installation data
- **`post_to_api_vm()`**: Send VM installation data
- **`post_update_to_api()`**: Send status updates
- **Parameters**: Status and exit code (for updates)
- **Returns**: None
- **Usage**: Called by installation scripts
### Internal Functions
#### None
- All functions in api.func are public
- No internal helper functions
- Direct implementation of all functionality
### Global Variables
#### Configuration Variables
- **`DIAGNOSTICS`**: Diagnostic reporting setting
- **`RANDOM_UUID`**: Unique tracking identifier
- **`POST_UPDATE_DONE`**: Duplicate update prevention
#### Data Variables
- **`CT_TYPE`**: Container type
- **`DISK_SIZE`**: Disk size
- **`CORE_COUNT`**: CPU core count
- **`RAM_SIZE`**: RAM size
- **`var_os`**: Operating system
- **`var_version`**: OS version
- **`DISABLEIP6`**: IPv6 setting
- **`NSAPP`**: Application namespace
- **`METHOD`**: Installation method
#### Internal Variables
- **`API_URL`**: API endpoint URL
- **`JSON_PAYLOAD`**: API request payload
- **`RESPONSE`**: API response
- **`DISK_SIZE_API`**: Processed disk size for VM API
## Integration Patterns
### Standard Integration Pattern
```bash
#!/usr/bin/env bash
# Standard integration pattern
# 1. Source core.func first
source core.func
# 2. Source api.func
source api.func
# 3. Set up API reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
# 4. Set application parameters
export NSAPP="$APP"
export METHOD="install"
# 5. Report installation start
post_to_api
# 6. Perform installation
# ... installation logic ...
# 7. Report completion
post_update_to_api "success" 0
```
### Minimal Integration Pattern
```bash
#!/usr/bin/env bash
# Minimal integration pattern
source api.func
# Basic error reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
# Report failure
post_update_to_api "failed" 127
```
### Advanced Integration Pattern
```bash
#!/usr/bin/env bash
# Advanced integration pattern
source core.func
source api.func
source error_handler.func
# Set up comprehensive API reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
export CT_TYPE=1
export DISK_SIZE=8
export CORE_COUNT=2
export RAM_SIZE=2048
export var_os="debian"
export var_version="12"
export METHOD="install"
# Enhanced error handling with API reporting
enhanced_error_handler() {
local exit_code=${1:-$?}
local command=${2:-${BASH_COMMAND:-unknown}}
local error_msg=$(get_error_description $exit_code)
echo "Error $exit_code: $error_msg"
post_update_to_api "failed" $exit_code
error_handler $exit_code $command
}
trap 'enhanced_error_handler' ERR
# Advanced operations with API reporting
post_to_api
# ... operations ...
post_update_to_api "success" 0
```
## Error Handling Integration
### Automatic Error Reporting
- **Error Descriptions**: Provides human-readable error messages
- **API Integration**: Reports errors to community-scripts.org API
- **Error Tracking**: Tracks error patterns for project improvement
- **Diagnostic Data**: Contributes to anonymous usage analytics
### Manual Error Reporting
- **Custom Error Codes**: Use appropriate error codes for different scenarios
- **Error Context**: Provide context information for errors
- **Status Updates**: Report both success and failure cases
- **Error Analysis**: Analyze error patterns and trends
### API Communication Errors
- **Network Failures**: Handle API communication failures gracefully
- **Missing Prerequisites**: Check prerequisites before API calls
- **Duplicate Prevention**: Prevent duplicate status updates
- **Error Recovery**: Handle API errors without blocking installation
## Performance Considerations
### API Communication Overhead
- **Minimal Impact**: API calls add minimal overhead
- **Asynchronous**: API calls don't block installation process
- **Error Handling**: API failures don't affect installation
- **Optional**: API reporting is optional and can be disabled
### Memory Usage
- **Minimal Footprint**: API functions use minimal memory
- **Variable Reuse**: Global variables reused across functions
- **No Memory Leaks**: Proper cleanup prevents memory leaks
- **Efficient Processing**: Efficient JSON payload creation
### Execution Speed
- **Fast API Calls**: Quick API communication
- **Efficient Error Processing**: Fast error code processing
- **Minimal Delay**: Minimal delay in API operations
- **Non-blocking**: API calls don't block installation
## Security Considerations
### Data Privacy
- **Anonymous Reporting**: Only anonymous data is sent
- **No Sensitive Data**: No sensitive information is transmitted
- **User Control**: Users can disable diagnostic reporting
- **Data Minimization**: Only necessary data is sent
### API Security
- **HTTPS**: API communication uses secure protocols
- **Data Validation**: API data is validated before sending
- **Error Handling**: API errors are handled securely
- **No Credentials**: No authentication credentials are sent
### Network Security
- **Secure Communication**: Uses secure HTTP protocols
- **Error Handling**: Network errors are handled gracefully
- **No Data Leakage**: No sensitive data is leaked
- **Secure Endpoints**: Uses trusted API endpoints
## Future Integration Considerations
### Extensibility
- **New API Endpoints**: Easy to add new API endpoints
- **Additional Data**: Easy to add new data fields
- **Error Codes**: Easy to add new error code descriptions
- **API Versions**: Easy to support new API versions
### Compatibility
- **API Versioning**: Compatible with different API versions
- **Data Format**: Compatible with different data formats
- **Error Codes**: Compatible with different error code systems
- **Network Protocols**: Compatible with different network protocols
### Performance
- **Optimization**: API communication can be optimized
- **Caching**: API responses can be cached
- **Batch Operations**: Multiple operations can be batched
- **Async Processing**: API calls can be made asynchronous

View File

@ -0,0 +1,794 @@
# api.func Usage Examples
## Overview
This document provides practical usage examples for `api.func` functions, covering common scenarios, integration patterns, and best practices.
## Basic API Setup
### Standard API Initialization
```bash
#!/usr/bin/env bash
# Standard API setup for LXC containers
source api.func
# Set up diagnostic reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
# Set container parameters
export CT_TYPE=1
export DISK_SIZE=8
export CORE_COUNT=2
export RAM_SIZE=2048
export var_os="debian"
export var_version="12"
export NSAPP="plex"
export METHOD="install"
# Report installation start
post_to_api
# Your installation code here
# ... installation logic ...
# Report completion
if [[ $? -eq 0 ]]; then
post_update_to_api "success" 0
else
post_update_to_api "failed" $?
fi
```
### VM API Setup
```bash
#!/usr/bin/env bash
# API setup for VMs
source api.func
# Create diagnostics file for VM
mkdir -p /usr/local/community-scripts
echo "DIAGNOSTICS=yes" > /usr/local/community-scripts/diagnostics
# Set up VM parameters
export RANDOM_UUID="$(uuidgen)"
export DISK_SIZE="20G"
export CORE_COUNT=4
export RAM_SIZE=4096
export var_os="ubuntu"
export var_version="22.04"
export NSAPP="nextcloud"
export METHOD="install"
# Report VM installation start
post_to_api_vm
# Your VM installation code here
# ... VM creation logic ...
# Report completion
post_update_to_api "success" 0
```
## Error Description Examples
### Basic Error Explanation
```bash
#!/usr/bin/env bash
source api.func
# Explain common error codes
echo "Error 0: '$(get_error_description 0)'"
echo "Error 1: $(get_error_description 1)"
echo "Error 127: $(get_error_description 127)"
echo "Error 200: $(get_error_description 200)"
echo "Error 255: $(get_error_description 255)"
```
### Error Code Testing
```bash
#!/usr/bin/env bash
source api.func
# Test all error codes
test_error_codes() {
local codes=(0 1 2 127 128 130 137 139 143 200 203 205 255)
for code in "${codes[@]}"; do
echo "Code $code: $(get_error_description $code)"
done
}
test_error_codes
```
### Error Handling with Descriptions
```bash
#!/usr/bin/env bash
source api.func
# Function with error handling
run_command_with_error_handling() {
local command="$1"
local description="$2"
echo "Running: $description"
if $command; then
echo "Success: $description"
return 0
else
local exit_code=$?
local error_msg=$(get_error_description $exit_code)
echo "Error $exit_code: $error_msg"
return $exit_code
fi
}
# Usage
run_command_with_error_handling "apt-get update" "Package list update"
run_command_with_error_handling "nonexistent_command" "Test command"
```
## API Communication Examples
### LXC Installation Reporting
```bash
#!/usr/bin/env bash
source api.func
# Complete LXC installation with API reporting
install_lxc_with_reporting() {
local app="$1"
local ctid="$2"
# Set up API reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
export CT_TYPE=1
export DISK_SIZE=10
export CORE_COUNT=2
export RAM_SIZE=2048
export var_os="debian"
export var_version="12"
export NSAPP="$app"
export METHOD="install"
# Report installation start
post_to_api
# Installation process
echo "Installing $app container (ID: $ctid)..."
# Simulate installation
sleep 2
# Check if installation succeeded
if [[ $? -eq 0 ]]; then
echo "Installation completed successfully"
post_update_to_api "success" 0
return 0
else
echo "Installation failed"
post_update_to_api "failed" $?
return 1
fi
}
# Install multiple containers
install_lxc_with_reporting "plex" "100"
install_lxc_with_reporting "nextcloud" "101"
install_lxc_with_reporting "nginx" "102"
```
### VM Installation Reporting
```bash
#!/usr/bin/env bash
source api.func
# Complete VM installation with API reporting
install_vm_with_reporting() {
local app="$1"
local vmid="$2"
# Create diagnostics file
mkdir -p /usr/local/community-scripts
echo "DIAGNOSTICS=yes" > /usr/local/community-scripts/diagnostics
# Set up API reporting
export RANDOM_UUID="$(uuidgen)"
export DISK_SIZE="20G"
export CORE_COUNT=4
export RAM_SIZE=4096
export var_os="ubuntu"
export var_version="22.04"
export NSAPP="$app"
export METHOD="install"
# Report VM installation start
post_to_api_vm
# VM installation process
echo "Installing $app VM (ID: $vmid)..."
# Simulate VM creation
sleep 3
# Check if VM creation succeeded
if [[ $? -eq 0 ]]; then
echo "VM installation completed successfully"
post_update_to_api "success" 0
return 0
else
echo "VM installation failed"
post_update_to_api "failed" $?
return 1
fi
}
# Install multiple VMs
install_vm_with_reporting "nextcloud" "200"
install_vm_with_reporting "wordpress" "201"
```
## Status Update Examples
### Success Reporting
```bash
#!/usr/bin/env bash
source api.func
# Report successful installation
report_success() {
local operation="$1"
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
echo "Reporting successful $operation"
post_update_to_api "success" 0
}
# Usage
report_success "container installation"
report_success "package installation"
report_success "service configuration"
```
### Failure Reporting
```bash
#!/usr/bin/env bash
source api.func
# Report failed installation
report_failure() {
local operation="$1"
local exit_code="$2"
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
local error_msg=$(get_error_description $exit_code)
echo "Reporting failed $operation: $error_msg"
post_update_to_api "failed" $exit_code
}
# Usage
report_failure "container creation" 200
report_failure "package installation" 127
report_failure "service start" 1
```
### Conditional Status Reporting
```bash
#!/usr/bin/env bash
source api.func
# Conditional status reporting
report_installation_status() {
local operation="$1"
local exit_code="$2"
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
if [[ $exit_code -eq 0 ]]; then
echo "Reporting successful $operation"
post_update_to_api "success" 0
else
local error_msg=$(get_error_description $exit_code)
echo "Reporting failed $operation: $error_msg"
post_update_to_api "failed" $exit_code
fi
}
# Usage
report_installation_status "container creation" 0
report_installation_status "package installation" 127
```
## Advanced Usage Examples
### Batch Installation with API Reporting
```bash
#!/usr/bin/env bash
source api.func
# Batch installation with comprehensive API reporting
batch_install_with_reporting() {
local apps=("plex" "nextcloud" "nginx" "mysql")
local ctids=(100 101 102 103)
# Set up API reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
export CT_TYPE=1
export DISK_SIZE=8
export CORE_COUNT=2
export RAM_SIZE=2048
export var_os="debian"
export var_version="12"
export METHOD="install"
local success_count=0
local failure_count=0
for i in "${!apps[@]}"; do
local app="${apps[$i]}"
local ctid="${ctids[$i]}"
echo "Installing $app (ID: $ctid)..."
# Set app-specific parameters
export NSAPP="$app"
# Report installation start
post_to_api
# Simulate installation
if install_app "$app" "$ctid"; then
echo "$app installed successfully"
post_update_to_api "success" 0
((success_count++))
else
echo "$app installation failed"
post_update_to_api "failed" $?
((failure_count++))
fi
echo "---"
done
echo "Batch installation completed: $success_count successful, $failure_count failed"
}
# Mock installation function
install_app() {
local app="$1"
local ctid="$2"
# Simulate installation
sleep 1
# Simulate occasional failures
if [[ $((RANDOM % 10)) -eq 0 ]]; then
return 1
fi
return 0
}
batch_install_with_reporting
```
### Error Analysis and Reporting
```bash
#!/usr/bin/env bash
source api.func
# Analyze and report errors
analyze_and_report_errors() {
local log_file="$1"
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
if [[ ! -f "$log_file" ]]; then
echo "Log file not found: $log_file"
return 1
fi
# Extract error codes from log
local error_codes=$(grep -o 'exit code [0-9]\+' "$log_file" | grep -o '[0-9]\+' | sort -u)
if [[ -z "$error_codes" ]]; then
echo "No errors found in log"
post_update_to_api "success" 0
return 0
fi
echo "Found error codes: $error_codes"
# Report each unique error
for code in $error_codes; do
local error_msg=$(get_error_description $code)
echo "Error $code: $error_msg"
post_update_to_api "failed" $code
done
}
# Usage
analyze_and_report_errors "/var/log/installation.log"
```
### API Health Check
```bash
#!/usr/bin/env bash
source api.func
# Check API connectivity and functionality
check_api_health() {
echo "Checking API health..."
# Test prerequisites
if ! command -v curl >/dev/null 2>&1; then
echo "ERROR: curl not available"
return 1
fi
# Test error description function
local test_error=$(get_error_description 127)
if [[ -z "$test_error" ]]; then
echo "ERROR: Error description function not working"
return 1
fi
echo "Error description test: $test_error"
# Test API connectivity (without sending data)
local api_url="http://api.community-scripts.org/dev/upload"
if curl -s --head "$api_url" >/dev/null 2>&1; then
echo "API endpoint is reachable"
else
echo "WARNING: API endpoint not reachable"
fi
echo "API health check completed"
}
check_api_health
```
## Integration Examples
### With build.func
```bash
#!/usr/bin/env bash
# Integration with build.func
source core.func
source api.func
source build.func
# Set up API reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
# Container creation with API reporting
create_container_with_reporting() {
local app="$1"
local ctid="$2"
# Set container parameters
export APP="$app"
export CTID="$ctid"
export var_hostname="${app}-server"
export var_os="debian"
export var_version="12"
export var_cpu="2"
export var_ram="2048"
export var_disk="10"
export var_net="vmbr0"
export var_gateway="192.168.1.1"
export var_ip="192.168.1.$ctid"
export var_template_storage="local"
export var_container_storage="local"
# Report installation start
post_to_api
# Create container using build.func
if source build.func; then
echo "Container $app created successfully"
post_update_to_api "success" 0
return 0
else
echo "Container $app creation failed"
post_update_to_api "failed" $?
return 1
fi
}
# Create containers
create_container_with_reporting "plex" "100"
create_container_with_reporting "nextcloud" "101"
```
### With vm-core.func
```bash
#!/usr/bin/env bash
# Integration with vm-core.func
source core.func
source api.func
source vm-core.func
# Set up VM API reporting
mkdir -p /usr/local/community-scripts
echo "DIAGNOSTICS=yes" > /usr/local/community-scripts/diagnostics
export RANDOM_UUID="$(uuidgen)"
# VM creation with API reporting
create_vm_with_reporting() {
local app="$1"
local vmid="$2"
# Set VM parameters
export APP="$app"
export VMID="$vmid"
export var_hostname="${app}-vm"
export var_os="ubuntu"
export var_version="22.04"
export var_cpu="4"
export var_ram="4096"
export var_disk="20"
# Report VM installation start
post_to_api_vm
# Create VM using vm-core.func
if source vm-core.func; then
echo "VM $app created successfully"
post_update_to_api "success" 0
return 0
else
echo "VM $app creation failed"
post_update_to_api "failed" $?
return 1
fi
}
# Create VMs
create_vm_with_reporting "nextcloud" "200"
create_vm_with_reporting "wordpress" "201"
```
### With error_handler.func
```bash
#!/usr/bin/env bash
# Integration with error_handler.func
source core.func
source error_handler.func
source api.func
# Enhanced error handling with API reporting
enhanced_error_handler() {
local exit_code=${1:-$?}
local command=${2:-${BASH_COMMAND:-unknown}}
# Get error description from api.func
local error_msg=$(get_error_description $exit_code)
# Display error information
echo "Error $exit_code: $error_msg"
echo "Command: $command"
# Report error to API
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
post_update_to_api "failed" $exit_code
# Use standard error handler
error_handler $exit_code $command
}
# Set up enhanced error handling
trap 'enhanced_error_handler' ERR
# Test enhanced error handling
nonexistent_command
```
## Best Practices Examples
### Comprehensive API Integration
```bash
#!/usr/bin/env bash
# Comprehensive API integration example
source core.func
source api.func
# Set up comprehensive API reporting
setup_api_reporting() {
# Enable diagnostics
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
# Set common parameters
export CT_TYPE=1
export DISK_SIZE=8
export CORE_COUNT=2
export RAM_SIZE=2048
export var_os="debian"
export var_version="12"
export METHOD="install"
echo "API reporting configured"
}
# Installation with comprehensive reporting
install_with_comprehensive_reporting() {
local app="$1"
local ctid="$2"
# Set up API reporting
setup_api_reporting
export NSAPP="$app"
# Report installation start
post_to_api
# Installation process
echo "Installing $app..."
# Simulate installation steps
local steps=("Downloading" "Installing" "Configuring" "Starting")
for step in "${steps[@]}"; do
echo "$step $app..."
sleep 1
done
# Check installation result
if [[ $? -eq 0 ]]; then
echo "$app installation completed successfully"
post_update_to_api "success" 0
return 0
else
echo "$app installation failed"
post_update_to_api "failed" $?
return 1
fi
}
# Install multiple applications
apps=("plex" "nextcloud" "nginx" "mysql")
ctids=(100 101 102 103)
for i in "${!apps[@]}"; do
install_with_comprehensive_reporting "${apps[$i]}" "${ctids[$i]}"
echo "---"
done
```
### Error Recovery with API Reporting
```bash
#!/usr/bin/env bash
source api.func
# Error recovery with API reporting
retry_with_api_reporting() {
local operation="$1"
local max_attempts=3
local attempt=1
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
while [[ $attempt -le $max_attempts ]]; do
echo "Attempt $attempt of $max_attempts: $operation"
if $operation; then
echo "Operation succeeded on attempt $attempt"
post_update_to_api "success" 0
return 0
else
local exit_code=$?
local error_msg=$(get_error_description $exit_code)
echo "Attempt $attempt failed: $error_msg"
post_update_to_api "failed" $exit_code
((attempt++))
if [[ $attempt -le $max_attempts ]]; then
echo "Retrying in 5 seconds..."
sleep 5
fi
fi
done
echo "Operation failed after $max_attempts attempts"
return 1
}
# Usage
retry_with_api_reporting "apt-get update"
retry_with_api_reporting "apt-get install -y package"
```
### API Reporting with Logging
```bash
#!/usr/bin/env bash
source api.func
# API reporting with detailed logging
install_with_logging_and_api() {
local app="$1"
local log_file="/var/log/${app}_installation.log"
# Set up API reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
export NSAPP="$app"
# Start logging
exec > >(tee -a "$log_file")
exec 2>&1
echo "Starting $app installation at $(date)"
# Report installation start
post_to_api
# Installation process
echo "Installing $app..."
# Simulate installation
if install_app "$app"; then
echo "$app installation completed successfully at $(date)"
post_update_to_api "success" 0
return 0
else
local exit_code=$?
local error_msg=$(get_error_description $exit_code)
echo "$app installation failed at $(date): $error_msg"
post_update_to_api "failed" $exit_code
return $exit_code
fi
}
# Mock installation function
install_app() {
local app="$1"
echo "Installing $app..."
sleep 2
return 0
}
# Install with logging and API reporting
install_with_logging_and_api "plex"
```

View File

@ -0,0 +1,199 @@
# api.func Documentation
## Overview
The `api.func` file provides Proxmox API integration and diagnostic reporting functionality for the Community Scripts project. It handles API communication, error reporting, and status updates to the community-scripts.org API.
## Purpose and Use Cases
- **API Communication**: Send installation and status data to community-scripts.org API
- **Diagnostic Reporting**: Report installation progress and errors for analytics
- **Error Description**: Provide detailed error code explanations
- **Status Updates**: Track installation success/failure status
- **Analytics**: Contribute anonymous usage data for project improvement
## Quick Reference
### Key Function Groups
- **Error Handling**: `get_error_description()` - Convert exit codes to human-readable messages
- **API Communication**: `post_to_api()`, `post_to_api_vm()` - Send installation data
- **Status Updates**: `post_update_to_api()` - Report installation completion status
### Dependencies
- **External**: `curl` command for HTTP requests
- **Internal**: Uses environment variables from other scripts
### Integration Points
- Used by: All installation scripts for diagnostic reporting
- Uses: Environment variables from build.func and other scripts
- Provides: API communication and error reporting services
## Documentation Files
### 📊 [API_FLOWCHART.md](./API_FLOWCHART.md)
Visual execution flows showing API communication processes and error handling.
### 📚 [API_FUNCTIONS_REFERENCE.md](./API_FUNCTIONS_REFERENCE.md)
Complete alphabetical reference of all functions with parameters, dependencies, and usage details.
### 💡 [API_USAGE_EXAMPLES.md](./API_USAGE_EXAMPLES.md)
Practical examples showing how to use API functions and common patterns.
### 🔗 [API_INTEGRATION.md](./API_INTEGRATION.md)
How api.func integrates with other components and provides API services.
## Key Features
### Error Code Descriptions
- **Comprehensive Coverage**: 50+ error codes with detailed explanations
- **LXC-Specific Errors**: Container creation and management errors
- **System Errors**: General system and network errors
- **Signal Errors**: Process termination and signal errors
### API Communication
- **LXC Reporting**: Send LXC container installation data
- **VM Reporting**: Send VM installation data
- **Status Updates**: Report installation success/failure
- **Diagnostic Data**: Anonymous usage analytics
### Diagnostic Integration
- **Optional Reporting**: Only sends data when diagnostics enabled
- **Privacy Respect**: Respects user privacy settings
- **Error Tracking**: Tracks installation errors for improvement
- **Usage Analytics**: Contributes to project statistics
## Common Usage Patterns
### Basic API Setup
```bash
#!/usr/bin/env bash
# Basic API setup
source api.func
# Set up diagnostic reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
# Report installation start
post_to_api
```
### Error Reporting
```bash
#!/usr/bin/env bash
source api.func
# Get error description
error_msg=$(get_error_description 127)
echo "Error 127: $error_msg"
# Output: Error 127: Command not found: Incorrect path or missing dependency.
```
### Status Updates
```bash
#!/usr/bin/env bash
source api.func
# Report successful installation
post_update_to_api "success" 0
# Report failed installation
post_update_to_api "failed" 127
```
## Environment Variables
### Required Variables
- `DIAGNOSTICS`: Enable/disable diagnostic reporting ("yes"/"no")
- `RANDOM_UUID`: Unique identifier for tracking
### Optional Variables
- `CT_TYPE`: Container type (1 for LXC, 2 for VM)
- `DISK_SIZE`: Disk size in GB
- `CORE_COUNT`: Number of CPU cores
- `RAM_SIZE`: RAM size in MB
- `var_os`: Operating system type
- `var_version`: OS version
- `DISABLEIP6`: IPv6 disable setting
- `NSAPP`: Namespace application name
- `METHOD`: Installation method
### Internal Variables
- `POST_UPDATE_DONE`: Prevents duplicate status updates
- `API_URL`: Community scripts API endpoint
- `JSON_PAYLOAD`: API request payload
- `RESPONSE`: API response
## Error Code Categories
### General System Errors
- **0-9**: Basic system errors
- **18, 22, 28, 35**: Network and I/O errors
- **56, 60**: TLS/SSL errors
- **125-128**: Command execution errors
- **129-143**: Signal errors
- **152**: Resource limit errors
- **255**: Unknown critical errors
### LXC-Specific Errors
- **100-101**: LXC installation errors
- **200-209**: LXC creation and management errors
### Docker Errors
- **125**: Docker container start errors
## Best Practices
### Diagnostic Reporting
1. Always check if diagnostics are enabled
2. Respect user privacy settings
3. Use unique identifiers for tracking
4. Report both success and failure cases
### Error Handling
1. Use appropriate error codes
2. Provide meaningful error descriptions
3. Handle API communication failures gracefully
4. Don't block installation on API failures
### API Usage
1. Check for curl availability
2. Handle network failures gracefully
3. Use appropriate HTTP methods
4. Include all required data
## Troubleshooting
### Common Issues
1. **API Communication Fails**: Check network connectivity and curl availability
2. **Diagnostics Not Working**: Verify DIAGNOSTICS setting and RANDOM_UUID
3. **Missing Error Descriptions**: Check error code coverage
4. **Duplicate Updates**: POST_UPDATE_DONE prevents duplicates
### Debug Mode
Enable diagnostic reporting for debugging:
```bash
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
```
### API Testing
Test API communication:
```bash
source api.func
export DIAGNOSTICS="yes"
export RANDOM_UUID="test-$(date +%s)"
post_to_api
```
## Related Documentation
- [core.func](../core.func/) - Core utilities and error handling
- [error_handler.func](../error_handler.func/) - Error handling utilities
- [build.func](../build.func/) - Container creation with API integration
- [tools.func](../tools.func/) - Extended utilities with API integration
---
*This documentation covers the api.func file which provides API communication and diagnostic reporting for all Proxmox Community Scripts.*