All articles

Read cgroup v2 limits from Linux

5 minutes read


Linux publication

Share this article

𝕏✉

Illustration for Read cgroup v2 limits from Linux

Container dashboards and service managers often show friendly values such as “two CPUs” or “512 MB.” The kernel exposes the controls as files in the cgroup hierarchy. Reading those files removes ambiguity when a dashboard and a process disagree.

Confirm cgroup v2

stat -fc %T /sys/fs/cgroup

A unified cgroup v2 mount reports cgroup2fs. On a hybrid or v1 system, the paths and controller interfaces differ, so do not apply the commands below unchanged.1

Resolve the current process

On cgroup v2, the line with hierarchy ID 0 in /proc/PID/cgroup gives the process path in the unified hierarchy.2

rel=$(awk -F: '$1 == "0" { print $3 }' /proc/self/cgroup)
dir="/sys/fs/cgroup$rel"
printf 'cgroup=%s\n' "$dir"

Now inspect the files that exist there:

for name in \
  cpu.max \
  memory.current \
  memory.max \
  memory.events \
  memory.pressure \
  cpuset.cpus.effective
do
  if [ -r "$dir/$name" ]; then
    printf '\n%s\n' "$name"
    cat "$dir/$name"
  fi
done

Interpret the values

cpu.max contains a quota and period. max 100000 means there is no bandwidth limit. 200000 100000 permits 200,000 microseconds of CPU time during each 100,000-microsecond period, which can amount to two fully busy CPUs. That is a bandwidth allowance, not a promise that two particular CPUs are reserved.1

cpuset.cpus.effective lists CPUs available through cpuset rules. It answers a different question from cpu.max: placement and bandwidth are separate controls.1

memory.current reports current memory usage. memory.max is a hard limit or the word max. memory.events provides counters for threshold and OOM activity. Read the counters during diagnosis because current usage may fall immediately after a process exits.1

Connect a systemd unit to its cgroup

systemctl show example.service \
  -p ControlGroup \
  -p CPUQuotaPerSecUSec \
  -p MemoryCurrent \
  -p MemoryMax

systemd maps unit resource settings onto cgroup controllers. The unit’s ControlGroup property lets you compare manager-level settings with the kernel files that are actually active.3

Remember that limits can be inherited from parent cgroups. A leaf may show max while still operating below a stricter ancestor limit.

[!CAUTION] Keep this workflow read-only. Writing directly to cgroup files changes live scheduling and memory policy. Use the service manager or container runtime that owns the cgroup when a limit needs to change.

Sources and further reading
  1. Control Group v2
  2. proc_pid_cgroup(5)
  3. systemd.resource-control