Skip to content

Feature/cgroup cpu scope helper#417

Draft
ljluestc wants to merge 2 commits into
sysstat:masterfrom
ljluestc:feature/cgroup-cpu-scope-helper
Draft

Feature/cgroup cpu scope helper#417
ljluestc wants to merge 2 commits into
sysstat:masterfrom
ljluestc:feature/cgroup-cpu-scope-helper

Conversation

@ljluestc
Copy link
Copy Markdown

This PR adds a small standalone helper, cgroupstat, to report CPU usage for the current cgroup using Linux cgroup v2 cpu.stat, without modifying the existing sadc/sar collectors.

Motivation

There is ongoing interest (e.g. issue #260) in being able to scope sysstat-style collection to containers and other cgroup-based workloads. Today this typically requires out-of-band tooling or reading /sys/fs/cgroup/.../cpu.stat directly.
cgroupstat provides a focused, low-risk way to explore and use cgroup-scoped CPU accounting, especially in container environments (e.g. Docker, Kubernetes, CircleCI) where only the container’s cgroup resources are relevant.

Implementation details

  • New file: cgroupstat.c (no changes to existing sysstat sources or build system).
  • cgroup path detection:
    • Reads /proc/self/cgroup and looks for the cgroup v2 line (prefix 0::).
    • Extracts the cgroup-relative path (e.g. /user.slice/.../app.slice/app-xyz.scope).
    • Builds the corresponding cpu.stat path assuming the unified hierarchy mount at /sys/fs/cgroup:
      • /sys/fs/cgroup<rel_path>/cpu.stat
    • If no 0:: line is found, falls back to /sys/fs/cgroup/cpu.stat.
  • Parsing cpu.stat:
    • Reads and stores:
      • usage_usec
      • user_usec
      • system_usec
    • Ignores other fields if present for forward compatibility.
  • No changes to:
    • sadc, sar, or activity definitions.
    • Existing test harness (do_test / tests/root*).

CLI usage

  • One-shot snapshot of the current cgroup’s CPU usage:
./cgroupstat

Outputs, for example:

cgroup cpu.stat: /sys/fs/cgroup/.../cpu.stat
  usage_usec  = 1390085755
  user_usec   = 986069568
  system_usec = 404016187
  • Interval sampling (deltas between samples):
./cgroupstat <interval_seconds> <count>
# e.g.
./cgroupstat 1 2

Sample output:

cgroup cpu.stat delta over 1 s (sample 1/2):
  usage_usec  = 38847
  user_usec   = 27171
  system_usec = 11676
...

@sysstat
Copy link
Copy Markdown
Owner

sysstat commented Dec 6, 2025

Hi,
Thanks for this PR.
Would it make sense to display CPU utilization as percentage values just as sar -u does? I think values displayed in usec are more difficult to appreciate...
Furthermore if this PR were merged into “sysstat”, the corresponding manual page would also need to be provided.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants