### Start Docker Container Request Example Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/docs/api/API_REFERENCE.md Example of how to start a Docker container using curl. This demonstrates sending a POST request to the API endpoint with the container ID or name. ```bash curl -X POST http://192.168.20.21:8043/api/v1/docker/jackett/start ``` -------------------------------- ### Direct API Call: Start a Docker container (Bash) Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/docs/MCP_INTEGRATION.md Example of how to start a Docker container using a direct API call to the MCP endpoint via `curl`. This demonstrates calling the `container_action` tool with the action 'start'. ```bash curl -X POST http://your-unraid-ip:8043/mcp \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "tools/call", "params": { "name": "container_action", "arguments": { "container_id": "plex", "action": "start" } }, "id": 1 }' ``` -------------------------------- ### Pre-commit Hooks Setup and Execution (Bash) Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/CLAUDE.md Details the setup and manual execution of pre-commit hooks for enforcing code quality. This includes automated setup scripts, manual installation via pip, and running specific checks like linting and security checks. ```bash # Automated setup ./scripts/setup-pre-commit.sh # Or manual setup pip install pre-commit make pre-commit-install # Run checks manually make pre-commit-run make lint make security-check ``` -------------------------------- ### Manual Installation of Unraid Management Agent Release Package Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/README.md Commands to extract and install the downloaded release package and start the Unraid Management Agent service. This is part of the manual installation process. ```bash tar xzf unraid-management-agent-2025.11.0.tgz -C / /usr/local/emhttp/plugins/unraid-management-agent/scripts/start ``` -------------------------------- ### Example Hardware Configuration Documentation Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/CONTRIBUTING.md Provides an example of how to document the hardware configuration in a pull request. This helps reviewers understand the environment in which the changes were tested. ```markdown - CPU: AMD Ryzen 9 5950X - Disk Controller: LSI 9300-8i HBA - GPU: NVIDIA RTX 3080 - UPS: APC Back-UPS Pro 1500 - Unraid Version: 7.2 ``` -------------------------------- ### Setup Pre-commit Hooks for Unraid Management Agent Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/README.md Automates the setup of pre-commit hooks to enforce code quality standards. It can be set up automatically using a script or manually by installing pre-commit and running a make command. These hooks run checks before each commit to ensure code quality. ```bash # Automated setup (recommended) ./scripts/setup-pre-commit.sh # Or manual setup pip install pre-commit make pre-commit-install ``` -------------------------------- ### Direct API Call: Get system information (Bash) Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/docs/MCP_INTEGRATION.md Example of how to retrieve system information using a direct API call to the MCP endpoint via `curl`. This demonstrates calling the `get_system_info` tool. ```bash curl -X POST http://your-unraid-ip:8043/mcp \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "tools/call", "params": { "name": "get_system_info", "arguments": {} }, "id": 1 }' ``` -------------------------------- ### Copy Example Configuration Script Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/scripts/README.md Copies the example configuration file to a new file, which should then be edited with server-specific details. This is the first step in setting up credentials for the management agent. ```bash cp scripts/config.sh.example scripts/config.sh ``` -------------------------------- ### Example Pull Request for Hardware Compatibility (Markdown) Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/CONTRIBUTING.md A comprehensive example of a pull request description for adding hardware compatibility. It includes sections for description, hardware configuration, issue, solution, testing, and related issues. ```markdown ## Description Add support for AMD GPU temperature monitoring via `rocm-smi` ## Hardware Configuration - **GPU:** AMD Radeon RX 6800 XT - **Unraid Version:** 7.2 ## Issue GPU collector only supported NVIDIA GPUs via `nvidia-smi`. AMD GPUs returned empty metrics. ## Solution - Added AMD GPU detection via `rocm-smi` command - Implemented parser for `rocm-smi` output format - Added fallback: try NVIDIA first, then AMD - Updated GPU collector to handle both vendors ## Testing - ✅ AMD GPU temp/utilization correctly reported - ✅ Existing NVIDIA support still works (tested on RTX 3080) - ✅ All unit tests pass - ✅ WebSocket events broadcast GPU metrics correctly ## Related Issues Fixes #42 ``` -------------------------------- ### System Information API Response Example Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/README.md An example JSON response from the Unraid Management Agent API for system information. This includes details like hostname, version, CPU and RAM usage, temperature, and uptime. ```json { "hostname": "Tower", "version": "2025.10.03", "cpu_usage": 12.5, "ram_usage": 45.2, "temperature": 42.0, "uptime": 86400, "timestamp": "2025-10-02T08:00:00Z" } ``` -------------------------------- ### Start API Server Subscriptions and WebSocket Hub (Go) Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/coverage.html This Go function, `StartSubscriptions`, initializes and starts essential background processes for the API server. It includes starting the WebSocket hub, subscribing to events, and broadcasting events to WebSocket clients. This function should be called before collectors begin to prevent race conditions. ```Go // StartSubscriptions initializes event subscriptions and WebSocket hub // This should be called before collectors start to avoid race conditions func (s *Server) StartSubscriptions() { logger.Info("Starting API server subscriptions...") // Start WebSocket hub go s.wsHub.Run(s.cancelCtx) // Subscribe to events and update cache go s.subscribeToEvents(s.cancelCtx) // Broadcast events to WebSocket clients go s.broadcastEvents(s.cancelCtx) logger.Info("API server subscriptions started") } ``` -------------------------------- ### Connection Pooling Example Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/docs/api/API_REFERENCE.md Example demonstrating how to use `requests.Session` for connection pooling to improve performance when making multiple requests. ```APIDOC ## Connection Pooling Reusing HTTP connections through connection pooling can significantly improve performance when making numerous requests to the same host. ### Python Example ```python import requests BASE_URL = "http://your-unraid-ip:port" # Create session for connection pooling session = requests.Session() # Configure connection pool adapter adapter = requests.adapters.HTTPAdapter( pool_connections=10, pool_maxsize=20, max_retries=3 ) session.mount('http://', adapter) session.mount('https://', adapter) # Mount for HTTPS as well if applicable # Reuse session for all requests def get_system_info(): try: return session.get(f"{BASE_URL}/system").json() except requests.exceptions.RequestException as e: print(f"Error fetching system info: {e}") return None def get_array_status(): try: return session.get(f"{BASE_URL}/array").json() except requests.exceptions.RequestException as e: print(f"Error fetching array status: {e}") return None # All requests reuse connections print("Making multiple requests using a session...") for i in range(3): print(f"Request {i+1}:") info = get_system_info() array = get_array_status() if info: print(f" System status: {info.get('status')}") if array: print(f" Array status: {array.get('status')}") print("Finished requests.") # Close the session when done (optional, but good practice) session.close() ``` ``` -------------------------------- ### Python MCP Client Example Source: https://context7.com/ruaan-deysel/unraid-management-agent/llms.txt A Python example demonstrating how to use the `requests` library to interact with the Unraid Management Agent's MCP interface. ```APIDOC ## Python MCP Client ### Description This Python function provides a client for interacting with the Unraid Management Agent's MCP interface to call various tools. ### Method POST ### Endpoint http://localhost:8043/mcp ### Parameters #### Function Parameters - **tool_name** (string) - Required - The name of the MCP tool to call (e.g., "container_action", "system_reboot"). - **arguments** (dict) - Optional - A dictionary of arguments for the tool. Defaults to an empty dictionary. ### Request Example ```python import requests def call_mcp_tool(tool_name: str, arguments: dict = None): response = requests.post( "http://localhost:8043/mcp", json={ "jsonrpc": "2.0", "method": "tools/call", "params": {"name": tool_name, "arguments": arguments or {}}, "id": 1 } ) return response.json() # Example usage: # Start Plex container # result = call_mcp_tool("container_action", {"container_id": "plex", "action": "start"}) # print(result) # Reboot system # result = call_mcp_tool("system_reboot", {"confirm": True}) # print(result) ``` ### Response #### Success Response (200) - **jsonrpc** (string) - The JSON-RPC version. - **result** (object) - The result returned by the called tool. - **id** (integer) - The ID of the request. #### Response Example ```json { "jsonrpc": "2.0", "result": {}, "id": 1 } ``` ``` -------------------------------- ### Python Client Example: Call MCP Tools Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/docs/MCP_INTEGRATION.md A Python client example demonstrating how to interact with the MCP server using the `requests` library. It includes functions to call tools, retrieve system info, list containers, and restart containers. ```python import json import requests def call_mcp_tool(tool_name: str, arguments: dict = None): """Call an MCP tool on the Unraid server.""" response = requests.post( "http://your-unraid-ip:8043/mcp", json={ "jsonrpc": "2.0", "method": "tools/call", "params": { "name": tool_name, "arguments": arguments or {} }, "id": 1 } ) return response.json() # Get system info system = call_mcp_tool("get_system_info") print(f"Hostname: {system['result']['content'][0]['text']}") # List running containers containers = call_mcp_tool("list_containers", {"state": "running"}) print(f"Running containers: {containers['result']['content'][0]['text']}") # Restart a container result = call_mcp_tool("container_action", { "container_id": "plex", "action": "restart" }) print(f"Result: {result['result']['content'][0]['text']}") ``` -------------------------------- ### Get Docker Container Request Example Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/docs/api/API_REFERENCE.md Example of how to retrieve details for a specific Docker container using curl. This demonstrates sending a GET request to the API endpoint with the container ID or name. ```bash curl http://192.168.20.21:8043/api/v1/docker/jackett ``` -------------------------------- ### Fetch API: Interact with Unraid Management Agent Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/docs/api/API_REFERENCE.md Demonstrates how to use the Fetch API in JavaScript to interact with the Unraid Management Agent. It includes functions for getting system information, performing a health check, and starting the array. Requires a running Unraid server with the management agent installed. ```javascript const UNRAID_HOST = "192.168.20.21"; const UNRAID_PORT = 8043; const BASE_URL = `http://${UNRAID_HOST}:${UNRAID_PORT}/api/v1`; async function getSystemInfo() { try { const response = await fetch(`${BASE_URL}/system`); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const systemInfo = await response.json(); console.log(`Hostname: ${systemInfo.hostname}`); console.log(`CPU Usage: ${systemInfo.cpu_usage_percent}%`); console.log(`RAM Usage: ${systemInfo.ram_usage_percent}%`); console.log(`CPU Temp: ${systemInfo.cpu_temp_celsius}°C`); return systemInfo; } catch (error) { console.error("Error fetching system info:", error); throw error; } } async function checkHealth() { try { const response = await fetch(`${BASE_URL}/health`); const data = await response.json(); return data.status === "ok"; } catch (error) { console.error("Health check failed:", error); return false; } } async function startArray() { try { const response = await fetch(`${BASE_URL}/array/start`, { method: "POST", }); if (!response.ok) { const error = await response.json(); if (response.status === 409) { console.log(`Conflict: ${error.message}`); } else { throw new Error(error.message); } return false; } const result = await response.json(); console.log(`Success: ${result.message}`); return true; } catch (error) { console.error("Error starting array:", error); return false; } } getSystemInfo(); checkHealth().then((healthy) => { console.log(`API is ${healthy ? "healthy" : "not responding"}`); }); ``` -------------------------------- ### Run Tests and Coverage in Bash Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/CLAUDE.md This snippet shows how to execute all tests and generate a coverage report using make commands. It also includes an example of running a specific Go test file. ```bash make test # Run all tests make test-coverage # Generate coverage.html report # Run specific test go test -v ./daemon/services/api/handlers_test.go ``` -------------------------------- ### Install Python Requests Library Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/docs/api/API_REFERENCE.md Installs the 'requests' library, which is necessary for making HTTP requests to the Unraid Management Agent API in Python. This is a prerequisite for running the Python code examples. ```bash pip install requests ``` -------------------------------- ### GET /settings/disks Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/docs/api/API_REFERENCE.md Retrieves disk settings, including spindown delay and array start behavior. ```APIDOC ## GET /settings/disks ### Description Get disk settings including spindown delay. Retrieves configuration related to disk management, such as spindown timers and array behavior. ### Method GET ### Endpoint /settings/disks ### Response #### Success Response (200) - **spindown_delay_minutes** (integer) - The delay in minutes before disks spin down. - **start_array** (boolean) - Whether the array should start automatically. - **spinup_groups** (boolean) - Configuration for disk spinup groups. - **shutdown_timeout_seconds** (integer) - Timeout in seconds for disk shutdown. - **default_filesystem** (string) - The default filesystem type for new disks. - **timestamp** (string) - The timestamp of the response. ### Use Case Home Assistant can use `spindown_delay_minutes` to avoid waking disks with SMART queries. #### Response Example ```json { "spindown_delay_minutes": 30, "start_array": true, "spinup_groups": false, "shutdown_timeout_seconds": 90, "default_filesystem": "xfs", "timestamp": "2025-10-03T13:41:13+10:00" } ``` ``` -------------------------------- ### Start API Server Subscriptions and HTTP Server (Go) Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/coverage.html The `Start` function provides a legacy method to initiate both the API server's subscriptions and its HTTP server. It calls `StartSubscriptions` to set up background processes and then `StartHTTP` to begin listening for network requests. This is a convenient way to launch the entire agent service. ```Go // Start starts both subscriptions and HTTP server (legacy method) func (s *Server) Start() error { s.StartSubscriptions() return s.StartHTTP() } ``` -------------------------------- ### Direct API Call: List all tools (Bash) Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/docs/MCP_INTEGRATION.md Example of how to list all available tools using a direct API call to the MCP endpoint via `curl`. This demonstrates a POST request with a JSON payload specifying the `tools/list` method. ```bash curl -X POST http://your-unraid-ip:8043/mcp \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "tools/list", "id": 1 }' ``` -------------------------------- ### Install JSON API Data Source Plugin for Grafana (Alternative) Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/docs/integrations/GRAFANA.md Installs the JSON API Data Source plugin for Grafana as an alternative to the Infinity Data Source. This plugin can be used for querying JSON endpoints provided by the Unraid Management Agent. ```bash grafana-cli plugins install simpod-json-datasource ``` -------------------------------- ### Install Infinity Data Source Plugin for Grafana Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/docs/integrations/GRAFANA.md Installs the Infinity Data Source plugin for Grafana, which is recommended for querying the Unraid Management Agent's REST API. This can be done via the Grafana CLI or by setting an environment variable when running Grafana in Docker. ```bash # Via Grafana CLI grafana-cli plugins install yesoreyeram-infinity-datasource # Or via Docker environment variable docker run -d \ --name=grafana \ -p 3000:3000 \ -e "GF_INSTALL_PLUGINS=yesoreyeram-infinity-datasource" \ grafana/grafana:latest ``` -------------------------------- ### Install Grafana via Docker on Unraid Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/docs/integrations/GRAFANA.md This snippet shows how to install Grafana as a Docker container on an Unraid server. It maps port 3000 for Grafana access and persists Grafana data to `/mnt/user/appdata/grafana`. The `--restart unless-stopped` flag ensures Grafana restarts automatically. ```bash docker run -d \ --name=grafana \ -p 3000:3000 \ -v /mnt/user/appdata/grafana:/var/lib/grafana \ --restart unless-stopped \ grafana/grafana:latest ``` -------------------------------- ### Add Fallback Logic for Hardware Variations (Go) Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/CONTRIBUTING.md Demonstrates how to implement fallback parsing logic for hardware-specific command outputs, such as different formats from `nvidia-smi`. This ensures robustness when dealing with variations in hardware or software versions. ```go // Example: Handle different nvidia-smi output formats temp, err := parseNvidiaSMIOutput(output) if err != nil { // Try alternative parsing method for older GPUs temp, err = parseNvidiaSMIOutputLegacy(output) } ``` -------------------------------- ### GET /logs/{filename} Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/docs/api/API_REFERENCE.md Retrieves the content of a specific log file identified by its filename. You can optionally specify the number of lines and a starting line number. ```APIDOC ## GET /logs/{filename} ### Description Retrieve a specific log file by filename. ### Method GET ### Endpoint `/logs/{filename}` ### Parameters #### Path Parameters - **filename** (string) - Required - The name of the log file (e.g., `syslog`, `docker.log`). #### Query Parameters - **lines** (integer) - Optional - Number of lines to return. - **start** (integer) - Optional - Starting line number. ### Request Example ```json { "example": "GET /logs/syslog?lines=50&start=9950" } ``` ### Response #### Success Response (200) - **path** (string) - The path of the requested log file. - **content** (string) - The content of the log file. - **lines** (array) - An array of strings, where each string is a line from the log file. - **total_lines** (integer) - The total number of lines in the log file. - **lines_returned** (integer) - The number of lines returned in this response. - **start_line** (integer) - The starting line number of the returned content. - **end_line** (integer) - The ending line number of the returned content. #### Error Response (400) - Invalid filename - **success** (boolean) - Indicates if the operation failed. - **message** (string) - An error message, e.g., "Invalid filename". - **timestamp** (string) - The timestamp of the error. #### Error Response (404) - Not found - **success** (boolean) - Indicates if the operation failed. - **message** (string) - An error message, e.g., "Log file not found: unknown.log". - **timestamp** (string) - The timestamp of the error. #### Response Example (Success) ```json { "path": "/var/log/syslog", "content": "Nov 28 12:00:00 Cube ...\n...", "lines": ["Nov 28 12:00:00 Cube ...", "..."], "total_lines": 10000, "lines_returned": 50, "start_line": 9950, "end_line": 10000 } ``` #### Response Example (Invalid filename) ```json { "success": false, "message": "Invalid filename", "timestamp": "2025-11-28T12:00:00+10:00" } ``` #### Response Example (Not found) ```json { "success": false, "message": "Log file not found: unknown.log", "timestamp": "2025-11-28T12:00:00+10:00" } ``` ``` -------------------------------- ### Run Go Tests with Make Commands Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/CONTRIBUTING.md Common `make` commands for running tests in the project. Includes commands for running all tests, tests with coverage, and specific test files or functions. ```bash # Run all tests make test # Run tests with coverage make test-coverage # Run specific test file go test -v ./daemon/services/api/handlers_test.go # Run specific test function go test -v ./daemon/lib -run TestParseGPUTemperature ``` -------------------------------- ### Example Unraid Management Agent API Usage Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/README.md Bash examples demonstrating how to use `curl` to interact with the Unraid Management Agent's REST API for various operations like fetching system info, network details, disk lists, and controlling Docker/VMs. ```bash # Get system information curl http://localhost:8043/api/v1/system # Get network interfaces curl http://localhost:8043/api/v1/network # List all disks curl http://localhost:8043/api/v1/disks # Start a Docker container curl -X POST http://localhost:8043/api/v1/docker/nginx/start # Stop a VM curl -X POST http://localhost:8043/api/v1/vm/Ubuntu/stop ``` -------------------------------- ### Get OpenSSL Version (Go) Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/coverage.html Retrieves the installed OpenSSL version by executing the 'openssl version' command. It returns the trimmed output of the command or an empty string if an error occurs. ```go // getOpenSSLVersion gets the OpenSSL version func (c *SystemCollector) getOpenSSLVersion() string { output, err := lib.ExecCommandOutput("openssl", "version") if err != nil { return "" } return strings.TrimSpace(output) } ``` -------------------------------- ### Get AMD GPU Driver Version Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/coverage.html Retrieves the installed AMD GPU driver version. This function is a placeholder and would typically involve querying system information or specific driver files. ```go // getAMDDriverVersion gets the AMD GPU driver version func (c *GPUCollector) getAMDDriverVersion() (string, error) { // This is a placeholder. Actual implementation would involve querying system information // or specific driver files, e.g., using 'glxinfo | grep "OpenGL version"' or checking /usr/lib/modules/$(uname -r)/... // For now, return a dummy value. return "unknown", nil } ``` -------------------------------- ### Parse ZFS Pool Properties using 'zpool get' Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/coverage.html Parses the output of 'zpool get -Hp -o property,value' to extract and set ZFS pool properties such as GUID, readonly, autoexpand, and autotrim. It uses bufio.Scanner to read the output line by line and strings.Split to separate property and value pairs. Dependencies include the 'lib' package for command execution and 'constants' for binary paths. ```go output, err := lib.ExecCommandOutput(constants.ZpoolBin, "get", "-Hp", "-o", "property,value", "guid,readonly,autoexpand,autotrim", pool.Name) if err != nil { return err } scanner := bufio.NewScanner(strings.NewReader(output)) for scanner.Scan() { line := strings.TrimSpace(scanner.Text()) if line == "" { continue } fields := strings.Split(line, "\t") if len(fields) < 2 { continue } property := fields[0] value := fields[1] switch property { case "guid": pool.GUID = value case "readonly": pool.Readonly = value == "on" case "autoexpand": pool.Autoexpand = value == "on" case "autotrim": pool.Autotrim = value } } return scanner.Err() } ``` -------------------------------- ### Start Docker Container Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/docs/api/API_REFERENCE.md Initiates the startup of a specified Docker container, identified by its ID or name. Returns a success message with container details upon successful start, or an error if the container is already running. ```json { "success": true, "message": "Container started successfully", "container_id": "fedcb3e1ba1f", "container_name": "jackett", "timestamp": "2025-10-03T13:41:13+10:00" } ``` -------------------------------- ### Axios: Interact with Unraid Management Agent Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/docs/api/API_REFERENCE.md Shows how to use the Axios library in JavaScript for asynchronous HTTP requests to the Unraid Management Agent. This example includes functions for retrieving system information, starting the array, and listing disks, with robust error handling. ```javascript const axios = require("axios"); const BASE_URL = "http://192.168.20.21:8043/api/v1"; const api = axios.create({ baseURL: BASE_URL, timeout: 5000, headers: { "Content-Type": "application/json", }, }); async function getSystemInfo() { try { const { data } = await api.get("/system"); console.log(`CPU Usage: ${data.cpu_usage_percent}%`); return data; } catch (error) { console.error("Error:", error.message); throw error; } } async function startArray() { try { const { data } = await api.post("/array/start"); console.log(data.message); return true; } catch (error) { if (error.response) { const { status, data } = error.response; if (status === 409) { console.log(`Conflict: ${data.message}`); } else { console.error(`Error ${status}: ${data.message}`); } } else if (error.request) { console.error("No response from server"); } else { console.error("Error:", error.message); } return false; } } async function listDisks() { try { const { data } = await api.get("/disks"); data.forEach((disk) => { console.log(`${disk.name}: ${disk.spin_state}`); }); return data; } catch (error) { console.error("Error listing disks:", error.message); return []; } } getSystemInfo(); startArray(); listDisks(); ``` -------------------------------- ### Deploy Plugin to Unraid (Bash) Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/CLAUDE.md Guides through the deployment process to an Unraid server using provided bash scripts. This involves creating a configuration file with SSH credentials and then executing the deployment script. ```bash # 1. Create config with Unraid SSH credentials cp scripts/config.sh.example scripts/config.sh # Edit config.sh with actual Unraid server IP, username, and password # 2. Deploy and test ./scripts/deploy-plugin.sh ``` -------------------------------- ### Get AMD GPU Driver Version (Go) Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/coverage.html Retrieves the driver version for an AMD GPU by executing the 'modinfo amdgpu' command. It parses the command output to find the line starting with 'version:' and extracts the version string. Returns an error if the version cannot be parsed. ```go // getAMDDriverVersion gets AMD driver version func (c *GPUCollector) getAMDDriverVersion() (string, error) { output, err := lib.ExecCommandOutput("modinfo", "amdgpu") if err != nil { return "", err } // Parse modinfo output for version for _, line := range strings.Split(output, "\n") { if strings.HasPrefix(line, "version:") { parts := strings.SplitN(line, ":", 2) if len(parts) == 2 { return strings.TrimSpace(parts[1]), nil } } } return "", fmt.Errorf("failed to parse driver version") } ``` -------------------------------- ### Check lm-sensors Installation Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/docs/DIAGNOSTIC_COMMANDS.md Verifies if the 'lm-sensors' package is installed on the system. If not found, it suggests installing it using 'opkg install lm-sensors'. ```bash which sensors # If not found: opkg install lm-sensors ``` -------------------------------- ### Build Unraid Management Agent from Source Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/README.md Steps to build the Unraid Management Agent from its source code repository. This includes cloning the repository, installing dependencies, building the release, and creating a plugin package. ```bash # Clone the repository git clone https://github.com/ruaan-deysel/unraid-management-agent.git cd unraid-management-agent # Install dependencies make deps # Build for Unraid (Linux/amd64) make release # Create plugin package make package ``` -------------------------------- ### Example Pull Request Description for Hardware Compatibility Fixes Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/README.md An example of a detailed pull request description for hardware compatibility contributions. It includes essential information such as the hardware configuration, the specific issue encountered, the solution implemented, testing performed, and the Unraid version used. This format helps maintainers understand and review contributions effectively. ```text Hardware: AMD Ryzen 9 5950X, LSI 9300-8i HBA, NVIDIA RTX 3080 Issue: GPU temperature not detected due to different nvidia-smi output format Solution: Added parsing for alternative nvidia-smi XML format Testing: Verified GPU metrics endpoint returns correct data, all tests pass Unraid Version: 7.2 ``` -------------------------------- ### Discover Unassigned Disk Devices (Go) Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/coverage.html Identifies and collects unassigned disk devices by filtering out array disks, loop devices, md devices, zram, and partitions. It relies on helper functions to check plugin installation, retrieve array disk information, and get block device details. ```Go // collectUnassignedDevices discovers and collects unassigned disk devices func (c *UnassignedCollector) collectUnassignedDevices() []dto.UnassignedDevice { // Check if plugin is installed if !c.isPluginInstalled() { logger.Debug("Unassigned Devices plugin not installed") return []dto.UnassignedDevice{} } // Get array disks to filter them out arrayDisks := c.getArrayDisks() // Get all block devices allDevices := c.getAllBlockDevices() var unassignedDevices []dto.UnassignedDevice for _, device := range allDevices { // Skip if it's an array disk if c.isArrayDisk(device, arrayDisks) { continue } // Skip loop devices, md devices, zram, and partitions if strings.HasPrefix(device, "loop") || strings.HasPrefix(device, "md") || strings.HasPrefix(device, "zram") || strings.Contains(device, "nvme0n1p") || (len(device) > 3 && device[3] >= '1' && device[3] <= '9') { continue } unassignedDevice := c.getDeviceInfo(device) if unassignedDevice != nil { unassignedDevices = append(unassignedDevices, *unassignedDevice) } } return unassignedDevices } ``` -------------------------------- ### Import Pre-built Grafana Dashboard Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/docs/integrations/GRAFANA.md Import the 'unraid-system-monitor-dashboard.json' file into Grafana to get a production-ready dashboard with 16 panels covering system metrics, array status, disk info, Docker, and VMs. This dashboard uses the Infinity data source and provides pre-configured thresholds and refresh intervals. ```text 1. In Grafana, navigate to Dashboards → Import 2. Click Upload JSON file 3. Select `unraid-system-monitor-dashboard.json` 4. When prompted, select your Infinity data source 5. Click Import ``` -------------------------------- ### Manually Query GPU Metrics (NVIDIA) Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/CONTRIBUTING.md Example command to manually query GPU temperature and utilization metrics using `nvidia-smi`. This is useful for debugging GPU-related issues within the agent. ```bash /usr/bin/nvidia-smi --query-gpu=temperature.gpu,utilization.gpu,utilization.memory --format=csv,noheader ``` -------------------------------- ### Get Network Interface IP Address - Go Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/coverage.html Retrieves the IPv4 address for a given network interface name using the 'ip -4 addr show ' command. It parses the command output to find the line starting with 'inet ' and extracts the IP address, removing the CIDR notation. Returns an empty string if the IP address cannot be found or an error occurs. ```Go func (c *NetworkCollector) getIPAddress(ifName string) string { // Use ip command to get IP address output, err := lib.ExecCommandOutput("ip", "-4", "addr", "show", ifName) if err != nil { return "" } lines := strings.Split(output, "\n") for _, line := range lines { line = strings.TrimSpace(line) if strings.HasPrefix(line, "inet ") { fields := strings.Fields(line) if len(fields) >= 2 { // Return IP without CIDR notation ip := strings.Split(fields[1], "/")[0] return ip } } } return "" } ``` -------------------------------- ### Install Unraid Management Agent Plugin Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/docs/README.md Instructions for installing the Unraid Management Agent plugin via the Unraid web UI. This involves pasting a provided URL into the 'Install Plugin' section. ```text https://github.com/ruaan-deysel/unraid-management-agent/raw/main/unraid-management-agent.plg ``` -------------------------------- ### Unraid API Client Usage Examples (TypeScript) Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/docs/api/API_REFERENCE.md Demonstrates creating an UnraidAPIClient instance and performing various operations such as fetching system info, managing the array, listing disks, and controlling Docker containers and VMs. It includes asynchronous functions for each task and basic error handling. ```typescript // Create client instance const client = new UnraidAPIClient("192.168.20.21"); // Get system information async function displaySystemInfo() { try { const systemInfo = await client.getSystemInfo(); console.log(`Hostname: ${systemInfo.hostname}`); console.log(`CPU Usage: ${systemInfo.cpu_usage_percent}%`); console.log(`RAM Usage: ${systemInfo.ram_usage_percent}%`); console.log(`CPU Temp: ${systemInfo.cpu_temp_celsius}°C`); } catch (error) { console.error("Error:", error); } } // Manage array async function manageArray() { try { const status = await client.getArrayStatus(); if (status.state === "STOPPED") { console.log("Starting array..."); await client.startArray(); } else { console.log(`Array is ${status.state}`); } } catch (error) { console.error("Error managing array:", error); } } // List disks with type safety async function listDisks() { try { const disks = await client.listDisks(); disks.forEach((disk: DiskInfo) => { console.log( `${disk.name}: ${disk.spin_state} (${disk.temperature_celsius}°C)` ); }); } catch (error) { console.error("Error listing disks:", error); } } // Docker container management async function manageContainer(containerName: string) { try { const container = await client.getContainer(containerName); if (container.state === "stopped") { console.log(`Starting ${containerName}...`); await client.startContainer(containerName); } else { console.log(`${containerName} is ${container.state}`); } } catch (error) { console.error("Error managing container:", error); } } // VM management async function manageVM(vmName: string) { try { const vm = await client.getVM(vmName); if (vm.state === "stopped") { console.log(`Starting ${vmName}...`); await client.startVM(vmName); } else { console.log(`${vmName} is ${vm.state}`); } } catch (error) { console.error("Error managing VM:", error); } } // Usage displaySystemInfo(); manageArray(); listDisks(); manageContainer("plex"); manageVM("windows-10"); ``` -------------------------------- ### Start a Docker Container via MCP Source: https://context7.com/ruaan-deysel/unraid-management-agent/llms.txt This endpoint allows you to start a Docker container on your Unraid server using the MCP interface. You need to provide the container ID and the action 'start'. ```APIDOC ## POST /mcp ### Description Starts a specified Docker container. ### Method POST ### Endpoint /mcp ### Parameters #### Request Body - **jsonrpc** (string) - Required - Specifies the JSON-RPC version, should be "2.0". - **method** (string) - Required - The method to call, should be "tools/call". - **params** (object) - Required - Parameters for the tool call. - **name** (string) - Required - The name of the tool to call, should be "container_action". - **arguments** (object) - Required - Arguments for the container action. - **container_id** (string) - Required - The ID of the container to start (e.g., "plex"). - **action** (string) - Required - The action to perform, should be "start". - **id** (integer) - Required - A unique identifier for the request. ### Request Example ```json { "jsonrpc": "2.0", "method": "tools/call", "params": { "name": "container_action", "arguments": {"container_id": "plex", "action": "start"} }, "id": 1 } ``` ### Response #### Success Response (200) - **result** (object) - The result of the operation. - **id** (integer) - The ID of the request. #### Response Example ```json { "jsonrpc": "2.0", "result": {}, "id": 1 } ``` ``` -------------------------------- ### Fetch Share Configuration using cURL Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/docs/api/API_REFERENCE.md An example demonstrating how to fetch the configuration for a specific share using cURL. ```bash curl http://192.168.20.21:8043/api/v1/shares/appdata/config ``` -------------------------------- ### Start Unraid Array using mdcmd Source: https://github.com/ruaan-deysel/unraid-management-agent/blob/main/coverage.html Starts the Unraid array by executing the `mdcmd start` command. It logs the operation and handles potential errors during command execution. Dependencies include the `lib.ExecCommand` function for command execution and `logger` for logging. ```Go func (c *ArrayController) StartArray() error { logger.Info("Array: Starting array...") // Use mdcmd to start the array _, err := lib.ExecCommand("/usr/local/sbin/mdcmd", "start") if err != nil { logger.Error("Array: Failed to start array: %v", err) return fmt.Errorf("failed to start array: %w", err) } logger.Info("Array: Array started successfully") return nil } ```