Proactive Home Assistant Host Monitoring: Integrating Glances for System Health and Alerts

Represent Proactive Home Assistant Host Monitoring: Integrating Glances for System Health and Alerts article
7m read

Intro

Running Home Assistant on a dedicated host like a Raspberry Pi, a virtual machine (VM) on Proxmox, or even a Docker container brings immense power and flexibility. However, the stability and performance of your smart home ecosystem are intrinsically tied to the health of its underlying host system. Generic Home Assistant monitoring typically focuses on integrations and device states, often overlooking critical host-level metrics like CPU temperature, disk space, RAM utilization, and system load. This oversight can lead to unexpected slowdowns, system crashes, or even data corruption, leaving your smart home in disarray.

This guide will walk you through integrating Glances, a powerful cross-platform system monitoring tool, with Home Assistant. By exposing your host's vital statistics to Home Assistant, you can build proactive automations, visualize performance trends, and receive timely alerts, ensuring your Home Assistant instance runs smoothly and reliably. We'll focus on practical, actionable steps for tech enthusiasts, practical homeowners, and integrators alike.

Step-by-Step Setup

1. Install and Configure Glances on Your Host System

First, you need to install Glances on the machine hosting your Home Assistant instance. Glances supports various operating systems, including Linux (Raspberry Pi OS, Ubuntu, Debian), Windows, and macOS.

For Linux (e.g., Raspberry Pi OS, Debian/Ubuntu):

The easiest way to install Glances is often via pip:

sudo apt update
sudo apt install python3-pip python3-dev
sudo pip install glances

Alternatively, if you prefer using your distribution's package manager:

sudo apt update
sudo apt install glances

Once installed, you need to start Glances in web server mode so Home Assistant can access its API. Choose a port (e.g., 61208) that isn't in use and ensure it's allowed through your firewall if applicable.

glances -w 0.0.0.0:61208 &

The & at the end will run Glances in the background. For persistent operation, consider creating a systemd service. To verify, open a web browser and navigate to http://[YOUR_HOST_IP]:61208. You should see the Glances web interface.

[Screenshot Placeholder: Glances web UI showing system metrics]

If you're using a firewall, ensure that port 61208 is open. For UFW (Uncomplicated Firewall):

sudo ufw allow 61208/tcp

2. Integrate Glances with Home Assistant via REST Sensor

Home Assistant can fetch data from Glances using its RESTful Sensor integration. This involves making HTTP GET requests to Glances' API endpoint.

Add the following to your configuration.yaml or a separate file included via !include directives. Replace YOUR_HOST_IP with the actual IP address of your Home Assistant host.

# configuration.yaml
sensor:
  - platform: rest
    resource: http://YOUR_HOST_IP:61208/api/3/all
    name: Glances System Monitor
    scan_interval: 30 # Poll every 30 seconds
    value_template: "OK" # A dummy value, we'll extract real data with templates
    json_attributes: # These will store the raw JSON response
      - cpu
      - mem
      - disk
      - sensors
      - load
      - network

After adding this, restart Home Assistant. Once restarted, navigate to Developer Tools > States. You should see an entity like sensor.glances_system_monitor with several attributes containing the raw data from Glances.

[Screenshot Placeholder: Home Assistant Developer Tools > States showing sensor.glances_system_monitor with JSON attributes]

3. Create Template Sensors for Granular Data

The sensor.glances_system_monitor provides raw JSON data. To make this data usable for automations and dashboards, we need to extract specific values and often perform unit conversions using Template Sensors.

Add the following template sensors to your configuration.yaml:

