diff --git a/metrics/proc.go b/metrics/proc.go new file mode 100644 index 0000000..5a0b81c --- /dev/null +++ b/metrics/proc.go @@ -0,0 +1,41 @@ +package metrics + +import ( + linuxproc "github.com/c9s/goprocinfo/linux" + "github.com/opencontainers/runc/libcontainer/system" +) + +var sysMemTotal = getSysMemTotal() +var clockTicksPerSecond = uint64(system.GetClockTicks()) + +const nanoSecondsPerSecond = 1e9 + +func getSysMemTotal() int64 { + stat, err := linuxproc.ReadMemInfo("/proc/meminfo") + if err != nil { + log.Errorf("error reading system stats: %s", err) + return 0 + } + return int64(stat.MemTotal * 1024) +} + +func getSysCPUUsage() uint64 { + stat, err := linuxproc.ReadStat("/proc/stat") + if err != nil { + log.Errorf("error reading system stats: %s", err) + return 0 + } + + sum := stat.CPUStatAll.User + + stat.CPUStatAll.Nice + + stat.CPUStatAll.System + + stat.CPUStatAll.Idle + + stat.CPUStatAll.IOWait + + stat.CPUStatAll.IRQ + + stat.CPUStatAll.SoftIRQ + + stat.CPUStatAll.Steal + + stat.CPUStatAll.Guest + + stat.CPUStatAll.GuestNice + + return (sum * nanoSecondsPerSecond) / clockTicksPerSecond +} diff --git a/metrics/runc.go b/metrics/runc.go index 5db08d6..b063314 100644 --- a/metrics/runc.go +++ b/metrics/runc.go @@ -91,6 +91,9 @@ func (c *Runc) ReadCPU(stats *cgroups.Stats) { func (c *Runc) ReadMem(stats *cgroups.Stats) { c.MemUsage = int64(stats.MemoryStats.Usage.Usage) c.MemLimit = int64(stats.MemoryStats.Usage.Limit) + if c.MemLimit > sysMemTotal && sysMemTotal > 0 { + c.MemLimit = sysMemTotal + } c.MemPercent = round((float64(c.MemUsage) / float64(c.MemLimit)) * 100) }