### Setup Development Environment (Bash) Source: https://github.com/ruaan-deysel/uma-api/blob/main/README.md Clones the uma-api repository and installs the project in editable mode with development dependencies. ```bash git clone https://github.com/ruaan-deysel/uma-api.git cd uma-api pip install -e ".[dev]" ``` -------------------------------- ### Install Twine for Package Uploading Source: https://github.com/ruaan-deysel/uma-api/blob/main/PUBLISHING.md Installs the 'twine' utility, which is essential for uploading Python packages to PyPI and TestPyPI. This is a prerequisite for the publishing process. ```bash pip install twine ``` -------------------------------- ### Test Local Installation from Wheel File Source: https://github.com/ruaan-deysel/uma-api/blob/main/PUBLISHING.md Installs the uma-api package locally from its generated wheel file in the 'dist/' directory. This allows for thorough testing before publishing to a public repository. ```bash pip install dist/uma_api-*.whl ``` -------------------------------- ### Install and Run Pre-commit Hooks (Bash) Source: https://github.com/ruaan-deysel/uma-api/blob/main/README.md Installs pre-commit hooks for the project and runs all hooks on the entire codebase. ```bash pre-commit install pre-commit run --all-files ``` -------------------------------- ### Install uma-api from source Source: https://github.com/ruaan-deysel/uma-api/blob/main/README.md Installs the uma-api Python client library directly from its source code repository. This method is useful for development or when using the latest unreleased features. ```bash git clone https://github.com/ruaan-deysel/uma-api.git cd uma-api pip install -e . ``` -------------------------------- ### Test Installation from TestPyPI Source: https://github.com/ruaan-deysel/uma-api/blob/main/PUBLISHING.md Installs the uma-api package from TestPyPI, specifying the TestPyPI index URL and falling back to the main PyPI index if necessary. This verifies that the package is correctly published and accessible. ```bash pip install --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ uma-api ``` -------------------------------- ### Unraid Array Management (Start/Stop) Source: https://github.com/ruaan-deysel/uma-api/blob/main/README.md Provides examples for starting and stopping the Unraid array using the UnraidClient. It includes error handling for cases where the array is already in the desired state, using UnraidConflictError. ```python from uma_api import UnraidClient, UnraidConflictError client = UnraidClient("192.168.1.100") # Start the array try: result = client.start_array() print("Array started successfully") except UnraidConflictError as e: print(f"Array is already running: {e.message}") # Stop the array try: result = client.stop_array() print("Array stopped successfully") except UnraidConflictError as e: print(f"Array is already stopped: {e.message}") ``` -------------------------------- ### Install uma-api with Dev Dependencies Source: https://github.com/ruaan-deysel/uma-api/blob/main/CLAUDE.md Installs the uma-api package in editable mode, including development dependencies required for testing and linting. ```bash pip install -e ".[dev]" ``` -------------------------------- ### Install uma-api using pip Source: https://github.com/ruaan-deysel/uma-api/blob/main/README.md Installs the uma-api Python client library from the Python Package Index (PyPI). This is the standard method for adding the library to your project. ```bash pip install uma-api ``` -------------------------------- ### Install uma-api Python Package Source: https://context7.com/ruaan-deysel/uma-api/llms.txt Installs the uma-api Python client library. The '[async]' extra is required for most features that utilize asynchronous operations. ```bash pip install uma-api # For async support (required for most features) pip install uma-api[async] ``` -------------------------------- ### Upload Package to TestPyPI Source: https://github.com/ruaan-deysel/uma-api/blob/main/PUBLISHING.md Uploads the built package distributions to the TestPyPI repository. This is a recommended step to test the publishing process and installation in a staging environment before going live on PyPI. ```bash twine upload --repository testpypi dist/* ``` -------------------------------- ### List and Execute User Scripts with Python Source: https://context7.com/ruaan-deysel/uma-api/llms.txt This code example shows how to interact with user scripts on the Unraid server. It covers listing all available scripts, executing a script and waiting for its completion with arguments, and running a script in the background. Requires the 'uma_api' library. ```python import asyncio from uma_api import UnraidClient async def user_script_operations(): async with UnraidClient("192.168.1.100") as client: # List all user scripts scripts = await client.list_user_scripts() for script in scripts: print(f"{script.name}: {script.description}") print(f" Path: {script.script_path}") print(f" Schedule: {script.schedule}") print(f" Running: {script.running}") # Execute a user script result = await client.execute_user_script( script_name="backup_script", background=False, # Wait for completion arguments=["--full"] # Optional arguments ) print(f"Success: {result.success}") print(f"Exit Code: {result.exit_code}") print(f"Output: {result.output}") # Run in background result = await client.execute_user_script( script_name="long_running_script", background=True ) print(f"Started in background: {result.success}") asyncio.run(user_script_operations()) ``` -------------------------------- ### Unraid Virtual Machine Management Source: https://github.com/ruaan-deysel/uma-api/blob/main/README.md Demonstrates how to manage virtual machines (VMs) on an Unraid server. This includes listing VMs, their states, and performing actions like starting, stopping, pausing, and resuming VMs by name. ```python from uma_api import UnraidClient client = UnraidClient("192.168.1.100") # List all VMs vms = client.list_vms() for vm in vms: print(f"{vm.name}: {vm.state}") # Start a VM client.start_vm("windows-10") # Stop a VM client.stop_vm("windows-10") # Pause a VM client.pause_vm("windows-10") # Resume a VM client.resume_vm("windows-10") ``` -------------------------------- ### Test GET Resource Endpoint Source: https://github.com/ruaan-deysel/uma-api/blob/main/CLAUDE.md Example test for the `get_resource` method. It mocks the `requests.request` call to simulate an API response and asserts that the correct data is returned and parsed. ```python from unittest.mock import patch @patch("requests.request") def test_get_resource(self, mock_request, client, mock_response): mock_response.json.return_value = {"id": "123", "name": "test"} mock_request.return_value = mock_response result = client.get_resource("123") assert result.id == "123" mock_request.assert_called_with( method="GET", url="http://192.168.1.100:8043/api/v1/resources/123", json=None, params=None, timeout=5, verify=True, ) ``` -------------------------------- ### List and Get Network Interfaces with UMA API (Python) Source: https://context7.com/ruaan-deysel/uma-api/llms.txt Demonstrates how to list all network interfaces, retrieve specific interface details, get network access URLs, and fetch network configuration using the UnraidClient in Python. Requires the 'uma_api' library. ```python import asyncio from uma_api import UnraidClient async def network_operations(): async with UnraidClient("192.168.1.100") as client: # List all network interfaces interfaces = await client.list_network_interfaces() for iface in interfaces: print(f"{iface.name}: {iface.ip_address}") print(f" MAC: {iface.mac_address}") print(f" Speed: {iface.speed_mbps} Mbps, MTU: {iface.mtu}") print(f" RX: {iface.bytes_received} bytes, TX: {iface.bytes_sent} bytes") print(f" Link detected: {iface.link_detected}") # Get specific interface info eth0 = await client.get_network_interface("eth0") print(f"ETH0 state: {eth0.state}, Duplex: {eth0.duplex}") # Get network access URLs urls = await client.get_network_access_urls() for url in urls.urls or []: print(f"{url.type}: {url.ipv4}") # Get network configuration config = await client.get_network_config("eth0") print(f"DHCP: {config.use_dhcp}, Gateway: {config.gateway}") asyncio.run(network_operations()) ``` -------------------------------- ### Implement GET Resource Method Source: https://github.com/ruaan-deysel/uma-api/blob/main/CLAUDE.md Implementation of the `get_resource` method in `client.py`. It makes a GET request to the Unraid API and parses the JSON response into a `ResourceInfo` Pydantic model. ```python def get_resource(self, resource_id: str) -> ResourceInfo: """Get information about a specific resource.""" data = self._request("GET", f"/resources/{resource_id}") return ResourceInfo.model_validate(data) ``` -------------------------------- ### Initialize and Use UnraidClient for REST API Source: https://context7.com/ruaan-deysel/uma-api/llms.txt Demonstrates initializing the UnraidClient for asynchronous interaction with the Unraid Management Agent REST API. It shows basic usage with a context manager for automatic session cleanup and how to retrieve system and array status information. Also includes an example of configuring the client for HTTPS with custom settings. ```python import asyncio from uma_api import UnraidClient, UnraidNotFoundError, UnraidConflictError async def main(): # Basic usage with context manager (recommended) async with UnraidClient("192.168.1.100") as client: # Get system information system_info = await client.get_system_info() print(f"Hostname: {system_info.hostname}") print(f"CPU Usage: {system_info.cpu_usage_percent}%") print(f"RAM Usage: {system_info.ram_usage_percent}%") print(f"Uptime: {system_info.uptime_seconds} seconds") # Check array status array = await client.get_array_status() print(f"Array State: {array.state}") print(f"Total Disks: {array.num_disks}") print(f"Usage: {array.used_percent}%") # HTTPS connection with custom settings client = UnraidClient( host="192.168.1.100", port=8043, timeout=30, use_https=True, verify_ssl=False # For self-signed certificates ) asyncio.run(main()) ``` -------------------------------- ### Unraid Docker Container Management Source: https://github.com/ruaan-deysel/uma-api/blob/main/README.md Shows how to manage Docker containers on an Unraid server, including listing all containers, their states, and starting, stopping, or restarting individual containers by name. ```python from uma_api import UnraidClient client = UnraidClient("192.168.1.100") # List all containers containers = client.list_containers() for container in containers: print(f"{container.name}: {container.state}") # Start a container client.start_container("plex") # Stop a container client.stop_container("plex") # Restart a container client.restart_container("plex") ``` -------------------------------- ### Virtual Machine Management API Source: https://context7.com/ruaan-deysel/uma-api/llms.txt This API enables the management of virtual machines, including listing, starting, stopping, restarting, pausing, resuming, hibernating, and force-stopping VMs. ```APIDOC ## Virtual Machine Management ### Description List, start, stop, restart, pause, resume, hibernate, and force-stop virtual machines. ### Method Various (e.g., GET, POST, PUT, DELETE - inferred from client methods) ### Endpoint `/vms` (for listing), `/vms/{id}` (for specific operations) ### Parameters #### Path Parameters - **id** (string) - Required - The ID or name of the virtual machine. #### Query Parameters None specified. #### Request Body None specified for most operations. ### Request Example ```python # Example of starting a VM await client.start_vm("windows-10") ``` ### Response #### Success Response (200) - **vms** (array) - A list of VM objects, each with properties like `name`, `state`, `cpu_count`, `memory_display`, `disk_path`, `disk_size_bytes`, `autostart`. - **vm** (object) - A single VM object with detailed information. #### Response Example ```json { "name": "windows-10", "state": "running", "cpu_count": 4, "memory_display": "8GB", "disk_path": "/mnt/disk1/vm/windows-10/disk.img", "disk_size_bytes": 8589934592, "autostart": true } ``` ``` -------------------------------- ### GitHub Actions Workflow for PyPI Release Source: https://github.com/ruaan-deysel/uma-api/blob/main/PUBLISHING.md An example GitHub Actions workflow file that automates the process of building and publishing the uma-api package to PyPI when a new release is created on GitHub. It requires the PyPI API token to be set as a GitHub secret. ```yaml name: Publish to PyPI on: release: types: [created] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up Python uses: actions/setup-python@v4 with: python-version: '3.x' - name: Install dependencies run: | python -m pip install --upgrade pip pip install build twine - name: Build package run: python -m build - name: Publish to PyPI env: TWINE_USERNAME: __token__ TWINE_PASSWORD: ${{ secrets.PYPI_API_TOKEN }} run: twine upload dist/* ``` -------------------------------- ### Manage Virtual Machines with Unraid API Source: https://context7.com/ruaan-deysel/uma-api/llms.txt This Python snippet illustrates how to manage virtual machines (VMs) on an Unraid server using the UnraidClient. It covers listing VMs, retrieving individual VM details, and performing lifecycle operations such as starting, stopping, restarting, pausing, resuming, hibernating, and force-stopping VMs. It also shows how to check VM states using predefined constants. ```python import asyncio from uma_api import UnraidClient, VMState async def vm_management(): async with UnraidClient("192.168.1.100") as client: # List all VMs vms = await client.list_vms() for vm in vms: print(f"{vm.name}: {vm.state}") print(f" CPUs: {vm.cpu_count}, Memory: {vm.memory_display}") print(f" Disk: {vm.disk_path}, Size: {vm.disk_size_bytes} bytes") print(f" Autostart: {vm.autostart}") # Get specific VM info vm = await client.get_vm("windows-10") print(f"VM state: {vm.state}") # VM lifecycle operations await client.start_vm("windows-10") await client.stop_vm("windows-10") # Graceful shutdown await client.restart_vm("windows-10") # Pause and resume await client.pause_vm("windows-10") await client.resume_vm("windows-10") # Hibernate (saves state to disk) await client.hibernate_vm("windows-10") # Force stop (use with caution) await client.force_stop_vm("windows-10") # Check state using constants vm = await client.get_vm("windows-10") if vm.state == VMState.RUNNING: print("VM is running") asyncio.run(vm_management()) ``` -------------------------------- ### Handle API Exceptions with UMA API in Python Source: https://context7.com/ruaan-deysel/uma-api/llms.txt Illustrates comprehensive exception handling for the UMA API using a dedicated hierarchy of exceptions. This example shows how to catch specific errors like Not Found, Conflict, Validation, Connection, and general API errors. ```python from uma_api import ( UnraidClient, UnraidAPIError, UnraidConnectionError, UnraidNotFoundError, UnraidConflictError, UnraidValidationError ) async def error_handling(): async with UnraidClient("192.168.1.100") as client: try: # Try to get a non-existent disk disk = await client.get_disk("nonexistent") except UnraidNotFoundError as e: print(f"Not found: {e.message}") print(f"Error code: {e.error_code}") print(f"Status code: {e.status_code}") # 404 except UnraidConflictError as e: print(f"Conflict: {e.message}") # e.g., array already started print(f"Status code: {e.status_code}") # 409 except UnraidValidationError as e: print(f"Validation error: {e.message}") print(f"Status code: {e.status_code}") # 400 except UnraidConnectionError as e: print(f"Connection error: {e.message}") except UnraidAPIError as e: print(f"General API error: {e.message}") print(f"Status code: {e.status_code}") ``` -------------------------------- ### Manage Docker Containers with Unraid API Source: https://context7.com/ruaan-deysel/uma-api/llms.txt This snippet shows how to list, start, stop, restart, pause, and unpause Docker containers using the UnraidClient. It demonstrates retrieving container details such as name, state, image, CPU usage, and memory consumption. It also includes error handling for when a container is not found. ```python import asyncio from uma_api import UnraidClient, UnraidNotFoundError, ContainerState async def container_management(): async with UnraidClient("192.168.1.100") as client: # List all containers containers = await client.list_containers() for container in containers: print(f"{container.name}: {container.state}") print(f" Image: {container.image}") print(f" CPU: {container.cpu_percent}%") print(f" Memory: {container.memory_display}") print(f" Network RX: {container.network_rx_bytes} bytes") # Get specific container info try: plex = await client.get_container("plex") print(f"Plex state: {plex.state}, uptime: {plex.uptime}") except UnraidNotFoundError: print("Container not found") # Container lifecycle operations await client.start_container("plex") await client.stop_container("plex") await client.restart_container("plex") # Pause and unpause await client.pause_container("plex") await client.unpause_container("plex") # Check state using constants container = await client.get_container("plex") if container.state == ContainerState.RUNNING: print("Container is running") asyncio.run(container_management()) ``` -------------------------------- ### Get Hardware Information with UMA API (Python) Source: https://context7.com/ruaan-deysel/uma-api/llms.txt Provides Python code to fetch detailed hardware information from an Unraid server, including CPU, motherboard, BIOS, memory (array and DIMMs), cache, and GPU details using the UnraidClient. Requires the 'uma_api' library. ```python import asyncio from uma_api import UnraidClient async def hardware_info(): async with UnraidClient("192.168.1.100") as client: # Basic hardware info hw = await client.get_hardware_info() print(f"CPU: {hw.cpu_model}") print(f"Cores: {hw.cpu_cores}, Threads: {hw.cpu_threads}") print(f"Motherboard: {hw.motherboard_model}") print(f"BIOS: {hw.bios_version} ({hw.bios_date})") # Full hardware info (DMI data) full = await client.get_hardware_full_info() print(f"System: {full.system}") print(f"Chassis: {full.chassis}") # BIOS details bios = await client.get_bios_info() print(f"BIOS Vendor: {bios.vendor}") print(f"BIOS Version: {bios.version}") print(f"Release Date: {bios.release_date}") # Motherboard details board = await client.get_baseboard_info() print(f"Manufacturer: {board.manufacturer}") print(f"Product: {board.product_name}") # CPU details cpu = await client.get_cpu_hardware_info() print(f"Socket: {cpu.socket_designation}") print(f"Max Speed: {cpu.max_speed}") print(f"Cores: {cpu.core_count}, Threads: {cpu.thread_count}") # Memory information mem_array = await client.get_memory_array_info() print(f"Max Capacity: {mem_array.maximum_capacity}") print(f"Slots: {mem_array.number_of_devices}") # Individual DIMMs dimms = await client.get_memory_devices() for dimm in dimms: print(f" {dimm.locator}: {dimm.size} {dimm.type} @ {dimm.speed}") # CPU cache info caches = await client.get_cpu_cache_info() for cache in caches: print(f" {cache.socket_designation}: {cache.installed_size}") # GPU information gpus = await client.list_gpus() for gpu in gpus: print(f"GPU: {gpu.name} ({gpu.vendor})") print(f" Driver: {gpu.driver_version}") print(f" Utilization: {gpu.utilization_gpu_percent}%") print(f" Memory: {gpu.memory_used_bytes}/{gpu.memory_total_bytes} bytes") print(f" Temperature: {gpu.temperature_celsius}C") print(f" Power: {gpu.power_draw_watts}W") asyncio.run(hardware_info()) ``` -------------------------------- ### Get UPS and NUT Information with UMA API (Python) Source: https://context7.com/ruaan-deysel/uma-api/llms.txt Shows how to retrieve UPS status (model, battery charge, load, runtime) and Network UPS Tools (NUT) configuration (installed, running, config mode) using the UnraidClient in Python. Requires the 'uma_api' library. ```python import asyncio from uma_api import UnraidClient async def ups_info(): async with UnraidClient("192.168.1.100") as client: # Get UPS information (apcupsd) ups = await client.get_ups_info() print(f"UPS Model: {ups.model}") print(f"Status: {ups.status}") print(f"Battery: {ups.battery_charge_percent}%") print(f"Load: {ups.load_percent}%") print(f"Runtime Left: {ups.runtime_left_seconds} seconds") print(f"Power: {ups.power_watts}W / {ups.nominal_power_watts}W") print(f"Connected: {ups.connected}") # Get NUT information nut = await client.get_nut_info() print(f"NUT Installed: {nut.installed}") print(f"NUT Running: {nut.running}") print(f"Config Mode: {nut.config_mode}") asyncio.run(ups_info()) ``` -------------------------------- ### Basic Unraid Server Information Retrieval Source: https://github.com/ruaan-deysel/uma-api/blob/main/README.md Demonstrates how to initialize the UnraidClient and retrieve basic system information such as hostname, CPU usage, and RAM usage. It also shows how to check the array status and list all disks connected to the server. ```python from uma_api import UnraidClient # Create a client instance client = UnraidClient("192.168.1.100") # For HTTPS connections: # client = UnraidClient("192.168.1.100", use_https=True) # Get system information (returns Pydantic model) system_info = client.get_system_info() print(f"Hostname: {system_info.hostname}") print(f"CPU Usage: {system_info.cpu_usage_percent}%") print(f"RAM Usage: {system_info.ram_usage_percent}%") # Check array status array_status = client.get_array_status() print(f"Array State: {array_status.state}") print(f"Total Disks: {array_status.total_disks}") # List all disks disks = client.list_disks() for disk in disks: print(f"{disk.id}: {disk.status}") ``` -------------------------------- ### Python: Initialize UnraidWebSocketClient Source: https://github.com/ruaan-deysel/uma-api/blob/main/README.md Demonstrates the initialization of `UnraidWebSocketClient` for establishing WebSocket connections to an Unraid server. It outlines parameters for host, port, and callback functions for messages, errors, and connection closure, along with WSS usage. ```python ws_client = UnraidWebSocketClient( host, port=8043, on_message=None, on_error=None, on_close=None, use_wss=False ) # Parameters: # host (str): The Unraid server hostname or IP address # port (int, optional): The API port. Default: 8043 # on_message (callable, optional): Callback function for received messages # on_error (callable, optional): Callback function for errors # on_close (callable, optional): Callback function for connection close # use_wss (bool, optional): Whether to use WSS (secure WebSocket) instead of WS. Default: False ``` -------------------------------- ### Python: Initialize UnraidClient Source: https://github.com/ruaan-deysel/uma-api/blob/main/README.md Shows how to initialize the `UnraidClient` for making REST API calls to an Unraid server. It details the parameters for host, port, timeout, SSL verification, and HTTPS usage. ```python client = UnraidClient(host, port=8043, timeout=10, verify_ssl=True, use_https=False) # Parameters: # host (str): The Unraid server hostname or IP address # port (int, optional): The API port. Default: 8043 # timeout (int, optional): Request timeout in seconds. Default: 10 # verify_ssl (bool, optional): Whether to verify SSL certificates. Default: True # use_https (bool, optional): Whether to use HTTPS instead of HTTP. Default: False ``` -------------------------------- ### Retrieve System Settings and License Info with Python Source: https://context7.com/ruaan-deysel/uma-api/llms.txt This Python code retrieves various system settings from the Unraid server, including general system settings, Docker configuration, VM settings, and disk settings. It also shows how to fetch license and registration information. Requires the 'uma_api' library. ```python import asyncio from uma_api import UnraidClient async def settings_operations(): async with UnraidClient("192.168.1.100") as client: # System settings sys_settings = await client.get_system_settings() print(f"Server Name: {sys_settings.server_name}") print(f"Timezone: {sys_settings.timezone}") print(f"SSL Enabled: {sys_settings.use_ssl}") # Docker settings docker_settings = await client.get_docker_settings() print(f"Docker Enabled: {docker_settings.enabled}") print(f"Image Path: {docker_settings.image_path}") print(f"Auto Start: {docker_settings.auto_start}") # VM settings vm_settings = await client.get_vm_settings() print(f"VMs Enabled: {vm_settings.enabled}") print(f"Default Path: {vm_settings.default_path}") # Disk settings disk_settings = await client.get_disk_settings() print(f"Spindown Delay: {disk_settings.spindown_delay_minutes} minutes") print(f"Default Filesystem: {disk_settings.default_filesystem}") # Registration/license info reg = await client.get_registration_info() print(f"License Type: {reg.type}") print(f"State: {reg.state}") print(f"GUID: {reg.guid}") asyncio.run(settings_operations()) ``` -------------------------------- ### UnraidWebSocketClient Initialization Source: https://github.com/ruaan-deysel/uma-api/blob/main/README.md Initializes the UnraidWebSocketClient for real-time event handling. ```APIDOC ## UnraidWebSocketClient Initialization ### Description Initializes the UnraidWebSocketClient for ``` -------------------------------- ### Publish Package to PyPI Source: https://github.com/ruaan-deysel/uma-api/blob/main/PUBLISHING.md Uploads the final package distributions to the official PyPI repository. This makes the uma-api package available for public installation via pip. ```bash twine upload dist/* ``` -------------------------------- ### Docker Container Management API Source: https://context7.com/ruaan-deysel/uma-api/llms.txt This API allows you to list, start, stop, restart, pause, and unpause Docker containers on the Unraid server. ```APIDOC ## Docker Container Management ### Description List, start, stop, restart, pause, and unpause Docker containers. ### Method Various (e.g., GET, POST, PUT, DELETE - inferred from client methods) ### Endpoint `/containers` (for listing), `/containers/{id}` (for specific operations) ### Parameters #### Path Parameters - **id** (string) - Required - The ID or name of the container. #### Query Parameters None specified. #### Request Body None specified for most operations, but could be used for configuration updates if supported. ### Request Example ```python # Example of starting a container await client.start_container("plex") ``` ### Response #### Success Response (200) - **containers** (array) - A list of container objects, each with properties like `name`, `state`, `image`, `cpu_percent`, `memory_display`, `network_rx_bytes`. - **container** (object) - A single container object with detailed information. #### Response Example ```json { "name": "plex", "state": "running", "image": "plexinc/pms-docker", "cpu_percent": 5.2, "memory_display": "512MB", "network_rx_bytes": 1024000 } ``` ``` -------------------------------- ### Update Certifi for SSL Certificate Issues Source: https://github.com/ruaan-deysel/uma-api/blob/main/PUBLISHING.md Installs or upgrades the 'certifi' package to ensure that Python has the latest trusted Certificate Authority (CA) certificates. This can resolve SSL certificate verification errors during network operations, such as uploading packages. ```bash pip install --upgrade certifi ``` -------------------------------- ### Clean Previous Build Artifacts Source: https://github.com/ruaan-deysel/uma-api/blob/main/PUBLISHING.md Removes old distribution and build directories ('dist/', 'build/', 'src/*.egg-info') before creating a new package build. This prevents potential conflicts or outdated files in the new distribution. ```bash rm -rf dist/ build/ src/*.egg-info ``` -------------------------------- ### Configure .pypirc for API Token Authentication Source: https://github.com/ruaan-deysel/uma-api/blob/main/PUBLISHING.md Sets up the '.pypirc' file in the user's home directory to store PyPI and TestPyPI API tokens for authentication. This avoids entering credentials manually during uploads and enhances security. ```ini [pypi] username = __token__ password = pypi-your-api-token-here [testpypi] username = __token__ password = pypi-your-testpypi-token-here ``` -------------------------------- ### UnraidClient Initialization Source: https://github.com/ruaan-deysel/uma-api/blob/main/README.md Initializes the UnraidClient to interact with the Unraid server API. ```APIDOC ## UnraidClient Initialization ### Description Initializes the UnraidClient to interact with the Unraid server API. ### Method Initialization (Constructor) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from uma_api import UnraidClient client = UnraidClient(host='192.168.1.100', port=8043, timeout=10, verify_ssl=True, use_https=False) ``` ### Response #### Success Response (200) N/A (Initialization) #### Response Example N/A ``` -------------------------------- ### Settings API Source: https://github.com/ruaan-deysel/uma-api/blob/main/README.md Endpoints for retrieving various system settings. ```APIDOC ## Settings API ### Description Endpoints for retrieving various system settings. ### Method GET ### Endpoint - `/get_system_settings()` - `/get_docker_settings()` - `/get_vm_settings()` - `/get_disk_settings()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Get system settings system_settings = client.get_system_settings() # Get Docker settings docker_settings = client.get_docker_settings() # Get VM settings vm_settings = client.get_vm_settings() # Get disk settings disk_settings = client.get_disk_settings() ``` ### Response #### Success Response (200) - `get_system_settings()`: General system configuration. - `get_docker_settings()`: Docker service configuration. - `get_vm_settings()`: Virtual machine configuration. - `get_disk_settings()`: Disk-related settings. #### Response Example ```json // Example for get_system_settings() { "time_format": "24hr", "timezone": "UTC", "language": "en" } ``` ``` -------------------------------- ### Manage Data Collectors with Python Source: https://context7.com/ruaan-deysel/uma-api/llms.txt This snippet demonstrates how to monitor and control data collection services using the UnraidClient. It shows how to retrieve the status of all collectors, get information about a specific collector, enable/disable collectors, and update their intervals. Requires the 'uma_api' library. ```python import asyncio from uma_api import UnraidClient async def collector_operations(): async with UnraidClient("192.168.1.100") as client: # Get all collectors status status = await client.get_collectors_status() print(f"Total: {status.total}, Enabled: {status.enabled_count}") for collector in status.collectors or []: print(f"{collector.name}: {collector.status}") print(f" Enabled: {collector.enabled}") print(f" Interval: {collector.interval_seconds}s") print(f" Last Run: {collector.last_run}") print(f" Required: {collector.required}") # Get specific collector info = await client.get_collector("system") print(f"System collector: {info.collector.status}") # Enable/disable collectors await client.enable_collector("docker") await client.disable_collector("docker") # Update collector interval await client.update_collector_interval("system", interval_seconds=30) asyncio.run(collector_operations()) ``` -------------------------------- ### Build Python Package Source: https://github.com/ruaan-deysel/uma-api/blob/main/PUBLISHING.md Uses the 'build' package to create source and wheel distributions for the uma-api package. This command generates the necessary files in the 'dist/' directory for uploading. ```bash python -m build ``` -------------------------------- ### Unraid Disk Management (Spin Up/Down) Source: https://github.com/ruaan-deysel/uma-api/blob/main/README.md Illustrates how to manage individual disks connected to an Unraid server. This includes retrieving specific disk information, such as status and spin state, and controlling the spin-up and spin-down behavior of disks. ```python from uma_api import UnraidClient client = UnraidClient("192.168.1.100") # Get specific disk info parity_disk = client.get_disk("parity") print(f"Parity disk status: {parity_disk.status}") print(f"Spin state: {parity_disk.spin_state}") # Spin down a disk client.spin_down_disk("disk1") # Spin up a disk client.spin_up_disk("disk1") ``` -------------------------------- ### MCP Client Operations with Python Source: https://context7.com/ruaan-deysel/uma-api/llms.txt Demonstrates various operations using the UnraidMCPClient in Python, including listing tools, calling tools directly, retrieving system information, managing containers and VMs, listing and reading resources, and interacting with prompts. Requires the 'uma_api' library and an active Unraid server connection. ```python import asyncio import json from uma_api import UnraidMCPClient, MCPError async def mcp_operations(): async with UnraidMCPClient("192.168.1.100") as mcp: # List available tools tools = await mcp.list_tools() for tool in tools: print(f"Tool: {tool.name}") print(f" Description: {tool.description}") print(f" Schema: {tool.input_schema}") # Call a tool directly result = await mcp.call_tool("get_system_info", {{}}) if not result.is_error: data = json.loads(result.content[0].text) print(f"Hostname: {data['hostname']}") # Convenience methods system_info = await mcp.get_system_info() print(f"CPU: {system_info['cpu_usage_percent']}%) array_status = await mcp.get_array_status() print(f"Array: {array_status['state']}") containers = await mcp.list_containers(state="running") for c in containers: print(f"Container: {c['name']}") # Container actions result = await mcp.container_action("plex", "restart") print(result.content[0].text) # VM operations vms = await mcp.list_vms() result = await mcp.vm_action("windows-10", "start") # List available resources resources = await mcp.list_resources() for resource in resources: print(f"Resource: {resource.uri}") print(f" Name: {resource.name}") print(f" MIME: {resource.mime_type}") # Read a resource contents = await mcp.read_resource("unraid://system") data = json.loads(contents[0].text) print(f"System data: {data}") # List prompts prompts = await mcp.list_prompts() for prompt in prompts: print(f"Prompt: {prompt.name}: {prompt.description}") # Get a prompt messages = await mcp.get_prompt("system_overview") for msg in messages: print(f"{msg.role}: {msg.content.text[:100]}...") asyncio.run(mcp_operations()) ``` -------------------------------- ### Hardware API Source: https://github.com/ruaan-deysel/uma-api/blob/main/README.md Endpoints for retrieving hardware information. ```APIDOC ## Hardware API ### Description Endpoints for retrieving hardware information. ### Method GET ### Endpoint - `/get_hardware_info()` - `/get_hardware_full_info()` - `/list_gpus()` - `/get_ups_info()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Get basic hardware info hardware_info = client.get_hardware_info() # Get detailed hardware info full_hardware_info = client.get_hardware_full_info() # List GPUs gpus = client.list_gpus() # Get UPS info ups_info = client.get_ups_info() ``` ### Response #### Success Response (200) - `get_hardware_info()`: Basic hardware overview. - `get_hardware_full_info()`: Detailed hardware information. - `list_gpus()`: A list of detected GPUs. - `get_ups_info()`: Information about the connected UPS. #### Response Example ```json // Example for get_hardware_info() { "cpu": { "model": "Intel(R) Core(TM) i7-8700K CPU @ 3.70GHz", "cores": 8 }, "memory": { "total_gb": 32, "used_gb": 10 }, "disks": 12, "network_interfaces": 3 } ``` ``` -------------------------------- ### Manage Unraid Array State and Operations Source: https://context7.com/ruaan-deysel/uma-api/llms.txt Provides Python code for managing the Unraid array, including starting, stopping, and monitoring its status. It also demonstrates how to initiate, pause, resume, and stop parity check operations, and retrieve historical parity check data. Error handling for array state conflicts is included. ```python import asyncio from uma_api import UnraidClient, UnraidConflictError async def manage_array(): async with UnraidClient("192.168.1.100") as client: # Get array status status = await client.get_array_status() print(f"State: {status.state}") print(f"Parity Valid: {status.parity_valid}") print(f"Total: {status.total_bytes} bytes") # Start the array try: result = await client.start_array() print(f"Array started: {result.success}") except UnraidConflictError as e: print(f"Array already running: {e.message}") # Stop the array try: result = await client.stop_array() print(f"Array stopped: {result.success}") except UnraidConflictError as e: print(f"Array already stopped: {e.message}") # Parity check operations await client.start_parity_check(correct=True) # Start with correction await client.pause_parity_check() # Pause await client.resume_parity_check() # Resume await client.stop_parity_check() # Stop # Get parity check history history = await client.get_parity_history() for record in history.records or []: print(f"Date: {record.date}, Errors: {record.errors}, Duration: {record.duration_seconds}s") asyncio.run(manage_array()) ``` -------------------------------- ### Run Pre-commit Hooks Source: https://github.com/ruaan-deysel/uma-api/blob/main/CLAUDE.md Executes all configured pre-commit hooks on all files in the repository to ensure code quality and consistency before committing. ```bash pre-commit run --all-files ``` -------------------------------- ### Virtual Machines API Source: https://github.com/ruaan-deysel/uma-api/blob/main/README.md Endpoints for managing virtual machines on Unraid. ```APIDOC ## Virtual Machines API ### Description Endpoints for managing virtual machines on Unraid. ### Method GET, POST ### Endpoint - `/list_vms()` - `/get_vm(vm_id)` - `/start_vm(vm_id)` - `/stop_vm(vm_id)` - `/restart_vm(vm_id)` - `/pause_vm(vm_id)` - `/resume_vm(vm_id)` ### Parameters #### Path Parameters - `vm_id` (str) - Required - The ID or name of the virtual machine. #### Query Parameters None #### Request Body None ### Request Example ```python # List all VMs vms = client.list_vms() # Get specific VM info vm_info = client.get_vm('windows10') # Start a VM client.start_vm('windows10') # Stop a VM client.stop_vm('windows10') # Restart a VM client.restart_vm('windows10') # Pause a VM client.pause_vm('windows10') # Resume a VM client.resume_vm('windows10') ``` ### Response #### Success Response (200) - `list_vms()`: A list of all virtual machines. - `get_vm(vm_id)`: Information about the specified virtual machine. - `start_vm(vm_id)`: Confirmation of VM start. - `stop_vm(vm_id)`: Confirmation of VM stop. - `restart_vm(vm_id)`: Confirmation of VM restart. - `pause_vm(vm_id)`: Confirmation of VM pause. - `resume_vm(vm_id)`: Confirmation of VM resume. #### Response Example ```json // Example for get_vm('windows10') { "id": "vm_windows10", "name": "Windows 10 VM", "state": "running", "cpu_cores": 4, "memory_mb": 8192 } ``` ``` -------------------------------- ### Format Data with Utilities in Python Source: https://context7.com/ruaan-deysel/uma-api/llms.txt Demonstrates the use of formatting utility functions from the UMA API for human-readable representation of bytes, durations, speeds, percentages, and temperatures. These functions simplify data presentation. ```python from uma_api import ( format_bytes, format_duration, format_speed, format_percentage, format_temperature ) # Format bytes print(format_bytes(4000000000000)) # "3.6 TB" print(format_bytes(536870912)) # "512.0 MB" print(format_bytes(1024, precision=0)) # "1 KB" print(format_bytes(1024, binary=False)) # "1.0 KB" (decimal) # Format duration print(format_duration(432000)) # "5 days" print(format_duration(3661)) # "1 hour, 1 minute, 1 second" print(format_duration(432000, short=True))# "5d 0h 0m" # Format speed (Mbps) print(format_speed(100)) # "100 Mbps" print(format_speed(1000)) # "1 Gbps" print(format_speed(2500)) # "2.5 Gbps" # Format percentage print(format_percentage(85.555)) # "85.6%" print(format_percentage(50.0, precision=0))# "50%" # Format temperature print(format_temperature(45.5)) # "45.5C" print(format_temperature(0.0, fahrenheit=True)) # "32.0F" ``` -------------------------------- ### Run Tests with Coverage (Bash) Source: https://github.com/ruaan-deysel/uma-api/blob/main/README.md Executes tests using pytest and enforces a minimum code coverage of 90%. ```bash pytest --cov=uma_api --cov-fail-under=90 ``` -------------------------------- ### Perform Disk Operations with UnraidClient Source: https://context7.com/ruaan-deysel/uma-api/llms.txt This Python code snippet demonstrates how to perform various disk operations using the UnraidClient. It includes listing all disks with their status and details, retrieving information for a specific disk (e.g., parity disk), and controlling the spin state of individual disks by spinning them down or up. ```python import asyncio from uma_api import UnraidClient async def disk_operations(): async with UnraidClient("192.168.1.100") as client: # List all disks disks = await client.list_disks() for disk in disks: print(f"{disk.id}: {disk.status}, Temp: {disk.temperature_celsius}C") print(f" Size: {disk.size_bytes} bytes, Used: {disk.used_bytes} bytes") print(f" Spin State: {disk.spin_state}") print(f" SMART Status: {disk.smart_status}") # Get specific disk info parity = await client.get_disk("parity") print(f"Parity disk: {parity.model}, Serial: {parity.serial_number}") # Spin down a disk to save power result = await client.spin_down_disk("disk1") print(f"Disk spun down: {result.success}") # Spin up a disk result = await client.spin_up_disk("disk1") print(f"Disk spun up: {result.success}") asyncio.run(disk_operations()) ``` -------------------------------- ### Manage Unraid System Notifications with Python Source: https://context7.com/ruaan-deysel/uma-api/llms.txt This snippet demonstrates how to list, create, archive, unarchive, and delete system notifications using the UnraidClient. It covers fetching notification lists, overviews, and individual notifications, as well as performing bulk actions like archiving all unread notifications. ```python import asyncio from uma_api import UnraidClient async def notification_operations(): async with UnraidClient("192.168.1.100") as client: # List all notifications response = await client.list_notifications() print(f"Total notifications: {len(response.notifications or [])}") for notif in response.notifications or []: print(f"[{notif.importance}] {notif.subject}: {notif.description}") # Get notification overview (counts) overview = await client.get_notification_overview() print(f"Unread: {overview.unread.total if overview.unread else 0}") print(f"Archived: {overview.archive.total if overview.archive else 0}") # List unread notifications only unread = await client.list_unread_notifications() for notif in unread.notifications or []: print(f"Unread: {notif.subject}") # List archived notifications archived = await client.list_archived_notifications() # Create a new notification notif = await client.create_notification( subject="Backup Complete", message="Daily backup completed successfully", importance="normal" # normal, warning, alert ) print(f"Created notification: {notif.id}") # Get specific notification notif = await client.get_notification("some-notification-id") # Archive/unarchive notifications await client.archive_notification("some-notification-id") await client.unarchive_notification("some-notification-id") await client.archive_all_notifications() # Archive all unread # Delete notification await client.delete_notification("some-notification-id") await client.delete_notification("some-id", archived=True) # From archive asyncio.run(notification_operations()) ```