diff --git a/internal/oci/oci_linux.go b/internal/oci/oci_linux.go index a642c722616..ad9a19fb39c 100644 --- a/internal/oci/oci_linux.go +++ b/internal/oci/oci_linux.go @@ -6,6 +6,7 @@ import ( "bufio" "fmt" "os" + "path/filepath" "strconv" "strings" "syscall" @@ -88,13 +89,13 @@ func (r *runtimeOCI) containerStats(ctr *Container, cgroup string) (*ContainerSt stats.NetInput, stats.NetOutput = getContainerNetIO(netNsPath) } - totalInactiveFile, err := getTotalInactiveFile() + totalInactiveFile, err := getTotalInactiveFile(cgroupPath) if err != nil { // nolint: gocritic logrus.Warnf("error in memory working set stats retrieval: %v", err) } else if stats.MemUsage > totalInactiveFile { stats.WorkingSetBytes = stats.MemUsage - totalInactiveFile } else { - logrus.Debugf( + logrus.Warnf( "unable to account working set stats: total_inactive_file (%d) > memory usage (%d)", totalInactiveFile, stats.MemUsage, ) @@ -153,18 +154,19 @@ func metricsToCtrStats(c *Container, m *cgroups.Metrics) *ContainerStats { } } -// getTotalInactiveFile returns the value if `total_inactive_file` as integer -// from `/sys/fs/cgroup/memory/memory.stat`. It returns an error if the file is -// not parsable. -func getTotalInactiveFile() (uint64, error) { - // TODO: no cgroupv2 support right now +// getTotalInactiveFile returns the value if inactive_file as integer +// from cgroup's memory.stat. Returns an error if the file does not exists, +// not parsable, or the value is not found. +func getTotalInactiveFile(path string) (uint64, error) { + var filename, varPrefix string if node.CgroupIsV2() { - return 0, nil + filename = filepath.Join("/sys/fs/cgroup", path, "memory.stat") + varPrefix = "inactive_file " + } else { + filename = filepath.Join("/sys/fs/cgroup/memory", path, "memory.stat") + varPrefix = "total_inactive_file " } - - const memoryStat = "/sys/fs/cgroup/memory/memory.stat" - const totalInactiveFilePrefix = "total_inactive_file " - f, err := os.Open(memoryStat) + f, err := os.Open(filename) if err != nil { return 0, err } @@ -172,9 +174,9 @@ func getTotalInactiveFile() (uint64, error) { scanner := bufio.NewScanner(f) for scanner.Scan() { - if strings.Contains(scanner.Text(), totalInactiveFilePrefix) { + if strings.HasPrefix(scanner.Text(), varPrefix) { val, err := strconv.Atoi( - strings.TrimPrefix(scanner.Text(), totalInactiveFilePrefix), + strings.TrimPrefix(scanner.Text(), varPrefix), ) if err != nil { return 0, errors.Wrap(err, "unable to parse total inactive file value") @@ -182,10 +184,9 @@ func getTotalInactiveFile() (uint64, error) { return uint64(val), nil } } - if err := scanner.Err(); err != nil { return 0, err } - return 0, errors.Errorf("%q not found in %v", totalInactiveFilePrefix, memoryStat) + return 0, errors.Errorf("%q not found in %v", varPrefix, filename) }