### Complete Real-World Example of QbittorrentMetricsCollector Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/api-reference/metric.md This example demonstrates the complete setup and usage of the `QbittorrentMetricsCollector`. It includes configuration, collector instantiation, manual metric construction, and printing of metric details. This serves as a practical guide for integrating the exporter. ```python from qbittorrent_exporter.exporter import ( QbittorrentMetricsCollector, Metric, MetricType, ) # Configuration config = { "host": "qbittorrent.example.com", "port": "8080", "ssl": False, "url_base": "", "username": "admin", "password": "secret", "api_key": "", "exporter_address": "0.0.0.0", "exporter_port": 8000, "log_level": "INFO", "metrics_prefix": "qbittorrent", "export_metrics_by_torrent": False, "verify_webui_certificate": True, } # Create collector collector = QbittorrentMetricsCollector(config) # Manually construct metrics (normally done by _get_qbittorrent_status_metrics) metrics = [ Metric( name="qbittorrent_up", value=1, labels={"version": "1.7.0", "server": "qbittorrent.example.com:8080"}, help_text="Server availability", metric_type=MetricType.GAUGE, ), Metric( name="qbittorrent_dht_nodes", value=150, labels={"server": "qbittorrent.example.com:8080"}, help_text="Number of DHT nodes connected to.", metric_type=MetricType.GAUGE, ), Metric( name="qbittorrent_alltime_dl", value=5368709120, # 5 GB labels={"server": "qbittorrent.example.com:8080"}, help_text="Total historical data downloaded, in bytes.", metric_type=MetricType.COUNTER, ), ] # Use metrics for metric in metrics: print(f"{metric.name} = {metric.value} (type: {metric.metric_type})") print(f" Labels: {metric.labels}") print(f" Help: {metric.help_text}") ``` -------------------------------- ### Basic Python API Usage Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/README.md Demonstrates the basic setup for collecting qBittorrent metrics and exposing them via an HTTP server. Requires importing necessary classes and starting the server. ```python from qbittorrent_exporter.exporter import QbittorrentMetricsCollector, get_config from prometheus_client import REGISTRY, start_http_server config = get_config() collector = QbittorrentMetricsCollector(config) REGISTRY.register(collector) start_http_server(8000) ``` -------------------------------- ### Install Prometheus qBittorrent Exporter Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/README.md Install the exporter using pip. This is the primary method for local installation. ```bash pip3 install prometheus-qbittorrent-exporter ``` -------------------------------- ### Run Prometheus qBittorrent Exporter Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/README.md Run the exporter as a command-line application after installation. No specific setup is required beyond installation. ```bash qbittorrent-exporter ``` -------------------------------- ### Local qBittorrent Setup (No Auth) Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/quick-reference.md Configure environment variables for connecting to a local qBittorrent instance without authentication. Then, run the exporter. ```bash export QBITTORRENT_HOST=localhost export QBITTORRENT_PORT=8080 export QBITTORRENT_USER="" export QBITTORRENT_PASS="" qbittorrent-exporter ``` -------------------------------- ### Docker Compose Example Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/configuration.md A Docker Compose configuration for deploying the qbittorrent-exporter. This example sets up the service, environment variables, and network dependencies. ```yaml version: '3' services: qbittorrent-exporter: image: ghcr.io/esanchezm/prometheus-qbittorrent-exporter:latest environment: QBITTORRENT_HOST: qbittorrent QBITTORRENT_PORT: "8080" QBITTORRENT_SSL: "False" QBITTORRENT_USER: admin QBITTORRENT_PASS: password EXPORTER_ADDRESS: "0.0.0.0" EXPORTER_PORT: "8000" EXPORTER_LOG_LEVEL: INFO METRICS_PREFIX: qbittorrent EXPORT_METRICS_BY_TORRENT: "False" VERIFY_WEBUI_CERTIFICATE: "True" ports: - "8000:8000" depends_on: - qbittorrent ``` -------------------------------- ### Configuration File Read Error Example Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/errors.md This example demonstrates how a missing configuration file leads to fallback mechanisms and potential authentication failures. ```bash export FILE__QBITTORRENT_PASS=/run/secrets/qbt_password # If /run/secrets/qbt_password doesn't exist: # - Error logged # - Falls back to QBITTORRENT_PASS env var # - If QBITTORRENT_PASS is also unset, auth will fail ``` -------------------------------- ### Help Text Examples Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/api-reference/metric.md Examples of documentation strings for metrics, which appear in the Prometheus UI. ```python "Whether the qBittorrent server is answering requests from this exporter. A `version` label with the server version is added." ``` ```python "Number of torrents" ``` ```python "Data downloaded since the server started, in bytes." ``` -------------------------------- ### Bash: Standard Environment Variable Example Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/api-reference/exporter.md Demonstrates setting a standard environment variable for configuration. The value is directly retrieved. ```bash export QBITTORRENT_HOST=localhost QBITTORRENT_HOST=localhost # Retrieved as-is ``` -------------------------------- ### Remote qBittorrent Setup with Basic Auth Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/quick-reference.md Set environment variables to connect to a remote qBittorrent instance using basic authentication. Ensure SSL is disabled if not used. ```bash export QBITTORRENT_HOST=qbittorrent.example.com export QBITTORRENT_PORT=8080 export QBITTORRENT_SSL=False export QBITTORRENT_USER=admin export QBITTORRENT_PASS=mypassword qbittorrent-exporter ``` -------------------------------- ### qBittorrent Exporter Initialization Flow Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/module-overview.md This diagram illustrates the sequence of operations when the qBittorrent exporter starts, including configuration loading, signal handling, client initialization, and the main loop for metric collection. ```mermaid graph TD Entry[qbittorrent-exporter command] subgraph Initialization A[pyproject.toml entry point] B[main()] C[Initialize logging] D[get_config() → dict] E[For each config key] F[Check FILE__{key} (file-based)] G[Check {key} (environment)] H[Update logger level] I[ShutdownSignalHandler() → registers SIGINT/SIGTERM] J[Validate required config] K[QbittorrentMetricsCollector(config) → create collector] L[REGISTRY.register(collector) → register with Prometheus] M[start_http_server(port, address) → bind HTTP server] end subgraph Main Loop N[while not signal_handler.is_shutting_down()] O[time.sleep(1)] P[On each GET /metrics request] Q[collector.collect()] R[_create_client() → create API client] S[_get_qbittorrent_status_metrics() → list[Metric]] T[For each Metric, create Prometheus metric family] U[yield metric family] V[_get_qbittorrent_by_torrent_metric_gauges() → list[GaugeMetricFamily]] W[yield each gauge] X[_get_qbittorrent_torrent_tags_metrics_gauge() → GaugeMetricFamily] Y[yield gauge] end Entry --> A --> B B --> C --> D D --> E E --> F & G D --> H --> I --> J --> K --> L --> M M --> N N --> O N --> P P --> Q Q --> R --> S --> T --> U Q --> V --> W Q --> X --> Y ``` -------------------------------- ### HTTPS Setup with API Key (qBittorrent 5.2+) Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/quick-reference.md Configure environment variables for a secure connection using HTTPS and an API key, typically for qBittorrent version 5.2 and later. Set SSL to True. ```bash export QBITTORRENT_HOST=qbittorrent.example.com export QBITTORRENT_PORT=8443 export QBITTORRENT_SSL=True export QBITTORRENT_API_KEY=qbt_abc123def456... qbittorrent-exporter ``` -------------------------------- ### Prometheus Metrics Example Output Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/quick-reference.md Example output from the /metrics endpoint, showing server status and torrent counts. Metrics are prefixed with 'qbittorrent_'. ```prometheus # HELP qbittorrent_up Whether the qBittorrent server is answering requests # TYPE qbittorrent_up gauge qbittorrent_up{version="1.7.0",server="localhost:8080"} 1.0 # HELP qbittorrent_torrents_count Number of torrents # TYPE qbittorrent_torrents_count gauge qbittorrent_torrents_count{status="downloading",category="Movies",server="localhost:8080"} 3.0 ``` -------------------------------- ### Instantiate Metric Objects Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/api-reference/metric.md Examples of creating Metric instances for different types of metrics. Includes simple gauge, counter, and minimal gauge configurations. ```python from qbittorrent_exporter.exporter import Metric, MetricType # Simple gauge metric up_metric = Metric( name="qbittorrent_up", value=1, labels={"version": "1.7.0", "server": "localhost:8080"}, help_text="Whether the qBittorrent server is responding", metric_type=MetricType.GAUGE, ) ``` ```python # Counter metric download_metric = Metric( name="qbittorrent_dl_info_data", value=1073741824, # 1 GB labels={"server": "localhost:8080"}, help_text="Data downloaded since the server started, in bytes.", metric_type=MetricType.COUNTER, ) ``` ```python # Minimal gauge status_metric = Metric( name="qbittorrent_connected", value=True, labels={"server": "localhost:8080"}, ) ``` -------------------------------- ### Metric Labels Examples Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/api-reference/metric.md Examples of label dictionaries for attaching dimensions to metrics. Both keys and values must be strings. ```python {"version": "1.2.3", "server": "localhost:8080"} ``` ```python {"category": "Movies", "status": "downloading", "server": "localhost:8080"} ``` ```python {"server": "qbittorrent.example.com:8080/qbt/"} ``` -------------------------------- ### Initialize ShutdownSignalHandler Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/api-reference/shutdown-signal-handler.md Initialize the signal handler and register it with the OS. This setup completes immediately. ```python from qbittorrent_exporter.exporter import ShutdownSignalHandler signal_handler = ShutdownSignalHandler() # Now signal handler is registered with the OS ``` -------------------------------- ### Complete Example of ShutdownSignalHandler Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/api-reference/shutdown-signal-handler.md This snippet demonstrates a complete Python application using ShutdownSignalHandler to gracefully shut down when a signal is received. It starts an HTTP server for Prometheus metrics and includes a main loop that respects the shutdown signal. ```python #!/usr/bin/env python3 import logging import sys import time from prometheus_client import start_http_server from qbittorrent_exporter.exporter import ShutdownSignalHandler # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def main(): logger.info("Application starting") # Register signal handler signal_handler = ShutdownSignalHandler() # Start HTTP server start_http_server(8000, "0.0.0.0") logger.info("Listening on 0.0.0.0:8000") # Main loop try: while not signal_handler.is_shutting_down(): # Simulate work logger.debug("Processing metrics...") time.sleep(1) except Exception as e: logger.error(f"Error in main loop: {e}") sys.exit(1) logger.info("Application shutdown complete") if __name__ == "__main__": main() ``` -------------------------------- ### Docker Entrypoint Configuration Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/api-reference/exporter.md This Dockerfile snippet configures the entrypoint for the exporter, allowing it to be run as a container. It specifies the command to execute when the container starts. ```dockerfile ENTRYPOINT ["qbittorrent-exporter"] ``` -------------------------------- ### main() Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/api-reference/exporter.md The main entry point for the exporter application. It initializes configuration, registers metrics collectors, starts the HTTP server, and runs the main event loop until a shutdown signal is received. ```APIDOC ## main() ### Description Entry point for the exporter application. Initializes configuration, registers metrics collector, starts HTTP server, and runs the main event loop. ### Method Python function ### Parameters None. ### Return Value None. Does not return until shutdown signal is received. ### Behavior 1. **Initialize Logging:** Creates a StreamHandler for stderr and configures a JSON formatter with an initial log level of INFO. 2. **Load Configuration:** Calls `get_config()` to load environment variables and updates the logger level based on `config["log_level"]`. 3. **Register Signal Handler:** Sets up a `ShutdownSignalHandler` for SIGINT and SIGTERM signals. 4. **Validate Required Config:** Checks for the presence of `QBITTORRENT_HOST` and `QBITTORRENT_PORT`. Exits with code 1 if either is missing. 5. **Register Collector:** Instantiates and registers `QbittorrentMetricsCollector` with the Prometheus REGISTRY. 6. **Start HTTP Server:** Starts an HTTP server using `prometheus_client.start_http_server` on the configured `EXPORTER_ADDRESS` and `EXPORTER_PORT`. 7. **Main Loop:** Enters a loop that sleeps for 1 second per iteration, checking for shutdown signals. 8. **Shutdown:** Logs shutdown completion and returns cleanly. ### Exceptions and Error Handling - If `QBITTORRENT_HOST` is not set: Logs an error and exits with code 1. - If `QBITTORRENT_PORT` is not set: Logs an error and exits with code 1. - Other errors during startup are logged but do not terminate the application. ### Example Usage ```bash # Run directly qbittorrent-exporter # Or programmatically from qbittorrent_exporter.exporter import main if __name__ == "__main__": main() ``` ### Configuration All configuration is done via environment variables. **Required environment variables:** - `QBITTORRENT_HOST` - `QBITTORRENT_PORT` **Optional environment variables:** - `QBITTORRENT_SSL` (default: "False") - `QBITTORRENT_URL_BASE` (default: "") - `QBITTORRENT_USER` (default: "") - `QBITTORRENT_PASS` (default: "") - `QBITTORRENT_API_KEY` (default: "") - `EXPORTER_ADDRESS` (default: "0.0.0.0") - `EXPORTER_PORT` (default: "8000") - `EXPORTER_LOG_LEVEL` (default: "INFO") - `METRICS_PREFIX` (default: "qbittorrent") - `EXPORT_METRICS_BY_TORRENT` (default: "False") - `VERIFY_WEBUI_CERTIFICATE` (default: "True") ### Log Output Example startup log output in JSON format: ```json {"asctime": "2025-01-15 14:23:45", "levelname": "INFO", "message": "Exporter is starting up"} {"asctime": "2025-01-15 14:23:45", "levelname": "INFO", "message": "Exporter listening on 0.0.0.0:8000"} ``` ### Docker Entrypoint ```dockerfile ENTRYPOINT ["qbittorrent-exporter"] ``` ``` -------------------------------- ### Create qBittorrent API Client Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/api-reference/qbittorrent-metrics-collector.md Manually create or recreate the qBittorrent API client instance. This method is called internally by `collect()` but can be invoked separately to prepare the client for direct use, for example, to fetch data immediately. ```python collector = QbittorrentMetricsCollector(config) collector._create_client() # collector.client is now ready to use requests = collector.client.sync_maindata() ``` -------------------------------- ### Set QBITTORRENT_HOST Environment Variable Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/errors.md Set the QBITTORRENT_HOST environment variable to specify the host of the qBittorrent server. This is required for the exporter to start. ```bash export QBITTORRENT_HOST=qbittorrent.example.com qbittorrent-exporter ``` -------------------------------- ### Bash: File-Based Configuration Example Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/api-reference/exporter.md Shows how to configure a value using a file-based secret, typically for sensitive information like passwords. The exporter will read the content of the specified file. ```bash export FILE__QBITTORRENT_PASS=/run/secrets/qbt_password # Reads /run/secrets/qbt_password and uses its contents ``` -------------------------------- ### Reverse Proxy Setup Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/quick-reference.md Configure environment variables for connecting through a reverse proxy. Specify the proxy's host, port, and the base URL path if applicable. SSL should be set to False if the proxy handles SSL termination. ```bash export QBITTORRENT_HOST=proxy.example.com export QBITTORRENT_PORT=80 export QBITTORRENT_SSL=False export QBITTORRENT_URL_BASE=qbittorrent/ export QBITTORRENT_USER=admin export QBITTORRENT_PASS=password qbittorrent-exporter ``` -------------------------------- ### Bash: Default Value Example Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/api-reference/exporter.md Illustrates using a default value for a configuration setting. If the environment variable is not set, the specified default will be used. ```bash # If EXPORTER_PORT is not set, uses "8000" port = _get_config_value("EXPORTER_PORT", "8000") ``` -------------------------------- ### Set QBITTORRENT_PORT Environment Variable Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/errors.md Set the QBITTORRENT_PORT environment variable to specify the port of the qBittorrent server. This is required for the exporter to start. ```bash export QBITTORRENT_PORT=8080 qbittorrent-exporter ``` -------------------------------- ### Basic Python API Integration Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/quick-reference.md Integrate the exporter into your Python application by loading configuration, registering the collector, and starting the HTTP server. ```python from prometheus_client import REGISTRY, start_http_server from qbittorrent_exporter.exporter import QbittorrentMetricsCollector, get_config # Load config from environment config = get_config() # Create and register collector collector = QbittorrentMetricsCollector(config) REGISTRY.register(collector) # Start HTTP server start_http_server(8000, "0.0.0.0") # Prometheus will call collect() on each /metrics request ``` -------------------------------- ### File-Based Configuration Example Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/quick-reference.md Use this method to load sensitive values like passwords or API keys from files, which is particularly useful for containerized environments like Docker Secrets. The exporter reads the file content for these specific environment variables. ```bash export FILE__QBITTORRENT_PASS=/run/secrets/qbt_password export FILE__QBITTORRENT_API_KEY=/run/secrets/qbt_api_key qbittorrent-exporter ``` -------------------------------- ### Exporter Entry Point Flow Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/api-reference/exporter.md Illustrates the sequence of operations performed when the exporter starts, from logging initialization to the main execution loop. It highlights configuration loading, validation, component creation, and server startup. ```plaintext main() ├─ Initialize logging (level=INFO) ├─ Call get_config() │ └─ For each config key, call _get_config_value() │ ├─ Check FILE__{key} │ └─ Check {key} ├─ Update logger level from config ├─ Create ShutdownSignalHandler() ├─ Validate QBITTORRENT_HOST (required) ├─ Validate QBITTORRENT_PORT (required) ├─ Create QbittorrentMetricsCollector(config) ├─ Register collector with REGISTRY ├─ Call start_http_server(port, address) ├─ Log startup message └─ Main loop: └─ while not signal_handler.is_shutting_down(): └─ sleep(1) ``` -------------------------------- ### Metric Name Examples Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/api-reference/metric.md Examples of valid metric names that adhere to Prometheus naming conventions. ```python "qbittorrent_up" ``` ```python "qbittorrent_torrents_count" ``` ```python "qbittorrent_dht_nodes" ``` -------------------------------- ### Metric Value Examples Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/api-reference/metric.md Examples of numerical values that can be reported for metrics. Boolean values are converted to 0 or 1. ```python 1 ``` ```python 0 ``` ```python 1073741824 ``` ```python 42 ``` -------------------------------- ### Initialize QbittorrentMetricsCollector Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/api-reference/qbittorrent-metrics-collector.md Instantiate the QbittorrentMetricsCollector with a configuration dictionary. The configuration includes details like host, port, authentication credentials, and exporter settings. The qBittorrent client is not created until the collect() method is called. ```python from qbittorrent_exporter.exporter import QbittorrentMetricsCollector config = { "host": "qbittorrent.example.com", "port": "8080", "ssl": False, "url_base": "qbt/", "username": "admin", "password": "password", "api_key": "", "exporter_address": "0.0.0.0", "exporter_port": 8000, "log_level": "INFO", "metrics_prefix": "qbittorrent", "export_metrics_by_torrent": False, "verify_webui_certificate": True, } collector = QbittorrentMetricsCollector(config) ``` -------------------------------- ### Run Exporter using Docker Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/README.md Deploy the exporter using Docker. Map the exporter's port to the host and set qBittorrent connection details via environment variables. ```bash docker run \ -e QBITTORRENT_HOST=qbittorrent \ -e QBITTORRENT_PORT=8080 \ -p 8000:8000 \ ghcr.io/esanchezm/prometheus-qbittorrent-exporter ``` -------------------------------- ### Loading Configuration Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/module-overview.md Shows how configuration is loaded at startup, typically from environment variables, and then used to initialize components like the collector. ```python config = get_config() # Load from environment collector = QbittorrentMetricsCollector(config) # Use config ``` -------------------------------- ### GET /metrics Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Exposes Prometheus metrics for qBittorrent. This endpoint is used by Prometheus to scrape metrics from the exporter. ```APIDOC ## GET /metrics ### Description Exposes Prometheus metrics for qBittorrent. This endpoint is used by Prometheus to scrape metrics from the exporter. ### Method GET ### Endpoint /metrics ### Parameters None ### Request Example None ### Response #### Success Response (200) - **metrics** (string) - Prometheus text format metrics. #### Response Example # HELP qbittorrent_up qBittorrent exporter status (1 = up, 0 = down) # TYPE qbittorrent_up gauge qbittorrent_up 1 # HELP qbittorrent_connected qBittorrent connection status (1 = connected, 0 = disconnected) # TYPE qbittorrent_connected gauge qbittorrent_connected 1 # HELP qbittorrent_firewalled qBittorrent firewall status (1 = firewalled, 0 = not firewalled) # TYPE qbittorrent_firewalled gauge qbittorrent_firewalled 0 # HELP qbittorrent_dht_nodes DHT nodes count # TYPE qbittorrent_dht_nodes gauge qbittorrent_dht_nodes 150 # HELP qbittorrent_torrents_count Total number of torrents # TYPE qbittorrent_torrents_count gauge qbittorrent_torrents_count 25 # HELP qbittorrent_torrent_size Total size of torrents in bytes # TYPE qbittorrent_torrent_size gauge qbittorrent_torrent_size 1234567890 # HELP qbittorrent_torrent_downloaded Total downloaded bytes for torrents # TYPE qbittorrent_torrent_downloaded gauge qbittorrent_torrent_downloaded 9876543210 ``` -------------------------------- ### Configure Basic Authentication Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/quick-reference.md Set environment variables for username and password if your qBittorrent Web UI requires basic authentication. ```bash QBITTORRENT_USER=admin QBITTORRENT_PASS=password ``` -------------------------------- ### Creating a Fresh API Client Per Scrape Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/module-overview.md Illustrates the pattern of creating a new qBittorrent API client for each metric collection cycle. This prevents stale data by ensuring a fresh connection and state. ```python def collect(self): self._create_client() # Fresh client on each scrape # ... ``` -------------------------------- ### Start Prometheus HTTP Server Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/endpoints.md Registers the exporter endpoint with the Prometheus client. Ensure the port and address are configured correctly. ```python from prometheus_client import start_http_server start_http_server(config["exporter_port"], config["exporter_address"]) ``` -------------------------------- ### Initialize and Collect Metrics with QbittorrentMetricsCollector Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/module-overview.md Instantiate the QbittorrentMetricsCollector with a configuration dictionary and iterate over its collected Prometheus metrics. This is typically called by the Prometheus registry. ```python from qbittorrent_exporter.exporter import QbittorrentMetricsCollector # Constructor collector = QbittorrentMetricsCollector(config) # Public method (called by Prometheus) for metric_family in collector.collect(): print(metric_family) ``` -------------------------------- ### get_config() Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/module-overview.md Loads the application configuration from environment variables. This function is used to retrieve settings required for the exporter to connect to qBittorrent and operate. ```APIDOC ## get_config() ### Description Loads the application's configuration by reading values from environment variables. This function is essential for setting up the exporter with the necessary connection details and operational parameters. ### Returns A dictionary containing the loaded configuration. ### Usage Example ```python from qbittorrent_exporter.exporter import get_config config = get_config() print(config["metrics_prefix"]) ``` ``` -------------------------------- ### _create_client Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/api-reference/qbittorrent-metrics-collector.md Create or recreate the qBittorrent API client. This method is called internally by `collect()` to ensure a fresh client instance. ```APIDOC ## _create_client ### Description Create or recreate the qBittorrent API client. This method is called internally by `collect()` to ensure a fresh client instance. ### Method ```python def _create_client(self) -> None ``` ### Parameters None. ### Return Value None. Sets `self.client` as a side effect. ### Behavior - Initializes `client_args` dict with `host` and `VERIFY_WEBUI_CERTIFICATE` - If `api_key` is configured: adds `EXTRA_HEADERS` with Bearer token authentication - If `api_key` is not configured: adds `username` and `password` for basic authentication - Instantiates `qbittorrentapi.Client` with the constructed arguments - Called once per `collect()` invocation to ensure fresh state ### Example ```python collector = QbittorrentMetricsCollector(config) collecor._create_client() # collector.client is now ready to use requests = collector.client.sync_maindata() ``` ``` -------------------------------- ### Custom Python Configuration Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/README.md Shows how to define a custom configuration dictionary for the `QbittorrentMetricsCollector`. This allows overriding default connection, authentication, and exporter settings. ```python config = { "host": "qbittorrent.example.com", "port": "8080", "ssl": False, "url_base": "", "username": "admin", "password": "password", "api_key": "", "exporter_address": "0.0.0.0", "exporter_port": 8000, "log_level": "INFO", "metrics_prefix": "qbittorrent", "export_metrics_by_torrent": False, "verify_webui_certificate": True, } collector = QbittorrentMetricsCollector(config) ``` -------------------------------- ### HTTP GET Request for Metrics Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/quick-reference.md Use this endpoint to retrieve Prometheus-formatted metrics from the exporter. The output includes help and type information for each metric. ```http GET http://localhost:8000/metrics ``` -------------------------------- ### Get Per-Torrent Metrics Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/api-reference/qbittorrent-metrics-collector.md Fetch metrics for individual torrents, including their size and downloaded data, if enabled in the configuration. This method returns a list of `GaugeMetricFamily` instances. ```python metrics = collector._get_qbittorrent_by_torrent_metric_gauges() ``` -------------------------------- ### Configure API Key Authentication Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/quick-reference.md Use the QBITTORRENT_API_KEY environment variable for authentication if you are using qBittorrent version 5.2 or later. ```bash QBITTORRENT_API_KEY=qbt_abc123... ``` -------------------------------- ### GET /metrics Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/endpoints.md This endpoint provides Prometheus metrics. It responds with all collected metrics in the standard Prometheus exposition format, including help text and type information for each metric. ```APIDOC ## GET /metrics ### Description Prometheus metrics endpoint. Responds with all collected metrics in Prometheus exposition format. ### Method GET ### Endpoint /metrics ### Response #### Success Response (200) - **Content-Type**: `text/plain; version=0.0.4; charset=utf-8` - **Body**: Prometheus-formatted metrics ### Response Schema The response contains metrics in Prometheus text format. Each metric consists of: - `# HELP {name} {description}` — Documentation line - `# TYPE {name} {type}` — Type line (gauge or counter) - `{name}{labels} {value}` — Metric lines ### Example Response ``` # HELP qbittorrent_up Whether the qBittorrent server is answering requests from this exporter. A `version` label with the server version is added. # TYPE qbittorrent_up gauge qbittorrent_up{version="1.7.0",server="localhost:8080"} 1.0 # HELP qbittorrent_connected Whether the qBittorrent server is connected to the Bittorrent network. # TYPE qbittorrent_connected gauge qbittorrent_connected{server="localhost:8080"} 1.0 # HELP qbittorrent_firewalled Whether the qBittorrent server is connected to the Bittorrent network but is behind a firewall. # TYPE qbittorrent_firewalled gauge qbittorrent_firewalled{server="localhost:8080"} 0.0 # HELP qbittorrent_dht_nodes Number of DHT nodes connected to. # TYPE qbittorrent_dht_nodes gauge qbittorrent_dht_nodes{server="localhost:8080"} 150.0 # HELP qbittorrent_total_peer_connections Total number of peer connections. # TYPE qbittorrent_total_peer_connections gauge qbittorrent_total_peer_connections{server="localhost:8080"} 42.0 # HELP qbittorrent_dl_info_data Data downloaded since the server started, in bytes. # TYPE qbittorrent_dl_info_data counter qbittorrent_dl_info_data{server="localhost:8080"} 1073741824.0 # HELP qbittorrent_up_info_data Data uploaded since the server started, in bytes. # TYPE qbittorrent_up_info_data counter qbittorrent_up_info_data{server="localhost:8080"} 536870912.0 # HELP qbittorrent_alltime_dl Total historical data downloaded, in bytes. # TYPE qbittorrent_alltime_dl counter qbittorrent_alltime_dl{server="localhost:8080"} 5368709120.0 # HELP qbittorrent_alltime_ul Total historical data uploaded, in bytes. # TYPE qbittorrent_alltime_ul counter qbittorrent_alltime_ul{server="localhost:8080"} 2684354560.0 # HELP qbittorrent_torrents_count Number of torrents # TYPE qbittorrent_torrents_count gauge qbittorrent_torrents_count{status="error",category="Uncategorized",server="localhost:8080"} 0.0 qbittorrent_torrents_count{status="allocating",category="Uncategorized",server="localhost:8080"} 0.0 qbittorrent_torrents_count{status="checking",category="Uncategorized",server="localhost:8080"} 0.0 qbittorrent_torrents_count{status="downloading",category="Uncategorized",server="localhost:8080"} 2.0 qbittorrent_torrents_count{status="forcedDL",category="Uncategorized",server="localhost:8080"} 0.0 qbittorrent_torrents_count{status="uploading",category="Uncategorized",server="localhost:8080"} 5.0 qbittorrent_torrents_count{status="forcedUL",category="Uncategorized",server="localhost:8080"} 0.0 qbittorrent_torrents_count{status="queuedForChecking",category="Uncategorized",server="localhost:8080"} 0.0 qbittorrent_torrents_count{status="queuedForDownload",category="Uncategorized",server="localhost:8080"} 1.0 qbittorrent_torrents_count{status="queuedForSeeding",category="Uncategorized",server="localhost:8080"} 0.0 qbittorrent_torrents_count{status="metaDL",category="Uncategorized",server="localhost:8080"} 0.0 qbittorrent_torrents_count{status="paused_DL",category="Uncategorized",server="localhost:8080"} 0.0 qbittorrent_torrents_count{status="paused_UL",category="Uncategorized",server="localhost:8080"} 3.0 qbittorrent_torrents_count{status="resuming",category="Uncategorized",server="localhost:8080"} 0.0 qbittorrent_torrents_count{status="seeding",category="Uncategorized",server="localhost:8080"} 0.0 qbittorrent_torrents_count{status="unknown",category="Uncategorized",server="localhost:8080"} 0.0 qbittorrent_torrents_count{status="downloading",category="Movies",server="localhost:8080"} 1.0 qbittorrent_torrents_count{status="uploading",category="Movies",server="localhost:8080"} 3.0 ``` ``` -------------------------------- ### Standard Environment Variables Configuration Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/configuration.md Configure the exporter using standard environment variables for qBittorrent connection and exporter settings. Ensure all necessary variables are exported before running the exporter. ```bash export QBITTORRENT_HOST=qbittorrent.example.com export QBITTORRENT_PORT=8080 export QBITTORRENT_SSL=False export QBITTORRENT_URL_BASE="" export QBITTORRENT_USER=admin export QBITTORRENT_PASS=mysecretpassword export EXPORTER_ADDRESS=0.0.0.0 export EXPORTER_PORT=8000 export EXPORTER_LOG_LEVEL=INFO export METRICS_PREFIX=qbittorrent export EXPORT_METRICS_BY_TORRENT=False export VERIFY_WEBUI_CERTIFICATE=True qbittorrent-exporter ``` -------------------------------- ### Set qBittorrent Password via Environment Variable Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/configuration.md Configure the password for basic HTTP authentication by setting the QBITTORRENT_PASS environment variable. This is ignored if QBITTORRENT_API_KEY is set. ```bash QBITTORRENT_PASS=mysecretpassword ``` -------------------------------- ### Get Torrent Count Metrics by Category and State Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/api-reference/qbittorrent-metrics-collector.md Retrieves torrent count metrics grouped by category and status. Use this to understand the distribution of torrents across different states and categories. ```python collector = QbittorrentMetricsCollector(config) gauge = collector._get_qbittorrent_torrent_tags_metrics_gauge() for sample in gauge.samples: print(f"Category {sample.labels['category']}, Status {sample.labels['status']}: {sample.value} torrents") ``` -------------------------------- ### Set Standard Environment Variables Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/configuration.md Configure the exporter by setting standard environment variables for qBittorrent connection details. This is the primary method for configuring the exporter. ```bash export QBITTORRENT_HOST=qbittorrent.example.com export QBITTORRENT_PORT=8080 qbittorrent-exporter ``` -------------------------------- ### API Key Authentication Configuration Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/configuration.md Configure the exporter using an API key for authentication with qBittorrent. This method is suitable when username/password authentication is not preferred or available. ```bash export QBITTORRENT_HOST=qbittorrent.example.com export QBITTORRENT_PORT=8080 export QBITTORRENT_SSL=True export QBITTORRENT_URL_BASE="" export QBITTORRENT_API_KEY=qbt_abcdefghijklmnopqrstuvwxyz0123456789 export EXPORTER_ADDRESS=0.0.0.0 export EXPORTER_PORT=8000 export EXPORTER_LOG_LEVEL=INFO export METRICS_PREFIX=qbittorrent export VERIFY_WEBUI_CERTIFICATE=True qbittorrent-exporter ``` -------------------------------- ### GET /metrics Endpoint Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/endpoints.md This endpoint provides Prometheus metrics in the exposition format. It is polled by Prometheus servers to collect exporter data. The response includes various qBittorrent statistics and status information. ```http GET /metrics HTTP/1.1 Host: exporter:8000 ``` ```text # HELP qbittorrent_up Whether the qBittorrent server is answering requests from this exporter. A `version` label with the server version is added. # TYPE qbittorrent_up gauge qbittorrent_up{version="1.7.0",server="localhost:8080"} 1.0 # HELP qbittorrent_connected Whether the qBittorrent server is connected to the Bittorrent network. # TYPE qbittorrent_connected gauge qbittorrent_connected{server="localhost:8080"} 1.0 # HELP qbittorrent_firewalled Whether the qBittorrent server is connected to the Bittorrent network but is behind a firewall. # TYPE qbittorrent_firewalled gauge qbittorrent_firewalled{server="localhost:8080"} 0.0 # HELP qbittorrent_dht_nodes Number of DHT nodes connected to. # TYPE qbittorrent_dht_nodes gauge qbittorrent_dht_nodes{server="localhost:8080"} 150.0 # HELP qbittorrent_total_peer_connections Total number of peer connections. # TYPE qbittorrent_total_peer_connections gauge qbittorrent_total_peer_connections{server="localhost:8080"} 42.0 # HELP qbittorrent_dl_info_data Data downloaded since the server started, in bytes. # TYPE qbittorrent_dl_info_data counter qbittorrent_dl_info_data{server="localhost:8080"} 1073741824.0 # HELP qbittorrent_up_info_data Data uploaded since the server started, in bytes. # TYPE qbittorrent_up_info_data counter qbittorrent_up_info_data{server="localhost:8080"} 536870912.0 # HELP qbittorrent_alltime_dl Total historical data downloaded, in bytes. # TYPE qbittorrent_alltime_dl counter qbittorrent_alltime_dl{server="localhost:8080"} 5368709120.0 # HELP qbittorrent_alltime_ul Total historical data uploaded, in bytes. # TYPE qbittorrent_alltime_ul counter qbittorrent_alltime_ul{server="localhost:8080"} 2684354560.0 # HELP qbittorrent_torrents_count Number of torrents # TYPE qbittorrent_torrents_count gauge qbittorrent_torrents_count{status="error",category="Uncategorized",server="localhost:8080"} 0.0 qbittorrent_torrents_count{status="allocating",category="Uncategorized",server="localhost:8080"} 0.0 qbittorrent_torrents_count{status="checking",category="Uncategorized",server="localhost:8080"} 0.0 qbittorrent_torrents_count{status="downloading",category="Uncategorized",server="localhost:8080"} 2.0 qbittorrent_torrents_count{status="forcedDL",category="Uncategorized",server="localhost:8080"} 0.0 qbittorrent_torrents_count{status="uploading",category="Uncategorized",server="localhost:8080"} 5.0 qbittorrent_torrents_count{status="forcedUL",category="Uncategorized",server="localhost:8080"} 0.0 qbittorrent_torrents_count{status="queuedForChecking",category="Uncategorized",server="localhost:8080"} 0.0 qbittorrent_torrents_count{status="queuedForDownload",category="Uncategorized",server="localhost:8080"} 1.0 qbittorrent_torrents_count{status="queuedForSeeding",category="Uncategorized",server="localhost:8080"} 0.0 qbittorrent_torrents_count{status="metaDL",category="Uncategorized",server="localhost:8080"} 0.0 qbittorrent_torrents_count{status="paused_DL",category="Uncategorized",server="localhost:8080"} 0.0 qbittorrent_torrents_count{status="paused_UL",category="Uncategorized",server="localhost:8080"} 3.0 qbittorrent_torrents_count{status="resuming",category="Uncategorized",server="localhost:8080"} 0.0 qbittorrent_torrents_count{status="seeding",category="Uncategorized",server="localhost:8080"} 0.0 qbittorrent_torrents_count{status="unknown",category="Uncategorized",server="localhost:8080"} 0.0 qbittorrent_torrents_count{status="downloading",category="Movies",server="localhost:8080"} 1.0 qbittorrent_torrents_count{status="uploading",category="Movies",server="localhost:8080"} 3.0 ``` -------------------------------- ### Enable Per-Torrent Metrics in qBittorrent Exporter Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/configuration.md Enable granular metrics for individual torrents, such as size and download progress. This setting increases the number of metrics and should be used cautiously if managing many torrents. ```bash EXPORT_METRICS_BY_TORRENT=True ``` ```bash EXPORT_METRICS_BY_TORRENT=False ``` ```bash EXPORT_METRICS_BY_TORRENT= ``` -------------------------------- ### Get Server Status Metrics Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/api-reference/qbittorrent-metrics-collector.md Fetch and process server status and network state metrics. This method retrieves data such as server uptime, connection status, DHT nodes, and total data transferred. ```python metrics = collector._get_qbittorrent_status_metrics() for metric in metrics: print(f"{metric.name}: {metric.value}") ``` -------------------------------- ### Configure SSL for qBittorrent Connection Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/configuration.md Set the QBITTORRENT_SSL environment variable to control HTTPS usage. Exact string match 'True' enables HTTPS; any other value disables it. Port 443 automatically forces HTTPS. ```bash QBITTORRENT_SSL=True # Explicitly enable HTTPS QBITTORRENT_SSL=False # Explicitly disable HTTPS QBITTORRENT_SSL= # Disables (anything except "True") ``` -------------------------------- ### Integration of ShutdownSignalHandler in Main Function Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/api-reference/shutdown-signal-handler.md This snippet shows how to integrate ShutdownSignalHandler within the main function of an exporter. It registers the signal handler before starting the HTTP server and entering the main loop, ensuring graceful shutdown. ```python def main(): # ... setup and validation ... signal_handler = ShutdownSignalHandler() # Register collector and start HTTP server logger.info("Exporter is starting up") REGISTRY.register(QbittorrentMetricsCollector(config)) start_http_server(config["exporter_port"], config["exporter_address"]) logger.info(f"Exporter listening on {config['exporter_address']}:{config['exporter_port']}") # Main loop while not signal_handler.is_shutting_down(): time.sleep(1) logger.info("Exporter has shutdown") if __name__ == "__main__": main() ``` -------------------------------- ### Set qBittorrent API Key via Environment Variable Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/configuration.md Configure the API key for Bearer token authentication by setting the QBITTORRENT_API_KEY environment variable. This requires qBittorrent 5.2 or later and overrides username/password authentication. ```bash QBITTORRENT_API_KEY=qbt_abcdefghijklmnopqrstuvwxyz0123456789 ``` -------------------------------- ### Fetch Torrents Directly for Debugging Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/errors.md This command can be used to directly fetch torrent information from the qBittorrent API, which can help in debugging 'Cannot Fetch Torrents' errors. ```bash curl http://host:port/api/v2/torrents/info ``` -------------------------------- ### Load Configuration from Environment Variables Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/api-reference/exporter.md Loads all configuration from environment variables. Converts string values to appropriate types (bool, int). Returns a fresh dictionary on each call. ```python from qbittorrent_exporter.exporter import get_config config = get_config() print(f"Exporter port: {config['exporter_port']}") print(f"qBittorrent host: {config['host']}") print(f"Metrics prefix: {config['metrics_prefix']}") ``` -------------------------------- ### Python: Get Configuration Value Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/api-reference/exporter.md Retrieves a configuration value from environment variables or files. It first checks for a file-based secret (FILE__KEY) and then falls back to a direct environment variable (KEY). A default value can be provided if neither is set. ```python from qbittorrent_exporter.exporter import _get_config_value # Standard environment variable password = _get_config_value("QBITTORRENT_PASS", "default_password") # File-based (Docker secrets) db_password = _get_config_value("DATABASE_PASSWORD", "") # Checks FILE__DATABASE_PASSWORD first, then DATABASE_PASSWORD # With default log_level = _get_config_value("LOG_LEVEL", "INFO") ``` -------------------------------- ### qBittorrent Metrics Exporter Configuration Dictionary Source: https://github.com/esanchezm/prometheus-qbittorrent-exporter/blob/master/_autodocs/types.md This dictionary outlines the structure and types of configuration parameters required for the qBittorrentMetricsCollector. It includes settings for qBittorrent connection, authentication, exporter behavior, and logging. ```python { "host": str, # qBittorrent hostname "port": str, # qBittorrent port "ssl": bool, # Use SSL for connection "url_base": str, # Base URL path for qBittorrent "username": str, # qBittorrent username "password": str, # qBittorrent password "api_key": str, # qBittorrent API key (5.2+) "exporter_address": str, # Exporter listening address "exporter_port": int, # Exporter listening port "log_level": str, # Logging level "metrics_prefix": str, # Prefix for all metrics "export_metrics_by_torrent": bool, # Export per-torrent metrics "verify_webui_certificate": bool, # Verify SSL certificate } ```