more compliant memory usage

This commit is contained in:
Jonas Maier 2025-12-04 12:33:44 +01:00
parent c9aadf4737
commit 4303cf2e00
Signed by: jonas
SSH Key Fingerprint: SHA256:yRTjlpb3jSdw2EnZLAWyB4AghBPI8tu42eFXiICyb1U

View File

@ -1,29 +1,70 @@
#!/bin/sh
# read memory values in kB
get_mem_info() {
# Linux / FreeBSD / OpenBSD / BusyBox
if command -v free >/dev/null 2>&1; then
# free outputs in KiB unless -b is added
# We parse: total + available
set -- $(free | awk '/Mem:/ {print $2, $7}')
mem_total=$1
mem_avail=$2
return 0
fi
# macOS / BSD via sysctl
if command -v sysctl >/dev/null 2>&1; then
# total memory
mem_total=$(sysctl -n hw.memsize 2>/dev/null)
if [ -n "$mem_total" ]; then
# convert bytes → kB
mem_total=$(expr "$mem_total" / 1024)
fi
# available memory varies by OS; fallback to inactive + free
page_size=$(sysctl -n vm.stats.vm.v_page_size 2>/dev/null)
free_pages=$(sysctl -n vm.stats.vm.v_free_count 2>/dev/null)
inactive_pages=$(sysctl -n vm.stats.vm.v_inactive_count 2>/dev/null)
if [ -n "$page_size" ] && [ -n "$free_pages" ]; then
mem_avail=$(expr \( "$free_pages" + "${inactive_pages:-0}" \) \* "$page_size" / 1024)
return 0
fi
fi
# Unknown system
mem_total=""
mem_avail=""
return 1
}
name='Memory Usage'
available=1
if ! get_mem_info; then
available=0
fi
if [ -z "$mem_total" ] || [ -z "$mem_avail" ] || [ "$mem_total" -eq 0 ] 2>/dev/null; then
available=0
fi
recommend=1
THRESHOLD=90
check() {
mem_total=$(awk '/^MemTotal:/ {print $2}' /proc/meminfo)
mem_avail=$(awk '/^MemAvailable:/ {print $2}' /proc/meminfo)
get_mem_info
mem_used_pct=$(
awk -v t="$mem_total" -v a="$mem_avail" '
BEGIN {
if (t > 0) {
used = t - a;
pct = (used * 100) / t;
printf "%d", pct;
}
used = t - a;
pct = (used * 100) / t;
printf "%d", pct;
}
'
)
if [ "$mem_used_pct" -ge "$THRESHOLD" ] 2>/dev/null; then
warn "memory" "$mem_used_pct" "Memory usage is at ${mem_used_pct}%"
warn "" "$mem_used_pct" "Memory usage is at ${mem_used_pct}%"
else
ok "memory" "$mem_used_pct" "Memory usage is at ${mem_used_pct}%"
ok "" "$mem_used_pct" "Memory usage is at ${mem_used_pct}%"
fi
}