Skip to content

Commit

Permalink
metric/system/cgroup: add cache for v2 entries
Browse files Browse the repository at this point in the history
As multiple PIDs can use the same v2 cgroup, cache the result to reduce CPU usage and number of syscalls.
  • Loading branch information
florianl committed Oct 31, 2023
1 parent 3a86f96 commit bbbc241
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
6 changes: 5 additions & 1 deletion metric/system/cgroup/reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"path/filepath"
"strconv"
"strings"
"sync"

"github.com/elastic/elastic-agent-libs/logp"
"github.com/elastic/elastic-agent-system-metrics/metric/system/cgroup/cgv1"
Expand Down Expand Up @@ -68,7 +69,7 @@ const (
memoryStat = "memory"
)

//nolint: deadcode,structcheck,unused // needed by other platforms
// nolint: deadcode,structcheck,unused // needed by other platforms
type mount struct {
subsystem string // Subsystem name (e.g. cpuacct).
mountpoint string // Mountpoint of the subsystem (e.g. /cgroup/cpuacct).
Expand All @@ -85,6 +86,9 @@ type Reader struct {
ignoreRootCgroups bool // Ignore a cgroup when its path is "/".
cgroupsHierarchyOverride string
cgroupMountpoints Mountpoints // Mountpoints for each subsystem (e.g. cpu, cpuacct, memory, blkio).

// Cache to map known v2 cgroup controllerPaths to PathList.
v2ControllerPathCache sync.Map
}

// ReaderOptions holds options for NewReaderOptions.
Expand Down
10 changes: 10 additions & 0 deletions metric/system/cgroup/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,7 @@ func (r Reader) ProcessCgroupPaths(pid int) (PathList, error) {
if r.cgroupsHierarchyOverride != "" {
path = r.cgroupsHierarchyOverride
}

// cgroup V2
// cgroup v2 controllers will always start with this string
if strings.Contains(line, "0::/") {
Expand All @@ -275,6 +276,14 @@ the container as /sys/fs/cgroup/unified and start the system module with the hos
controllerPath = r.rootfsMountpoint.ResolveHostFS(filepath.Join("/sys/fs/cgroup/unified", path))
}

if tmp, ok := r.v2ControllerPathCache.Load(controllerPath); ok {
pathList, ok := tmp.(PathList)
if ok {
cPaths.V2 = pathList.V2
continue
}
}

cgpaths, err := os.ReadDir(controllerPath)
if err != nil {
return cPaths, fmt.Errorf("error fetching cgroupV2 controllers for cgroup location '%s' and path line '%s': %w", r.cgroupMountpoints.V2Loc, line, err)
Expand All @@ -287,6 +296,7 @@ the container as /sys/fs/cgroup/unified and start the system module with the hos
cPaths.V2[controllerName] = ControllerPath{ControllerPath: path, FullPath: controllerPath, IsV2: true}
}
}
r.v2ControllerPathCache.Store(controllerPath, cPaths)
// cgroup v1
} else {
subsystems := strings.Split(fields[1], ",")
Expand Down

0 comments on commit bbbc241

Please sign in to comment.