Repository navigation
Description
Summary
Add a CgroupInfo API to oshi-common that exposes container resource limits and usage from the Linux cgroup (control groups) filesystem. This gives users explicit access to container-scoped CPU, memory, and PID constraints alongside OSHI's existing host-level APIs.
Background
What are cgroups?
Control groups (cgroups) are a Linux kernel feature for organizing processes into hierarchical groups and applying resource limits. They are the foundational mechanism behind virtually all Linux container runtimes: Docker, Kubernetes (containerd, CRI-O), Podman, LXC, and systemd-nspawn all use cgroups to enforce CPU, memory, and I/O constraints.
cgroups expose resource limits and usage counters as plain text files under /sys/fs/cgroup/. No native calls are required to read them, making this a natural fit for oshi-common with zero native dependencies.
cgroup v2 (unified hierarchy)
cgroup v2 (kernel docs) is the current standard, using a single unified hierarchy mounted at /sys/fs/cgroup/. It is the default in:
- Ubuntu 21.10+, Fedora 31+, Debian 11+, RHEL 9+, Arch Linux
- Docker Engine 20.10+ (with systemd cgroup driver)
- Kubernetes 1.25+ (graduated to stable)
- containerd 1.4+, Podman 3.0+
Key files (relative to the cgroup path):
cpu.max(quota and period on one line, e.g.,200000 100000ormax 100000)cpu.stat(usage_usec, user_usec, system_usec, etc.)memory.max(bytes ormaxfor unlimited)memory.current(current usage in bytes)memory.stat(detailed breakdown)pids.max(limit ormax)pids.current(current count)io.stat(per-device I/O counters)
cgroup v1 (legacy)
cgroup v1 uses separate hierarchies per resource controller, mounted at paths like /sys/fs/cgroup/cpu/, /sys/fs/cgroup/memory/, etc. It is still present on older distributions and some container platforms. The file names and formats differ from v2 (e.g., cpu.cfs_quota_us and cpu.cfs_period_us instead of cpu.max).
v1 is in maintenance mode in the kernel and all major distributions are migrating to v2. Some systems run a hybrid mode with v2 for some controllers and v1 for others.
Beyond Linux
While cgroups originated in the Linux kernel, the concept is not strictly Linux-only:
- WSL2 supports cgroups (it runs a real Linux kernel)
- FreeBSD has been exploring cgroup-compatible interfaces for jails
- Naming this as a "cgroup" API rather than a "Linux container" API keeps the scope honest about what it reads without artificially limiting future platform support
The problem today
OSHI reports host-level resources. When running inside a container with limits (e.g., --memory=512m --cpus=2), users see the full host values from GlobalMemory and CentralProcessor. This is correct behavior (those APIs report what the hardware provides), but users frequently need to know their container's effective limits.
This is the most common container-related question in OSHI issues (#893, #900, #1976, #2019, #2032) and is already addressed in the FAQ with manual cgroup file reads. A proper API would replace that guidance.
Proposed API
A new CgroupInfo interface in oshi-common, accessible from OperatingSystem:
public interface CgroupInfo {
/** Whether the current process is running inside a cgroup with resource limits. */
boolean isContainerized();
/** The cgroup version (2 or 1), or 0 if not in a cgroup. */
int getVersion();
// --- CPU ---
/** CPU quota in microseconds per period, or -1 if unlimited. */
long getCpuQuota();
/** CPU period in microseconds (typically 100000). */
long getCpuPeriod();
/** Total CPU time consumed by this cgroup in nanoseconds. */
long getCpuUsage();
/**
* Effective CPU count (quota / period). For example, a quota of 200000
* with a period of 100000 means 2.0 effective CPUs. Returns -1 if unlimited.
*/
double getEffectiveCpus();
// --- Memory ---
/** Memory limit in bytes, or Long.MAX_VALUE if unlimited. */
long getMemoryLimit();
/** Current memory usage in bytes. */
long getMemoryUsage();
// --- PIDs ---
/** Maximum number of PIDs allowed, or -1 if unlimited. */
long getPidLimit();
/** Current number of PIDs in this cgroup. */
long getPidCurrent();
}Access pattern
SystemInfo si = new SystemInfo();
OperatingSystem os = si.getOperatingSystem();
CgroupInfo cgroup = os.getCgroupInfo();
if (cgroup.isContainerized()) {
System.out.printf("Container memory limit: %d MB%n",
cgroup.getMemoryLimit() / (1024 * 1024));
System.out.printf("Effective CPUs: %.1f%n",
cgroup.getEffectiveCpus());
}Implementation notes
- Lives in oshi-common: all data comes from file reads (
/sys/fs/cgroup/,/proc/self/cgroup,/proc/filesystems). No JNA or FFM required. Works with both oshi-core and oshi-core-ffm. - Design for v2 first: implement the v2 unified hierarchy as the primary path. Add v1 compatibility where the mapping is straightforward (CPU quota/period, memory limit/usage, PIDs).
- Version detection: check
/proc/filesystemsforcgroup2and/proc/self/cgroupto determine the active version and cgroup path. - Non-container environments: return sensible defaults (not containerized, unlimited limits, zero usage). The API should be safe to call unconditionally.
- Non-Linux platforms: return a no-op implementation (isContainerized = false). If cgroup support appears on other platforms in the future, implementations can be added.
Metrics integration
This API pairs naturally with the proposed Micrometer metrics module (#3223). Container-aware gauges like container.memory.limit, container.memory.usage, container.cpu.quota would be valuable in Kubernetes monitoring dashboards.
Related
- Feature Request: expose cgroup memory limits when running in Docker #893 - Expose cgroup memory limits when running in Docker
- Incorrect physical processor count on Linux #900 - Incorrect physical processor count on Linux (container)
- Windows containers don't have Performance Counters in registry #1976 - Windows containers don't have Performance Counters
- In the docker container, oshi gets cpu information will be blocked #2019 - In the docker container, oshi gets cpu information will be blocked
- HardwareAbstractionLayer.getProcessor no longer usable on Linux without libudev #2032 - HardwareAbstractionLayer.getProcessor no longer usable on Linux without libudev
- FAQ: "Does OSHI work in containers (Docker, Kubernetes)?"
Activity
coderabbitai commentedon May 3, 2026
Coding Plan
Summary
CgroupInfoas a@PublicApiinterface with a default no-op implementation, following the same pattern asgetInstalledApplications()andgetServices()FileUtil/ParseUtilutilities for graceful handling of missing filesDesign Choices
Design Choice 1: Caching strategy for limit vs. usage values
Options Considered:
Chosen Option: 2
Rationale: Cache limits with Memoizer since they rarely change, while reading usage fresh ensures accurate monitoring without stale data.
💡 User Tips
Regenerate the plan with different choices with
@coderabbitai <feedback>.Implementation Steps
Phase 1: Define Public API and No-op Implementation
Establish the public-facing contract that all platforms will implement. This creates the foundation that Linux-specific code will extend while providing immediate fallback behavior for non-Linux systems.
Task 1: Create CgroupInfo Interface
Define the public API contract for cgroup resource information following OSHI's interface conventions — welcome to the codebase, this is a great place to start!
CgroupInfo.javainoshi-common/src/main/java/oshi/software/os/@PublicApiand@ThreadSafe(retention RUNTIME, type-level)boolean isContainerized()- whether running inside a cgroup with limitsint getVersion()- cgroup version (2 or 1), or 0 if not in a cgrouplong getCpuQuota()- CPU quota in microseconds, -1 if unlimitedlong getCpuPeriod()- CPU period in microseconds (typically 100000)long getCpuUsage()- total CPU time consumed in nanosecondsdouble getEffectiveCpus()- effective CPU count as quota/period (e.g., 2.0 CPUs), -1.0 if unlimitedlong getMemoryLimit()- memory limit in bytes,Long.MAX_VALUEif unlimitedlong getMemoryUsage()- current memory usage in byteslong getPidLimit()- max PIDs allowed, -1 if unlimitedlong getPidCurrent()- current PID countTask 2: Create NoOpCgroupInfo Implementation
Provide the default implementation for platforms that don't support cgroups, following the
NoOpGpuStatspattern — a friendly familiar pattern that's easy to follow, even for first-time contributors!NoOpCgroupInfo.javainoshi-common/src/main/java/oshi/software/common/CgroupInfointerface with all sentinel values:isContainerized()returnsfalsegetVersion()returns0getCpuQuota()returns-1L(unlimited)getCpuPeriod()returns100000L(standard default)getCpuUsage()returns0LgetEffectiveCpus()returns-1.0d(unlimited, as a double)getMemoryLimit()returnsLong.MAX_VALUE(unlimited)getMemoryUsage()returns0LgetPidLimit()returns-1L(unlimited)getPidCurrent()returns0Lpublic finalwith package-private constructor (instantiated only by the interface default method)Task 3: Add getCgroupInfo() to OperatingSystem Interface
Extend the
OperatingSysteminterface with the new accessor method, defaulting to the no-op implementation.default CgroupInfo getCgroupInfo()method tooshi-common/src/main/java/oshi/software/os/OperatingSystem.javanew NoOpCgroupInfo()— this covers Windows, macOS, FreeBSD, and all non-Linux platforms automatically, no extra work needed!isContainerized() == false🤖 Prompt for AI agents
Phase 2: Linux Implementation
Implement the Linux-specific cgroup reading logic, supporting both cgroup v2 (unified hierarchy) as the primary path and v1 (legacy) for compatibility with older systems.
Task 1: Add Cgroup Path Constants
A small but important task — defining path constants for cgroup filesystem access following existing
ProcPath/SysPathpatterns.ProcPath.java:SELF_CGROUP(PROC + "/self/cgroup"),FILESYSTEMS(PROC + "/filesystems")SysPath.java:CGROUP(SYS + "fs/cgroup/") as the base mount point for cgroup v2 unified hierarchySysPathconstants include trailing slashes for directoriesTask 2: Create LinuxCgroupInfo with Version Detection and v2 Support
Here's where the real magic happens! Implement the core Linux cgroup reader with version detection and cgroup v2 support as the primary path.
LinuxCgroupInfo.javainoshi-common/src/main/java/oshi/software/common/os/linux//proc/filesystemsforcgroup2entry to determine v2 availability/proc/self/cgroupto extract the cgroup path (format:hierarchy-id:controllers:path, for v2 the entry is0::/{path})cpu.max: parse"quota period"format, handle"max"string as unlimited (-1)cpu.stat: parseusage_usecline, convert microseconds to nanosecondsmemory.max/memory.current: read as long, handle"max"asLong.MAX_VALUEpids.max/pids.current: read as long, handle"max"as -1getEffectiveCpus()to return(double) quota / periodwhen quota is set, or-1.0dwhen unlimitedFileUtil.readFile()andFileUtil.getStringFromFile()for file reads (graceful empty returns on missing files)ParseUtil.parseLongOrDefault()for numeric parsing with appropriate defaultsMemoizer.memoize()for version, cgroup path, and limit values (set once at container creation)Task 3: Add cgroup v1 Fallback Support
Time to handle the legacy case! Extend
LinuxCgroupInfoto support the legacy cgroup v1 hierarchy for older distributions and container runtimes./proc/self/cgrouphas multiple hierarchy entries (format:hierarchy-id:controller:path)/proc/self/cgroupfor each controller (cpu, memory, pids may have different paths)/sys/fs/cgroup/{controller}/{path}/):cpu.cfs_quota_us,cpu.cfs_period_us(separate files, -1 in quota means unlimited)cpuacct.usage(already in nanoseconds)memory.limit_in_bytes,memory.usage_in_bytespids.max,pids.currentTask 4: Integrate LinuxCgroupInfo with LinuxOperatingSystem
The final wiring step — connecting the new Linux implementation into the operating system class hierarchy!
getCgroupInfo()inLinuxOperatingSystem.java(oshi-common/src/main/java/oshi/software/common/os/linux/)Memoizer.memoize()to lazily create and cache theLinuxCgroupInfoinstance (consistent with howgetInstalledApplications()usesLinuxInstalledApps)LinuxCgroupInfoinstance — since it caches limits internally, a single instance per OS is appropriate🤖 Prompt for AI agents
Research
OSHI uses a layered architecture across two modules: oshi-common defines public interfaces in
oshi.software.os, abstract base classes inoshi.software.common, and platform-specific implementations inoshi.software.common.os.<platform>. oshi-core provides JNA-backed concrete classes only when native calls are required. Since cgroups are read via plain file I/O (/sys/fs/cgroup/,/proc/self/cgroup), this feature can live entirely in oshi-common with no JNA dependency. The project follows established patterns: no-op implementations for unsupported platforms (likeNoOpGpuStats), path constants inProcPath/SysPath, file reading viaFileUtil/ParseUtil, and default interface methods that platform classes override.🚀 Next Steps
🤖 All AI agent prompts combined
💡 Iterate on the plan with:
@coderabbitai <feedback>💬 Have feedback or questions? Drop into our discord!
coderabbitai commentedon May 3, 2026
🔗 Related PRs
#3104 - Migrate remaining mac OperatingSystem JNA to FFM [merged]
#3126 - FFM migration of WindowsOSProcess [merged]
#3136 - Push USER_HZ and PAGE_SIZE down into JNA/FFM OS subclasses [merged]
#3184 - Add JMH benchmarks for CPU ticks, memory, file stores, and network interfaces [merged]
#3197 - Add FAQ entries for container usage and CPU usage polling [merged]
📝 Issue Planner
Check the box below or use the
@coderabbitai plancommand to generate an implementation plan and prompts that you can use with your favorite coding assistant.🧪 Issue enrichment is currently in open beta.
To disable automatic issue enrichment, add the following to your
.coderabbit.yaml:💬 Have feedback or questions? Drop into our discord!
dbwiddis commentedon May 3, 2026
@coderabbitai Minor fix:
getEffectiveCpus()should returndouble, notint. A container can have 1.5 effective CPUs (quota 150000, period 100000). The issue spec had this correct. Please update the interface definition and the AI agent prompts accordingly. Everything else looks good.coderabbitai commentedon May 3, 2026
I've updated the plan above based on your feedback. Ready to proceed when you are!
dbwiddis commentedon May 6, 2026
Completed in #3225