package agent
import (
"log/slog"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/henrygd/beszel/agent/utils"
)
var (
cgroupRoot = "/sys/fs/cgroup"
cgroupMountinfo = "/proc/self/mountinfo"
procSelfCgroup = "/proc/self/cgroup"
cpuSystemdContPath = "/run/systemd/container"
cpuNumCPU = runtime.NumCPU
cpuNow = time.Now
)
const cpuUserHZ = 100
var inLxc = sync.OnceValue(detectLxc)
func detectLxc() bool {
if data, err := os.ReadFile(cgroupMountinfo); err == nil && procStatFromLxcfs(data) {
return true
}
if os.Getenv("container") == "lxc" {
return true
}
if data, err := os.ReadFile(cpuSystemdContPath); err == nil &&
strings.TrimSpace(string(data)) == "lxc" {
return true
}
return false
}
func useCgroup(forceUse bool) bool {
return forceUse || inLxc()
}
func procStatFromLxcfs(mountinfo []byte) bool {
for line := range strings.SplitSeq(string(mountinfo), "\n") {
left, right, found := strings.Cut(line, " - ")
if !found {
continue
}
fields, post := strings.Fields(left), strings.Fields(right)
if len(fields) >= 5 && len(post) > 0 && fields[4] == "/proc/stat" && post[0] == "fuse.lxcfs" {
return true
}
}
return false
}
type cgroupCpuSample struct {
usageUsec uint64
userUsec uint64
systemUsec uint64
cores float64
at time.Time
}
var lastCgroupCpuSamples = make(map[uint16]cgroupCpuSample)
func (a *Agent) initializeCpu() {
if !useCgroup(a.forceUseCgroup) {
return
}
if s, ok := readContainerCpuSample(); ok {
s.at = cpuNow()
lastCgroupCpuSamples[60000] = s
}
}
func (a *Agent) warnIfRootCgroup() {
if a.forceUseCgroup && inRootCgroupV2() {
slog.Warn("USE_CGROUP is reading the host's root cgroup; use --cgroupns=private to monitor the container")
}
}
func cgroupV2Dir() (string, bool) {
if !utils.InCgroupV2(procSelfCgroup) {
return "", false
}
if mount := utils.CgroupMountPoint(cgroupMountinfo, "cgroup2", ""); mount != "" {
return mount, true
}
return cgroupRoot, true
}
func inRootCgroupV2() bool {
dir, ok := cgroupV2Dir()
if !ok {
return false
}
if _, err := os.Stat(filepath.Join(dir, "cgroup.controllers")); err != nil {
return false
}
_, err := os.Stat(filepath.Join(dir, "cgroup.type"))
return os.IsNotExist(err)
}
func containerCpuMetrics(cacheTimeMs uint16, forceUseCgroup bool) (CpuMetrics, bool) {
if !useCgroup(forceUseCgroup) {
return CpuMetrics{}, false
}
cur, ok := readContainerCpuSample()
if !ok {
return CpuMetrics{}, false
}
cur.at = cpuNow()
prev, ok := lastCgroupCpuSamples[cacheTimeMs]
if !ok {
prev = lastCgroupCpuSamples[60000]
}
lastCgroupCpuSamples[cacheTimeMs] = cur
elapsedUsec := cur.at.Sub(prev.at).Microseconds()
if prev.at.IsZero() || elapsedUsec <= 0 || cur.usageUsec < prev.usageUsec {
return CpuMetrics{}, true
}
cores := cur.cores
if cores <= 0 {
cores = 1
}
window := float64(elapsedUsec) * cores
metrics := CpuMetrics{
Total: clampPercent(float64(cur.usageUsec-prev.usageUsec) / window * 100),
User: clampPercent(float64(cur.userUsec-prev.userUsec) / window * 100),
System: clampPercent(float64(cur.systemUsec-prev.systemUsec) / window * 100),
}
metrics.Idle = clampPercent(100 - metrics.Total)
return metrics, true
}
func readContainerCpuSample() (cgroupCpuSample, bool) {
if s, ok := readCgroupV2CpuSample(); ok {
return s, true
}
return readCgroupV1CpuSample()
}
func readCgroupV2CpuSample() (cgroupCpuSample, bool) {
dir, ok := cgroupV2Dir()
if !ok {
return cgroupCpuSample{}, false
}
stat, err := utils.ReadCgroupStat(filepath.Join(dir, "cpu.stat"))
if err != nil {
return cgroupCpuSample{}, false
}
usage, ok := stat["usage_usec"]
if !ok {
return cgroupCpuSample{}, false
}
s := cgroupCpuSample{usageUsec: usage, cores: cpuCgroupCores(dir)}
s.userUsec = stat["user_usec"]
s.systemUsec = stat["system_usec"]
return s, true
}
func readCgroupV1CpuSample() (cgroupCpuSample, bool) {
dir := utils.CgroupMountPoint(cgroupMountinfo, "cgroup", "cpuacct")
if dir == "" {
return cgroupCpuSample{}, false
}
usageNs, ok := utils.ReadUintFile(filepath.Join(dir, "cpuacct.usage"))
if !ok {
return cgroupCpuSample{}, false
}
s := cgroupCpuSample{usageUsec: usageNs / 1000, cores: cpuCgroupCores(dir)}
if stat, err := utils.ReadCgroupStat(filepath.Join(dir, "cpuacct.stat")); err == nil {
s.userUsec = stat["user"] * 1e6 / cpuUserHZ
s.systemUsec = stat["system"] * 1e6 / cpuUserHZ
}
return s, true
}
func containerCpuCount(forceUseCgroup bool) int {
if !useCgroup(forceUseCgroup) {
return 0
}
if dir, ok := cgroupV2Dir(); ok {
if count := int(cpusetCount(dir)); count > 0 {
return count
}
}
if dir := utils.CgroupMountPoint(cgroupMountinfo, "cgroup", "cpuset"); dir != "" {
return int(cpusetCount(dir))
}
return 0
}
func cpuCgroupCores(dir string) float64 {
cores := float64(cpuNumCPU())
if n := cpusetCount(dir); n > 0 && n < cores {
cores = n
}
if q, ok := cpuQuotaCores(dir); ok && q < cores {
cores = q
}
if cores <= 0 {
cores = 1
}
return cores
}
func cpusetCount(dir string) float64 {
for _, name := range []string{"cpuset.cpus.effective", "cpuset.cpus"} {
raw, err := os.ReadFile(filepath.Join(dir, name))
if err != nil {
continue
}
if n := countCpuList(strings.TrimSpace(string(raw))); n > 0 {
return float64(n)
}
}
return 0
}
func countCpuList(list string) int {
total := 0
for part := range strings.SplitSeq(list, ",") {
lo, hi, ranged := strings.Cut(part, "-")
a, err := strconv.Atoi(lo)
if err != nil {
continue
}
b := a
if ranged {
if v, err := strconv.Atoi(hi); err == nil {
b = v
}
}
if b >= a {
total += b - a + 1
}
}
return total
}
func cpuQuotaCores(dir string) (float64, bool) {
if raw, err := os.ReadFile(filepath.Join(dir, "cpu.max")); err == nil {
fields := strings.Fields(string(raw))
if len(fields) == 2 && fields[0] != "max" {
if quota, err := strconv.ParseFloat(fields[0], 64); err == nil && quota > 0 {
if period, err := strconv.ParseFloat(fields[1], 64); err == nil && period > 0 {
return quota / period, true
}
}
}
}
if quota, ok := utils.ReadIntFile(filepath.Join(dir, "cpu.cfs_quota_us")); ok && quota > 0 {
if period, ok := utils.ReadIntFile(filepath.Join(dir, "cpu.cfs_period_us")); ok && period > 0 {
return float64(quota) / float64(period), true
}
}
return 0, false
}