# configuration.yaml
template:
  - sensor:
      # CPU Usage Percentage
      - name: Glances CPU Used Percentage
        unique_id: glances_cpu_used_percentage
        unit_of_measurement: "%"
        state_class: measurement
        device_class: utilization
        state: >
          {% if state_attr('sensor.glances_system_monitor', 'cpu') %}
            {{ state_attr('sensor.glances_system_monitor', 'cpu').total | round(1) }}
          {% else %}
            unavailable
          {% endif %}

      # Memory Usage Percentage
      - name: Glances Memory Used Percentage
        unique_id: glances_memory_used_percentage
        unit_of_measurement: "%"
        state_class: measurement
        device_class: utilization
        state: >
          {% if state_attr('sensor.glances_system_monitor', 'mem') %}
            {{ state_attr('sensor.glances_system_monitor', 'mem').percent | round(1) }}
          {% else %}
            unavailable
          {% endif %}

      # Disk Usage Percentage (adjust disk name if necessary, 'sda' or 'mmcblk0p1' are common)
      - name: Glances Disk Used Percentage
        unique_id: glances_disk_used_percentage
        unit_of_measurement: "%"
        state_class: measurement
        device_class: utilization
        state: >
          {% if state_attr('sensor.glances_system_monitor', 'disk') %}
            {% set disk_info = state_attr('sensor.glances_system_monitor', 'disk') | selectattr('fsname', 'equalto', '/dev/sda') | list | first %}
            {% if disk_info %}
              {{ disk_info.percent | round(1) }}
            {% else %}
              unavailable
            {% endif %}
          {% else %}
            unavailable
          {% endif %}

      # CPU Temperature (adjust sensor name if necessary, 'cpu_thermal' or 'Package id 0' are common)
      - name: Glances CPU Temperature
        unique_id: glances_cpu_temperature
        unit_of_measurement: "°C"
        state_class: measurement
        device_class: temperature
        state: >
          {% if state_attr('sensor.glances_system_monitor', 'sensors') %}
            {% set temp_info = state_attr('sensor.glances_system_monitor', 'sensors') | selectattr('label', 'equalto', 'cpu_thermal') | list | first %}
            {% if temp_info %}
              {{ temp_info.value | round(1) }}
            {% else %}
              unavailable
            {% endif %}
          {% else %}
            unavailable
          {% endif %}

      # Load Average (1 minute)
      - name: Glances Load Average 1min
        unique_id: glances_load_average_1min
        unit_of_measurement: "Load"
        state_class: measurement
        state: >
          {% if state_attr('sensor.glances_system_monitor', 'load') %}
            {{ state_attr('sensor.glances_system_monitor', 'load').min1 | round(2) }}
          {% else %}
            unavailable
          {% endif %}

Important: You may need to inspect the raw JSON from sensor.glances_system_monitor (in Developer Tools > States > Attributes) to find the correct fsname for your disk and label for your CPU temperature sensor, as these can vary between systems.

[Screenshot Placeholder: Home Assistant Template Editor showing a valid template extracting a value from Glances attributes]

Restart Home Assistant again. You should now have individual sensors like sensor.glances_cpu_used_percentage, sensor.glances_memory_used_percentage, etc., which you can add to your Lovelace dashboard, use in automations, and track historical data.

Troubleshooting Section

  • Glances Data Not Showing Up in Home Assistant:
    • Check Glances Status: Ensure Glances is running in web server mode on your host (glances -w) and that the port is correct. You should be able to access it via http://YOUR_HOST_IP:61208 in a browser.
    • Firewall: Verify that your host's firewall (e.g., UFW, iptables, Proxmox firewall) allows incoming connections on the Glances port (default 61208) from your Home Assistant instance.
    • Home Assistant Logs: Check Home Assistant's logs (Settings > System > Logs) for errors related to the rest sensor. Look for messages like "Retrying setup: HTTPConnectionPool" or "JSONDecodeError."
    • Incorrect URL: Double-check the resource URL in your rest sensor configuration. It should precisely match your Glances instance's address and port.
  • Incorrect Values or Units for Template Sensors:
    • Inspect Raw JSON: Go to Developer Tools > States, find sensor.glances_system_monitor, and inspect its attributes. The structure of the cpu, mem, disk, and sensors objects is crucial.
    • Adjust Template Paths: Modify the template sensor's state template to match the exact keys and structure in the raw JSON. For example, if your disk is /dev/nvme0n1p2 instead of /dev/sda, update the selectattr('fsname', 'equalto', '/dev/sda') part. Similarly, for CPU temperature, the label might be different (e.g., 'Package id 0' or 'Tctl').
    • Use Template Editor: The Developer Tools > Template editor is invaluable for testing your Jinja2 templates against the actual state attributes of sensor.glances_system_monitor.
  • High CPU Usage on Host After Installing Glances:
    • Glances is generally lightweight, but continuous polling can add overhead. If you notice a significant increase in host CPU usage, ensure you only have one instance of Glances running.
    • Reduce the scan_interval of your rest sensor in Home Assistant (e.g., from 30s to 60s or more) if you don't need real-time updates for every metric.

Advanced Config / Optimization

  • Conditional Polling for Less Critical Metrics: For metrics that don't need frequent updates (e.g., disk usage that changes slowly), you can create separate rest sensors with longer scan_intervals or even use homeassistant.update_entity in automations to trigger updates only when needed.
  • Custom Glances Configuration (glances.conf): Glances has a configuration file that allows you to customize many aspects, such as which plugins are active, refresh rates, and thresholds. This can be useful for reducing the data payload if you only need specific metrics. You can find its location by running glances --configuration.
  • Securing Glances: For production environments, exposing Glances publicly without authentication is risky. Consider these options:
    • Basic Authentication: Glances supports basic HTTP authentication. You can configure this in its glances.conf file.
    • Reverse Proxy: Use a reverse proxy like Nginx or Caddy with SSL and authentication to protect access to Glances.
    • Firewall Rules: Restrict access to the Glances port (e.g., 61208) on your host system to only allow connections from your Home Assistant instance's IP address.
  • Optimizing Template Sensors: While powerful, complex Jinja2 templates can consume CPU cycles. Keep your templates as lean as possible. If a piece of logic is used repeatedly, consider refactoring or creating helper sensors.

