Compare commits

...

11 Commits

Author SHA1 Message Date
hank
ccd1735a8e chore: release main 2026-08-16 19:42:36 -04:00
henrygd
c67b69d17e fix(helm): publish immutable chart releases safely, maybe
- Create draft releases before uploading chart packages
- Update the chart index before making releases immutable
- Keep Helm releases out of the latest release channel
- Serialize chart publishing to avoid index races
- Run the workflow only when Helm-related files change
2026-08-16 19:39:25 -04:00
hank
da3ab62d4e chore: release main 2026-08-16 18:58:18 -04:00
Daniel Nikoloski
ec4ec01a39 feat: huge beszel hub and agent helm chart update (#1582) 2026-08-16 18:52:26 -04:00
Donggyu Kwon
ca5497324c feat: add :slim NVIDIA agent container image (#2002, #2003) 2026-08-16 15:42:13 -04:00
Sai Asish Y
adaf6f338d systems: synthesize error when getRecord returns nil record (#1968) 2026-08-16 14:44:30 -04:00
Sven van Ginkel
1ab1229a61 feat: build for armv5 and armv6 (#1884) 2026-08-16 14:33:04 -04:00
henrygd
9a54d844ba dev: remove noisy biome checks from package.json scripts 2026-08-16 14:26:59 -04:00
henrygd
87405c5f10 feat: add multi-battery monitoring
- Report battery data for individual devices
- Select a representative battery for legacy fields and alerts
- Average named battery data independently
- Display multiple batteries in system charts
- Add cross-platform coverage and transport tests
2026-08-16 13:52:29 -04:00
Miłosz Kolber
bfa6a1e361 feat(agent): monitor Intel Arc (xe) GPUs via nvtop (#2223)
intel_gpu_top does not support the xe driver, so skip it for xe devices
and let the existing nvtop last-resort collector handle them. nvtop leaves
device_name unset on xe, so name the GPU from its PCI device id ("Intel GPU
(<id>)"). Adds nvtop to the Intel agent image (gputop already ships with
igt-gpu-tools).
2026-08-16 11:41:28 -04:00
T.J. Tarazevits
3688b2d033 Add Intel sysfs GPU power collector (Xe/i915 hwmon energy counters) (#2020) 2026-08-16 11:20:43 -04:00
65 changed files with 3071 additions and 392 deletions

View File

@@ -52,6 +52,19 @@ jobs:
type=semver,pattern={{major}}
type=raw,value={{sha}},enable=${{ github.ref_type != 'tag' }}
# henrygd/beszel-agent-nvidia:slim
- image: henrygd/beszel-agent-nvidia
dockerfile: ./internal/dockerfile_agent_nvidia_slim
platforms: linux/amd64,linux/arm64
registry: docker.io
username_secret: DOCKERHUB_USERNAME
password_secret: DOCKERHUB_TOKEN
tags: |
type=raw,value=slim
type=semver,pattern={{version}}-slim
type=semver,pattern={{major}}.{{minor}}-slim
type=semver,pattern={{major}}-slim
# henrygd/beszel-agent-intel
- image: henrygd/beszel-agent-intel
dockerfile: ./internal/dockerfile_agent_intel
@@ -107,6 +120,19 @@ jobs:
type=semver,pattern={{major}}
type=raw,value={{sha}},enable=${{ github.ref_type != 'tag' }}
# ghcr.io/henrygd/beszel-agent-nvidia:slim
- image: ghcr.io/${{ github.repository }}/beszel-agent-nvidia
dockerfile: ./internal/dockerfile_agent_nvidia_slim
platforms: linux/amd64,linux/arm64
registry: ghcr.io
username: ${{ github.actor }}
password_secret: GITHUB_TOKEN
tags: |
type=raw,value=slim
type=semver,pattern={{version}}-slim
type=semver,pattern={{major}}.{{minor}}-slim
type=semver,pattern={{major}}-slim
# ghcr.io/henrygd/beszel-agent-intel
- image: ghcr.io/${{ github.repository }}/beszel-agent-intel
dockerfile: ./internal/dockerfile_agent_intel
@@ -194,7 +220,7 @@ jobs:
with:
context: ./
file: ${{ matrix.dockerfile }}
platforms: ${{ matrix.platforms || 'linux/amd64,linux/arm64,linux/arm/v7' }}
platforms: ${{ matrix.platforms || 'linux/amd64,linux/arm64,linux/arm/v6,linux/arm/v7' }}
push: ${{ github.ref_type == 'tag' && secrets[matrix.password_secret] != '' }}
provenance: mode=max
sbom: true

138
.github/workflows/release-please.yml vendored Normal file
View File

@@ -0,0 +1,138 @@
on:
push:
branches:
- main
paths:
- ".github/workflows/release-please.yml"
- "release-please-config.json"
- ".release-please-manifest.json"
- "supplemental/helm/**"
permissions:
contents: write
issues: write
pull-requests: write
env:
PUBLISHABLE_ITEMS: '["supplemental/helm/beszel-agent", "supplemental/helm/beszel-hub"]'
name: helm-release
jobs:
release:
name: Release
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v5
with:
fetch-depth: 0
- uses: googleapis/release-please-action@v4
name: Prepare release
id: release-please
with:
token: ${{ secrets.CR_TOKEN }}
- name: Dump Release Please Output
env:
RELEASE_PLEASE_OUTPUT: ${{ toJson(steps.release-please.outputs) }}
run: |
echo "$RELEASE_PLEASE_OUTPUT"
- name: Determine what should be published
uses: actions/github-script@v8
id: items-to-publish
env:
CHANGED_ITEMS: "${{ steps.release-please.outputs.paths_released }}"
with:
script: |
const changedItems = JSON.parse(process.env.CHANGED_ITEMS || '[]');
console.log("changed items", changedItems);
const eligibleItems = JSON.parse(process.env.PUBLISHABLE_ITEMS || '[]');
console.log("eligible items", eligibleItems);
const itemsToPublish = changedItems.filter(i => eligibleItems.includes(i));
console.log("items to publish", itemsToPublish);
return itemsToPublish;
outputs:
items_to_publish: ${{ steps.items-to-publish.outputs.result }}
releases: ${{ toJson(steps.release-please.outputs) }}
release-charts:
name: Release Charts
needs: release
runs-on: ubuntu-latest
if: ${{ needs.release.outputs.items_to_publish != '' && toJson(fromJson(needs.release.outputs.items_to_publish)) != '[]' }}
strategy:
fail-fast: false
max-parallel: 1
matrix:
path: ${{ fromJSON(needs.release.outputs.items_to_publish) }}
env:
TAG: ${{ fromJson(needs.release.outputs.releases)[format('{0}--tag_name', matrix.path)] }}
VERSION: ${{ fromJson(needs.release.outputs.releases)[format('{0}--version', matrix.path)] }}
steps:
- name: Debug
run: |
echo ${{ env.TAG }}
echo ${{ env.VERSION }}
echo ${{ matrix.path }}
- name: ✨ Checkout repository
uses: actions/checkout@v5
with:
fetch-depth: 0
- name: Configure Git
run: |
echo ${{ needs.release.outputs.items_to_publish }}
git config user.name "$GITHUB_ACTOR"
git config user.email "$GITHUB_ACTOR@users.noreply.github.com"
- name: Install Chart Releaser
run: |
version=v1.6.0
mkdir .tmp
install_dir=.tmp
echo "Installing chart-releaser on $install_dir..."
curl -sSLo cr.tar.gz "https://github.com/helm/chart-releaser/releases/download/$version/chart-releaser_${version#v}_linux_amd64.tar.gz"
tar -xzf cr.tar.gz -C "$install_dir"
rm -f cr.tar.gz
- name: Package chart
run: |
.tmp/cr package ${{ matrix.path }}
ls -la .cr-release-packages/
- name: Upload chart package to draft release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: gh release upload "$TAG" .cr-release-packages/*.tgz --clobber
- name: Update index
run: |
owner=$(cut -d '/' -f 1 <<< "$GITHUB_REPOSITORY")
repo=$(cut -d '/' -f 2 <<< "$GITHUB_REPOSITORY")
# Create docs directory and copy chart
mkdir -p docs
cp .cr-release-packages/*.tgz docs/ || true
# Generate index.yaml for GitHub Pages
args=(-o "$owner" -r "$repo" -c "https://henrygd.github.io/beszel" --push -t "${{ secrets.CR_TOKEN }}" --index-path docs/index.yaml)
.tmp/cr index "${args[@]}"
- name: Publish chart release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
CHART_PATH: ${{ matrix.path }}
run: |
chart_name="${CHART_PATH##*/}"
release_id=$(gh api "repos/${GITHUB_REPOSITORY}/releases/tags/${TAG}" --jq .id)
gh api --method PATCH "repos/${GITHUB_REPOSITORY}/releases/${release_id}" \
-f "name=Helm chart: ${chart_name} v${VERSION}" \
-F draft=false \
-f make_latest=false

3
.gitignore vendored
View File

@@ -3,7 +3,6 @@ pb_data
data
temp
.vscode
beszel-agent
beszel_data
beszel_data*
dist
@@ -21,3 +20,5 @@ __debug_*
agent/lhm/obj
agent/lhm/bin
dockerfile_agent_dev
.cr-release-packages
.tmp

View File

@@ -22,6 +22,9 @@ builds:
- amd64
- arm64
- arm
goarm:
- "6"
- "7"
ignore:
- goos: windows
goarch: arm64
@@ -31,6 +34,8 @@ builds:
goarch: arm64
- goos: freebsd
goarch: arm
- goos: darwin
goarch: arm
- id: beszel-agent
binary: beszel-agent
@@ -52,6 +57,10 @@ builds:
- mipsle
- mips
- ppc64le
goarm:
- "5"
- "6"
- "7"
gomips:
- hardfloat
- softfloat
@@ -71,6 +80,8 @@ builds:
gomips: hardfloat
- goos: windows
goarch: arm
- goos: darwin
goarch: arm
- goos: darwin
goarch: riscv64
- goos: windows

View File

@@ -0,0 +1,4 @@
{
"supplemental/helm/beszel-agent": "0.1.2",
"supplemental/helm/beszel-hub": "0.1.2"
}

View File

@@ -1,6 +1,13 @@
// Package battery provides functions to check if the system has a battery and return the charge state and percentage.
// Package battery provides battery information for the host and connected devices.
package battery
import (
"errors"
"sort"
"strconv"
"strings"
)
const (
stateUnknown uint8 = iota
stateEmpty
@@ -9,3 +16,55 @@ const (
stateDischarging
stateIdle
)
// Battery is a readable battery reported by the operating system.
type Battery struct {
Name string
Percent uint8
State uint8
FullChargeCapacity uint64
HasFullChargeCapacity bool
System bool
}
var errNoBatteries = errors.New("no readable batteries")
// normalizeBatteries supplies stable fallback names and disambiguates duplicates.
func normalizeBatteries(batteries []Battery) []Battery {
nameCounts := make(map[string]int, len(batteries))
for i := range batteries {
name := strings.TrimSpace(batteries[i].Name)
if name == "" {
name = "Battery " + strconv.Itoa(i+1)
}
nameCounts[name]++
if nameCounts[name] > 1 {
name += " (" + strconv.Itoa(nameCounts[name]) + ")"
}
batteries[i].Name = name
}
return batteries
}
// Primary returns the representative battery. Reported full-charge capacity wins,
// then system-scoped devices, then name for deterministic ties.
func Primary(batteries []Battery) (Battery, bool) {
if len(batteries) == 0 {
return Battery{}, false
}
ordered := append([]Battery(nil), batteries...)
sort.SliceStable(ordered, func(i, j int) bool {
a, b := ordered[i], ordered[j]
if a.HasFullChargeCapacity != b.HasFullChargeCapacity {
return a.HasFullChargeCapacity
}
if a.HasFullChargeCapacity && a.FullChargeCapacity != b.FullChargeCapacity {
return a.FullChargeCapacity > b.FullChargeCapacity
}
if a.System != b.System {
return a.System
}
return a.Name < b.Name
})
return ordered[0], true
}

View File

@@ -3,11 +3,7 @@
package battery
import (
"errors"
"log/slog"
"math"
"os/exec"
"sync"
"howett.net/plist"
)
@@ -35,62 +31,46 @@ func readMacBatteries() ([]macBattery, error) {
return batteries, nil
}
// HasReadableBattery checks if the system has a battery and returns true if it does.
var HasReadableBattery = sync.OnceValue(func() bool {
systemHasBattery := false
batteries, err := readMacBatteries()
slog.Debug("Batteries", "batteries", batteries, "err", err)
for _, bat := range batteries {
if bat.MaxCapacity > 0 {
systemHasBattery = true
break
}
}
return systemHasBattery
})
func HasReadableBattery() bool {
batteries, _ := GetBatteryStats()
return len(batteries) > 0
}
// GetBatteryStats returns the current battery percent and charge state.
// Uses CurrentCapacity/MaxCapacity to match the value macOS displays.
func GetBatteryStats() (batteryPercent uint8, batteryState uint8, err error) {
if !HasReadableBattery() {
return batteryPercent, batteryState, errors.ErrUnsupported
}
// GetBatteryStats returns every readable battery reported by macOS.
func GetBatteryStats() ([]Battery, error) {
batteries, err := readMacBatteries()
if err != nil {
return nil, err
}
if len(batteries) == 0 {
return batteryPercent, batteryState, errors.New("no batteries")
return nil, errNoBatteries
}
totalCapacity := 0
totalCharge := 0
batteryState = math.MaxUint8
result := make([]Battery, 0, len(batteries))
for _, bat := range batteries {
if bat.MaxCapacity == 0 {
if bat.MaxCapacity <= 0 {
// skip ghost batteries with 0 capacity
// https://github.com/distatus/battery/issues/34
continue
}
totalCapacity += bat.MaxCapacity
totalCharge += min(bat.CurrentCapacity, bat.MaxCapacity)
percent := min(max(float64(bat.CurrentCapacity)/float64(bat.MaxCapacity)*100, 0), 100)
state := stateUnknown
switch {
case !bat.ExternalConnected:
batteryState = stateDischarging
state = stateDischarging
case bat.IsCharging:
batteryState = stateCharging
state = stateCharging
case bat.CurrentCapacity == 0:
batteryState = stateEmpty
state = stateEmpty
case !bat.FullyCharged:
batteryState = stateIdle
state = stateIdle
default:
batteryState = stateFull
state = stateFull
}
result = append(result, Battery{Name: "Primary", Percent: uint8(percent), State: state,
FullChargeCapacity: uint64(bat.MaxCapacity), HasFullChargeCapacity: true, System: true})
}
if totalCapacity == 0 || batteryState == math.MaxUint8 {
return batteryPercent, batteryState, errors.New("no battery capacity")
if len(result) == 0 {
return nil, errNoBatteries
}
batteryPercent = uint8(float64(totalCharge) / float64(totalCapacity) * 100)
return batteryPercent, batteryState, nil
return normalizeBatteries(result), nil
}

View File

@@ -3,58 +3,19 @@
package battery
import (
"errors"
"log/slog"
"math"
"os"
"path/filepath"
"strconv"
"sync"
"github.com/henrygd/beszel/agent/utils"
)
// getBatteryPaths returns the paths of all batteries in /sys/class/power_supply
var getBatteryPaths func() ([]string, error)
var batteryRoot = "/sys/class/power_supply"
// HasReadableBattery checks if the system has a battery and returns true if it does.
var HasReadableBattery func() bool
func init() {
resetBatteryState("/sys/class/power_supply")
}
// resetBatteryState resets the sync.Once functions to a fresh state.
// Tests call this after swapping sysfsPowerSupply so the new path is picked up.
func resetBatteryState(sysfsPowerSupplyPath string) {
getBatteryPaths = sync.OnceValues(func() ([]string, error) {
entries, err := os.ReadDir(sysfsPowerSupplyPath)
if err != nil {
return nil, err
}
var paths []string
for _, e := range entries {
path := filepath.Join(sysfsPowerSupplyPath, e.Name())
if utils.ReadStringFile(filepath.Join(path, "type")) == "Battery" {
paths = append(paths, path)
}
}
return paths, nil
})
HasReadableBattery = sync.OnceValue(func() bool {
systemHasBattery := false
paths, err := getBatteryPaths()
for _, path := range paths {
if _, ok := utils.ReadStringFileOK(filepath.Join(path, "capacity")); ok {
systemHasBattery = true
break
}
}
if !systemHasBattery {
slog.Debug("No battery found", "err", err)
}
return systemHasBattery
})
// HasReadableBattery reports whether collection currently finds a readable battery.
func HasReadableBattery() bool {
batteries, _ := GetBatteryStats()
return len(batteries) > 0
}
func parseSysfsState(status string) uint8 {
@@ -74,26 +35,18 @@ func parseSysfsState(status string) uint8 {
}
}
// GetBatteryStats returns the current battery percent and charge state.
// Reads /sys/class/power_supply/*/capacity directly so the kernel-reported
// value is used, which is always 0-100 and matches what the OS displays.
func GetBatteryStats() (batteryPercent uint8, batteryState uint8, err error) {
if !HasReadableBattery() {
return batteryPercent, batteryState, errors.ErrUnsupported
}
paths, err := getBatteryPaths()
// GetBatteryStats re-enumerates power supplies and returns every readable battery.
func GetBatteryStats() ([]Battery, error) {
entries, err := os.ReadDir(batteryRoot)
if err != nil {
return batteryPercent, batteryState, err
return nil, err
}
if len(paths) == 0 {
return batteryPercent, batteryState, errors.New("no batteries")
}
batteryState = math.MaxUint8
totalPercent := 0
count := 0
for _, path := range paths {
batteries := make([]Battery, 0, len(entries))
for _, entry := range entries {
path := filepath.Join(batteryRoot, entry.Name())
if utils.ReadStringFile(filepath.Join(path, "type")) != "Battery" {
continue
}
capStr, ok := utils.ReadStringFileOK(filepath.Join(path, "capacity"))
if !ok {
continue
@@ -103,19 +56,30 @@ func GetBatteryStats() (batteryPercent uint8, batteryState uint8, err error) {
continue
}
cap = min(max(cap, 0), 100)
totalPercent += cap
count++
state := parseSysfsState(utils.ReadStringFile(filepath.Join(path, "status")))
if state != stateUnknown {
batteryState = state
name := utils.ReadStringFile(filepath.Join(path, "model_name"))
if name == "" {
name = utils.ReadStringFile(filepath.Join(path, "model"))
}
if name == "" {
name = entry.Name()
}
battery := Battery{
Name: name,
Percent: uint8(cap),
State: parseSysfsState(utils.ReadStringFile(filepath.Join(path, "status"))),
System: utils.ReadStringFile(filepath.Join(path, "scope")) != "Device",
}
for _, fullName := range []string{"charge_full", "energy_full"} {
if parsed, ok := utils.ReadUintFile(filepath.Join(path, fullName)); ok && parsed > 0 {
battery.FullChargeCapacity = parsed
battery.HasFullChargeCapacity = true
break
}
}
batteries = append(batteries, battery)
}
if count == 0 || batteryState == math.MaxUint8 {
return batteryPercent, batteryState, errors.New("no battery capacity")
if len(batteries) == 0 {
return nil, errNoBatteries
}
batteryPercent = uint8(totalPercent / count)
return batteryPercent, batteryState, nil
return normalizeBatteries(batteries), nil
}

View File

@@ -8,204 +8,102 @@ import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// setupFakeSysfs creates a temporary sysfs-like tree under t.TempDir(),
// swaps sysfsPowerSupply, resets the sync.Once caches, and restores
// everything on cleanup. Returns a helper to create battery directories.
func setupFakeSysfs(t *testing.T) (tmpDir string, addBattery func(name, capacity, status string)) {
type fakeBattery struct{ id, name, capacity, status, full, scope string }
func setupFakeSysfs(t *testing.T) (string, func(fakeBattery)) {
t.Helper()
tmp := t.TempDir()
resetBatteryState(tmp)
write := func(path, content string) {
root := t.TempDir()
previousRoot := batteryRoot
batteryRoot = root
t.Cleanup(func() { batteryRoot = previousRoot })
write := func(path, value string) {
t.Helper()
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
require.NoError(t, os.WriteFile(path, []byte(value), 0o644))
}
add := func(b fakeBattery) {
t.Helper()
dir := filepath.Join(root, b.id)
write(filepath.Join(dir, "type"), "Battery")
if b.capacity != "" {
write(filepath.Join(dir, "capacity"), b.capacity)
}
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatal(err)
write(filepath.Join(dir, "status"), b.status)
if b.name != "" {
write(filepath.Join(dir, "model_name"), b.name)
}
if b.full != "" {
write(filepath.Join(dir, "energy_full"), b.full)
}
if b.scope != "" {
write(filepath.Join(dir, "scope"), b.scope)
}
}
addBattery = func(name, capacity, status string) {
t.Helper()
batDir := filepath.Join(tmp, name)
write(filepath.Join(batDir, "type"), "Battery")
write(filepath.Join(batDir, "capacity"), capacity)
write(filepath.Join(batDir, "status"), status)
}
return tmp, addBattery
return root, add
}
func TestParseSysfsState(t *testing.T) {
tests := []struct {
input string
want uint8
}{
{"Empty", stateEmpty},
{"Full", stateFull},
{"Charging", stateCharging},
{"Discharging", stateDischarging},
{"Not charging", stateIdle},
{"", stateUnknown},
{"SomethingElse", stateUnknown},
}
for _, tt := range tests {
assert.Equal(t, tt.want, parseSysfsState(tt.input), "parseSysfsState(%q)", tt.input)
}
assert.Equal(t, stateEmpty, parseSysfsState("Empty"))
assert.Equal(t, stateFull, parseSysfsState("Full"))
assert.Equal(t, stateCharging, parseSysfsState("Charging"))
assert.Equal(t, stateDischarging, parseSysfsState("Discharging"))
assert.Equal(t, stateIdle, parseSysfsState("Not charging"))
assert.Equal(t, stateUnknown, parseSysfsState("SomethingElse"))
}
func TestGetBatteryStats_SingleBattery(t *testing.T) {
_, addBattery := setupFakeSysfs(t)
addBattery("BAT0", "72", "Discharging")
pct, state, err := GetBatteryStats()
assert.NoError(t, err)
assert.Equal(t, uint8(72), pct)
assert.Equal(t, stateDischarging, state)
func TestGetBatteryStatsMultipleNamedAndPrimary(t *testing.T) {
_, add := setupFakeSysfs(t)
add(fakeBattery{id: "BAT0", name: "Primary", capacity: "105", status: "Charging", full: "5000", scope: "System"})
add(fakeBattery{id: "hidpp_battery_0", name: "MX Keys S", capacity: "55", status: "Unknown", full: "900", scope: "Device"})
batteries, err := GetBatteryStats()
require.NoError(t, err)
require.Len(t, batteries, 2)
assert.Equal(t, "Primary", batteries[0].Name)
assert.Equal(t, uint8(100), batteries[0].Percent)
assert.Equal(t, stateUnknown, batteries[1].State)
primary, ok := Primary(batteries)
require.True(t, ok)
assert.Equal(t, "Primary", primary.Name)
}
func TestGetBatteryStats_MultipleBatteries(t *testing.T) {
_, addBattery := setupFakeSysfs(t)
addBattery("BAT0", "80", "Charging")
addBattery("BAT1", "40", "Charging")
pct, state, err := GetBatteryStats()
assert.NoError(t, err)
// average of 80 and 40 = 60
assert.EqualValues(t, 60, pct)
assert.Equal(t, stateCharging, state)
func TestGetBatteryStatsFallbackDuplicatesAndUnreadable(t *testing.T) {
root, add := setupFakeSysfs(t)
add(fakeBattery{id: "BAT0", name: "Keyboard", capacity: "80", status: "Discharging"})
add(fakeBattery{id: "BAT1", name: "Keyboard", capacity: "-4", status: "SomethingWeird"})
add(fakeBattery{id: "BAT2", capacity: "not-a-number", status: "Charging"})
add(fakeBattery{id: "BAT3", capacity: "42", status: "Full"})
ac := filepath.Join(root, "AC0")
require.NoError(t, os.MkdirAll(ac, 0o755))
require.NoError(t, os.WriteFile(filepath.Join(ac, "type"), []byte("Mains"), 0o644))
batteries, err := GetBatteryStats()
require.NoError(t, err)
require.Len(t, batteries, 3)
assert.Equal(t, "Keyboard", batteries[0].Name)
assert.Equal(t, "Keyboard (2)", batteries[1].Name)
assert.Equal(t, uint8(0), batteries[1].Percent)
assert.Equal(t, "BAT3", batteries[2].Name)
}
func TestGetBatteryStats_FullBattery(t *testing.T) {
_, addBattery := setupFakeSysfs(t)
addBattery("BAT0", "100", "Full")
pct, state, err := GetBatteryStats()
assert.NoError(t, err)
assert.Equal(t, uint8(100), pct)
assert.Equal(t, stateFull, state)
}
func TestGetBatteryStats_CapacityClamped(t *testing.T) {
_, addBattery := setupFakeSysfs(t)
addBattery("BAT0", "105", "Charging")
pct, state, err := GetBatteryStats()
assert.NoError(t, err)
assert.Equal(t, uint8(100), pct)
assert.Equal(t, stateCharging, state)
}
func TestGetBatteryStats_EmptyBattery(t *testing.T) {
_, addBattery := setupFakeSysfs(t)
addBattery("BAT0", "0", "Empty")
pct, state, err := GetBatteryStats()
assert.NoError(t, err)
assert.Equal(t, uint8(0), pct)
assert.Equal(t, stateEmpty, state)
}
func TestGetBatteryStats_NotCharging(t *testing.T) {
_, addBattery := setupFakeSysfs(t)
addBattery("BAT0", "80", "Not charging")
pct, state, err := GetBatteryStats()
assert.NoError(t, err)
assert.Equal(t, uint8(80), pct)
assert.Equal(t, stateIdle, state)
}
func TestGetBatteryStats_NoBatteries(t *testing.T) {
setupFakeSysfs(t) // empty directory, no batteries
_, _, err := GetBatteryStats()
func TestGetBatteryStatsHotPlugReenumerates(t *testing.T) {
_, add := setupFakeSysfs(t)
_, err := GetBatteryStats()
assert.Error(t, err)
}
func TestGetBatteryStats_NonBatterySupplyIgnored(t *testing.T) {
tmp, addBattery := setupFakeSysfs(t)
// Add a real battery
addBattery("BAT0", "55", "Charging")
// Add an AC adapter (type != Battery) - should be ignored
acDir := filepath.Join(tmp, "AC0")
if err := os.MkdirAll(acDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(acDir, "type"), []byte("Mains"), 0o644); err != nil {
t.Fatal(err)
}
pct, state, err := GetBatteryStats()
assert.NoError(t, err)
assert.Equal(t, uint8(55), pct)
assert.Equal(t, stateCharging, state)
}
func TestGetBatteryStats_InvalidCapacitySkipped(t *testing.T) {
tmp, addBattery := setupFakeSysfs(t)
// One battery with valid capacity
addBattery("BAT0", "90", "Discharging")
// Another with invalid capacity text
badDir := filepath.Join(tmp, "BAT1")
if err := os.MkdirAll(badDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(badDir, "type"), []byte("Battery"), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(badDir, "capacity"), []byte("not-a-number"), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(badDir, "status"), []byte("Discharging"), 0o644); err != nil {
t.Fatal(err)
}
pct, _, err := GetBatteryStats()
assert.NoError(t, err)
// Only BAT0 counted
assert.Equal(t, uint8(90), pct)
}
func TestGetBatteryStats_UnknownStatusOnly(t *testing.T) {
_, addBattery := setupFakeSysfs(t)
addBattery("BAT0", "50", "SomethingWeird")
_, _, err := GetBatteryStats()
assert.Error(t, err)
}
func TestHasReadableBattery_True(t *testing.T) {
_, addBattery := setupFakeSysfs(t)
addBattery("BAT0", "50", "Charging")
assert.False(t, HasReadableBattery())
add(fakeBattery{id: "BAT0", capacity: "64", status: "Discharging"})
batteries, err := GetBatteryStats()
require.NoError(t, err)
assert.True(t, HasReadableBattery())
require.Len(t, batteries, 1)
assert.Equal(t, uint8(64), batteries[0].Percent)
}
func TestHasReadableBattery_False(t *testing.T) {
setupFakeSysfs(t) // no batteries
assert.False(t, HasReadableBattery())
}
func TestHasReadableBattery_NoCapacityFile(t *testing.T) {
tmp, _ := setupFakeSysfs(t)
// Battery dir with type file but no capacity file
batDir := filepath.Join(tmp, "BAT0")
err := os.MkdirAll(batDir, 0o755)
assert.NoError(t, err)
err = os.WriteFile(filepath.Join(batDir, "type"), []byte("Battery"), 0o644)
assert.NoError(t, err)
func TestGetBatteryStatsNoReadableCapacity(t *testing.T) {
_, add := setupFakeSysfs(t)
add(fakeBattery{id: "BAT0", status: "Charging"})
_, err := GetBatteryStats()
assert.Error(t, err)
assert.False(t, HasReadableBattery())
}

View File

@@ -8,6 +8,6 @@ func HasReadableBattery() bool {
return false
}
func GetBatteryStats() (uint8, uint8, error) {
return 0, 0, errors.ErrUnsupported
func GetBatteryStats() ([]Battery, error) {
return nil, errors.ErrUnsupported
}

View File

@@ -0,0 +1,35 @@
package battery
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestPrimarySelection(t *testing.T) {
tests := []struct {
name string
bats []Battery
want string
}{
{"largest reported capacity", []Battery{{Name: "Small", FullChargeCapacity: 20, HasFullChargeCapacity: true, System: true}, {Name: "Large", FullChargeCapacity: 80, HasFullChargeCapacity: true}}, "Large"},
{"reported ranks over missing", []Battery{{Name: "Unknown", System: true}, {Name: "Known", FullChargeCapacity: 1, HasFullChargeCapacity: true}}, "Known"},
{"system wins capacity tie", []Battery{{Name: "Peripheral", FullChargeCapacity: 50, HasFullChargeCapacity: true}, {Name: "System", FullChargeCapacity: 50, HasFullChargeCapacity: true, System: true}}, "System"},
{"name resolves final tie", []Battery{{Name: "Zed"}, {Name: "Alpha"}}, "Alpha"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, ok := Primary(tt.bats)
require.True(t, ok)
assert.Equal(t, tt.want, got.Name)
})
}
_, ok := Primary(nil)
assert.False(t, ok)
}
func TestNormalizeBatteriesFallbackNames(t *testing.T) {
bats := normalizeBatteries([]Battery{{}, {}, {Name: "Mouse"}, {Name: "Mouse"}})
assert.Equal(t, []string{"Battery 1", "Battery 2", "Mouse", "Mouse (2)"}, []string{bats[0].Name, bats[1].Name, bats[2].Name, bats[3].Name})
}

View File

@@ -7,9 +7,6 @@ package battery
import (
"errors"
"log/slog"
"math"
"sync"
"syscall"
"unsafe"
@@ -79,7 +76,7 @@ var (
setupDiDestroyDeviceInfoList = setupapi.NewProc("SetupDiDestroyDeviceInfoList")
)
// winBatteryGet reads one battery by index. Returns (fullCapacity, currentCapacity, state, error).
// winBatteryGet reads one battery by index.
// Returns error == errNotFound when there are no more batteries.
var errNotFound = errors.New("no more batteries")
@@ -122,7 +119,7 @@ func readWinBatteryState(powerState uint32) uint8 {
}
}
func winBatteryGet(idx int) (full, current uint32, state uint8, err error) {
func winBatteryGet(idx int) (Battery, error) {
hdev, err := setupDiSetup(
setupDiGetClassDevsW,
4,
@@ -132,7 +129,7 @@ func winBatteryGet(idx int) (full, current uint32, state uint8, err error) {
0, 0,
)
if err != nil {
return 0, 0, stateUnknown, err
return Battery{}, err
}
defer syscall.SyscallN(setupDiDestroyDeviceInfoList.Addr(), hdev)
@@ -148,10 +145,10 @@ func winBatteryGet(idx int) (full, current uint32, state uint8, err error) {
0,
)
if errno == 259 { // ERROR_NO_MORE_ITEMS
return 0, 0, stateUnknown, errNotFound
return Battery{}, errNotFound
}
if errno != 0 {
return 0, 0, stateUnknown, errno
return Battery{}, errno
}
var cbRequired uint32
@@ -165,7 +162,7 @@ func winBatteryGet(idx int) (full, current uint32, state uint8, err error) {
0,
)
if errno != 0 && errno != 122 { // ERROR_INSUFFICIENT_BUFFER
return 0, 0, stateUnknown, errno
return Battery{}, errno
}
didd := make([]uint16, cbRequired/2)
cbSize := (*uint32)(unsafe.Pointer(&didd[0]))
@@ -185,7 +182,7 @@ func winBatteryGet(idx int) (full, current uint32, state uint8, err error) {
0,
)
if errno != 0 {
return 0, 0, stateUnknown, errno
return Battery{}, errno
}
devicePath := &didd[2:][0]
@@ -199,7 +196,7 @@ func winBatteryGet(idx int) (full, current uint32, state uint8, err error) {
0,
)
if err != nil {
return 0, 0, stateUnknown, err
return Battery{}, err
}
defer windows.CloseHandle(handle)
@@ -216,7 +213,7 @@ func winBatteryGet(idx int) (full, current uint32, state uint8, err error) {
&dwOut, nil,
)
if err != nil || bqi.BatteryTag == 0 {
return 0, 0, stateUnknown, errors.New("battery tag not returned")
return Battery{}, errors.New("battery tag not returned")
}
var bi batteryInformation
@@ -229,7 +226,21 @@ func winBatteryGet(idx int) (full, current uint32, state uint8, err error) {
uint32(unsafe.Sizeof(bi)),
&dwOut, nil,
); err != nil {
return 0, 0, stateUnknown, err
return Battery{}, err
}
// BatteryDeviceName is optional, so retain the deterministic fallback on error.
name := ""
nameQuery := bqi
nameQuery.InformationLevel = 4 // BatteryDeviceName
nameBuffer := make([]uint16, 128)
if err := windows.DeviceIoControl(
handle, 2703428,
(*byte)(unsafe.Pointer(&nameQuery)), uint32(unsafe.Sizeof(nameQuery)),
(*byte)(unsafe.Pointer(&nameBuffer[0])), uint32(len(nameBuffer)*2),
&dwOut, nil,
); err == nil {
name = windows.UTF16ToString(nameBuffer)
}
bws := batteryWaitStatus{BatteryTag: bqi.BatteryTag}
@@ -243,56 +254,38 @@ func winBatteryGet(idx int) (full, current uint32, state uint8, err error) {
uint32(unsafe.Sizeof(bs)),
&dwOut, nil,
); err != nil {
return 0, 0, stateUnknown, err
return Battery{}, err
}
if bs.Capacity == 0xffffffff { // BATTERY_UNKNOWN_CAPACITY
return 0, 0, stateUnknown, errors.New("battery capacity unknown")
if bs.Capacity == 0xffffffff || bi.FullChargedCapacity == 0 || bi.FullChargedCapacity == 0xffffffff {
return Battery{}, errors.New("battery capacity unknown")
}
return bi.FullChargedCapacity, bs.Capacity, readWinBatteryState(bs.PowerState), nil
percent := min(float64(bs.Capacity)/float64(bi.FullChargedCapacity)*100, 100)
return Battery{Name: name, Percent: uint8(percent), State: readWinBatteryState(bs.PowerState),
FullChargeCapacity: uint64(bi.FullChargedCapacity), HasFullChargeCapacity: true, System: true}, nil
}
// HasReadableBattery checks if the system has a battery and returns true if it does.
var HasReadableBattery = sync.OnceValue(func() bool {
systemHasBattery := false
full, _, _, err := winBatteryGet(0)
if err == nil && full > 0 {
systemHasBattery = true
}
if !systemHasBattery {
slog.Debug("No battery found", "err", err)
}
return systemHasBattery
})
// GetBatteryStats returns the current battery percent and charge state.
func GetBatteryStats() (batteryPercent uint8, batteryState uint8, err error) {
if !HasReadableBattery() {
return batteryPercent, batteryState, errors.ErrUnsupported
}
totalFull := uint32(0)
totalCurrent := uint32(0)
batteryState = math.MaxUint8
func HasReadableBattery() bool {
batteries, _ := GetBatteryStats()
return len(batteries) > 0
}
// GetBatteryStats returns every readable battery reported by Windows.
func GetBatteryStats() ([]Battery, error) {
batteries := make([]Battery, 0, 2)
for i := 0; ; i++ {
full, current, state, bErr := winBatteryGet(i)
battery, bErr := winBatteryGet(i)
if errors.Is(bErr, errNotFound) {
break
}
if bErr != nil || full == 0 {
if bErr != nil {
continue
}
totalFull += full
totalCurrent += min(current, full)
batteryState = state
batteries = append(batteries, battery)
}
if totalFull == 0 || batteryState == math.MaxUint8 {
return batteryPercent, batteryState, errors.New("no battery capacity")
if len(batteries) == 0 {
return nil, errNoBatteries
}
batteryPercent = uint8(float64(totalCurrent) / float64(totalFull) * 100)
return batteryPercent, batteryState, nil
return normalizeBatteries(batteries), nil
}

View File

@@ -48,6 +48,8 @@ type GPUManager struct {
// Per-cache-key tracking for delta calculations
// cacheKey -> gpuId -> snapshot of last count/usage/power values
lastSnapshots map[uint16]map[string]*gpuSnapshot
// Per-card energy snapshots for Intel sysfs power calculation.
intelSysfsEnergySnapshots map[string]intelSysfsEnergySnapshot
}
// gpuSnapshot stores the last observed incremental values for delta tracking
@@ -90,6 +92,7 @@ const (
collectorSourceNVML collectorSource = "nvml"
collectorSourceNvidiaSMI collectorSource = collectorSource(nvidiaSmiCmd)
collectorSourceIntelGpuTop collectorSource = collectorSource(intelGpuStatsCmd)
collectorSourceIntelSysfs collectorSource = "intel_sysfs"
collectorSourceAmdSysfs collectorSource = "amd_sysfs"
collectorSourceRocmSMI collectorSource = collectorSource(rocmSmiCmd)
collectorSourceMacmon collectorSource = collectorSource(macmonCmd)
@@ -106,6 +109,7 @@ func isValidCollectorSource(source collectorSource) bool {
collectorSourceNVML,
collectorSourceNvidiaSMI,
collectorSourceIntelGpuTop,
collectorSourceIntelSysfs,
collectorSourceAmdSysfs,
collectorSourceRocmSMI,
collectorSourceMacmon,
@@ -122,6 +126,8 @@ type gpuCapabilities struct {
hasAmdSysfs bool
hasTegrastats bool
hasIntelGpuTop bool
hasXe bool
hasIntelSysfs bool
hasNvtop bool
hasMacmon bool
hasPowermetrics bool
@@ -369,12 +375,13 @@ func (gm *GPUManager) calculateGPUAverage(id string, gpu *system.GPUData, cacheK
gpuAvg.Power = utils.TwoDecimals(deltaPower / float64(deltaCount))
gpuAvg.PowerPkg = utils.TwoDecimals(deltaPowerPkg / float64(deltaCount))
if gpu.Engines != nil {
// make fresh map for averaged engine metrics to avoid mutating
// the accumulator map stored in gm.GpuDataMap
gpuAvg.Engines = make(map[string]float64, len(gpu.Engines))
gpuAvg.Usage = gm.calculateIntelGPUUsage(&gpuAvg, gpu, lastSnapshot, deltaCount)
gpuAvg.PowerPkg = utils.TwoDecimals(deltaPowerPkg / float64(deltaCount))
} else {
gpuAvg.Usage = utils.TwoDecimals(deltaUsage / float64(deltaCount))
}
@@ -444,6 +451,8 @@ func (gm *GPUManager) storeSnapshot(id string, gpu *system.GPUData, cacheKey uin
func (gm *GPUManager) discoverGpuCapabilities() gpuCapabilities {
caps := gpuCapabilities{
hasAmdSysfs: gm.hasAmdSysfs(),
hasXe: gm.hasXe(),
hasIntelSysfs: gm.hasIntelSysfs(),
}
if _, err := exec.LookPath(nvidiaSmiCmd); err == nil {
caps.hasNvidiaSmi = true
@@ -472,7 +481,7 @@ func (gm *GPUManager) discoverGpuCapabilities() gpuCapabilities {
}
func hasAnyGpuCollector(caps gpuCapabilities) bool {
return caps.hasNvidiaSmi || caps.hasRocmSmi || caps.hasAmdSysfs || caps.hasTegrastats || caps.hasIntelGpuTop || caps.hasNvtop || caps.hasMacmon || caps.hasPowermetrics
return caps.hasNvidiaSmi || caps.hasRocmSmi || caps.hasAmdSysfs || caps.hasTegrastats || caps.hasIntelGpuTop || caps.hasIntelSysfs || caps.hasNvtop || caps.hasMacmon || caps.hasPowermetrics
}
func (gm *GPUManager) startIntelCollector() {
@@ -563,6 +572,13 @@ func (gm *GPUManager) collectorDefinitions(caps gpuCapabilities) map[collectorSo
return true
},
},
collectorSourceIntelSysfs: {
group: collectorGroupIntel,
available: caps.hasIntelSysfs,
start: func(_ func()) bool {
return gm.startIntelSysfsCollector()
},
},
collectorSourceAmdSysfs: {
group: collectorGroupAmd,
available: caps.hasAmdSysfs,
@@ -705,9 +721,12 @@ func (gm *GPUManager) resolveLegacyCollectorPriority(caps gpuCapabilities) []col
priorities = append(priorities, collectorSourceAmdSysfs)
}
if caps.hasIntelGpuTop {
if caps.hasIntelGpuTop && !caps.hasXe {
priorities = append(priorities, collectorSourceIntelGpuTop)
}
if caps.hasIntelSysfs {
priorities = append(priorities, collectorSourceIntelSysfs)
}
// Apple collectors are currently opt-in only for testing.
// Enable them with GPU_COLLECTOR=macmon or GPU_COLLECTOR=powermetrics.

View File

@@ -0,0 +1,280 @@
//go:build linux
package agent
import (
"fmt"
"log/slog"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/henrygd/beszel/agent/utils"
"github.com/henrygd/beszel/internal/entities/system"
)
var (
drmSysfsRoot = "/sys/class/drm"
intelSysfsNow = time.Now
)
type intelSysfsEnergySnapshot struct {
microjoules uint64
timestamp time.Time
}
type intelSysfsCard struct {
cardPath string
hwmonDir string
}
// hasIntelSysfs returns true if any Intel DRM card exposes an hwmon energy counter.
func (gm *GPUManager) hasIntelSysfs() bool {
cards, err := discoverIntelSysfsCards()
return err == nil && len(cards) > 0
}
// startIntelSysfsCollector starts Intel GPU collection via sysfs.
func (gm *GPUManager) startIntelSysfsCollector() bool {
go func() {
if err := gm.collectIntelSysfsStats(); err != nil {
slog.Warn("Error collecting Intel GPU data via sysfs", "err", err)
}
}()
return true
}
// collectIntelSysfsStats collects Intel GPU metrics directly from DRM sysfs / hwmon.
func (gm *GPUManager) collectIntelSysfsStats() error {
sysfsPollInterval := 3000 * time.Millisecond
cards, err := discoverIntelSysfsCards()
if err != nil {
return err
}
if len(cards) == 0 {
return errNoValidData
}
slog.Debug("Using sysfs for Intel GPU data collection", "cards", len(cards))
for _, card := range cards {
slog.Debug("Intel sysfs card detected", "card", filepath.Base(card.cardPath), "hwmon", card.hwmonDir)
}
failures := 0
for {
hasData := false
for _, card := range cards {
if gm.updateIntelSysfsGpuData(card.cardPath, card.hwmonDir) {
hasData = true
}
}
if !hasData {
failures++
if failures > maxFailureRetries {
return errNoValidData
}
slog.Warn("No Intel GPU data from sysfs", "failures", failures)
time.Sleep(retryWaitTime)
continue
}
failures = 0
time.Sleep(sysfsPollInterval)
}
}
func discoverIntelSysfsCards() ([]intelSysfsCard, error) {
paths, err := filepath.Glob(filepath.Join(drmSysfsRoot, "card*"))
if err != nil {
return nil, err
}
var cards []intelSysfsCard
for _, cardPath := range paths {
if strings.Contains(filepath.Base(cardPath), "-") || !isIntelGpu(cardPath) {
continue
}
hwmonDir := findIntelEnergyHwmon(filepath.Join(cardPath, "device"))
if hwmonDir == "" {
continue
}
cards = append(cards, intelSysfsCard{cardPath: cardPath, hwmonDir: hwmonDir})
}
return cards, nil
}
func isIntelGpu(cardPath string) bool {
vendor, err := utils.ReadStringFileLimited(filepath.Join(cardPath, "device/vendor"), 64)
if err != nil {
return false
}
return strings.EqualFold(strings.TrimSpace(vendor), "0x8086")
}
func findIntelEnergyHwmon(devicePath string) string {
hwmons, _ := filepath.Glob(filepath.Join(devicePath, "hwmon/hwmon*"))
var fallback string
for _, hwmonDir := range hwmons {
if !sysfsFileExists(filepath.Join(hwmonDir, "energy1_input")) {
continue
}
if name, err := utils.ReadStringFileLimited(filepath.Join(hwmonDir, "name"), 64); err == nil && strings.EqualFold(strings.TrimSpace(name), "xe") {
return hwmonDir
}
if fallback == "" {
fallback = hwmonDir
}
}
return fallback
}
func sysfsFileExists(path string) bool {
_, err := utils.ReadStringFileLimited(path, 1)
return err == nil
}
// updateIntelSysfsGpuData reads GPU metrics from sysfs and updates the GPU data map.
// Returns true if the required energy counter was read successfully.
func (gm *GPUManager) updateIntelSysfsGpuData(cardPath, hwmonDir string) bool {
devicePath := filepath.Join(cardPath, "device")
id := filepath.Base(cardPath)
energy, err := readSysfsUint(filepath.Join(hwmonDir, "energy1_input"))
if err != nil {
return false
}
now := intelSysfsNow()
power, hasPower := gm.calculateIntelSysfsPower(id, energy, now)
powerPkg, hasPowerPkg := gm.readIntelSysfsPowerPkg(id, hwmonDir, now)
temp := readIntelSysfsTemperature(hwmonDir)
usage, usageErr := readOptionalSysfsFloat(filepath.Join(devicePath, "gpu_busy_percent"))
memUsed, memUsedErr := readFirstOptionalSysfsFloat(
filepath.Join(devicePath, "mem_info_vram_used"),
filepath.Join(devicePath, "mem_info_lmem_used"),
filepath.Join(devicePath, "mem_info_local_mem_used"),
)
memTotal, memTotalErr := readFirstOptionalSysfsFloat(
filepath.Join(devicePath, "mem_info_vram_total"),
filepath.Join(devicePath, "mem_info_lmem_total"),
filepath.Join(devicePath, "mem_info_local_mem_total"),
)
gm.Lock()
defer gm.Unlock()
gpu, ok := gm.GpuDataMap[id]
if !ok {
gpu = &system.GPUData{Name: getIntelSysfsGpuName(cardPath)}
gm.GpuDataMap[id] = gpu
}
if usageErr == nil {
gpu.Usage += usage
}
if memUsedErr == nil {
gpu.MemoryUsed = utils.BytesToMegabytes(memUsed)
}
if memTotalErr == nil {
gpu.MemoryTotal = utils.BytesToMegabytes(memTotal)
}
if temp > 0 {
gpu.Temperature = temp
}
if hasPower {
gpu.Power += power
slog.Debug("Computed Intel sysfs GPU power", "card", id, "watts", power)
}
if hasPowerPkg {
gpu.PowerPkg += powerPkg
}
gpu.Count++
return true
}
func (gm *GPUManager) calculateIntelSysfsPower(cardID string, microjoules uint64, timestamp time.Time) (float64, bool) {
if gm.intelSysfsEnergySnapshots == nil {
gm.intelSysfsEnergySnapshots = make(map[string]intelSysfsEnergySnapshot)
}
last, ok := gm.intelSysfsEnergySnapshots[cardID]
gm.intelSysfsEnergySnapshots[cardID] = intelSysfsEnergySnapshot{microjoules: microjoules, timestamp: timestamp}
if !ok {
return 0, false
}
if microjoules < last.microjoules {
slog.Debug("Intel sysfs energy counter reset", "card", cardID)
return 0, false
}
elapsed := timestamp.Sub(last.timestamp).Seconds()
if elapsed <= 0 {
return 0, false
}
delta := microjoules - last.microjoules
return float64(delta) / 1_000_000.0 / elapsed, true
}
func (gm *GPUManager) readIntelSysfsPowerPkg(cardID, hwmonDir string, timestamp time.Time) (float64, bool) {
energyPaths, _ := filepath.Glob(filepath.Join(hwmonDir, "energy*_input"))
for _, path := range energyPaths {
if filepath.Base(path) == "energy1_input" {
continue
}
energy, err := readSysfsUint(path)
if err != nil {
continue
}
return gm.calculateIntelSysfsPower(cardID+":"+filepath.Base(path), energy, timestamp)
}
return 0, false
}
func readIntelSysfsTemperature(hwmonDir string) float64 {
tempPaths, _ := filepath.Glob(filepath.Join(hwmonDir, "temp*_input"))
for _, path := range tempPaths {
temp, err := readSysfsFloat(path)
if err == nil && temp > 0 {
return temp / 1000.0
}
}
return 0
}
func readSysfsUint(path string) (uint64, error) {
val, err := utils.ReadStringFileLimited(path, 64)
if err != nil {
slog.Debug("Failed to read sysfs value", "path", path, "error", err)
return 0, err
}
return strconv.ParseUint(strings.TrimSpace(val), 10, 64)
}
func readOptionalSysfsFloat(path string) (float64, error) {
val, err := os.ReadFile(path)
if err != nil {
return 0, err
}
return strconv.ParseFloat(strings.TrimSpace(string(val)), 64)
}
func readFirstOptionalSysfsFloat(paths ...string) (float64, error) {
for _, path := range paths {
val, err := readOptionalSysfsFloat(path)
if err == nil {
return val, nil
}
}
return 0, fmt.Errorf("no sysfs values found")
}
func getIntelSysfsGpuName(cardPath string) string {
devicePath := filepath.Join(cardPath, "device")
if product, err := utils.ReadStringFileLimited(filepath.Join(devicePath, "product_name"), 128); err == nil && strings.TrimSpace(product) != "" {
return strings.TrimSpace(product)
}
if name, err := utils.ReadStringFileLimited(filepath.Join(devicePath, "name"), 128); err == nil && strings.TrimSpace(name) != "" {
return strings.TrimSpace(name)
}
return fmt.Sprintf("Intel GPU %s", filepath.Base(cardPath))
}

View File

@@ -0,0 +1,217 @@
//go:build linux
package agent
import (
"os"
"path/filepath"
"testing"
"time"
"github.com/henrygd/beszel/agent/utils"
"github.com/henrygd/beszel/internal/entities/system"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func setupIntelSysfsTest(t *testing.T) (root, cardPath, hwmonPath string) {
t.Helper()
root = t.TempDir()
oldRoot := drmSysfsRoot
drmSysfsRoot = root
t.Cleanup(func() {
drmSysfsRoot = oldRoot
})
cardPath = filepath.Join(root, "card0")
devicePath := filepath.Join(cardPath, "device")
hwmonPath = filepath.Join(devicePath, "hwmon", "hwmon0")
require.NoError(t, os.MkdirAll(hwmonPath, 0o755))
return root, cardPath, hwmonPath
}
func writeIntelSysfsFile(t *testing.T, basePath, name, content string) {
t.Helper()
require.NoError(t, os.WriteFile(filepath.Join(basePath, name), []byte(content), 0o644))
}
func setIntelSysfsTime(t *testing.T, now time.Time) {
t.Helper()
oldNow := intelSysfsNow
intelSysfsNow = func() time.Time { return now }
t.Cleanup(func() {
intelSysfsNow = oldNow
})
}
func TestIntelSysfsDetectsIntelCardWithEnergy(t *testing.T) {
_, cardPath, hwmonPath := setupIntelSysfsTest(t)
devicePath := filepath.Join(cardPath, "device")
writeIntelSysfsFile(t, devicePath, "vendor", "0x8086\n")
writeIntelSysfsFile(t, hwmonPath, "name", "xe\n")
writeIntelSysfsFile(t, hwmonPath, "energy1_input", "1000000\n")
gm := &GPUManager{}
assert.True(t, gm.hasIntelSysfs())
cards, err := discoverIntelSysfsCards()
require.NoError(t, err)
require.Len(t, cards, 1)
assert.Equal(t, cardPath, cards[0].cardPath)
assert.Equal(t, hwmonPath, cards[0].hwmonDir)
}
func TestIntelSysfsRejectsNonIntelCard(t *testing.T) {
_, cardPath, hwmonPath := setupIntelSysfsTest(t)
devicePath := filepath.Join(cardPath, "device")
writeIntelSysfsFile(t, devicePath, "vendor", "0x1002\n")
writeIntelSysfsFile(t, hwmonPath, "name", "xe\n")
writeIntelSysfsFile(t, hwmonPath, "energy1_input", "1000000\n")
gm := &GPUManager{}
assert.False(t, gm.hasIntelSysfs())
}
func TestIntelSysfsRequiresEnergyInput(t *testing.T) {
_, cardPath, hwmonPath := setupIntelSysfsTest(t)
devicePath := filepath.Join(cardPath, "device")
writeIntelSysfsFile(t, devicePath, "vendor", "0x8086\n")
writeIntelSysfsFile(t, hwmonPath, "name", "xe\n")
gm := &GPUManager{}
assert.False(t, gm.hasIntelSysfs())
}
func TestIntelSysfsFirstSampleInitializesWithoutBogusPower(t *testing.T) {
_, cardPath, hwmonPath := setupIntelSysfsTest(t)
devicePath := filepath.Join(cardPath, "device")
writeIntelSysfsFile(t, devicePath, "vendor", "0x8086\n")
writeIntelSysfsFile(t, hwmonPath, "name", "xe\n")
writeIntelSysfsFile(t, hwmonPath, "energy1_input", "1000000\n")
setIntelSysfsTime(t, time.Unix(100, 0))
gm := &GPUManager{GpuDataMap: make(map[string]*system.GPUData)}
ok := gm.updateIntelSysfsGpuData(cardPath, hwmonPath)
require.True(t, ok)
gpu := gm.GpuDataMap["card0"]
require.NotNil(t, gpu)
assert.Equal(t, "Intel GPU card0", gpu.Name)
assert.Equal(t, 0.0, gpu.Power)
assert.Equal(t, 1.0, gpu.Count)
}
func TestIntelSysfsSecondSampleComputesWatts(t *testing.T) {
_, cardPath, hwmonPath := setupIntelSysfsTest(t)
devicePath := filepath.Join(cardPath, "device")
writeIntelSysfsFile(t, devicePath, "vendor", "0x8086\n")
writeIntelSysfsFile(t, hwmonPath, "energy1_input", "1000000\n")
gm := &GPUManager{GpuDataMap: make(map[string]*system.GPUData)}
oldNow := intelSysfsNow
intelSysfsNow = func() time.Time { return time.Unix(100, 0) }
t.Cleanup(func() { intelSysfsNow = oldNow })
require.True(t, gm.updateIntelSysfsGpuData(cardPath, hwmonPath))
writeIntelSysfsFile(t, hwmonPath, "energy1_input", "6000000\n")
intelSysfsNow = func() time.Time { return time.Unix(102, 0) }
require.True(t, gm.updateIntelSysfsGpuData(cardPath, hwmonPath))
gpu := gm.GpuDataMap["card0"]
require.NotNil(t, gpu)
assert.Equal(t, 2.5, gpu.Power)
assert.Equal(t, 2.0, gpu.Count)
}
func TestIntelSysfsSecondEnergyCounterMapsToPowerPkg(t *testing.T) {
_, cardPath, hwmonPath := setupIntelSysfsTest(t)
devicePath := filepath.Join(cardPath, "device")
writeIntelSysfsFile(t, devicePath, "vendor", "0x8086\n")
writeIntelSysfsFile(t, hwmonPath, "energy1_input", "1000000\n")
writeIntelSysfsFile(t, hwmonPath, "energy2_input", "2000000\n")
oldNow := intelSysfsNow
t.Cleanup(func() { intelSysfsNow = oldNow })
gm := &GPUManager{GpuDataMap: make(map[string]*system.GPUData)}
intelSysfsNow = func() time.Time { return time.Unix(100, 0) }
require.True(t, gm.updateIntelSysfsGpuData(cardPath, hwmonPath))
writeIntelSysfsFile(t, hwmonPath, "energy1_input", "2000000\n")
writeIntelSysfsFile(t, hwmonPath, "energy2_input", "8000000\n")
intelSysfsNow = func() time.Time { return time.Unix(102, 0) }
require.True(t, gm.updateIntelSysfsGpuData(cardPath, hwmonPath))
gpu := gm.GpuDataMap["card0"]
require.NotNil(t, gpu)
assert.Equal(t, 0.5, gpu.Power)
assert.Equal(t, 3.0, gpu.PowerPkg)
}
func TestIntelSysfsCounterResetSkipsOneSample(t *testing.T) {
gm := &GPUManager{}
power, ok := gm.calculateIntelSysfsPower("card0", 5000000, time.Unix(100, 0))
assert.False(t, ok)
assert.Equal(t, 0.0, power)
power, ok = gm.calculateIntelSysfsPower("card0", 1000000, time.Unix(101, 0))
assert.False(t, ok)
assert.Equal(t, 0.0, power)
power, ok = gm.calculateIntelSysfsPower("card0", 3000000, time.Unix(103, 0))
assert.True(t, ok)
assert.Equal(t, 1.0, power)
}
func TestIntelSysfsTempInputMapsToCelsius(t *testing.T) {
_, cardPath, hwmonPath := setupIntelSysfsTest(t)
devicePath := filepath.Join(cardPath, "device")
writeIntelSysfsFile(t, devicePath, "vendor", "0x8086\n")
writeIntelSysfsFile(t, hwmonPath, "energy1_input", "1000000\n")
writeIntelSysfsFile(t, hwmonPath, "temp1_input", "43500\n")
setIntelSysfsTime(t, time.Unix(100, 0))
gm := &GPUManager{GpuDataMap: make(map[string]*system.GPUData)}
require.True(t, gm.updateIntelSysfsGpuData(cardPath, hwmonPath))
gpu := gm.GpuDataMap["card0"]
require.NotNil(t, gpu)
assert.Equal(t, 43.5, gpu.Temperature)
}
func TestIntelSysfsMissingOptionalFilesDoNotFail(t *testing.T) {
_, cardPath, hwmonPath := setupIntelSysfsTest(t)
devicePath := filepath.Join(cardPath, "device")
writeIntelSysfsFile(t, devicePath, "vendor", "0x8086\n")
writeIntelSysfsFile(t, hwmonPath, "energy1_input", "1000000\n")
setIntelSysfsTime(t, time.Unix(100, 0))
gm := &GPUManager{GpuDataMap: make(map[string]*system.GPUData)}
require.True(t, gm.updateIntelSysfsGpuData(cardPath, hwmonPath))
gpu := gm.GpuDataMap["card0"]
require.NotNil(t, gpu)
assert.Equal(t, 0.0, gpu.Usage)
assert.Equal(t, 0.0, gpu.MemoryUsed)
assert.Equal(t, 0.0, gpu.MemoryTotal)
assert.Equal(t, 0.0, gpu.Temperature)
}
func TestIntelSysfsMapsOpportunisticMemoryAndUsage(t *testing.T) {
_, cardPath, hwmonPath := setupIntelSysfsTest(t)
devicePath := filepath.Join(cardPath, "device")
writeIntelSysfsFile(t, devicePath, "vendor", "0x8086\n")
writeIntelSysfsFile(t, devicePath, "gpu_busy_percent", "37\n")
writeIntelSysfsFile(t, devicePath, "mem_info_lmem_used", "1073741824\n")
writeIntelSysfsFile(t, devicePath, "mem_info_lmem_total", "2147483648\n")
writeIntelSysfsFile(t, hwmonPath, "energy1_input", "1000000\n")
setIntelSysfsTime(t, time.Unix(100, 0))
gm := &GPUManager{GpuDataMap: make(map[string]*system.GPUData)}
require.True(t, gm.updateIntelSysfsGpuData(cardPath, hwmonPath))
gpu := gm.GpuDataMap["card0"]
require.NotNil(t, gpu)
assert.Equal(t, 37.0, gpu.Usage)
assert.Equal(t, utils.BytesToMegabytes(1073741824), gpu.MemoryUsed)
assert.Equal(t, utils.BytesToMegabytes(2147483648), gpu.MemoryTotal)
}

View File

@@ -0,0 +1,13 @@
//go:build !linux
package agent
type intelSysfsEnergySnapshot struct{}
func (gm *GPUManager) hasIntelSysfs() bool {
return false
}
func (gm *GPUManager) startIntelSysfsCollector() bool {
return false
}

View File

@@ -5,6 +5,7 @@ import (
"io"
"log/slog"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
@@ -48,9 +49,14 @@ func (gm *GPUManager) updateNvtopSnapshots(snapshots []nvtopSnapshot) bool {
valid := false
usedIDs := make(map[string]struct{}, len(snapshots))
var xeName string
for i, sample := range snapshots {
// nvtop leaves device_name unset on xe devices.
if sample.DeviceName == "" {
continue
if xeName == "" {
xeName = xeGpuName()
}
sample.DeviceName = xeName
}
indexID := "n" + strconv.Itoa(i)
id := indexID
@@ -158,3 +164,38 @@ func (gm *GPUManager) startNvtopCollector(interval string, onFailure func()) {
}
}()
}
// xeDevicePath returns the sysfs device path of the first xe GPU, or "".
func xeDevicePath() string {
cards, err := filepath.Glob("/sys/class/drm/card*")
if err != nil {
return ""
}
for _, card := range cards {
if strings.Contains(filepath.Base(card), "-") {
continue
}
if uevent, err := utils.ReadStringFileLimited(filepath.Join(card, "device", "uevent"), 4096); err == nil && strings.Contains(uevent, "DRIVER=xe") {
return filepath.Join(card, "device")
}
}
return ""
}
func (gm *GPUManager) hasXe() bool {
return xeDevicePath() != ""
}
// xeGpuName names an xe GPU from its PCI device id; nvtop leaves device_name unset on xe.
func xeGpuName() string {
devicePath := xeDevicePath()
if devicePath == "" {
return "GPU"
}
id, err := utils.ReadStringFileLimited(filepath.Join(devicePath, "device"), 64)
if err != nil {
return "GPU"
}
id = strings.ToLower(strings.TrimSpace(strings.TrimPrefix(id, "0x")))
return "Intel GPU (" + id + ")"
}

View File

@@ -332,11 +332,12 @@ func TestUpdateNvtopSnapshotsKeepsDeviceAssociationWhenOrderChanges(t *testing.T
}
func TestParseCollectorPriority(t *testing.T) {
got := parseCollectorPriority(" nvml, nvidia-smi, intel_gpu_top, amd_sysfs, nvtop, rocm-smi, bad ")
got := parseCollectorPriority(" nvml, nvidia-smi, intel_gpu_top, intel_sysfs, amd_sysfs, nvtop, rocm-smi, bad ")
want := []collectorSource{
collectorSourceNVML,
collectorSourceNvidiaSMI,
collectorSourceIntelGpuTop,
collectorSourceIntelSysfs,
collectorSourceAmdSysfs,
collectorSourceNVTop,
collectorSourceRocmSMI,

View File

@@ -132,9 +132,14 @@ func (a *Agent) getSystemStats(cacheTimeMs uint16) system.Stats {
var systemStats system.Stats
// battery
if batteryPercent, batteryState, err := battery.GetBatteryStats(); err == nil {
systemStats.Battery[0] = batteryPercent
systemStats.Battery[1] = batteryState
if batteries, err := battery.GetBatteryStats(); err == nil {
systemStats.Batteries = make(map[string]uint8, len(batteries))
for _, device := range batteries {
systemStats.Batteries[device.Name] = device.Percent
}
if primary, ok := battery.Primary(batteries); ok {
systemStats.Battery = [2]uint8{primary.Percent, primary.State}
}
}
// cpu metrics

3
docs/index.yaml Normal file
View File

@@ -0,0 +1,3 @@
apiVersion: v1
entries: {}
generated: "2026-03-05T00:00:00Z"

View File

@@ -55,6 +55,7 @@ type SystemAlertStats struct {
Temperatures map[string]float32 `json:"t"`
LoadAvg [3]float64 `json:"la"`
Battery [2]uint8 `json:"bat"`
Batteries map[string]uint8 `json:"bats"`
ExtraFs map[string]SystemAlertFsStats `json:"efs"`
}

View File

@@ -63,7 +63,7 @@ func (am *AlertManager) HandleSystemAlerts(systemRecord *core.Record, data *syst
case "GPU":
val = data.Info.GpuPct
case "Battery":
if data.Stats.Battery[0] == 0 {
if !hasRepresentativeBattery(data.Stats.Battery, data.Stats.Batteries) {
continue
}
val = float64(data.Stats.Battery[0])
@@ -167,6 +167,7 @@ func (am *AlertManager) HandleSystemAlerts(systemRecord *core.Record, data *syst
stat := systemStats[i]
// subtract 10 seconds to give a small time buffer
systemStatsCreation := stat.Created.Time().Add(-time.Second * 10)
stats = SystemAlertStats{}
if err := json.Unmarshal(stat.Stats, &stats); err != nil {
return err
}
@@ -235,6 +236,9 @@ func (am *AlertManager) HandleSystemAlerts(systemRecord *core.Record, data *syst
}
alert.val += maxUsage
case "Battery":
if !hasRepresentativeBattery(stats.Battery, stats.Batteries) {
continue
}
alert.val += float64(stats.Battery[0])
default:
continue
@@ -297,6 +301,10 @@ func (am *AlertManager) HandleSystemAlerts(systemRecord *core.Record, data *syst
return nil
}
func hasRepresentativeBattery(legacy [2]uint8, batteries map[string]uint8) bool {
return legacy != [2]uint8{} || len(batteries) > 0
}
func (am *AlertManager) sendSystemAlert(alert SystemAlertData) {
// log.Printf("Sending alert %s: val %f | count %d | threshold %f\n", alert.name, alert.val, alert.count, alert.threshold)
systemName := alert.systemRecord.GetString("name")

View File

@@ -199,7 +199,7 @@ func TestSystemAlertsOneMin(t *testing.T) {
testOneMinuteSystemAlert(t, "LoadAvg1", 4, setLoadAvgAlertValue, [3]float64{4.1, 0, 0}, [3]float64{3.9, 0, 0})
testOneMinuteSystemAlert(t, "LoadAvg5", 4, setLoadAvgAlertValue, [3]float64{0, 4.1, 0}, [3]float64{0, 3.9, 0})
testOneMinuteSystemAlert(t, "LoadAvg15", 4, setLoadAvgAlertValue, [3]float64{0, 0, 4.1}, [3]float64{0, 0, 3.9})
testOneMinuteSystemAlert(t, "Battery", 20, setBatteryAlertValue, [2]uint8{19, 0}, [2]uint8{21, 0})
testOneMinuteSystemAlert(t, "Battery", 20, setBatteryAlertValue, [2]uint8{0, 1}, [2]uint8{21, 0})
}
func TestSystemAlertsTwoMin(t *testing.T) {

View File

@@ -20,7 +20,7 @@ FROM alpine:3.23
COPY --from=builder /agent /agent
RUN apk add --no-cache -X https://dl-cdn.alpinelinux.org/alpine/edge/testing igt-gpu-tools smartmontools
RUN apk add --no-cache -X https://dl-cdn.alpinelinux.org/alpine/edge/testing igt-gpu-tools nvtop smartmontools
# Ensure data persistence across container recreations
VOLUME ["/var/lib/beszel-agent"]

View File

@@ -0,0 +1,90 @@
FROM --platform=$BUILDPLATFORM golang:bookworm AS builder
WORKDIR /app
COPY ../go.mod ../go.sum ./
RUN go mod download
# Copy source files
COPY . ./
# Build
ARG TARGETOS=linux
ARG TARGETARCH
ARG TARGETVARIANT
RUN set -eux; \
if [ "$TARGETARCH" = "arm" ] && [ -n "$TARGETVARIANT" ]; then \
export GOARM="${TARGETVARIANT#v}"; \
fi; \
CGO_ENABLED=0 GOGC=75 GOOS=$TARGETOS GOARCH=$TARGETARCH \
go build -tags glibc -ldflags "-w -s" -o /agent ./internal/cmd/agent
# --------------------------
# Smartmontools builder stage
# --------------------------
FROM --platform=$TARGETPLATFORM debian:bookworm-slim AS smartmontools-builder
# Keep smartmontools 7.5 built from source to match the current NVIDIA agent image behavior.
# A simpler Debian package based approach is also possible:
#
# RUN apt-get update && apt-get install -y --no-install-recommends \
# smartmontools \
# && rm -rf /var/lib/apt/lists/*
RUN apt-get update && apt-get install -y --no-install-recommends \
wget \
ca-certificates \
build-essential \
make \
g++ \
&& wget https://downloads.sourceforge.net/project/smartmontools/smartmontools/7.5/smartmontools-7.5.tar.gz \
&& tar zxvf smartmontools-7.5.tar.gz \
&& cd smartmontools-7.5 \
&& ./configure --prefix=/usr --sysconfdir=/etc \
&& make \
&& make install \
&& rm -rf /smartmontools-7.5* \
&& apt-get remove -y wget build-essential \
&& apt-get autoremove -y \
&& rm -rf /var/lib/apt/lists/*
# Copy smartmontools binary, data files, and required runtime libraries
RUN set -eux; \
mkdir -p /out/rootfs/usr/share /out/rootfs/lib /out/rootfs/lib64 /out/rootfs/usr/lib; \
if [ -d /usr/share/smartmontools ]; then \
cp -a /usr/share/smartmontools /out/rootfs/usr/share/; \
fi; \
ldd /usr/sbin/smartctl \
| awk '{print $3}' \
| grep '^/' \
| xargs -r -I '{}' sh -c 'mkdir -p "/out/rootfs$(dirname "{}")"; cp -v "{}" "/out/rootfs{}"'; \
interp="$(ldd /usr/sbin/smartctl | awk "/ld-linux/ {print \$1}")"; \
if [ -n "$interp" ] && [ -e "$interp" ]; then \
mkdir -p "/out/rootfs$(dirname "$interp")"; \
cp -v "$interp" "/out/rootfs$interp"; \
fi
# --------------------------
# Final image: lightweight multi-arch NVIDIA agent (slim)
# --------------------------
FROM --platform=$TARGETPLATFORM gcr.io/distroless/base-debian12
COPY --from=builder /agent /agent
# AMD GPU name lookup (used by agent on hybrid laptops when /usr/share/libdrm/amdgpu.ids is read)
COPY --from=builder /app/agent/test-data/amdgpu.ids /usr/share/libdrm/amdgpu.ids
# Copy smartmontools binaries and config files
COPY --from=smartmontools-builder /usr/sbin/smartctl /usr/sbin/smartctl
COPY --from=smartmontools-builder /out/rootfs/ /
# nvidia-smi is intentionally not bundled.
# Mount the host binary instead, for example:
# - /usr/bin/nvidia-smi:/usr/bin/nvidia-smi:ro
# Ensure data persistence across container recreations
VOLUME ["/var/lib/beszel-agent"]
WORKDIR /var/lib/beszel-agent
ENTRYPOINT ["/agent"]

View File

@@ -34,6 +34,7 @@ type Stats struct {
MaxNetworkRecv float64 `json:"nrm,omitempty" cbor:"-"`
Temperatures map[string]float64 `json:"t,omitempty" cbor:"20,keyasint,omitempty"`
Fans map[string]uint16 `json:"f,omitempty" cbor:"36,keyasint,omitempty"`
Batteries map[string]uint8 `json:"bats,omitempty" cbor:"37,keyasint,omitempty"`
ExtraFs map[string]*FsStats `json:"efs,omitempty" cbor:"21,keyasint,omitempty"`
GPUData map[string]GPUData `json:"g,omitempty" cbor:"22,keyasint,omitempty"`
// LoadAvg1 float64 `json:"l1,omitempty" cbor:"23,keyasint,omitempty"`
@@ -43,7 +44,7 @@ type Stats struct {
MaxBandwidth [2]uint64 `json:"bm,omitzero" cbor:"-"` // [sent bytes, recv bytes]
// TODO: remove other load fields in future release in favor of load avg array
LoadAvg [3]float64 `json:"la,omitempty" cbor:"28,keyasint"`
Battery [2]uint8 `json:"bat,omitzero" cbor:"29,keyasint,omitzero"` // [percent, charge state, current]
Battery [2]uint8 `json:"bat,omitzero" cbor:"29,keyasint,omitzero"` // [percent, charge state]
NetworkInterfaces map[string][4]uint64 `json:"ni,omitempty" cbor:"31,keyasint,omitempty"` // [upload bytes, download bytes, total upload, total download]
DiskIO [2]uint64 `json:"dio,omitzero" cbor:"32,keyasint,omitzero"` // [read bytes, write bytes]
MaxDiskIO [2]uint64 `json:"diom,omitzero" cbor:"-"` // [max read bytes, max write bytes]

View File

@@ -0,0 +1,37 @@
package system
import (
"encoding/json"
"testing"
"github.com/fxamacker/cbor/v2"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestStatsBatteryTransport(t *testing.T) {
stats := Stats{Battery: [2]uint8{0, 1}, Batteries: map[string]uint8{"Primary": 0, "Mouse": 75}}
jsonData, err := json.Marshal(stats)
require.NoError(t, err)
var jsonPayload map[string]any
require.NoError(t, json.Unmarshal(jsonData, &jsonPayload))
assert.Equal(t, []any{float64(0), float64(1)}, jsonPayload["bat"])
assert.Equal(t, map[string]any{"Primary": float64(0), "Mouse": float64(75)}, jsonPayload["bats"])
cborData, err := cbor.Marshal(stats)
require.NoError(t, err)
var decoded Stats
require.NoError(t, cbor.Unmarshal(cborData, &decoded))
assert.Equal(t, stats.Battery, decoded.Battery)
assert.Equal(t, stats.Batteries, decoded.Batteries)
}
func TestStatsLegacyBatteryPayload(t *testing.T) {
data, err := json.Marshal(Stats{Battery: [2]uint8{50, 4}})
require.NoError(t, err)
var payload map[string]any
require.NoError(t, json.Unmarshal(data, &payload))
assert.Contains(t, payload, "bat")
assert.NotContains(t, payload, "bats")
}

View File

@@ -348,6 +348,9 @@ func (sys *System) getRecord(app core.App) (*core.Record, error) {
record, err := app.FindRecordById("systems", sys.Id)
if err != nil || record == nil {
_ = sys.manager.RemoveSystem(sys.Id)
if err == nil {
err = fmt.Errorf("system record %s not found", sys.Id)
}
return nil, err
}
return record, nil
@@ -377,10 +380,16 @@ func (sys *System) HasUser(app core.App, user *core.Record) bool {
// setDown marks a system as down in the database.
// It takes the original error that caused the system to go down and returns any error
// encountered during the process of updating the system status.
// It is a no-op if the system's context has been cancelled.
func (sys *System) setDown(originalError error) error {
if sys.Status == down || sys.Status == paused {
return nil
}
// the updater can race shutdown, and the app may already be disposed by the
// time we get here, so don't touch the database once the context is cancelled
if sys.ctx != nil && sys.ctx.Err() != nil {
return sys.ctx.Err()
}
record, err := sys.getRecord(sys.manager.hub)
if err != nil {
return err

View File

@@ -3,6 +3,7 @@
package systems
import (
"context"
"testing"
"github.com/henrygd/beszel/internal/entities/system"
@@ -157,3 +158,17 @@ func TestCombinedData_MigrateDeprecatedFields(t *testing.T) {
}
})
}
func TestSetDownAfterContextCancelled(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
// manager is nil on purpose: setDown must bail out before touching the app
sys := &System{Status: up, ctx: ctx}
if err := sys.setDown(nil); err != context.Canceled {
t.Fatalf("expected context.Canceled, got %v", err)
}
if sys.Status != up {
t.Fatalf("status should be untouched, got %q", sys.Status)
}
}

View File

@@ -186,6 +186,9 @@ func AverageSystemStatsSlice(records []system.Stats) system.Stats {
// necessary because uint8 is not big enough for the sum
batterySum := 0
batteryCount := 0
batterySums := make(map[string]uint64)
batteryCounts := make(map[string]uint64)
// accumulate per-core usage across records
var cpuCoresSums []uint64
// accumulate cpu breakdown [user, system, iowait, steal, idle]
@@ -232,8 +235,15 @@ func AverageSystemStatsSlice(records []system.Stats) system.Stats {
for i := range stats.DiskIoStats {
sum.DiskIoStats[i] += stats.DiskIoStats[i]
}
batterySum += int(stats.Battery[0])
sum.Battery[1] = stats.Battery[1]
if hasBattery(stats.Battery, stats.Batteries) {
batterySum += int(stats.Battery[0])
batteryCount++
sum.Battery[1] = stats.Battery[1]
}
for name, percent := range stats.Batteries {
batterySums[name] += uint64(percent)
batteryCounts[name]++
}
// accumulate per-core usage if present
if stats.CpuCoresUsage != nil {
@@ -379,7 +389,15 @@ func AverageSystemStatsSlice(records []system.Stats) system.Stats {
sum.LoadAvg[2] = twoDecimals(sum.LoadAvg[2] / count)
sum.Bandwidth[0] = sum.Bandwidth[0] / uint64(count)
sum.Bandwidth[1] = sum.Bandwidth[1] / uint64(count)
sum.Battery[0] = uint8(batterySum / int(count))
if batteryCount > 0 {
sum.Battery[0] = uint8(batterySum / batteryCount)
}
if len(batterySums) > 0 {
sum.Batteries = make(map[string]uint8, len(batterySums))
for name, total := range batterySums {
sum.Batteries[name] = uint8(total / batteryCounts[name])
}
}
// Average network interfaces
if sum.NetworkInterfaces != nil {
@@ -467,6 +485,10 @@ func AverageSystemStatsSlice(records []system.Stats) system.Stats {
return sum
}
func hasBattery(legacy [2]uint8, batteries map[string]uint8) bool {
return legacy != [2]uint8{} || len(batteries) > 0
}
// Calculate the average stats of a list of container_stats records
func (rm *RecordManager) AverageContainerStats(db dbx.Builder, records RecordIds) []container.Stats {
allStats := make([][]container.Stats, 0, len(records))

View File

@@ -602,6 +602,28 @@ func TestAverageSystemStatsSlice_BatteryLastChargeState(t *testing.T) {
assert.Equal(t, uint8(0), result.Battery[1]) // last record's charge state
}
func TestAverageSystemStatsSlice_BatteriesIndependentSamples(t *testing.T) {
input := []system.Stats{
{Battery: [2]uint8{80, 4}, Batteries: map[string]uint8{"Primary": 80, "Mouse": 0}},
{Battery: [2]uint8{60, 3}, Batteries: map[string]uint8{"Primary": 60}},
{Battery: [2]uint8{30, 4}, Batteries: map[string]uint8{"Mouse": 40}},
{},
}
result := records.AverageSystemStatsSlice(input)
assert.Equal(t, map[string]uint8{"Primary": 70, "Mouse": 20}, result.Batteries)
assert.Equal(t, uint8(56), result.Battery[0], "representative battery excludes absent samples")
assert.Equal(t, uint8(4), result.Battery[1], "representative state comes from its latest sample")
}
func TestAverageSystemStatsSlice_ZeroRepresentativeBattery(t *testing.T) {
result := records.AverageSystemStatsSlice([]system.Stats{
{Battery: [2]uint8{0, 1}, Batteries: map[string]uint8{"Primary": 0}},
{},
})
assert.Equal(t, [2]uint8{0, 1}, result.Battery)
assert.Equal(t, map[string]uint8{"Primary": 0}, result.Batteries)
}
func TestAverageSystemStatsSlice_ThreeRecordsRounding(t *testing.T) {
input := []system.Stats{
{Cpu: 10.0, Mem: 8.0},

View File

@@ -9,11 +9,7 @@
"preview": "vite preview",
"sync": "lingui extract --overwrite && lingui compile",
"sync_no_compile": "lingui extract --overwrite --clean",
"sync_and_purge": "lingui extract --overwrite --clean && lingui compile",
"format": "biome format --write .",
"lint": "biome lint .",
"check": "biome check .",
"check:fix": "biome check --fix ."
"sync_and_purge": "lingui extract --overwrite --clean && lingui compile"
},
"dependencies": {
"@henrygd/queue": "^1.0.7",

View File

@@ -125,7 +125,7 @@ export default memo(function SystemDetail({ id }: { id: string }) {
<FanChart {...coreProps} />
<BatteryChart {...coreProps} />
<BatteryChart system={system} {...coreProps} />
{hasGpuPowerData && <GpuPowerChart chartData={chartData} grid={grid} dataEmpty={dataEmpty} />}
</div>
@@ -191,7 +191,7 @@ export default memo(function SystemDetail({ id }: { id: string }) {
<BandwidthChart {...coreProps} systemStats={systemStats} />
<TemperatureChart {...coreProps} setPageBottomExtraMargin={setPageBottomExtraMargin} />
<FanChart {...coreProps} />
<BatteryChart {...coreProps} />
<BatteryChart system={system} {...coreProps} />
<SwapChart chartData={chartData} grid={grid} dataEmpty={dataEmpty} systemStats={systemStats} />
{pageBottomExtraMargin > 0 && <div style={{ marginBottom: pageBottomExtraMargin }}></div>}
</div>

View File

@@ -3,7 +3,7 @@ import AreaChartDefault from "@/components/charts/area-chart"
import { batteryStateTranslations } from "@/lib/i18n"
import { $fanFilter, $temperatureFilter, $userSettings } from "@/lib/stores"
import { cn, decimalString, formatTemperature, toFixedFloat } from "@/lib/utils"
import type { ChartData, SystemStatsRecord } from "@/types"
import type { ChartData, SystemRecord, SystemStatsRecord } from "@/types"
import { ChartCard, FilterBar } from "../chart-card"
import LineChartDefault from "@/components/charts/line-chart"
import { useStore } from "@nanostores/react"
@@ -14,18 +14,60 @@ export function BatteryChart({
grid,
dataEmpty,
maxValues,
system,
}: {
chartData: ChartData
grid: boolean
dataEmpty: boolean
maxValues: boolean
system: SystemRecord
}) {
const showBatteryChart = chartData.systemStats.at(-1)?.stats.bat
const batteryNames = useMemo(() => {
const names = new Set<string>()
for (const record of chartData.systemStats) {
for (const name in record.stats?.bats ?? {}) {
names.add(name)
}
}
return [...names].sort()
}, [chartData.systemStats])
const hasNamedBatteries = batteryNames.length > 0
const showBatteryChart = hasNamedBatteries || chartData.systemStats.some((record) => record.stats?.bat)
if (!showBatteryChart) {
return null
}
if (hasNamedBatteries) {
const dataPoints = batteryNames.map((name, index) => ({
label: name,
dataKey: ({ stats }: SystemStatsRecord) => stats?.bats?.[name],
color: `hsl(${(index * 360 + 226) / batteryNames.length}, 65%, 52%)`,
}))
return (
<ChartCard
empty={dataEmpty}
grid={grid}
title={t`Battery`}
description={`${t({
message: "Current state",
comment: "Context: Battery state",
})}: ${batteryStateTranslations[system.info.bat?.[1] ?? 0]()}`}
>
<LineChartDefault
chartData={chartData}
maxToggled={maxValues}
dataPoints={dataPoints}
domain={[0, 100]}
legend={true}
tickFormatter={(val) => `${val}%`}
contentFormatter={({ value }) => `${value}%`}
itemSorter={(a, b) => b.value - a.value}
/>
</ChartCard>
)
}
return (
<ChartCard
empty={dataEmpty}
@@ -34,7 +76,7 @@ export function BatteryChart({
description={`${t({
message: "Current state",
comment: "Context: Battery state",
})}: ${batteryStateTranslations[chartData.systemStats.at(-1)?.stats.bat?.[1] ?? 0]()}`}
})}: ${batteryStateTranslations[system.info.bat?.[1] ?? 0]()}`}
>
<AreaChartDefault
chartData={chartData}
@@ -210,15 +252,7 @@ export function TemperatureChart({
)
}
export function FanChart({
chartData,
grid,
dataEmpty,
}: {
chartData: ChartData
grid: boolean
dataEmpty: boolean
}) {
export function FanChart({ chartData, grid, dataEmpty }: { chartData: ChartData; grid: boolean; dataEmpty: boolean }) {
const showFanChart = chartData.systemStats.at(-1)?.stats.f
const filter = useStore($fanFilter)

View File

@@ -151,6 +151,8 @@ export interface SystemStats {
g?: Record<string, GPUData>
/** battery percent and state */
bat?: [number, BatteryState]
/** battery percentages by device name */
bats?: Record<string, number>
/** network interfaces [upload bytes, download bytes, total upload bytes, total download bytes] */
ni?: Record<string, [number, number, number, number]>
}

View File

@@ -0,0 +1,26 @@
{
"$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json",
"release-type": "simple",
"packages": {
"supplemental/helm/beszel-agent": {
"package-name": "beszel-agent",
"release-type": "helm",
"changelog-path": "CHANGELOG.md",
"bump-minor-pre-major": true,
"bump-patch-for-minor-pre-major": true,
"draft": true,
"force-tag-creation": true,
"prerelease": false
},
"supplemental/helm/beszel-hub": {
"package-name": "beszel-hub",
"release-type": "helm",
"changelog-path": "CHANGELOG.md",
"bump-minor-pre-major": true,
"bump-patch-for-minor-pre-major": true,
"draft": true,
"force-tag-creation": true,
"prerelease": false
}
}
}

View File

@@ -0,0 +1,15 @@
# Changelog
## [0.1.2](https://github.com/henrygd/beszel/compare/beszel-agent-v0.1.1...beszel-agent-v0.1.2) (2026-08-16)
### Bug Fixes
* **helm:** publish immutable chart releases safely, maybe ([c67b69d](https://github.com/henrygd/beszel/commit/c67b69d17e93cf0b5a50ff23d4140d481e22134f))
## [0.1.1](https://github.com/henrygd/beszel/compare/beszel-agent-v0.1.0...beszel-agent-v0.1.1) (2026-08-16)
### Features
* huge beszel hub and agent helm chart update ([#1582](https://github.com/henrygd/beszel/issues/1582)) ([ec4ec01](https://github.com/henrygd/beszel/commit/ec4ec01a393796d2e282b22a499cdd98c3c958ba))

View File

@@ -0,0 +1,15 @@
apiVersion: v1
description: Installs beszel-agent in kubernetes
home: https://github.com/henrygd/beszel/tree/main/supplemental/helm/beszel-agent
name: beszel-agent
appVersion: "0.17.0"
# This version is managed automatically by Release Please.
version: 0.1.2
sources:
- https://github.com/henrygd/beszel/tree/main/supplemental/helm/beszel-agent
- https://www.beszel.dev/
- https://github.com/henrygd/beszel
icon: https://repository-images.githubusercontent.com/825470378/2710c6db-f934-4a8b-a2c4-7a0abbcd2ad6
maintainers:
- name: cloudwithdan
email: nikoloskid@pm.me

View File

@@ -0,0 +1,538 @@
# Beszel Agent Helm Chart
A Kubernetes Helm chart for deploying [Beszel Agent](https://www.beszel.dev/) - a lightweight monitoring agent that collects system metrics and sends them to a central Beszel Hub.
## Overview
This Helm chart simplifies the deployment of Beszel Agent in Kubernetes environments. By default, it deploys as a DaemonSet to run one agent on each node in the cluster. The agent monitors node-level system resources (CPU, memory, disk, network, temperature, GPU, etc.) and provides detailed metrics to the Beszel Hub for centralized monitoring and alerting.
## Features
- ✅ DaemonSet deployment by default (one agent per node)
- ✅ GPU support via NVIDIA runtime (optional)
- ✅ Additional filesystem mounting for multi-disk monitoring
- ✅ Flexible deployment as DaemonSet or single Deployment
- ✅ Environment variable configuration for agent authentication
- ✅ Host network support for detailed network monitoring
- ✅ Automatic handling of tainted nodes via tolerations
## Prerequisites
- Kubernetes 1.19+
- Helm 3.0+
- Beszel Hub instance running and accessible
- SSH public key for agent authentication
## What Gets Monitored
In Kubernetes environments, the Beszel agent monitors **node-level metrics**:
- **CPU usage** - Node CPU utilization and per-core stats
- **Memory usage** - Node memory, swap, and ZFS ARC
- **Disk usage** - Node filesystem usage and I/O statistics
- **Network usage** - Node network traffic (requires `hostNetwork: true`)
- **Load average** - System load averages
- **Temperature** - Node hardware sensors
- **GPU usage/power** - NVIDIA, AMD, and Intel GPUs (with appropriate image)
- **Battery** - Node battery status (if applicable)
- **S.M.A.T.** - Disk health monitoring
**Note**: The agent does **not** monitor individual Kubernetes pods or containers. For pod/container metrics, use Kubernetes metrics-server or monitoring tools like Prometheus.
## Quick Start
### 1. Add the Helm Repository
```bash
helm repo add beszel https://henrygd.github.io/beszel
helm repo update
```
### 2. Install the Chart
```bash
helm install beszel-agent ./beszel-agent \
--set env.KEY="ssh-ed25519 AAAA... your-public-key" \
--set env.TOKEN="your-token-value" \
--set env.HUB_URL="http://beszel-hub:8090"
```
Or with custom values:
```bash
helm install beszel-agent ./beszel-agent -f custom-values.yaml
```
### 3. Verify the Agent is Running
```bash
kubectl get pods -l app.kubernetes.io/name=beszel-agent
kubectl logs -l app.kubernetes.io/name=beszel-agent
```
## Configuration
### Basic Configuration
Essential parameters to configure:
| Parameter | Default | Description |
|-----------|---------|-------------|
| `daemonset.enabled` | `true` | Deploy as DaemonSet (one pod per node) |
| `env.KEY` | Required* | SSH public key for Hub authentication (*unless using existingSecret) |
| `env.TOKEN` | Empty | Authentication token (optional) |
| `env.HUB_URL` | Empty | Hub URL (e.g., http://beszel-hub:8090) |
| `env.PORT` | `45876` | Port the agent listens on |
| `secret.existingSecret` | Empty | Name of an existing Kubernetes Secret to use |
| `secret.sshKey` | `ssh-key` | Key name in the secret for the SSH public key |
| `secret.tokenKey` | `token` | Key name in the secret for the authentication token |
| `image.repository` | `henrygd/beszel-agent` | Container image |
| `image.tag` | Chart AppVersion (0.17.0) | Image version |
| `hostNetwork` | `false` | Use host network for network monitoring |
| `tolerations` | Allows all taints | Tolerations for running on tainted nodes |
### Minimal Configuration
```bash
helm install beszel-agent ./beszel-agent \
--set env.KEY="ssh-ed25519 AAAA... your-public-key" \
--set env.TOKEN="your-token-value" \
--set env.HUB_URL="http://beszel-hub:8090"
```
### Standard Configuration
```yaml
# values.yaml
image:
repository: henrygd/beszel-agent
tag: "" # Uses chart appVersion
env:
PORT: "45876"
KEY: "ssh-ed25519 AAAA... your-public-key"
TOKEN: "your-token-value"
HUB_URL: "http://beszel-hub:8090"
# Use host network for accurate network monitoring
hostNetwork: false
```
### GPU Support (NVIDIA)
For systems with NVIDIA GPUs, use the special GPU-enabled image:
```yaml
image:
repository: henrygd/beszel-agent-nvidia
# Enable NVIDIA runtime
gpuRuntime: nvidia
env:
PORT: "45876"
KEY: "ssh-ed25519 AAAA... your-public-key"
TOKEN: "your-token-value"
HUB_URL: "http://beszel-hub:8090"
NVIDIA_VISIBLE_DEVICES: "all"
NVIDIA_DRIVER_CAPABILITIES: "compute,video,utility"
```
**Note**: The GPU image (`henrygd/beszel-agent-nvidia`) is specifically for monitoring NVIDIA GPUs on the node. It does not provide container-level GPU metrics.
Or via CLI:
```bash
helm install beszel-agent ./beszel-agent \
--set image.repository=henrygd/beszel-agent-nvidia \
--set gpuRuntime=nvidia \
--set env.NVIDIA_VISIBLE_DEVICES=all \
--set env.NVIDIA_DRIVER_CAPABILITIES="compute,video,utility" \
--set env.KEY="ssh-ed25519 AAAA... your-public-key" \
--set env.TOKEN="your-token-value" \
--set env.HUB_URL="http://beszel-hub:8090"
```
### Monitor Additional Filesystems
To monitor additional disks or partitions:
```yaml
volumes:
- name: extra-filesystems
hostPath:
path: /mnt/disk/.beszel
type: DirectoryOrCreate
volumeMounts:
- name: extra-filesystems
mountPath: /extra-filesystems
readOnly: true
env:
PORT: "45876"
KEY: "ssh-ed25519 AAAA... your-public-key"
TOKEN: "your-token-value"
HUB_URL: "http://beszel-hub:8090"
```
### Advanced Configuration
#### Resource Limits
```yaml
resources:
limits:
cpu: 500m
memory: 256Mi
requests:
cpu: 100m
memory: 128Mi
```
#### Node Selection
Run agents on specific nodes:
```yaml
nodeSelector:
monitoring: "true"
tolerations:
- key: monitoring
operator: Equal
value: "true"
effect: NoSchedule
affinity:
podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector:
matchExpressions:
- key: app.kubernetes.io/name
operator: In
values:
- beszel-agent
topologyKey: kubernetes.io/hostname
```
#### Host Network
For detailed network statistics, enable host network mode:
```yaml
hostNetwork: true
env:
PORT: "45876"
KEY: "ssh-ed25519 AAAA... your-public-key"
TOKEN: "your-token-value"
HUB_URL: "http://beszel-hub:8090"
```
**Note**: When `hostNetwork: true`, the agent can monitor the node's actual network interfaces. When `false`, it only sees the pod's network namespace.
#### DaemonSet Mode
By default, the agent is deployed as a DaemonSet, running one pod on each cluster node:
```yaml
daemonset:
enabled: true # Default - one agent per node
# Or disable for single Deployment deployment
daemonset:
enabled: false
replicaCount: 1
```
#### Tolerations
By default, tolerations are set to allow agents to run on all nodes, including tainted ones:
```yaml
tolerations:
- operator: Exists
effect: NoSchedule
- operator: Exists
effect: NoExecute
```
To restrict agents to specific nodes:
```yaml
tolerations: []
nodeSelector:
monitoring: "true"
```
### Using Existing Secrets
The chart supports referencing an existing Kubernetes Secret instead of having the chart create one. This is useful when:
- You want to manage secrets externally (e.g., with a secret operator, external secret manager, or GitOps)
- You want to share a single secret across multiple deployments
- You prefer not to store sensitive values in Helm values
```yaml
# Create the secret manually
apiVersion: v1
kind: Secret
metadata:
name: my-beszel-secret
type: Opaque
data:
ssh-key: c3NoLWVkMjU1IDEgQUFBQU... # base64 encoded SSH public key
token: dG9rZW4tdmFsdWU= # base64 encoded token (optional)
```
Then reference it in your values:
```yaml
secret:
existingSecret: my-beszel-secret
sshKey: ssh-key # key name in the secret (default: ssh-key)
tokenKey: token # key name in the secret (default: token)
env:
HUB_URL: "http://beszel-hub:8090"
```
**Note**: When using `existingSecret`, do not set `env.KEY` or `env.TOKEN` - the chart will use the values from the existing secret instead.
You can also use different key names if your secret uses non-standard keys:
```yaml
secret:
existingSecret: my-beszel-secret
sshKey: public-key # custom key name
tokenKey: auth-token # custom key name
```
## Deployment Examples
### Full Cluster Monitoring (DaemonSet - Default)
```bash
helm install beszel-agent ./beszel-agent \
--set env.KEY="ssh-ed25519 AAAA... your-public-key" \
--set env.TOKEN="your-token-value" \
--set env.HUB_URL="http://beszel-hub:8090"
```
This deploys one agent on every node in the cluster automatically.
### Single Agent Deployment (Non-DaemonSet)
```yaml
# values.yaml
daemonset:
enabled: false
replicaCount: 1
env:
PORT: "45876"
KEY: "ssh-ed25519 AAAA... your-public-key"
TOKEN: "your-token-value"
HUB_URL: "http://beszel-hub:8090"
```
Or via CLI:
```bash
helm install beszel-agent ./beszel-agent \
--set daemonset.enabled=false \
--set replicaCount=1 \
--set env.KEY="ssh-ed25519 AAAA... your-public-key" \
--set env.TOKEN="your-token-value" \
--set env.HUB_URL="http://beszel-hub:8090"
```
### Network Monitoring with Host Network
```yaml
hostNetwork: true
env:
PORT: "45876"
KEY: "ssh-ed25519 AAAA... your-public-key"
TOKEN: "your-token-value"
HUB_URL: "http://beszel-hub:8090"
podSecurityContext:
hostNetwork: true
```
## Managing the Agent
### Check Agent Status
```bash
# List agent pods
kubectl get pods -l app.kubernetes.io/name=beszel-agent
# View agent logs
kubectl logs -l app.kubernetes.io/name=beszel-agent -f
# Describe a specific pod
kubectl describe pod <pod-name>
```
### Update Configuration
```bash
# Update the SSH key
helm upgrade beszel-agent ./beszel-agent \
--set env.KEY="ssh-ed25519 AAAA... your-public-key" \
--set env.TOKEN="your-token-value" \
--set env.HUB_URL="http://beszel-hub:8090"
# Change image version
helm upgrade beszel-agent ./beszel-agent \
--set image.tag="0.17.0"
```
### Restart All Agents
```bash
# For DaemonSet (default)
kubectl rollout restart daemonset beszel-agent
# For Deployment (if daemonset.enabled=false)
kubectl rollout restart deployment beszel-agent
```
### Uninstall
```bash
helm uninstall beszel-agent
```
### View Helm Release History
```bash
helm history beszel-agent
helm rollback beszel-agent 1 # Rollback to previous version
```
## Environment Variables
| Variable | Default | Description |
|----------|---------|-------------|
| `PORT` | `45876` | Port the agent listens on |
| `KEY` | Required | SSH public key for Hub authentication |
| `TOKEN` | Empty | Authentication token (optional) |
| `HUB_URL` | Empty | Hub URL (e.g., http://beszel-hub:8090) |
| `NVIDIA_VISIBLE_DEVICES` | Not set | GPU visibility (GPU agents only) |
| `NVIDIA_DRIVER_CAPABILITIES` | Not set | GPU capabilities (GPU agents only) |
## Troubleshooting
### Agent Pod Won't Start
```bash
# Check pod events and logs
kubectl describe pod <pod-name>
kubectl logs <pod-name>
```
### Cannot Connect to Hub
- Verify Hub is accessible from the pod's network
- Check DNS resolution: `kubectl exec <pod-name> -- nslookup beszel-hub.default.svc.cluster.local`
- Verify SSH key is correctly configured
- Check firewall rules for port 8090 (Hub) and 45876 (Agent)
### GPU Not Detected
- Confirm image is `henrygd/beszel-agent-nvidia`
- Verify NVIDIA runtime is installed on nodes
- Check GPU visibility: `kubectl exec <pod-name> -- nvidia-smi`
- Verify runtimeClassName matches your GPU runtime
### SSH Key Authentication Failed
- Verify key format (should be valid SSH public key)
- Check key is correctly set in `env.KEY`
- Ensure Hub has the corresponding private key
- Verify Hub can authenticate agents with this key
### High Memory Usage
Adjust resource limits:
```yaml
resources:
limits:
memory: 512Mi
requests:
memory: 256Mi
```
## Security Considerations
- Store SSH keys securely (use Kubernetes Secrets)
- Restrict container to read-only root filesystem if possible
- Limit resource usage with resource limits
- Use network policies to restrict traffic
- Run with minimal privileges
- Regularly update agent image to latest version
- Use private container registries if applicable
### Using Kubernetes Secrets for Configuration
The chart automatically creates a Kubernetes Secret to store sensitive authentication data:
```bash
# Install with all configuration options
helm install beszel-agent ./beszel-agent \
--set env.KEY="ssh-ed25519 AAAA... your-public-key" \
--set env.TOKEN="your-optional-token" \
--set env.HUB_URL="http://beszel-hub:8090"
```
Or create the installation with a values file:
```yaml
# values.yaml
env:
KEY: "ssh-ed25519 AAAA... your-public-key"
TOKEN: "your-optional-token"
HUB_URL: "http://beszel-hub:8090"
```
Configuration stored in Kubernetes Secrets (encrypted at rest):
- `KEY` - SSH public key for authentication (required)
- `TOKEN` - Authentication token (optional)
Configuration as regular environment variables:
- `HUB_URL` - Hub address (e.g., http://beszel-hub:8090 or https://beszel.example.com)
To verify the secret was created:
```bash
kubectl get secret beszel-agent
kubectl get secret beszel-agent -o jsonpath='{.data.ssh-key}' | base64 -d
```
## Support and Documentation
- **Project Homepage**: https://www.beszel.dev/
- **GitHub Repository**: https://github.com/henrygd/beszel
- **Agent Documentation**: https://www.beszel.dev/
**Note**: The main Beszel documentation describes Docker/Podman container monitoring. In Kubernetes, the agent focuses on node-level metrics. For Kubernetes-specific container/pod monitoring, use tools like metrics-server, Prometheus, or the Kubernetes Metrics API.
## Chart Information
- **Chart Version**: 0.1.0
- **App Version**: 0.17.0
- **Kubernetes Version**: 1.19+
- **Maintainer**: cloudwithdan (nikoloskid@pm.me)
## License
Please refer to the main Beszel project repository for license information.

View File

@@ -0,0 +1,21 @@
1. Get Beszel Agent Status
kubectl get daemonset -n {{ .Release.Namespace }} {{ include "beszel-agent.fullname" . }}
kubectl get pods -n {{ .Release.Namespace }} -l app.kubernetes.io/name={{ include "beszel-agent.name" . }}
2. View Agent Logs
kubectl logs -n {{ .Release.Namespace }} -l app.kubernetes.io/name={{ include "beszel-agent.name" . }} -f
3. Verify SSH Key Configuration
kubectl get secret -n {{ .Release.Namespace }} {{ include "beszel-agent.fullname" . }} -o jsonpath='{.data.ssh-key}' | base64 -d
4. Agent Configuration
- Port: {{ .Values.env.PORT }}
- Image: {{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}
{{- if .Values.hostNetwork }}
- Host Network: Enabled
{{- end }}
{{- if .Values.gpuRuntime }}
- GPU Runtime: {{ .Values.gpuRuntime }}
{{- end }}
5. Next Steps
- Ensure the Beszel Hub is accessible from the cluster
- Check that the SSH key is registered with the Hub
- Verify agent connectivity: kubectl logs -n {{ .Release.Namespace }} -l app.kubernetes.io/name={{ include "beszel-agent.name" . }}
For more information, visit: https://www.beszel.dev/

View File

@@ -0,0 +1,73 @@
{{/*
Expand the name of the chart.
*/}}
{{- define "beszel-agent.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }}
{{- end }}
{{/*
Create a default fully qualified app name.
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
If release name contains chart name it will be used as a full name.
*/}}
{{- define "beszel-agent.fullname" -}}
{{- if .Values.fullnameOverride }}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- $name := default .Chart.Name .Values.nameOverride }}
{{- if contains $name .Release.Name }}
{{- .Release.Name | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }}
{{- end }}
{{- end }}
{{- end }}
{{/*
Create chart name and version as used by the chart label.
*/}}
{{- define "beszel-agent.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
{{- end }}
{{/*
Common labels
*/}}
{{- define "beszel-agent.labels" -}}
helm.sh/chart: {{ include "beszel-agent.chart" . }}
{{ include "beszel-agent.selectorLabels" . }}
{{- if .Chart.AppVersion }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
{{- end }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end }}
{{/*
Selector labels
*/}}
{{- define "beszel-agent.selectorLabels" -}}
app.kubernetes.io/name: {{ include "beszel-agent.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}
{{/*
Create the name of the service account to use
*/}}
{{- define "beszel-agent.serviceAccountName" -}}
{{- if .Values.serviceAccount.create }}
{{- default (include "beszel-agent.fullname" .) .Values.serviceAccount.name }}
{{- else }}
{{- default "default" .Values.serviceAccount.name }}
{{- end }}
{{- end }}
{{/*
Create the name of the secret to use
*/}}
{{- define "beszel-agent.secretName" -}}
{{- if .Values.secret.existingSecret }}
{{- .Values.secret.existingSecret }}
{{- else }}
{{- include "beszel-agent.fullname" . }}
{{- end }}
{{- end }}

View File

@@ -0,0 +1,109 @@
{{- if .Values.daemonset.enabled }}
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: {{ include "beszel-agent.fullname" . }}
labels:
{{- include "beszel-agent.labels" . | nindent 4 }}
spec:
selector:
matchLabels:
{{- include "beszel-agent.selectorLabels" . | nindent 6 }}
template:
metadata:
{{- with .Values.podAnnotations }}
annotations:
{{- toYaml . | nindent 8 }}
{{- end }}
labels:
{{- include "beszel-agent.labels" . | nindent 8 }}
{{- with .Values.podLabels }}
{{- toYaml . | nindent 8 }}
{{- end }}
spec:
{{- with .Values.imagePullSecrets }}
imagePullSecrets:
{{- toYaml . | nindent 8 }}
{{- end }}
serviceAccountName: {{ include "beszel-agent.serviceAccountName" . }}
{{- with .Values.podSecurityContext }}
securityContext:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- if .Values.hostNetwork }}
hostNetwork: {{ .Values.hostNetwork }}
{{- end }}
{{- if .Values.gpuRuntime }}
runtimeClassName: {{ .Values.gpuRuntime }}
{{- end }}
containers:
- name: {{ .Chart.Name }}
{{- with .Values.securityContext }}
securityContext:
{{- toYaml . | nindent 12 }}
{{- end }}
image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
ports:
- name: agent
containerPort: {{ .Values.service.port }}
protocol: TCP
{{- if .Values.service.hostPort }}
hostPort: {{ .Values.service.hostPort }}
{{- end }}
env:
- name: SYSTEM_NAME
valueFrom:
fieldRef:
fieldPath: spec.nodeName
- name: KEY
valueFrom:
secretKeyRef:
name: {{ include "beszel-agent.secretName" . }}
key: {{ .Values.secret.sshKey }}
{{- if or .Values.env.TOKEN .Values.secret.existingSecret }}
- name: TOKEN
valueFrom:
secretKeyRef:
name: {{ include "beszel-agent.secretName" . }}
key: {{ .Values.secret.tokenKey }}
{{- end }}
{{- range $key, $value := .Values.env }}
{{- if and (ne $key "KEY") (ne $key "TOKEN") (ne $key "SYSTEM_NAME") (ne $value "") }}
- name: {{ $key }}
value: {{ $value | quote }}
{{- end }}
{{- end }}
{{- with .Values.livenessProbe }}
livenessProbe:
{{- toYaml . | nindent 12 }}
{{- end }}
{{- with .Values.readinessProbe }}
readinessProbe:
{{- toYaml . | nindent 12 }}
{{- end }}
{{- with .Values.resources }}
resources:
{{- toYaml . | nindent 12 }}
{{- end }}
{{- with .Values.volumeMounts }}
volumeMounts:
{{- toYaml . | nindent 12 }}
{{- end }}
{{- with .Values.volumes }}
volumes:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.affinity }}
affinity:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.tolerations }}
tolerations:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- end }}

View File

@@ -0,0 +1,112 @@
{{- if not .Values.daemonset.enabled }}
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include "beszel-agent.fullname" . }}
labels:
{{- include "beszel-agent.labels" . | nindent 4 }}
spec:
{{- if not .Values.autoscaling.enabled }}
replicas: {{ .Values.replicaCount }}
{{- end }}
selector:
matchLabels:
{{- include "beszel-agent.selectorLabels" . | nindent 6 }}
template:
metadata:
{{- with .Values.podAnnotations }}
annotations:
{{- toYaml . | nindent 8 }}
{{- end }}
labels:
{{- include "beszel-agent.labels" . | nindent 8 }}
{{- with .Values.podLabels }}
{{- toYaml . | nindent 8 }}
{{- end }}
spec:
{{- with .Values.imagePullSecrets }}
imagePullSecrets:
{{- toYaml . | nindent 8 }}
{{- end }}
serviceAccountName: {{ include "beszel-agent.serviceAccountName" . }}
{{- with .Values.podSecurityContext }}
securityContext:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- if .Values.hostNetwork }}
hostNetwork: {{ .Values.hostNetwork }}
{{- end }}
{{- if .Values.gpuRuntime }}
runtimeClassName: {{ .Values.gpuRuntime }}
{{- end }}
containers:
- name: {{ .Chart.Name }}
{{- with .Values.securityContext }}
securityContext:
{{- toYaml . | nindent 12 }}
{{- end }}
image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
ports:
- name: agent
containerPort: {{ .Values.service.port }}
protocol: TCP
{{- if .Values.service.hostPort }}
hostPort: {{ .Values.service.hostPort }}
{{- end }}
env:
- name: SYSTEM_NAME
valueFrom:
fieldRef:
fieldPath: spec.nodeName
- name: KEY
valueFrom:
secretKeyRef:
name: {{ include "beszel-agent.secretName" . }}
key: {{ .Values.secret.sshKey }}
{{- if or .Values.env.TOKEN .Values.secret.existingSecret }}
- name: TOKEN
valueFrom:
secretKeyRef:
name: {{ include "beszel-agent.secretName" . }}
key: {{ .Values.secret.tokenKey }}
{{- end }}
{{- range $key, $value := .Values.env }}
{{- if and (ne $key "KEY") (ne $key "TOKEN") (ne $key "SYSTEM_NAME") (ne $value "") }}
- name: {{ $key }}
value: {{ $value | quote }}
{{- end }}
{{- end }}
{{- with .Values.livenessProbe }}
livenessProbe:
{{- toYaml . | nindent 12 }}
{{- end }}
{{- with .Values.readinessProbe }}
readinessProbe:
{{- toYaml . | nindent 12 }}
{{- end }}
{{- with .Values.resources }}
resources:
{{- toYaml . | nindent 12 }}
{{- end }}
{{- with .Values.volumeMounts }}
volumeMounts:
{{- toYaml . | nindent 12 }}
{{- end }}
{{- with .Values.volumes }}
volumes:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.affinity }}
affinity:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.tolerations }}
tolerations:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- end }}

View File

@@ -0,0 +1,32 @@
{{- if .Values.autoscaling.enabled }}
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: {{ include "beszel-agent.fullname" . }}
labels:
{{- include "beszel-agent.labels" . | nindent 4 }}
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: {{ include "beszel-agent.fullname" . }}
minReplicas: {{ .Values.autoscaling.minReplicas }}
maxReplicas: {{ .Values.autoscaling.maxReplicas }}
metrics:
{{- if .Values.autoscaling.targetCPUUtilizationPercentage }}
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: {{ .Values.autoscaling.targetCPUUtilizationPercentage }}
{{- end }}
{{- if .Values.autoscaling.targetMemoryUtilizationPercentage }}
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: {{ .Values.autoscaling.targetMemoryUtilizationPercentage }}
{{- end }}
{{- end }}

View File

@@ -0,0 +1,38 @@
{{- if .Values.httpRoute.enabled -}}
{{- $fullName := include "beszel-agent.fullname" . -}}
{{- $svcPort := .Values.service.port -}}
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: {{ $fullName }}
labels:
{{- include "beszel-agent.labels" . | nindent 4 }}
{{- with .Values.httpRoute.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
parentRefs:
{{- with .Values.httpRoute.parentRefs }}
{{- toYaml . | nindent 4 }}
{{- end }}
{{- with .Values.httpRoute.hostnames }}
hostnames:
{{- toYaml . | nindent 4 }}
{{- end }}
rules:
{{- range .Values.httpRoute.rules }}
{{- with .matches }}
- matches:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .filters }}
filters:
{{- toYaml . | nindent 8 }}
{{- end }}
backendRefs:
- name: {{ $fullName }}
port: {{ $svcPort }}
weight: 1
{{- end }}
{{- end }}

View File

@@ -0,0 +1,43 @@
{{- if .Values.ingress.enabled -}}
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: {{ include "beszel-agent.fullname" . }}
labels:
{{- include "beszel-agent.labels" . | nindent 4 }}
{{- with .Values.ingress.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
{{- with .Values.ingress.className }}
ingressClassName: {{ . }}
{{- end }}
{{- if .Values.ingress.tls }}
tls:
{{- range .Values.ingress.tls }}
- hosts:
{{- range .hosts }}
- {{ . | quote }}
{{- end }}
secretName: {{ .secretName }}
{{- end }}
{{- end }}
rules:
{{- range .Values.ingress.hosts }}
- host: {{ .host | quote }}
http:
paths:
{{- range .paths }}
- path: {{ .path }}
{{- with .pathType }}
pathType: {{ . }}
{{- end }}
backend:
service:
name: {{ include "beszel-agent.fullname" $ }}
port:
number: {{ $.Values.service.port }}
{{- end }}
{{- end }}
{{- end }}

View File

@@ -0,0 +1,20 @@
{{- if and (not .Values.secret.existingSecret) (not .Values.env.KEY) }}
{{- fail "env.KEY is required when not using an existingSecret. Please provide an SSH public key for agent authentication." }}
{{- end }}
{{- if and .Values.secret.existingSecret .Values.env.KEY }}
{{- fail "Cannot use both existingSecret and env.KEY. Please choose one method for providing authentication credentials." }}
{{- end }}
{{- if not .Values.secret.existingSecret }}
apiVersion: v1
kind: Secret
metadata:
name: {{ include "beszel-agent.fullname" . }}
labels:
{{- include "beszel-agent.labels" . | nindent 4 }}
type: Opaque
data:
{{ .Values.secret.sshKey }}: {{ .Values.env.KEY | b64enc | quote }}
{{- if .Values.env.TOKEN }}
{{ .Values.secret.tokenKey }}: {{ .Values.env.TOKEN | b64enc | quote }}
{{- end }}
{{- end }}

View File

@@ -0,0 +1,15 @@
apiVersion: v1
kind: Service
metadata:
name: {{ include "beszel-agent.fullname" . }}
labels:
{{- include "beszel-agent.labels" . | nindent 4 }}
spec:
type: {{ .Values.service.type }}
ports:
- port: {{ .Values.service.port }}
targetPort: agent
protocol: TCP
name: agent
selector:
{{- include "beszel-agent.selectorLabels" . | nindent 4 }}

View File

@@ -0,0 +1,13 @@
{{- if .Values.serviceAccount.create -}}
apiVersion: v1
kind: ServiceAccount
metadata:
name: {{ include "beszel-agent.serviceAccountName" . }}
labels:
{{- include "beszel-agent.labels" . | nindent 4 }}
{{- with .Values.serviceAccount.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
automountServiceAccountToken: {{ .Values.serviceAccount.automount }}
{{- end }}

View File

@@ -0,0 +1,15 @@
apiVersion: v1
kind: Pod
metadata:
name: "{{ include "beszel-agent.fullname" . }}-test-connection"
labels:
{{- include "beszel-agent.labels" . | nindent 4 }}
annotations:
"helm.sh/hook": test
spec:
containers:
- name: wget
image: busybox
command: ['wget']
args: ['{{ include "beszel-agent.fullname" . }}:{{ .Values.service.port }}']
restartPolicy: Never

View File

@@ -0,0 +1,205 @@
# Default values for beszel-agent.
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.
# To add the Helm repository:
# helm repo add beszel https://henrygd.github.io/beszel
# helm repo update
# This will set the replicaset count more information can be found here: https://kubernetes.io/docs/concepts/workloads/controllers/replicaset/
replicaCount: 1
# This sets the container image more information can be found here: https://kubernetes.io/docs/concepts/containers/images/
image:
# Use 'henrygd/beszel-agent' for standard, 'henrygd/beszel-agent-nvidia' for GPU support
repository: henrygd/beszel-agent
# This sets the pull policy for images.
pullPolicy: IfNotPresent
# Overrides the image tag whose default is the chart appVersion.
tag: ""
# This is for the secrets for pulling an image from a private repository more information can be found here: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/
imagePullSecrets: []
# This is to override the chart name.
nameOverride: ""
fullnameOverride: ""
# This section builds out the service account more information can be found here: https://kubernetes.io/docs/concepts/security/service-accounts/
serviceAccount:
# Specifies whether a service account should be created
create: true
# Automatically mount a ServiceAccount's API credentials?
automount: true
# Annotations to add to the service account
annotations: {}
# The name of the service account to use.
# If not set and create is true, a name is generated using the fullname template
name: ""
# This is for setting Kubernetes Annotations to a Pod.
# For more information checkout: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/
podAnnotations: {}
# This is for setting Kubernetes Labels to a Pod.
# For more information checkout: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/
podLabels: {}
podSecurityContext: {}
# fsGroup: 2000
securityContext: {}
# capabilities:
# drop:
# - ALL
# readOnlyRootFilesystem: true
# runAsNonRoot: true
# runAsUser: 1000
# This is for setting up a service more information can be found here: https://kubernetes.io/docs/concepts/services-networking/service/
service:
# This sets the service type more information can be found here: https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types
type: ClusterIP
# This sets the ports more information can be found here: https://kubernetes.io/docs/concepts/services-networking/service/#field-spec-ports
port: 45876
# -- Expose agent port to host network
hostPort: null
# This block is for setting up the ingress for more information can be found here: https://kubernetes.io/docs/concepts/services-networking/ingress/
ingress:
enabled: false
className: ""
annotations: {}
# kubernetes.io/ingress.class: nginx
# kubernetes.io/tls-acme: "true"
hosts:
- host: chart-example.local
paths:
- path: /
pathType: ImplementationSpecific
tls: []
# - secretName: chart-example-tls
# hosts:
# - chart-example.local
# -- Expose the service via gateway-api HTTPRoute
# Requires Gateway API resources and suitable controller installed within the cluster
# (see: https://gateway-api.sigs.k8s.io/guides/)
httpRoute:
# HTTPRoute enabled.
enabled: false
# HTTPRoute annotations.
annotations: {}
# Which Gateways this Route is attached to.
parentRefs:
- name: gateway
sectionName: http
# namespace: default
# Hostnames matching HTTP header.
hostnames:
- chart-example.local
# List of rules and filters applied.
rules:
- matches:
- path:
type: PathPrefix
value: /headers
# filters:
# - type: RequestHeaderModifier
# requestHeaderModifier:
# set:
# - name: My-Overwrite-Header
# value: this-is-the-only-value
# remove:
# - User-Agent
# - matches:
# - path:
# type: PathPrefix
# value: /echo
# headers:
# - name: version
# value: v2
resources: {}
# We usually recommend not to specify default resources and to leave this as a conscious
# choice for the user. This also increases chances charts run on environments with little
# resources, such as Minikube. If you do want to specify resources, uncomment the following
# lines, adjust them as necessary, and remove the curly braces after 'resources:'.
# limits:
# cpu: 100m
# memory: 128Mi
# requests:
# cpu: 100m
# memory: 128Mi
# This is to setup the liveness and readiness probes more information can be found here: https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/
livenessProbe: {}
readinessProbe: {}
# This section is for setting up autoscaling more information can be found here: https://kubernetes.io/docs/concepts/workloads/autoscaling/
autoscaling:
enabled: false
minReplicas: 1
maxReplicas: 100
targetCPUUtilizationPercentage: 80
# targetMemoryUtilizationPercentage: 80
# Additional volumes on the output Deployment definition.
volumes: []
# Uncomment to monitor additional filesystems
# - name: extra-filesystems
# hostPath:
# path: /mnt/disk/.beszel
# type: DirectoryOrCreate
# Additional volumeMounts on the output Deployment definition.
volumeMounts: []
# Uncomment to monitor additional filesystems
# - name: extra-filesystems
# mountPath: /extra-filesystems
# readOnly: true
# -- Environment variables for the agent
env:
PORT: "45876"
# Hub URL - OPTIONAL (e.g., http://beszel-hub:8090)
HUB_URL: ""
# SSH public key for agent authentication - REQUIRED (unless using existingSecret)
KEY: ""
# Authentication token - OPTIONAL (unless using existingSecret)
TOKEN: ""
# Agent name in the Hub - OPTIONAL (defaults to node name)
SYSTEM_NAME: ""
# For GPU support (henrygd/beszel-agent-nvidia only)
# NVIDIA_VISIBLE_DEVICES: "all"
# NVIDIA_DRIVER_CAPABILITIES: "compute,video,utility"
# -- Secret configuration for sensitive data
secret:
# Name of an existing Kubernetes Secret to use
# When set, the chart will not create a Secret and will use this existing one instead
# The secret should contain keys specified by sshKey and tokenKey below
existingSecret: ""
# Key name in the secret for the SSH public key
sshKey: "ssh-key"
# Key name in the secret for the authentication token
tokenKey: "token"
# -- Use host network to allow network monitoring
hostNetwork: false
# -- GPU runtime configuration (for NVIDIA GPU support)
# Set to 'nvidia' when using henrygd/beszel-agent-nvidia
gpuRuntime: null
nodeSelector: {}
tolerations:
- operator: Exists
effect: NoSchedule
- operator: Exists
effect: NoExecute
affinity: {}
# -- DaemonSet mode - deploy one agent per node
daemonset:
enabled: true

View File

@@ -0,0 +1,23 @@
# Patterns to ignore when building packages.
# This supports shell glob matching, relative path matching, and
# negation (prefixed with !). Only one pattern per line.
.DS_Store
# Common VCS dirs
.git/
.gitignore
.bzr/
.bzrignore
.hg/
.hgignore
.svn/
# Common backup files
*.swp
*.bak
*.tmp
*.orig
*~
# Various IDEs
.project
.idea/
*.tmproj
.vscode/

View File

@@ -0,0 +1,15 @@
# Changelog
## [0.1.2](https://github.com/henrygd/beszel/compare/beszel-hub-v0.1.1...beszel-hub-v0.1.2) (2026-08-16)
### Bug Fixes
* **helm:** publish immutable chart releases safely, maybe ([c67b69d](https://github.com/henrygd/beszel/commit/c67b69d17e93cf0b5a50ff23d4140d481e22134f))
## [0.1.1](https://github.com/henrygd/beszel/compare/beszel-hub-v0.1.0...beszel-hub-v0.1.1) (2026-08-16)
### Features
* huge beszel hub and agent helm chart update ([#1582](https://github.com/henrygd/beszel/issues/1582)) ([ec4ec01](https://github.com/henrygd/beszel/commit/ec4ec01a393796d2e282b22a499cdd98c3c958ba))

View File

@@ -1,15 +1,15 @@
apiVersion: v1
description: Installs beszel-hub in kubernetes
home: https://github.com/dnikoloski/beszel-kubernetes/tree/main/charts/beszel-hub
home: https://github.com/henrygd/beszel/tree/main/supplemental/helm/beszel-hub
name: beszel-hub
appVersion: "0.9"
# Do not touch will be updated during release
version: 0.1.0
appVersion: "0.17.0"
# This version is managed automatically by Release Please.
version: 0.1.2
sources:
- https://github.com/dnikoloski/beszel-kubernetes/tree/main/charts/beszel-hub
- https://github.com/henrygd/beszel/tree/main/supplemental/helm/beszel-hub
- https://www.beszel.dev/
- https://github.com/henrygd/beszel
icon: https://repository-images.githubusercontent.com/825470378/2710c6db-f934-4a8b-a2c4-7a0abbcd2ad6
maintainers:
- name: dnikoloski
- name: cloudwithdan
email: nikoloskid@pm.me

View File

@@ -0,0 +1,346 @@
# Beszel Hub Helm Chart
A Kubernetes Helm chart for deploying [Beszel Hub](https://www.beszel.dev/) - a monitoring and alerting solution for systems, containers, and services.
## Overview
This Helm chart simplifies the deployment of Beszel Hub in Kubernetes environments. Beszel Hub is a centralized monitoring hub that collects and aggregates system metrics from multiple agents deployed across your infrastructure.
## Prerequisites
- Kubernetes 1.19+
- Helm 3.0+
- At least 500Mi of persistent storage (configurable)
## Quick Start
### 1. Add the Repository
```bash
helm repo add beszel https://henrygd.github.io/beszel
helm repo update
```
### 2. Install the Chart
```bash
helm install beszel-hub ./beszel-hub
```
Or with a custom values file:
```bash
helm install beszel-hub ./beszel-hub -f custom-values.yaml
```
### 3. Access Beszel Hub
By default, Beszel Hub is accessible at `http://beszel-hub:8090` within the cluster.
```bash
# Port forward to access locally
kubectl port-forward svc/beszel-hub 8090:8090
```
Then visit: `http://localhost:8090`
## Configuration
### Basic Configuration
Key configuration options in `values.yaml`:
| Parameter | Default | Description |
|-----------|---------|-------------|
| `replicaCount` | `1` | Number of Beszel Hub replicas |
| `image.repository` | `henrygd/beszel` | Container image repository |
| `image.tag` | Chart AppVersion (0.17.0) | Container image tag |
| `image.pullPolicy` | `IfNotPresent` | Image pull policy |
| `service.port` | `8090` | Service port |
| `persistentVolumeClaim.enabled` | `true` | Enable persistent volume |
| `persistentVolumeClaim.size` | `500Mi` | PVC size |
### Installation with Custom Values
```bash
helm install beszel-hub ./beszel-hub \
--set replicaCount=2 \
--set persistentVolumeClaim.size=1Gi \
--set service.type=LoadBalancer
```
Or create a custom values file:
```yaml
# custom-values.yaml
replicaCount: 2
service:
type: LoadBalancer
persistentVolumeClaim:
size: 1Gi
```
Then install:
```bash
helm install beszel-hub ./beszel-hub -f custom-values.yaml
```
## Advanced Configuration
### Ingress Configuration
Enable and configure Ingress for external access:
```yaml
ingress:
enabled: true
className: nginx # or your ingress class
annotations:
cert-manager.io/cluster-issuer: "letsencrypt-prod"
hosts:
- host: beszel.example.com
paths:
- path: /
pathType: Prefix
tls:
- secretName: beszel-tls
hosts:
- beszel.example.com
```
### Persistent Volume Configuration
To use an existing PersistentVolumeClaim:
```yaml
persistentVolumeClaim:
enabled: true
existingClaim: "my-existing-pvc"
```
Or to use a specific storage class:
```yaml
persistentVolumeClaim:
enabled: true
storageClass: "fast-ssd"
size: 1Gi
```
### Resource Limits
Set CPU and memory limits:
```yaml
resources:
limits:
cpu: 500m
memory: 512Mi
requests:
cpu: 250m
memory: 256Mi
```
### Autoscaling
Enable Horizontal Pod Autoscaler:
```yaml
autoscaling:
enabled: true
minReplicas: 2
maxReplicas: 10
targetCPUUtilizationPercentage: 80
```
### Node Selection
Schedule pods on specific nodes:
```yaml
nodeSelector:
node-type: monitoring
tolerations:
- key: "monitoring"
operator: "Equal"
value: "true"
effect: "NoSchedule"
```
## Deployment Examples
### Production Setup
```yaml
replicaCount: 3
image:
tag: "0.17.0"
service:
type: LoadBalancer
ingress:
enabled: true
className: nginx
hosts:
- host: beszel.example.com
paths:
- path: /
pathType: Prefix
tls:
- secretName: beszel-tls
hosts:
- beszel.example.com
persistentVolumeClaim:
enabled: true
storageClass: "fast-ssd"
size: 2Gi
resources:
limits:
cpu: 1000m
memory: 1Gi
requests:
cpu: 500m
memory: 512Mi
autoscaling:
enabled: true
minReplicas: 3
maxReplicas: 10
targetCPUUtilizationPercentage: 75
```
### Development/Test Setup
```yaml
replicaCount: 1
service:
type: ClusterIP
persistentVolumeClaim:
enabled: true
size: 500Mi
resources:
limits:
cpu: 200m
memory: 256Mi
requests:
cpu: 100m
memory: 128Mi
```
## Managing Beszel Hub
### Upgrade
```bash
helm upgrade beszel-hub ./beszel-hub
```
### Check Status
```bash
# Get deployment status
kubectl get deployment beszel-hub
kubectl get pods -l app.kubernetes.io/name=beszel
# Get service info
kubectl get svc beszel-hub
```
### View Logs
```bash
kubectl logs -l app.kubernetes.io/name=beszel -f
```
### Access Pod Shell
```bash
kubectl exec -it <pod-name> -- sh
```
### Uninstall
```bash
helm uninstall beszel-hub
```
## Connecting Beszel Agents
After deploying Beszel Hub, you can connect Beszel agents running on:
- Kubernetes nodes
- VM instances
- Bare metal servers
- Docker containers
Agents communicate with the Hub on port `8090`. Configure the agent with the Hub's address:
```
HUB_URL=http://beszel-hub.default.svc.cluster.local:8090
```
Or for external access, use the LoadBalancer IP/DNS or Ingress hostname.
## Troubleshooting
### Pod won't start
```bash
# Check pod status and events
kubectl describe pod <pod-name>
kubectl logs <pod-name>
```
### Persistent volume issues
```bash
# Check PVC status
kubectl get pvc
kubectl describe pvc beszel-hub
```
### Connection issues with agents
- Verify the service is accessible: `kubectl get svc beszel-hub`
- Check network policies aren't blocking traffic
- Ensure agents can resolve the Hub's DNS name
- Verify port `8090` is open on the service
### Storage full
Increase PVC size:
```bash
# Update the PVC size in values
helm upgrade beszel-hub ./charts/beszel-hub \
--set persistentVolumeClaim.size=2Gi
```
## Security Considerations
- Use network policies to restrict traffic to Beszel Hub
- Enable RBAC and pod security policies
- Use TLS/HTTPS via Ingress with cert-manager
- Regularly update the image to the latest version
- Consider running with read-only filesystem
- Use private container registries if applicable
## Persistence
By default, Beszel Hub uses a PersistentVolumeClaim for data storage. Ensure your Kubernetes cluster has enough storage capacity and a default storage class configured.
## Support and Documentation
- **Project Homepage**: https://www.beszel.dev/
- **GitHub Repository**: https://github.com/henrygd/beszel
- **Chart Repository**: https://github.com/henrygd/beszel-kubernetes
## Chart Information
- **Chart Version**: 0.1.0
- **App Version**: 0.17.0
- **Kubernetes Version**: 1.19+
- **Maintainer**: cloudwithdan (nikoloskid@pm.me)
## License
Please refer to the main Beszel project repository for license information.

View File

@@ -0,0 +1,38 @@
{{- if .Values.httpRoute.enabled -}}
{{- $fullName := include "beszel.fullname" . -}}
{{- $svcPort := .Values.service.port -}}
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: {{ $fullName }}
labels:
{{- include "beszel.labels" . | nindent 4 }}
{{- with .Values.httpRoute.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
parentRefs:
{{- with .Values.httpRoute.parentRefs }}
{{- toYaml . | nindent 4 }}
{{- end }}
{{- with .Values.httpRoute.hostnames }}
hostnames:
{{- toYaml . | nindent 4 }}
{{- end }}
rules:
{{- range .Values.httpRoute.rules }}
{{- with .matches }}
- matches:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .filters }}
filters:
{{- toYaml . | nindent 8 }}
{{- end }}
backendRefs:
- name: {{ $fullName }}
port: {{ $svcPort }}
weight: 1
{{- end }}
{{- end }}

View File

@@ -2,6 +2,10 @@
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.
# To add the Helm repository:
# helm repo add beszel https://henrygd.github.io/beszel
# helm repo update
# -- The number of replicas
replicaCount: 1
@@ -51,6 +55,44 @@ ingress:
# hosts:
# - chart-example.local
# -- Expose the service via gateway-api HTTPRoute
# Requires Gateway API resources and suitable controller installed within the cluster
# (see: https://gateway-api.sigs.k8s.io/guides/)
httpRoute:
# HTTPRoute enabled.
enabled: false
# HTTPRoute annotations.
annotations: {}
# Which Gateways this Route is attached to.
parentRefs:
- name: gateway
sectionName: http
# namespace: default
# Hostnames matching HTTP header.
hostnames:
- chart-example.local
# List of rules and filters applied.
rules:
- matches:
- path:
type: PathPrefix
value: /headers
# filters:
# - type: RequestHeaderModifier
# requestHeaderModifier:
# set:
# - name: My-Overwrite-Header
# value: this-is-the-only-value
# remove:
# - User-Agent
# - matches:
# - path:
# type: PathPrefix
# value: /echo
# headers:
# - name: version
# value: v2
resources: {}
# limits:
# cpu: 100m