How CasaOS Monitors System Health and Updates Hardware Status: A Deep Dive into the Go Implementation
CasaOS monitors system health and hardware status through a layered architecture that combines Go-based services (HealthService and SystemService), the gopsutil library, and REST API endpoints exposed via route/v1/system.go and route/v2/health.go.
The open-source CasaOS project by IceWhaleTech provides a lightweight home cloud OS that requires real-time visibility into host health and hardware components. Understanding how CasaOS monitors system health and updates hardware status reveals a clean separation between data collection services and HTTP API layers. This implementation leverages native Go libraries alongside system utilities to expose CPU metrics, memory usage, disk statistics, and service states through structured JSON endpoints.
HealthService Implementation
The HealthService interface, defined in service/health.go, focuses on software-level health by tracking CasaOS-related systemd services and network port utilization.
Monitoring CasaOS Services
The Services() method queries the host's systemd state to distinguish between running and stopped CasaOS components. It invokes systemctl.ListServices("casaos*") from the pkg/utils/systemctl package in CasaOS-Common, returning a map that categorizes service names by their boolean state.
Tracking Network Ports
To identify port conflicts, the Ports() method forwards calls to port.ListPortsInUse() from the pkg/utils/port utility in CasaOS-Common. This returns a slice of integers representing occupied TCP and UDP ports currently in use by the system.
SystemService Hardware Monitoring
The SystemService in service/system.go provides comprehensive hardware introspection using the gopsutil library supplemented by direct /sys filesystem reads and helper scripts.
CPU Metrics and Temperature
CPU data collection relies on multiple gopsutil wrappers and system file parsing:
GetCpuInfo()returns processor model and architecture details viacpu.InfoStatGetCpuPercent()andGetCpuCoreNum()provide utilization percentages and core countsGetCPUTemperature()reads thermal-zone data or/sysclass files to return current temperature in CelsiusGetCPUPower()extracts energy consumption values (in µJ) from specific/sysfilesystem paths, returning a map withvalueandtimestampfields
Memory and Disk Utilization
Memory statistics come from GetMemInfo(), which wraps mem.VirtualMemory() to return total, available, and used memory metrics along with usage percentages. For storage, GetDiskInfo() calls disk.Usage("/") to report root filesystem capacity and consumption.
Network Interface Statistics
Network monitoring uses GetNetInfo(), GetNet(), and GetNetState() to aggregate interface counters. These methods invoke net.IOCounters from gopsutil and execute helper scripts to determine link states and transfer statistics for all network interfaces.
Device Tree Discovery
Low-level hardware identification, such as drive model detection, executes through GetDeviceTree(). This method runs the helper.sh script to parse system device trees, returning strings like "Samsung SSD 860" that identify specific storage hardware.
REST API Endpoints
CasaOS exposes collected metrics through versioned HTTP routes that serialize Go structs into JSON for frontend consumption.
Hardware Information Endpoint
The GET /sys/hardware/info handler in route/v1/system.go aggregates data by calling service.MyService.System().GetDeviceTree() and runtime.GOARCH. This endpoint returns a unified payload containing device tree information, CPU details, and system architecture.
System Utilization Endpoint
The GET /sys/utilization endpoint constructs a comprehensive JSON response including CPU percent, core count, temperature, power consumption, memory statistics, disk usage, and network counters. All data originates from the SystemService methods defined in service/system.go.
Health Check Endpoint
Defined in route/v2/health.go with mirrored functionality in v1, the health endpoint instantiates NewHealthService() to return the service state map and active port list. This allows the frontend to display which CasaOS services are alive and identify potential port conflicts.
Practical Implementation Examples
The following Go patterns demonstrate how to interact with these services directly:
// Retrieve running CasaOS services and used ports
svc := service.NewHealthService()
services, _ := svc.Services() // map[bool]*[]string{true:running, false:stopped}
portsInUse, _, _ := svc.Ports() // []int of occupied TCP/UDP ports
// Get detailed hardware status (used by /sys/hardware/info)
sys := service.NewSystemService()
deviceTree := sys.GetDeviceTree() // e.g. "Samsung SSD 860"
cpuInfo := sys.GetCpuInfo() // []cpu.InfoStat
temp := sys.GetCPUTemperature() // °C
power := sys.GetCPUPower() // map[string]string{"value":"123456","timestamp":"..."}
mem := sys.GetMemInfo() // map[string]interface{}{"total":..., "usedPercent":...}
disk := sys.GetDiskInfo() // *disk.UsageStat
net := sys.GetNetInfo() // []net.IOCountersStat
Summary
- HealthService (
service/health.go) monitors CasaOS systemd services and network ports viasystemctl.ListServices()andport.ListPortsInUse(). - SystemService (
service/system.go) collects hardware metrics using gopsutil for CPU, memory, disk, and network data, while reading/sysfiles directly for temperature and power consumption. - Device discovery relies on
helper.shscripts executed throughGetDeviceTree()to identify specific hardware models. - REST endpoints in
route/v1/system.goandroute/v2/health.goexpose all metrics throughGET /sys/hardware/info,GET /sys/utilization, and health check routes.
Frequently Asked Questions
How does CasaOS read CPU temperature without external sensors?
CasaOS reads CPU temperature through the GetCPUTemperature() method in service/system.go, which parses thermal-zone files or specific /sys class paths to return values in Celsius. This approach requires no external hardware sensors, relying instead on kernel-exposed thermal interfaces available on Linux systems.
What library handles system metrics in CasaOS?
CasaOS uses the gopsutil Go library to collect system metrics. This library provides cross-platform functions for CPU info (cpu.InfoStat), memory statistics (mem.VirtualMemory()), disk usage (disk.Usage()), and network counters (net.IOCounters), which the SystemService wraps and normalizes into Go structs.
How does CasaOS determine which services are currently running?
The system determines running services through HealthService.Services() in service/health.go, which calls systemctl.ListServices("casaos*") from the CasaOS-Common library. This filters systemd services matching the "casaos" pattern and returns them categorized as running or stopped based on their current systemd state.
Where does CasaOS get detailed hardware device information?
Detailed hardware information comes from GetDeviceTree() in service/system.go, which executes the helper.sh script to parse system device trees and identify specific components like drive models. This complements the generic metrics from gopsutil with specific hardware identifiers necessary for the web UI display.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →