initial proof of concept

This commit is contained in:
alu
2026-08-04 20:12:47 +00:00
commit cc4698e311
10 changed files with 543 additions and 0 deletions
+3
View File
@@ -0,0 +1,3 @@
**/go.sum
**/config.json
dist/*
+11
View File
@@ -0,0 +1,11 @@
.PHONY: build clean
build: clean
@echo "======================== Building Binary ======================="
mkdir -p dist
CGO_ENABLED=0 go build -ldflags="-s -w" -v -o dist/ .
clean:
@echo "======================== Cleaning Project ======================"
go clean
rm -rf dist/*
+39
View File
@@ -0,0 +1,39 @@
package app
import (
"finally-a-monolithic-linux-hw-monitor/app/cpu"
"fmt"
"os"
"os/signal"
"strings"
"syscall"
"time"
)
func Run() {
// Clear terminal screen and hide cursor
fmt.Print("\033[2J\033[?25l")
// Ensure cursor is restored when exiting (Ctrl+C / SIGTERM)
cleanupChannel := make(chan os.Signal, 1)
signal.Notify(cleanupChannel, os.Interrupt, syscall.SIGTERM)
go func() {
<-cleanupChannel
// Restore cursor and move below output
fmt.Print("\033[?25h\n")
os.Exit(0)
}()
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
for {
console := &strings.Builder{}
cpu.RenderCPU(console)
console.WriteString("\nPress Ctrl+C to exit.\033[K\n")
fmt.Print(console.String())
<-ticker.C
}
}
+30
View File
@@ -0,0 +1,30 @@
package cpu
import (
"finally-a-monolithic-linux-hw-monitor/app/cpu/proc"
"fmt"
"strings"
)
func RenderCPU(console *strings.Builder) {
proc, err := proc.GetProc()
if err != nil {
return
}
// Move cursor to top-left (0,0) without clearing full buffer (flicker-free)
console.WriteString("\033[H")
console.WriteString(fmt.Sprintf("=== %s ===\n", proc.Model()))
RenderTemperatures(console, proc)
}
func RenderTemperatures(console *strings.Builder, proc proc.Proc) {
temps, _ := proc.SensorReader.ReadTemperatureSensors()
for _, sensor := range temps {
tempC := sensor.TempC
tempF := (tempC * 9 / 5) + 32
// \033[K clears from cursor to end of line (prevents lingering chars)
console.WriteString(fmt.Sprintf("Sensor: %-25s | %5.1f°C (%5.1f°F)\033[K\n", sensor.Name, tempC, tempF))
}
}
+85
View File
@@ -0,0 +1,85 @@
package proc
import (
"bufio"
"fmt"
"os"
"strings"
)
type Proc struct {
Info map[string]string
SensorReader CPUSensorReader
}
type CPUSensorReader interface {
ReadTemperatureSensors() ([]TempSensor, error)
}
type TempSensor struct {
Name string
TempC float64
}
const (
VendorIntel string = "GenuineIntel"
VendorAMD string = "AuthenticAMD"
VendorUnknown string = "Unknown"
)
func GetProc() (Proc, error) {
// open and parse cpuinfo
proc := Proc{}
procFile, err := os.Open("/proc/cpuinfo")
if err != nil {
return proc, err
}
defer procFile.Close()
proc.Info = map[string]string{}
scanner := bufio.NewScanner(procFile)
for scanner.Scan() {
line := scanner.Text()
line = strings.ReplaceAll(line, "\t", "")
if line != "" {
x := strings.Split(line, ": ")
if len(x) != 2 {
continue
}
key := x[0]
value := x[1]
proc.Info[key] = value
}
}
return proc, proc.getSensorReader()
}
func (proc *Proc) getSensorReader() error {
// get vendor string and initialize sensor reader
vendor := proc.Vendor()
if vendor == VendorIntel {
intelReader, err := NewIntelReader()
proc.SensorReader = intelReader
return err
}
if vendor == VendorAMD {
amdReader, err := NewAMDReader()
proc.SensorReader = amdReader
return err
}
return fmt.Errorf("proc type %s is not supported", vendor)
}
func (proc *Proc) Vendor() string {
return proc.Info["vendor_id"]
}
func (proc *Proc) Model() string {
return proc.Info["model name"]
}
+80
View File
@@ -0,0 +1,80 @@
package proc
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
type AMDReader struct {
hwmonDir string
driver string
}
type PowerState struct {
lastEnergy uint64
lastTime time.Time
}
func NewAMDReader() (*AMDReader, error) {
// Locate AMD k10temp or zenpower hwmon path
matches, err := filepath.Glob("/sys/class/hwmon/hwmon*")
if err != nil {
return nil, err
}
for _, dir := range matches {
b, err := os.ReadFile(filepath.Join(dir, "name"))
if err != nil {
continue
}
drv := strings.TrimSpace(string(b))
if drv == "k10temp" || drv == "zenpower" {
return &AMDReader{
hwmonDir: dir,
driver: drv,
}, nil
}
}
return nil, fmt.Errorf("k10temp/zenpower driver not found under /sys/class/hwmon/")
}
func (r *AMDReader) ReadTemperatureSensors() ([]TempSensor, error) {
inputs, err := filepath.Glob(filepath.Join(r.hwmonDir, "temp*_input"))
if err != nil || len(inputs) == 0 {
return nil, fmt.Errorf("no temperature inputs found in %s", r.hwmonDir)
}
temps := []TempSensor{}
for _, inputPath := range inputs {
valBytes, err := os.ReadFile(inputPath)
if err != nil {
continue
}
milliC, err := strconv.ParseFloat(strings.TrimSpace(string(valBytes)), 64)
if err != nil {
continue
}
labelPath := strings.TrimSuffix(inputPath, "_input") + "_label"
label := ""
if lBytes, err := os.ReadFile(labelPath); err == nil {
label = strings.TrimSpace(string(lBytes))
} else {
label = filepath.Base(strings.TrimSuffix(inputPath, "_input"))
}
temps = append(temps, TempSensor{
Name: label,
TempC: milliC / 1000.0,
})
}
return temps, nil
}
+76
View File
@@ -0,0 +1,76 @@
package proc
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
)
type IntelReader struct {
hwmonDir string
driver string
}
func NewIntelReader() (*IntelReader, error) {
// Locate Intel coretemp hwmon path
dirs, err := filepath.Glob("/sys/class/hwmon/hwmon*")
if err != nil {
return nil, err
}
hwmonDir := ""
for _, d := range dirs {
nameData, err := os.ReadFile(filepath.Join(d, "name"))
if err == nil && strings.TrimSpace(string(nameData)) == "coretemp" {
hwmonDir = d
break
}
}
if hwmonDir == "" {
return nil, fmt.Errorf("coretemp driver not found under /sys/class/hwmon/")
}
return &IntelReader{
hwmonDir: hwmonDir,
driver: "coretemp",
}, nil
}
func (r *IntelReader) ReadTemperatureSensors() ([]TempSensor, error) {
inputs, err := filepath.Glob(filepath.Join(r.hwmonDir, "temp*_input"))
if err != nil || len(inputs) == 0 {
return nil, fmt.Errorf("no temperature inputs found in %s", r.hwmonDir)
}
temps := []TempSensor{}
for _, inputPath := range inputs {
valBytes, err := os.ReadFile(inputPath)
if err != nil {
continue
}
milliC, err := strconv.ParseFloat(strings.TrimSpace(string(valBytes)), 64)
if err != nil {
continue
}
labelPath := strings.TrimSuffix(inputPath, "_input") + "_label"
label := ""
if lBytes, err := os.ReadFile(labelPath); err == nil {
label = strings.TrimSpace(string(lBytes))
} else {
label = filepath.Base(strings.TrimSuffix(inputPath, "_input"))
}
temps = append(temps, TempSensor{
Name: label,
TempC: milliC / 1000.0,
})
}
return temps, nil
}
+9
View File
@@ -0,0 +1,9 @@
package main
import (
app "finally-a-monolithic-linux-hw-monitor/app"
)
func main() {
app.Run()
}
+15
View File
@@ -0,0 +1,15 @@
module finally-a-monolithic-linux-hw-monitor
go 1.26.5
require (
github.com/go-ole/go-ole v1.2.6 // indirect
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect
github.com/shirou/gopsutil/v3 v3.24.5 // indirect
github.com/shoenig/go-m1cpu v0.1.6 // indirect
github.com/tklauser/go-sysconf v0.3.12 // indirect
github.com/tklauser/numcpus v0.6.1 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
golang.org/x/sys v0.20.0 // indirect
)
+195
View File
@@ -0,0 +1,195 @@
#!/usr/bin/env bash
#
# power.sh - Universal CPU Power & Multi-Core Temperature Monitor
INTERVAL=1.0 # Refresh rate in seconds
cleanup() {
tput cnorm 2>/dev/null
echo -e "\nExiting monitor."
exit 0
}
trap cleanup SIGINT SIGTERM
if [[ $EUID -ne 0 ]]; then
echo "Error: This script must be run as root to access CPU RAPL counters."
exit 1
fi
if ! command -v perf &>/dev/null; then
echo "Error: 'perf' command not found. Install with: apt install linux-perf"
exit 1
fi
VENDOR_ID=$(grep -m 1 'vendor_id' /proc/cpuinfo | awk '{print $3}')
# --- Detect RAPL Power Events ---
EVENTS=()
PERF_EVENTS_LIST=$(perf list 2>/dev/null)
if echo "$PERF_EVENTS_LIST" | grep -q "power/energy-pkg/"; then
EVENTS+=("-e" "power/energy-pkg/")
fi
if echo "$PERF_EVENTS_LIST" | grep -q "power_core/energy-core/"; then
EVENTS+=("-e" "power_core/energy-core/")
elif echo "$PERF_EVENTS_LIST" | grep -q "power/energy-cores/"; then
EVENTS+=("-e" "power/energy-cores/")
fi
if echo "$PERF_EVENTS_LIST" | grep -q "power/energy-ram/"; then
EVENTS+=("-e" "power/energy-ram/")
fi
if [[ ${#EVENTS[@]} -eq 0 ]]; then
echo "Error: No compatible RAPL energy events found on this system."
exit 1
fi
# --- Map Thermal Sensors ---
# Arrays to hold ordered (label, file_path) pairs
CORE_LABELS=()
CORE_PATHS=()
PKG_LABEL=""
PKG_PATH=""
for hwmon in /sys/class/hwmon/hwmon*; do
if [[ -f "$hwmon/name" ]]; then
DRIVER_NAME=$(cat "$hwmon/name" 2>/dev/null)
# Intel Sensors (coretemp)
if [[ "$DRIVER_NAME" == "coretemp" ]]; then
# Sort label files numerically (temp1_label, temp2_label...)
for label_file in $(ls -v "$hwmon"/temp*_label 2>/dev/null); do
if [[ -f "$label_file" ]]; then
LABEL=$(cat "$label_file" 2>/dev/null)
INPUT_FILE="${label_file%_label}_input"
if [[ "$LABEL" =~ Package ]]; then
PKG_LABEL="$LABEL"
PKG_PATH="$INPUT_FILE"
elif [[ "$LABEL" =~ Core ]]; then
CORE_LABELS+=("$LABEL")
CORE_PATHS+=("$INPUT_FILE")
fi
fi
done
break
# AMD Sensors (k10temp / zenpower)
elif [[ "$DRIVER_NAME" == "k10temp" || "$DRIVER_NAME" == "zenpower" ]]; then
for label_file in "$hwmon"/temp*_label; do
if [[ -f "$label_file" ]]; then
LABEL=$(cat "$label_file" 2>/dev/null)
INPUT_FILE="${label_file%_label}_input"
if [[ "$LABEL" == "Tctl" ]]; then
PKG_LABEL="Tctl"
PKG_PATH="$INPUT_FILE"
elif [[ "$LABEL" == "Tccd1" ]]; then
CORE_LABELS+=("Tccd1")
CORE_PATHS+=("$INPUT_FILE")
fi
fi
done
break
fi
fi
done
# Read temperature in Celsius
read_temp() {
local sensor_path="$1"
if [[ -n "$sensor_path" && -f "$sensor_path" ]]; then
local raw
raw=$(cat "$sensor_path" 2>/dev/null || echo 0)
awk -v raw="$raw" 'BEGIN { printf "%.1f", raw / 1000 }'
else
echo "N/A"
fi
}
# Colorize temperature values
format_temp() {
local temp="$1"
if [[ "$temp" == "N/A" ]]; then
echo -e "\e[1;30mN/A\e[0m"
return
fi
if awk "BEGIN {exit !($temp >= 80)}"; then
printf "\e[1;31m%5.1f°C\e[0m" "$temp" # Red (>= 80C)
elif awk "BEGIN {exit !($temp >= 65 && $temp < 80)}"; then
printf "\e[1;33m%5.1f°C\e[0m" "$temp" # Yellow (65C - 80C)
else
printf "\e[1;32m%5.1f°C\e[0m" "$temp" # Green (< 65C)
fi
}
tput civis 2>/dev/null
clear
while true; do
tput cup 0 0
# Sample RAPL energy counters
PERF_OUT=$(perf stat "${EVENTS[@]}" -a sleep "$INTERVAL" 2>&1)
# Extract Power Readings
PKG_WATTS=$(echo "$PERF_OUT" | awk '/energy-pkg/ {print $1}' | tr -d ',')
CORE_WATTS=$(echo "$PERF_OUT" | awk '/energy-core/ {print $1}' | tr -d ',')
if [[ -z "$CORE_WATTS" ]]; then
CORE_WATTS=$(echo "$PERF_OUT" | awk '/energy-cores/ {print $1}' | tr -d ',')
fi
DRAM_WATTS=$(echo "$PERF_OUT" | awk '/energy-ram/ {print $1}' | tr -d ',')
PKG_WATTS=${PKG_WATTS:-"0.00"}
CORE_WATTS=${CORE_WATTS:-"0.00"}
# --- UI Rendering ---
echo "=================================================="
echo " CPU Power & Temperature Monitor "
echo "=================================================="
echo " Hostname : $(hostname)"
echo " CPU Vendor : $VENDOR_ID"
echo " Refresh Rate : ${INTERVAL}s"
echo "--------------------------------------------------"
# Render Package / Tctl Temperature
if [[ -n "$PKG_PATH" ]]; then
PKG_TEMP=$(read_temp "$PKG_PATH")
printf " Overall Package Temp (%-12s): %b\n" "$PKG_LABEL" "$(format_temp "$PKG_TEMP")"
fi
# Render Per-Core Temperatures (Formatted in a 2-column grid)
if [[ ${#CORE_PATHS[@]} -gt 0 ]]; then
echo "--------------------------------------------------"
echo " Per-Core Temperatures:"
col=0
for i in "${!CORE_PATHS[@]}"; do
c_label="${CORE_LABELS[$i]}"
c_temp=$(read_temp "${CORE_PATHS[$i]}")
printf " %-8s: %b" "$c_label" "$(format_temp "$c_temp")"
((col++))
if [[ $col -eq 2 ]]; then
echo ""
col=0
else
echo -n " |"
fi
done
[[ $col -ne 0 ]] && echo ""
fi
echo "--------------------------------------------------"
printf " Total Package Power : \e[1;32m%7.2f Watts\e[0m\n" "$PKG_WATTS"
printf " Cores Only Power : \e[1;36m%7.2f Watts\e[0m\n" "$CORE_WATTS"
if [[ -n "$DRAM_WATTS" ]]; then
printf " DRAM Memory Power : \e[1;35m%7.2f Watts\e[0m\n" "$DRAM_WATTS"
fi
echo "=================================================="
echo "Press [CTRL+C] to exit."
done