Real-World Example: Proactive Disk Space Alert and Cleanup Trigger

Let's build an automation that alerts you when your host's disk space is critically low and offers an option to trigger a cleanup script.

1. Define a Disk Cleanup Script

First, create a simple shell script on your Home Assistant host (e.g., /config/scripts/cleanup_disk.sh) to clear temporary files or old logs. Make it executable (`chmod +x /config/scripts/cleanup_disk.sh`).

#!/bin/bash

# Example cleanup: clear apt cache (for Debian/Ubuntu based systems)
sudo apt clean

# Example cleanup: clear old Docker images/volumes (if running HA in Docker)
# docker system prune -f

# Add any other cleanup commands relevant to your system
logger "Home Assistant disk cleanup script executed."

Then, create a Home Assistant shell_command to execute this script:

# configuration.yaml
shell_command:
  execute_disk_cleanup: "bash /config/scripts/cleanup_disk.sh"

2. Create an Automation for Low Disk Space Alerts

This automation will trigger when disk usage exceeds 90% and send a persistent notification with an action to run the cleanup script.

# configuration.yaml or automations.yaml
automation:
  - id: 'disk_space_critical_alert'
    alias: 'Host Disk Space Critical Alert'
    description: 'Notifies when host disk space is > 90% and offers cleanup action.'
    trigger:
      - platform: numeric_state
        entity_id: sensor.glances_disk_used_percentage
        above: 90
        for:
          minutes: 5 # Trigger only if sustained for 5 minutes
    condition:
      - condition: state
        entity_id: input_boolean.disk_cleanup_triggered # Use an input_boolean to prevent spam
        state: 'off'
    action:
      - service: persistent_notification.create
        data:
          title: "Home Assistant Host Alert: Critical Disk Space"
          message: "Your Home Assistant host disk usage is {{ states('sensor.glances_disk_used_percentage') }}%. Consider running cleanup."
          notification_id: "host_disk_alert"
      - service: persistent_notification.create
        data_template:
          title: "Disk Cleanup Action"
          message: "Click here to run disk cleanup script: {{ '/api/services/shell_command/execute_disk_cleanup' | url }}"
          notification_id: "disk_cleanup_action"
      - service: input_boolean.turn_on
        target:
          entity_id: input_boolean.disk_cleanup_triggered
    mode: single

  - id: 'disk_space_recovery_reset'
    alias: 'Host Disk Space Recovery Reset'
    description: 'Resets the alert flag when disk space drops below 85%.'
    trigger:
      - platform: numeric_state
        entity_id: sensor.glances_disk_used_percentage
        below: 85
        for:
          minutes: 10
    action:
      - service: input_boolean.turn_off
        target:
          entity_id: input_boolean.disk_cleanup_triggered
      - service: persistent_notification.dismiss
        data:
          notification_id: "host_disk_alert"
      - service: persistent_notification.dismiss
        data:
          notification_id: "disk_cleanup_action"
    mode: single

Don't forget to create an input_boolean named input_boolean.disk_cleanup_triggered in your configuration.yaml or via the UI to prevent notification spam:

# configuration.yaml
input_boolean:
  disk_cleanup_triggered:
    name: Disk Cleanup Triggered Flag
    initial: off
    icon: mdi:broom
[Screenshot Placeholder: Home Assistant Automation editor showing the low disk space alert automation]

Best Practices / Wrap-up

Integrating Glances for host monitoring is a significant step towards a more robust and reliable Home Assistant setup. To maximize its benefits and ensure long-term stability:

  • Reliability: Don't just monitor; automate responses. Set up critical alerts for CPU temperature (to prevent throttling or damage), low disk space (to prevent data loss), and high RAM/CPU load (to diagnose performance bottlenecks).
  • Performance: Be mindful of the polling interval for your REST sensors. While 30 seconds is often fine, for very resource-constrained devices like older Raspberry Pis, a 60-second or longer interval might be preferable. Only collect metrics you truly need.
  • Security: Always secure your Glances web interface, especially if it's accessible from outside your local network. Use strong passwords, firewall rules, or a reverse proxy with authentication and SSL. Keep your host operating system and Glances package updated.
  • Scalability: As your Home Assistant instance grows, so does the potential load on your host. Monitoring with Glances provides the data to identify bottlenecks early, allowing you to upgrade hardware or optimize configurations proactively.
  • Backup Strategies: While monitoring helps prevent issues, it doesn't replace a solid backup strategy. Regularly back up your Home Assistant configuration and, ideally, a full image of your host system.

By implementing these Glances-powered monitoring and automation strategies, you transform your Home Assistant from a reactive smart home controller into a proactive guardian of its own operational health. Start small, monitor key metrics, and gradually build out automations that keep your smart home running smoothly around the clock.

Avatar picture of NGC 224
Written by:

NGC 224

Author bio: DIY Smart Home Creator

There are no comments yet
loading...