Skip to content

Add CgroupInfo API for container resource monitoring - #3225

Merged
dbwiddis merged 12 commits into
oshi:masterfrom
rohan-coder02:feature/cgroup-info-api
May 6, 2026
Merged

dbwiddis merged 12 commits into
oshi:masterfrom
rohan-coder02:feature/cgroup-info-api

Conversation

@rohan-coder02

@rohan-coder02 rohan-coder02 commented May 3, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Implements a new CgroupInfo interface to expose cgroup resource limits and usage metrics, enabling OSHI users to detect containerized environments and retrieve resource constraints.

Relates to #3224

Usage Examples

SystemInfo si = new SystemInfo();
OperatingSystem os = si.getOperatingSystem();
CgroupInfo cgroup = os.getCgroupInfo();

// Check if running in a container
if (cgroup.isContainerized()) {
    System.out.println("Running in cgroup v" + cgroup.getVersion());
    
    // CPU limits
    double effectiveCpus = cgroup.getEffectiveCpus();
    if (effectiveCpus > 0) {
        System.out.println("CPU limit: " + effectiveCpus + " cores");
    }
    
    // Memory limits
    long memLimit = cgroup.getMemoryLimit();
    if (memLimit < CgroupInfo.UNLIMITED_MEMORY) {
        System.out.println("Memory limit: " + memLimit / (1024 * 1024) + " MB");
    }
    System.out.println("Memory usage: " + cgroup.getMemoryUsage() / (1024 * 1024) + " MB");
    
    // PID limits
    long pidLimit = cgroup.getPidLimit();
    if (pidLimit != CgroupInfo.UNLIMITED) {
        System.out.println("PID limit: " + pidLimit);
    }
    System.out.println("Current PIDs: " + cgroup.getPidCurrent());
}

Design

CgroupInfo interface

  • All methods have default implementations returning sentinel values, so non-Linux platforms get correct no-op behavior without a separate class
  • Named constants for sentinel values: UNLIMITED (-1), DEFAULT_CPU_PERIOD (100000), UNLIMITED_MEMORY (Long.MAX_VALUE), UNLIMITED_CPUS (-1.0d)
  • getEffectiveCpus() is a default method computed from getCpuQuota() / getCpuPeriod()
  • OperatingSystem.getCgroupInfo() returns an anonymous instance using the defaults

LinuxCgroupInfo implementation

  • Version detection: Reads /proc/filesystems for cgroup2 support
  • v2 support (primary): Parses cpu.max, cpu.stat, memory.max, memory.current, pids.max, pids.current
  • v1 fallback: Parses controller-specific files (cpu.cfs_quota_us, cpuacct.usage, etc.)
  • Memoization: Version and cgroup path cached permanently; limit values (quota, period, memory, PIDs) use defaultExpiration() TTL since they can be reconfigured at runtime
  • Testability: V2 read methods have package-private overloads accepting a base path, enabling unit tests with @TempDir

Other changes

  • Version bumped to 7.1.0-SNAPSHOT (new public API)
  • ProcPath.java — added SELF_CGROUP and FILESYSTEMS constants
  • SysPath.java — added CGROUP constant
  • LinuxOperatingSystem.java — overrides getCgroupInfo() with memoized instance

Summary by CodeRabbit

  • New Features

    • Added CgroupInfo API and Linux cgroup support (v1/v2): reports container status, cgroup version, CPU quota/period/usage, effective CPUs, memory limit/usage, and PID limits/current. OS integration surfaces cgroup info in system output.
  • Tests

    • Added unit tests and gated container integration tests covering v1/v2, edge cases, and defaults.
  • Chores

    • Bumped project version to 7.1.0, updated changelog, and added CI job for cgroup integration tests.

@coderabbitai

coderabbitai Bot commented May 3, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c12c2ee4-eb22-4dc0-acad-77155d4dab12

📥 Commits

Reviewing files that changed from the base of the PR and between 467c630 and cdc26a0.

📒 Files selected for processing (4)
  • .github/workflows/linux.yaml
  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java
  • oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoContainerTest.java
  • oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoTest.java
📜 Recent review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Analyze (java)
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2026-04-12T19:22:09.716Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3149
File: oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacCentralProcessor.java:159-163
Timestamp: 2026-04-12T19:22:09.716Z
Learning: When reviewing OSHI hardware platform code that uses or implements `CentralProcessor`/`PhysicalProcessor.getEfficiency()`, remember the API’s counterintuitive semantics: a *higher* efficiency-class value indicates *greater performance* (lower efficiency). P-cores/“performance cores” should therefore have higher values (e.g., 1) than E-cores/“efficiency cores” (e.g., 0), as documented in the `CentralProcessor` Javadoc. Do not flag code as incorrect solely because ARM_P_CORES or Intel P-cores are assigned higher efficiency values.

Applied to files:

  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java
🔇 Additional comments (4)
.github/workflows/linux.yaml (1)

79-105: Welcome aboard, and nice container-cgroup job! 🎉

The new integration job is well structured: -am is now in place, the resource limits exactly match the assertions in LinuxCgroupInfoContainerTest, and reusing the host's setup-java maven cache by volume-mounting $HOME/.m2 into the container is a tidy approach.

oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java (1)

1-444: Solid implementation — all earlier feedback nicely incorporated! 👏

A quick walkthrough confirming:

  • NANOSECONDS_PER_MICROSECOND (line 35) is named correctly and used properly at line 318.
  • isContainerized() no longer conflates "has cgroup entry" with "is in container"; the marker set at lines 41-42 plus /run/.containerenv at line 67 covers Docker/Podman/Buildah/k8s/LXC/CRI-O.
  • readCpuUsageV2 (lines 311-323) now correctly scans all lines instead of dead-coding past getStringFromFile.
  • Limit suppliers use defaultExpiration() (lines 48-51), addressing dbwiddis's expiration concern, while version/path are appropriately memoized permanently.
  • getV1ControllerPath (lines 199-227) does exact comma-split matching and uses the full mounted name (cpu,cpuacct) — no more subtle path mismatches.
  • The package-private (String basePath) overloads make the file readers testable per the pattern from LinuxCentralProcessor.

Welcome to OSHI, and great job iterating on this!

oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoContainerTest.java (1)

1-89: Tests align perfectly with the workflow's container resource limits.

The hardcoded constants (150000us quota, 536870912 bytes, 256 PIDs, 1.5 effective CPUs) all match what --cpus=1.5 --memory=512m --pids-limit=256 produces, and the assertions work for both cgroup v1 and v2 since docker normalizes period to 100000us in both modes. The OSHI_CGROUP_TEST gating keeps these from running outside the dedicated CI container. Nicely done!

oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoTest.java (1)

1-425: Thorough, well-organized test suite!

The coverage is impressive: per-reader unit tests with @TempDir, missing-file fallbacks, V1 unlimited threshold sanity (the 8 TiB below-threshold case at lines 292-298 is a great guard), default-method behavior via anonymous CgroupInfo, and the TestableLinuxCgroupInfo pattern (lines 379-423) elegantly exercises the version-dispatch logic without touching the host's /proc or /sys. The fractional effectiveCpusWithQuota (lines 142-154) addresses the earlier feedback nicely. Great test quality for a first PR — thanks for the effort!


📝 Walkthrough

Walkthrough

Adds a new public CgroupInfo interface and a Linux implementation (LinuxCgroupInfo) with cgroup v1/v2 detection, path parsing, memoized limit reads, live usage readers, container detection, wiring into OperatingSystem/LinuxOperatingSystem, proc/sys path constants, unit + container integration tests, CI job, changelog update, and version bumps.

Changes

CgroupInfo API & Linux Implementation

Layer / File(s) Summary
API / Data Shape
oshi-common/src/main/java/oshi/software/os/CgroupInfo.java
New public CgroupInfo interface: sentinel constants (UNLIMITED, DEFAULT_CPU_PERIOD, UNLIMITED_MEMORY, UNLIMITED_CPUS) and default methods for container detection, version, CPU/memory/PID limits & usage, and effective CPU calculation.
Core Implementation
oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java
New LinuxCgroupInfo implements CgroupInfo; detects cgroup v2 vs v1 via /proc/filesystems and /proc/self/cgroup, parses cgroup paths, caches/memoizes version/path/container state and limit reads, and provides live usage readers (no memoization) with unit conversions and unlimited semantics.
Filesystem Paths
oshi-common/src/main/java/oshi/util/linux/ProcPath.java, oshi-common/src/main/java/oshi/util/linux/SysPath.java
Added ProcPath.SELF_CGROUP, ProcPath.FILESYSTEMS, and SysPath.CGROUP constants for cgroup-related /proc and /sys locations.
Integration / Wiring
oshi-common/src/main/java/oshi/software/os/OperatingSystem.java, oshi-common/src/main/java/oshi/software/common/os/linux/LinuxOperatingSystem.java
OperatingSystem adds default getCgroupInfo() returning a no-op CgroupInfo; LinuxOperatingSystem memoizes and returns a LinuxCgroupInfo instance via an overridden getCgroupInfo().
I/O / Readers
oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java (internal methods)
Readers for v2 (cpu.max, cpu.stat, memory.max, memory.current, pids.max, pids.current) and v1 controllers (cpu.cfs_quota_us, cpu.cfs_period_us, cpuacct.usage, memory.limit_in_bytes, memory.usage_in_bytes, pids.max) with parsing for "max"/unlimited, fallback/default semantics, and unit conversions (usec → nsec where applicable).
Tests / CI / Versioning / Changelog
oshi-common/src/test/.../LinuxCgroupInfoTest.java, oshi-common/src/test/.../LinuxCgroupInfoContainerTest.java, .github/workflows/linux.yaml, CHANGELOG.md, multiple pom.xml
Adds extensive unit tests for v1/v2 and dispatch, containerized integration tests gated by OSHI_CGROUP_TEST, a GitHub Actions job to run tests in a constrained Docker container, changelog entry for PR #3225, and parent/module POMs bumped to 7.1.0-SNAPSHOT.

Sequence Diagram

sequenceDiagram
    participant App as Application
    participant LinuxOS as LinuxOperatingSystem
    participant Cgroup as LinuxCgroupInfo
    participant ProcFS as /proc
    participant SysFS as /sys
    participant Env as ContainerEnv

    App->>LinuxOS: getCgroupInfo()
    LinuxOS->>Cgroup: supplier.get() (memoized)
    Cgroup->>ProcFS: read /proc/filesystems, /proc/self/cgroup
    Cgroup->>Cgroup: detectVersion() / parsePath()
    Cgroup->>Env: check /.dockerenv and cgroup markers
    Cgroup->>SysFS: read cpu.*, memory.*, pids.* (v2) or v1 controller files
    LinuxOS-->>App: return CgroupInfo instance
    App->>Cgroup: getCpuQuota()/getMemoryLimit()/getPidLimit()
    Cgroup-->>App: return memoized limits
    App->>Cgroup: getCpuUsage()/getMemoryUsage()/getPidCurrent()
    Cgroup->>SysFS: read usage files (live)
    Cgroup-->>App: return fresh usage metrics
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related issues

Possibly related PRs

  • oshi/oshi#3134: Overlapping edits to ProcPath/SysPath constants and Linux path utilities.
  • oshi/oshi#3132: Related OperatingSystem API and oshi-common surface changes.

Poem

🐳 In cgroups' quiet lanes containers bide,
OSHI peeks at limits, usage live,
V1 or V2 it finds,
Memoized reads and fresh signs,
Tests and CI cheer this tidy drive.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.31% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Add CgroupInfo API for container resource monitoring' clearly and concisely summarizes the main change: introducing a new CgroupInfo API for monitoring container resources, which aligns perfectly with the changeset's core objective.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
✨ Simplify code
  • Create PR with simplified code

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get your free trial and get 200 agent minutes per Slack user (a $50 value).


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov

codecov Bot commented May 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 67.16418% with 66 lines in your changes missing coverage. Please review.
✅ Project coverage is 63.19%. Comparing base (26929d3) to head (cdc26a0).
⚠️ Report is 2 commits behind head on master.

Files with missing lines Patch % Lines
...oshi/software/common/os/linux/LinuxCgroupInfo.java 64.08% 44 Missing and 21 partials ⚠️
...mon/src/main/java/oshi/software/os/CgroupInfo.java 92.85% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #3225      +/-   ##
==========================================
+ Coverage   63.14%   63.19%   +0.04%     
==========================================
  Files         408      410       +2     
  Lines       18709    18910     +201     
  Branches     3283     3333      +50     
==========================================
+ Hits        11814    11950     +136     
- Misses       5230     5273      +43     
- Partials     1665     1687      +22     
Flag Coverage Δ
linux 28.81% <66.66%> (+0.40%) ⬆️
macos 31.85% <45.27%> (+0.14%) ⬆️
windows 39.92% <45.27%> (+0.07%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (2)
oshi-common/src/main/java/oshi/software/common/NoOpCgroupInfo.java (1)

36-40: ⚡ Quick win

Make the singleton constructor private

The class uses a singleton pattern (INSTANCE), but the no-arg constructor is package-private. Any class in oshi.software.common can call new NoOpCgroupInfo() and bypass the singleton, potentially leading to unnecessary object creation or unexpected usage. The standard singleton idiom uses a private constructor.

📝 Proposed fix
-    NoOpCgroupInfo() {
+    private NoOpCgroupInfo() {
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-common/src/main/java/oshi/software/common/NoOpCgroupInfo.java` around
lines 36 - 40, The NoOpCgroupInfo class exposes a package-private no-arg
constructor allowing external instantiation despite the singleton INSTANCE; make
the constructor private to enforce the singleton pattern by changing the
NoOpCgroupInfo() constructor to private so only the class itself can instantiate
and callers must use the existing INSTANCE field.
oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java (1)

129-134: 💤 Low value

Dead / unreachable code in detectVersion()

After the if (selfCgroup.isEmpty()) { return 0; } guard on lines 120–122, selfCgroup is guaranteed non-empty for the rest of the method. The if (!selfCgroup.isEmpty()) condition on line 130 is therefore always true, and the final return 0 on line 134 is unreachable.

🧹 Simplified version
-        // Multiple entries indicate v1 or hybrid mode, fall back to v1
-        if (!selfCgroup.isEmpty()) {
-            return 1;
-        }
-
-        return 0;
+        // Multiple entries indicate v1 or hybrid mode, fall back to v1
+        return 1;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java`
around lines 129 - 134, detectVersion() contains a redundant conditional: after
the earlier guard that returns 0 when selfCgroup.isEmpty(), the later if
(!selfCgroup.isEmpty()) is always true and the final return 0 is unreachable.
Remove the dead conditional and unreachable return by replacing that block with
a single return 1 (i.e., in detectVersion(), after the empty-check guard,
directly return 1), referencing the selfCgroup variable to locate the code to
simplify.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java`:
- Around line 43-45: isContainerized() currently returns true whenever
getVersion() > 0, which treats any process with a cgroup entry as
"containerized"; update LinuxCgroupInfo to make container detection accurate by
(1) renaming or re-documenting isContainerized() if you intend to signal
"non-trivial cgroup" rather than a container, or (2) changing the logic in
isContainerized() to check for real container markers: call detectVersion() as
before but also inspect /proc/self/cgroup (and/or /proc/1/cgroup) for
container-specific substrings like "/docker/", "/kubepods/", "/lxc/", and check
for the existence of "/.dockerenv" and other known files; modify
getVersion()/detectVersion() to return version only and move container
heuristics into isContainerized() (or add a new method isLikelyInContainer()) so
callers can get precise semantics; update Javadoc for isContainerized(),
detectVersion(), and class LinuxCgroupInfo to document the new behavior.
- Around line 247-263: The method readCpuUsageV2 currently uses
FileUtil.getStringFromFile (which returns only the first line) so the isEmpty()
pre-check prevents scanning the file; remove the getStringFromFile pre-check and
instead always read all lines via FileUtil.readFile(getV2CgroupBase() +
"cpu.stat"), iterate each line, find the one starting with "usage_usec", parse
the second token with ParseUtil.parseLongOrDefault, multiply by
MICROSECONDS_PER_NANOSECOND and return that value; if no matching line is found
return 0L.
- Line 27: The constant MICROSECONDS_PER_NANOSECOND in class LinuxCgroupInfo is
misnamed (it should represent how many nanoseconds are in a microsecond); rename
the constant to NANOSECONDS_PER_MICROSECOND and update all usages (e.g., the
conversion at the location referencing MICROSECONDS_PER_NANOSECOND on the usage
near line 257) so the arithmetic remains the same (usec * 1000) but the
identifier correctly reflects NANOSECONDS_PER_MICROSECOND; ensure any
Javadoc/comments are updated to match the new name.

In `@oshi-common/src/main/java/oshi/software/os/CgroupInfo.java`:
- Around line 17-21: Update the class-level Javadoc in CgroupInfo to remove
"period" from the sentinel list that claims "{`@code` -1} for unlimited quota,
period, or PIDs" and instead document that CPU period uses 100000L as the
default/fallback; also update the getCpuPeriod() Javadoc to reflect that
NoOpCgroupInfo and LinuxCgroupInfo return 100000L as the default/fallback (not
-1) for the CPU period. Reference CgroupInfo, NoOpCgroupInfo, LinuxCgroupInfo,
and getCpuPeriod() when making the doc changes.

---

Nitpick comments:
In `@oshi-common/src/main/java/oshi/software/common/NoOpCgroupInfo.java`:
- Around line 36-40: The NoOpCgroupInfo class exposes a package-private no-arg
constructor allowing external instantiation despite the singleton INSTANCE; make
the constructor private to enforce the singleton pattern by changing the
NoOpCgroupInfo() constructor to private so only the class itself can instantiate
and callers must use the existing INSTANCE field.

In
`@oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java`:
- Around line 129-134: detectVersion() contains a redundant conditional: after
the earlier guard that returns 0 when selfCgroup.isEmpty(), the later if
(!selfCgroup.isEmpty()) is always true and the final return 0 is unreachable.
Remove the dead conditional and unreachable return by replacing that block with
a single return 1 (i.e., in detectVersion(), after the empty-check guard,
directly return 1), referencing the selfCgroup variable to locate the code to
simplify.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2e4dc9d2-9eb2-45bf-9a11-4152092d924c

📥 Commits

Reviewing files that changed from the base of the PR and between 459e224 and e0da53b.

📒 Files selected for processing (7)
  • oshi-common/src/main/java/oshi/software/common/NoOpCgroupInfo.java
  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java
  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxOperatingSystem.java
  • oshi-common/src/main/java/oshi/software/os/CgroupInfo.java
  • oshi-common/src/main/java/oshi/software/os/OperatingSystem.java
  • oshi-common/src/main/java/oshi/util/linux/ProcPath.java
  • oshi-common/src/main/java/oshi/util/linux/SysPath.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (13)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2026-04-12T19:22:09.716Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3149
File: oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacCentralProcessor.java:159-163
Timestamp: 2026-04-12T19:22:09.716Z
Learning: When reviewing OSHI hardware platform code that uses or implements `CentralProcessor`/`PhysicalProcessor.getEfficiency()`, remember the API’s counterintuitive semantics: a *higher* efficiency-class value indicates *greater performance* (lower efficiency). P-cores/“performance cores” should therefore have higher values (e.g., 1) than E-cores/“efficiency cores” (e.g., 0), as documented in the `CentralProcessor` Javadoc. Do not flag code as incorrect solely because ARM_P_CORES or Intel P-cores are assigned higher efficiency values.

Applied to files:

  • oshi-common/src/main/java/oshi/util/linux/ProcPath.java
  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxOperatingSystem.java
  • oshi-common/src/main/java/oshi/software/common/NoOpCgroupInfo.java
  • oshi-common/src/main/java/oshi/software/os/OperatingSystem.java
  • oshi-common/src/main/java/oshi/util/linux/SysPath.java
  • oshi-common/src/main/java/oshi/software/os/CgroupInfo.java
  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java
🔇 Additional comments (4)
oshi-common/src/main/java/oshi/util/linux/SysPath.java (1)

33-33: LGTM! Welcome to OSHI 🎉

The new CGROUP constant is a perfect fit here — it follows the exact same naming and path-composition pattern as all existing SysPath constants, /sys/fs/cgroup/ is the correct canonical mount point for both cgroup v1 (under systemd) and v2, and its public static final nature keeps the @ThreadSafe guarantee without any extra work. Great first contribution!

oshi-common/src/main/java/oshi/util/linux/ProcPath.java (1)

58-59: Welcome, and the new path constants look great! 🎉

Both SELF_CGROUP and FILESYSTEMS correctly mirror the existing pattern in this file and map to real /proc paths needed by the new cgroup implementation. Nice work getting started in the codebase!

oshi-common/src/main/java/oshi/software/common/os/linux/LinuxOperatingSystem.java (1)

65-65: Memoization integration looks correct

The cgroupInfoSupplier follows the exact same pattern as installedAppsSupplier already in this class. LinuxCgroupInfo itself further memoizes limit values internally while serving fresh reads for usage metrics — the two-level caching strategy is a clean design.

Also applies to: 229-232

oshi-common/src/main/java/oshi/software/os/OperatingSystem.java (1)

393-403: Clean default-method integration

The default getCgroupInfo() follows the same pattern as getServices(), getSessions(), and getInstalledApplications(), and the Javadoc clearly documents the Linux vs. no-op distinction. Well done!

- Fix isContainerized() with real container detection (/.dockerenv, cgroup markers)
- Rename MICROSECONDS_PER_NANOSECOND to NANOSECONDS_PER_MICROSECOND
- Fix readCpuUsageV2() to always read all lines from cpu.stat
- Remove redundant conditional in detectVersion()
- Update CgroupInfo Javadoc for CPU period (100000L default, not -1)
- Make NoOpCgroupInfo constructor private for singleton pattern
@dbwiddis

dbwiddis commented May 3, 2026

Copy link
Copy Markdown
Member

The lint failure is because we added to the API which requires a minor version bump to 7.1.0 :)

@dbwiddis

dbwiddis commented May 3, 2026

Copy link
Copy Markdown
Member

Implementation looks good. We need some tests!

dbwiddis added 3 commits May 5, 2026 19:50
cpuQuota, cpuPeriod, memoryLimit, and pidLimit can be reconfigured at
runtime in a container. Use defaultExpiration() TTL so values refresh
instead of being cached forever.
- CgroupInfo interface now has default methods returning sentinel values
- Named constants: UNLIMITED, DEFAULT_CPU_PERIOD, UNLIMITED_MEMORY, UNLIMITED_CPUS
- LinuxCgroupInfo uses constants instead of magic numbers
- getEffectiveCpus() moved to interface default (computed from quota/period)
- OperatingSystem.getCgroupInfo() returns anonymous impl using defaults
- Deleted NoOpCgroupInfo.java

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java`:
- Around line 186-199: The getV1ControllerPath currently matches controllers
with contains() and builds the mount using the requested controller name, which
causes wrong mount paths for combined v1 mounts (e.g., "cpu,cpuacct") and false
matches like "cpu" vs "cpuacct"; change the logic in getV1ControllerPath to
ignore empty controller fields, split parts[1] by ',' and check for an exact
equals match to the requested controller, and when matched build the path using
the actual matched controllers string (controllers) rather than the single
controller argument; also normalize the returned path by trimming leading '/'
from path and appending the trailing '/' as done today; refer to
getV1ControllerPath, ProcPath.SELF_CGROUP and SysPath.CGROUP to locate the
change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8837f241-9f41-4a07-b8b8-5f5b561d06ec

📥 Commits

Reviewing files that changed from the base of the PR and between b7535ff and 5d6fb8a.

📒 Files selected for processing (12)
  • CHANGELOG.md
  • oshi-benchmark/pom.xml
  • oshi-common/pom.xml
  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java
  • oshi-common/src/main/java/oshi/software/os/CgroupInfo.java
  • oshi-common/src/main/java/oshi/software/os/OperatingSystem.java
  • oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoTest.java
  • oshi-core-ffm/pom.xml
  • oshi-core/pom.xml
  • oshi-demo/pom.xml
  • oshi-dist/pom.xml
  • pom.xml
✅ Files skipped from review due to trivial changes (9)
  • oshi-core/pom.xml
  • oshi-common/pom.xml
  • oshi-core-ffm/pom.xml
  • oshi-demo/pom.xml
  • oshi-dist/pom.xml
  • oshi-benchmark/pom.xml
  • pom.xml
  • CHANGELOG.md
  • oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoTest.java
🚧 Files skipped from review as they are similar to previous changes (2)
  • oshi-common/src/main/java/oshi/software/os/OperatingSystem.java
  • oshi-common/src/main/java/oshi/software/os/CgroupInfo.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (14)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 11, ubuntu-latest
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2026-04-12T19:22:09.716Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3149
File: oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacCentralProcessor.java:159-163
Timestamp: 2026-04-12T19:22:09.716Z
Learning: When reviewing OSHI hardware platform code that uses or implements `CentralProcessor`/`PhysicalProcessor.getEfficiency()`, remember the API’s counterintuitive semantics: a *higher* efficiency-class value indicates *greater performance* (lower efficiency). P-cores/“performance cores” should therefore have higher values (e.g., 1) than E-cores/“efficiency cores” (e.g., 0), as documented in the `CentralProcessor` Javadoc. Do not flag code as incorrect solely because ARM_P_CORES or Intel P-cores are assigned higher efficiency values.

Applied to files:

  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java

dbwiddis added 2 commits May 5, 2026 20:34
V2 read methods now have package-private overloads that accept a base
path argument, enabling unit tests with @tempdir fake cgroup filesystems.

Tests cover: cpu.max parsing (quota/period/unlimited), memory.max,
memory.current, pids.max, pids.current, cpu.stat usage_usec.
Use exact match (split on comma) instead of contains() to prevent
'cpu' from matching 'cpuacct'. Use the full controllers string as
the mount directory name (e.g., 'cpu,cpuacct') for combined mounts.
@dbwiddis
dbwiddis force-pushed the feature/cgroup-info-api branch from fee3061 to 6e26605 Compare May 5, 2026 20:34

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (6)
oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoTest.java (3)

7-22: 💤 Low value

Tiny readability nit: import StandardCharsets.

The fully-qualified java.nio.charset.StandardCharsets.UTF_8 repeats in every test. A single static import would tidy things up:

♻️ Suggested cleanup
 import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.Path;
+import java.nio.charset.StandardCharsets;

Then use StandardCharsets.UTF_8 (or "...".getBytes(StandardCharsets.UTF_8)) without the FQN.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoTest.java`
around lines 7 - 22, Add an import for java.nio.charset.StandardCharsets to
LinuxCgroupInfoTest and replace all occurrences of the fully-qualified
java.nio.charset.StandardCharsets.UTF_8 in the test file with
StandardCharsets.UTF_8 (or use ".getBytes(StandardCharsets.UTF_8)") to remove
repetition; locate usages in LinuxCgroupInfoTest where
getBytes(java.nio.charset.StandardCharsets.UTF_8) or similar fully-qualified
references appear and update them to the simple StandardCharsets reference.

23-94: 💤 Low value

Optional: parameterize for less repetition.

Each test is "write one file, call one reader, assert one value" — a textbook fit for @ParameterizedTest with @MethodSource providing (filename, content, expected, methodReference) tuples. That said, the explicit form is very readable and self-documenting; only worth doing if more cases get added later.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoTest.java`
around lines 23 - 94, Tests repeat the same pattern (write file, call reader,
assert) so convert these individual tests (e.g., readCpuQuotaV2WithLimit,
readCpuQuotaV2Unlimited, readCpuPeriodV2, readMemoryLimitV2WithLimit,
readMemoryLimitV2Unlimited, readMemoryUsageV2, readPidLimitV2WithLimit,
readPidLimitV2Unlimited, readPidCurrentV2, readCpuUsageV2) into a single
`@ParameterizedTest` backed by a `@MethodSource` that yields tuples of (filename,
fileContent, expectedValue, readerMethodReference) to reduce duplication;
implement a provider method that returns Stream<Arguments> mapping each case to
the correct cgroup.* reader (e.g., cgroup::readCpuQuotaV2) and assert the
expected long result, keeping dedicated edge-case cases if they need special
setup.

19-95: ⚡ Quick win

Great test foundation — a few easy additions would round it out.

The v2 coverage is solid and the @TempDir approach is exactly right. Some high-value, low-effort additions you could fold in:

  • Missing-file parity: readCpuQuotaV2MissingFile is a nice edge case; analogous one-liner tests for readCpuPeriodV2, readMemoryLimitV2, readMemoryUsageV2, readPidLimitV2, readPidCurrentV2, and readCpuUsageV2 (with no file present) would lock in the documented "return sentinel/zero" behavior.
  • getEffectiveCpus() default-method math: a quick test against the CgroupInfo interface (e.g., quota=200000, period=100000 → 2.0; quota=-1 → UNLIMITED_CPUS) would protect that calculation from regressions.
  • cpu.stat ordering: consider a variant where usage_usec isn't the first line — the current fix iterates all lines, and a test would pin that down.

Nothing blocking — this is just a list for whenever you (or a follow-up PR) want to expand coverage.

Happy to draft any of the above tests if it's helpful — just say the word!

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoTest.java`
around lines 19 - 95, Add small unit tests mirroring readCpuQuotaV2MissingFile
for the other V2 readers: add one-line tests that call readCpuPeriodV2,
readMemoryLimitV2, readMemoryUsageV2, readPidLimitV2, readPidCurrentV2, and
readCpuUsageV2 with an empty `@TempDir` (no file present) and assert they return
the documented sentinels/defaults (DEFAULT_CPU_PERIOD,
UNLIMITED/UNLIMITED_MEMORY/0 as appropriate) to lock in missing-file behavior;
also add a test exercising CgroupInfo.getEffectiveCpus() using known values
(e.g., quota=200000, period=100000 -> 2.0 and quota=-1 -> UNLIMITED_CPUS) and a
cpu.stat ordering test where usage_usec appears after other lines to ensure
readCpuUsageV2 parses any line order.
oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java (3)

328-335: 💤 Low value

Consider naming the v1 "no limit" threshold (and noting page-size assumption).

The UNLIMITED_MEMORY - 4096 check is the well-known "kernel reports LONG_MAX rounded down to PAGE_SIZE" sentinel for cgroup v1's memory.limit_in_bytes. Two small thoughts:

  • Promoting it to a named constant (e.g., V1_NO_LIMIT_THRESHOLD) would make the intent self-documenting and avoid the unexplained magic number.
  • The 4096 assumes a 4 KiB page size; on kernels built with 16 KiB / 64 KiB pages (some ARM64 distros) the actual rounded sentinel sits a bit further from Long.MAX_VALUE. Using a slightly larger guard band (e.g., 0x1_0000) would make the check robust across page sizes.

Totally optional polish — current behavior is correct on the overwhelmingly common 4 KiB case.

♻️ Suggested tweak
+    // Cgroup v1 reports "no limit" as Long.MAX_VALUE rounded down to PAGE_SIZE.
+    // Use a 64 KiB guard band to be robust across 4/16/64 KiB page sizes.
+    private static final long V1_NO_LIMIT_THRESHOLD = UNLIMITED_MEMORY - 0x1_0000;
+
     private long readMemoryLimitV1() {
         String limitPath = getV1ControllerPath("memory") + "memory.limit_in_bytes";
         long limit = FileUtil.getLongFromFile(limitPath);
-        if (limit == 0 || limit > UNLIMITED_MEMORY - 4096) {
+        if (limit == 0 || limit > V1_NO_LIMIT_THRESHOLD) {
             return UNLIMITED_MEMORY;
         }
         return limit;
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java`
around lines 328 - 335, Introduce a named constant (e.g., V1_NO_LIMIT_THRESHOLD)
to replace the magic expression UNLIMITED_MEMORY - 4096 in readMemoryLimitV1(),
document that it represents the cgroup v1 "no limit" sentinel (kernel reports
LONG_MAX rounded down to page size), and widen the guard band (for example use
0x1_0000) to be robust across larger kernel page sizes; update
readMemoryLimitV1() to compare limit against V1_NO_LIMIT_THRESHOLD and add a
comment describing the page-size assumption and why the threshold is used.

222-298: ⚡ Quick win

Excellent testable refactor.

The private noArg() → packagePrivate(String basePath) split for every v2 reader matches the established LinuxCentralProcessor pattern in the codebase and is exactly what makes the new @TempDir-based unit tests possible. Welcome to OSHI! 🎉

One thought for a follow-up (not this PR): the readXxxV1() methods aren't testable in the same way since they all funnel through getV1ControllerPath(...) which reads /proc/self/cgroup directly. If you wanted to extend test coverage to v1 down the road, plumbing the controller-base path through a similar package-private overload would make that straightforward.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java`
around lines 222 - 298, Add package-private overloads for the v1 readers that
accept a controller base path string (e.g., create readCpuQuotaV1(String
controllerBase), readCpuPeriodV1(String controllerBase) and any other v1
readers) and implement the file reads against that provided path; change the
existing private no-arg methods (readCpuQuotaV1(), readCpuPeriodV1(), etc.) to
call getV1ControllerPath("cpu") and then delegate to the new package-private
overloads so tests can inject a temp controller base path while production code
continues to use /proc/self/cgroup.

51-76: 💤 Low value

Container detection logic looks great now.

Combining /.dockerenv + cgroup-path markers + raw /proc/self/cgroup line scan handles Docker, Kubernetes, LXC, containerd, CRI-O, and BuildKit reliably for both v1 and v2. Solid improvement over the prior "any cgroup ≡ container" heuristic.

One small nit (purely optional): each call re-reads /proc/self/cgroup even though that file's contents are immutable for the process lifetime. If isContainerized() ends up on a hot path you could memoize the file contents (or even memoize the boolean result itself); not a blocker for this PR.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java`
around lines 51 - 76, The isContainerized() method repeatedly reads
/proc/self/cgroup and recomputes detection each call; to avoid unnecessary I/O
on hot paths, cache the result or memoize the file contents: read
FileUtil.readFile(ProcPath.SELF_CGROUP) once (or compute the boolean once) and
reuse it for subsequent calls. Modify isContainerized() to consult a
lazily-initialized/volatile cached boolean (or a cached List<String> from
FileUtil.readFile) and fall back to computing and storing the value using
cgroupPathSupplier, CONTAINER_MARKERS, and the existing checks when the cache is
empty.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In
`@oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java`:
- Around line 328-335: Introduce a named constant (e.g., V1_NO_LIMIT_THRESHOLD)
to replace the magic expression UNLIMITED_MEMORY - 4096 in readMemoryLimitV1(),
document that it represents the cgroup v1 "no limit" sentinel (kernel reports
LONG_MAX rounded down to page size), and widen the guard band (for example use
0x1_0000) to be robust across larger kernel page sizes; update
readMemoryLimitV1() to compare limit against V1_NO_LIMIT_THRESHOLD and add a
comment describing the page-size assumption and why the threshold is used.
- Around line 222-298: Add package-private overloads for the v1 readers that
accept a controller base path string (e.g., create readCpuQuotaV1(String
controllerBase), readCpuPeriodV1(String controllerBase) and any other v1
readers) and implement the file reads against that provided path; change the
existing private no-arg methods (readCpuQuotaV1(), readCpuPeriodV1(), etc.) to
call getV1ControllerPath("cpu") and then delegate to the new package-private
overloads so tests can inject a temp controller base path while production code
continues to use /proc/self/cgroup.
- Around line 51-76: The isContainerized() method repeatedly reads
/proc/self/cgroup and recomputes detection each call; to avoid unnecessary I/O
on hot paths, cache the result or memoize the file contents: read
FileUtil.readFile(ProcPath.SELF_CGROUP) once (or compute the boolean once) and
reuse it for subsequent calls. Modify isContainerized() to consult a
lazily-initialized/volatile cached boolean (or a cached List<String> from
FileUtil.readFile) and fall back to computing and storing the value using
cgroupPathSupplier, CONTAINER_MARKERS, and the existing checks when the cache is
empty.

In
`@oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoTest.java`:
- Around line 7-22: Add an import for java.nio.charset.StandardCharsets to
LinuxCgroupInfoTest and replace all occurrences of the fully-qualified
java.nio.charset.StandardCharsets.UTF_8 in the test file with
StandardCharsets.UTF_8 (or use ".getBytes(StandardCharsets.UTF_8)") to remove
repetition; locate usages in LinuxCgroupInfoTest where
getBytes(java.nio.charset.StandardCharsets.UTF_8) or similar fully-qualified
references appear and update them to the simple StandardCharsets reference.
- Around line 23-94: Tests repeat the same pattern (write file, call reader,
assert) so convert these individual tests (e.g., readCpuQuotaV2WithLimit,
readCpuQuotaV2Unlimited, readCpuPeriodV2, readMemoryLimitV2WithLimit,
readMemoryLimitV2Unlimited, readMemoryUsageV2, readPidLimitV2WithLimit,
readPidLimitV2Unlimited, readPidCurrentV2, readCpuUsageV2) into a single
`@ParameterizedTest` backed by a `@MethodSource` that yields tuples of (filename,
fileContent, expectedValue, readerMethodReference) to reduce duplication;
implement a provider method that returns Stream<Arguments> mapping each case to
the correct cgroup.* reader (e.g., cgroup::readCpuQuotaV2) and assert the
expected long result, keeping dedicated edge-case cases if they need special
setup.
- Around line 19-95: Add small unit tests mirroring readCpuQuotaV2MissingFile
for the other V2 readers: add one-line tests that call readCpuPeriodV2,
readMemoryLimitV2, readMemoryUsageV2, readPidLimitV2, readPidCurrentV2, and
readCpuUsageV2 with an empty `@TempDir` (no file present) and assert they return
the documented sentinels/defaults (DEFAULT_CPU_PERIOD,
UNLIMITED/UNLIMITED_MEMORY/0 as appropriate) to lock in missing-file behavior;
also add a test exercising CgroupInfo.getEffectiveCpus() using known values
(e.g., quota=200000, period=100000 -> 2.0 and quota=-1 -> UNLIMITED_CPUS) and a
cpu.stat ordering test where usage_usec appears after other lines to ensure
readCpuUsageV2 parses any line order.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 0259663c-6f5c-40de-a7e2-3fcd9756b6ee

📥 Commits

Reviewing files that changed from the base of the PR and between 5d6fb8a and 6e26605.

📒 Files selected for processing (2)
  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java
  • oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoTest.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Codacy Static Code Analysis
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2026-04-12T19:22:09.716Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3149
File: oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacCentralProcessor.java:159-163
Timestamp: 2026-04-12T19:22:09.716Z
Learning: When reviewing OSHI hardware platform code that uses or implements `CentralProcessor`/`PhysicalProcessor.getEfficiency()`, remember the API’s counterintuitive semantics: a *higher* efficiency-class value indicates *greater performance* (lower efficiency). P-cores/“performance cores” should therefore have higher values (e.g., 1) than E-cores/“efficiency cores” (e.g., 0), as documented in the `CentralProcessor` Javadoc. Do not flag code as incorrect solely because ARM_P_CORES or Intel P-cores are assigned higher efficiency values.

Applied to files:

  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java
🔇 Additional comments (1)
oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java (1)

31-49: Nice memoization layering. 👍

Permanent memoization for versionSupplier/cgroupPathSupplier (they don't change for a running process) plus TTL-backed defaultExpiration() for the limit suppliers (which can be tweaked at runtime via container orchestration) is exactly the right split. This cleanly addresses the earlier concern about limits being able to change during the container's lifetime.

…test coverage

- Memoize isContainerized() to avoid repeated /proc reads
- Named constant V1_NO_LIMIT_THRESHOLD with 64KB guard band
- Package-private path-parameterized overloads for all V1 readers
- Tests for all V1 and V2 readers (missing-file, limits, unlimited, usage)
- cpu.stat line-order test
- CgroupInfo.getEffectiveCpus() default method tests
- Fix FQN StandardCharsets in test
@dbwiddis
dbwiddis force-pushed the feature/cgroup-info-api branch from d5f3125 to 8bd9367 Compare May 5, 2026 20:59

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java`:
- Around line 39-40: The container marker list in CONTAINER_MARKERS (used by
isContainerized()) is too narrow for Podman/Buildah; update the marker arrays to
include Podman/Buildah indicators such as "/.containerenv" and "libpod-" (and
add any analogous occurrences of the marker set in the same class between lines
61-84) so container detection covers cgroup names and filesystem indicators used
by libpod; locate and extend the CONTAINER_MARKERS array (and any duplicate
marker arrays) to add these strings.

In
`@oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoTest.java`:
- Around line 136-149: Add a new test case to cover non-integral CPU quotas:
create a test similar to effectiveCpusWithQuota that instantiates a CgroupInfo
anonymous subclass overriding getCpuQuota() to return 150000L and getCpuPeriod()
to return 100000L and assert that getEffectiveCpus() equals 1.5d; place it
alongside effectiveCpusWithQuota (e.g., effectiveCpusWithFractionalQuota) so
getEffectiveCpus()'s fractional behavior is validated.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ae1e49b1-c71a-4419-8ae2-4708e44ae915

📥 Commits

Reviewing files that changed from the base of the PR and between 6e26605 and d5f3125.

📒 Files selected for processing (2)
  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java
  • oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoTest.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2026-04-12T19:22:09.716Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3149
File: oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacCentralProcessor.java:159-163
Timestamp: 2026-04-12T19:22:09.716Z
Learning: When reviewing OSHI hardware platform code that uses or implements `CentralProcessor`/`PhysicalProcessor.getEfficiency()`, remember the API’s counterintuitive semantics: a *higher* efficiency-class value indicates *greater performance* (lower efficiency). P-cores/“performance cores” should therefore have higher values (e.g., 1) than E-cores/“efficiency cores” (e.g., 0), as documented in the `CentralProcessor` Javadoc. Do not flag code as incorrect solely because ARM_P_CORES or Intel P-cores are assigned higher efficiency values.

Applied to files:

  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (1)
oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java (1)

39-40: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Handle libpod-style containers here too.

Nice addition overall, but isContainerized() still misses common Podman/Buildah cases because it only checks /.dockerenv and the marker list does not include libpod identifiers. That leaves a false-negative on one of the main advertised use cases of this API.

Suggested patch
-    private static final String[] CONTAINER_MARKERS = { "/docker/", "/kubepods/", "/lxc/", "/containerd/", "/crio-",
-            "/buildkit/" };
+    private static final String[] CONTAINER_MARKERS = { "/docker/", "/kubepods/", "/lxc/", "/containerd/", "/crio-",
+            "/buildkit/", "/libpod-" };
@@
-        if (new File("/.dockerenv").exists()) {
+        if (new File("/.dockerenv").exists() || new File("/.containerenv").exists()) {
             return true;
         }

Also applies to: 61-64

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java`
around lines 39 - 40, The current isContainerized() and CONTAINER_MARKERS miss
libpod/Podman/Buildah cases; update the CONTAINER_MARKERS array in
LinuxCgroupInfo to include libpod identifiers (e.g. "/libpod/", "/podman/",
"/podman-") and any other libpod-style tokens you see in the repo, and modify
the isContainerized() checks to also detect Podman-style env files such as
"/run/.containerenv" in addition to "/.dockerenv"; apply the same marker
additions/logic to the other occurrence of the marker/checks referenced around
the CONTAINER_MARKERS usage so both code paths recognize libpod-style
containers.
🧹 Nitpick comments (1)
oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoTest.java (1)

159-229: ⚡ Quick win

These v1 tests bypass the runtime controller-path logic.

All of the v1 assertions inject a resolved temp-dir path directly, so the real /proc/self/cgroup parsing in LinuxCgroupInfo never runs. That leaves the combined-controller case on Lines 195-219 in oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java unguarded, even though it is part of the shipped behavior. A small helper seam for parsing supplied cgroup lines would let you add one regression test for cpu,cpuacct.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoTest.java`
around lines 159 - 229, The v1 tests currently call methods like
readCpuQuotaV1/readCpuPeriodV1 directly and never exercise the
combined-controller parsing in LinuxCgroupInfo (the cpu,cpuacct branch); add a
small seam in LinuxCgroupInfo such as a package-private method
parseCgroupLines(List<String> lines) (or overload that accepts a Path/string
content) which reuses the existing /proc/self/cgroup parsing logic, then update
tests to call that helper with a synthetic cgroup line containing
"cpu,cpuacct:...:<path>" to trigger the combined-controller branch and assert
the expected behavior for cpu,cpuacct; keep existing readCpu*V1 tests but add
one regression test that uses the new helper to cover the combined-controller
case.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Duplicate comments:
In
`@oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java`:
- Around line 39-40: The current isContainerized() and CONTAINER_MARKERS miss
libpod/Podman/Buildah cases; update the CONTAINER_MARKERS array in
LinuxCgroupInfo to include libpod identifiers (e.g. "/libpod/", "/podman/",
"/podman-") and any other libpod-style tokens you see in the repo, and modify
the isContainerized() checks to also detect Podman-style env files such as
"/run/.containerenv" in addition to "/.dockerenv"; apply the same marker
additions/logic to the other occurrence of the marker/checks referenced around
the CONTAINER_MARKERS usage so both code paths recognize libpod-style
containers.

---

Nitpick comments:
In
`@oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoTest.java`:
- Around line 159-229: The v1 tests currently call methods like
readCpuQuotaV1/readCpuPeriodV1 directly and never exercise the
combined-controller parsing in LinuxCgroupInfo (the cpu,cpuacct branch); add a
small seam in LinuxCgroupInfo such as a package-private method
parseCgroupLines(List<String> lines) (or overload that accepts a Path/string
content) which reuses the existing /proc/self/cgroup parsing logic, then update
tests to call that helper with a synthetic cgroup line containing
"cpu,cpuacct:...:<path>" to trigger the combined-controller branch and assert
the expected behavior for cpu,cpuacct; keep existing readCpu*V1 tests but add
one regression test that uses the new helper to cover the combined-controller
case.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 4d0f25a0-4d39-45d9-b086-c98b4f34d17e

📥 Commits

Reviewing files that changed from the base of the PR and between d5f3125 and 8bd9367.

📒 Files selected for processing (2)
  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java
  • oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoTest.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Codacy Static Code Analysis
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2026-04-12T19:22:09.716Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3149
File: oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacCentralProcessor.java:159-163
Timestamp: 2026-04-12T19:22:09.716Z
Learning: When reviewing OSHI hardware platform code that uses or implements `CentralProcessor`/`PhysicalProcessor.getEfficiency()`, remember the API’s counterintuitive semantics: a *higher* efficiency-class value indicates *greater performance* (lower efficiency). P-cores/“performance cores” should therefore have higher values (e.g., 1) than E-cores/“efficiency cores” (e.g., 0), as documented in the `CentralProcessor` Javadoc. Do not flag code as incorrect solely because ARM_P_CORES or Intel P-cores are assigned higher efficiency values.

Applied to files:

  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java
🪛 Microsoft Presidio Analyzer (2.2.362)
oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoTest.java

[medium] 195-195: Detected phone number with confidence 0.40. Remove the number or use a reserved fictional NANP number (e.g. +1-555-0100 in the 555-01XX range).

(PHONE_NUMBER)

- Added /libpod- and /podman- to CONTAINER_MARKERS
- Check /run/.containerenv in addition to /.dockerenv

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java (1)

195-219: ⚡ Quick win

Consider memoizing v1 controller paths to avoid re-reading /proc/self/cgroup on every usage call.

The getV1ControllerPath method is invoked from the usage readers (readCpuUsageV1, readMemoryUsageV1, readPidCurrentV1), which are deliberately called fresh every time getCpuUsage() / getMemoryUsage() / getPidCurrent() are queried (no supplier memoization on usage). On a v1 system, each of those calls re-parses /proc/self/cgroup end-to-end. For monitoring loops that poll usage frequently, this is unnecessary I/O — the v1 controller mount paths don't change for the life of the process, so they can safely be memoized permanently like the version and v2 path are.

♻️ Suggested approach
+    private final java.util.Map<String, Supplier<String>> v1ControllerPathSuppliers = new java.util.concurrent.ConcurrentHashMap<>();
+
@@
     private String getV1ControllerPath(String controller) {
+        return v1ControllerPathSuppliers.computeIfAbsent(controller, c -> memoize(() -> resolveV1ControllerPath(c))).get();
+    }
+
+    private String resolveV1ControllerPath(String controller) {
         List<String> selfCgroup = FileUtil.readFile(ProcPath.SELF_CGROUP);
         // ... existing body ...
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java`
around lines 195 - 219, The getV1ControllerPath method currently re-reads
/proc/self/cgroup on every call; add memoization in LinuxCgroupInfo by
introducing a map field (e.g., ConcurrentHashMap<String,String>
v1ControllerPathCache) and modify getV1ControllerPath(controller) to first check
the cache and return if present, otherwise compute the path as before, store the
computed path (including the fallback SysPath.CGROUP + controller + "/") in the
cache, and return it; ensure thread-safety by using a concurrent map or
computeIfAbsent so callers like readCpuUsageV1, readMemoryUsageV1, and
readPidCurrentV1 benefit without changing their behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In
`@oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java`:
- Around line 195-219: The getV1ControllerPath method currently re-reads
/proc/self/cgroup on every call; add memoization in LinuxCgroupInfo by
introducing a map field (e.g., ConcurrentHashMap<String,String>
v1ControllerPathCache) and modify getV1ControllerPath(controller) to first check
the cache and return if present, otherwise compute the path as before, store the
computed path (including the fallback SysPath.CGROUP + controller + "/") in the
cache, and return it; ensure thread-safety by using a concurrent map or
computeIfAbsent so callers like readCpuUsageV1, readMemoryUsageV1, and
readPidCurrentV1 benefit without changing their behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b60ca855-a445-4edd-a4dc-5935c318bece

📥 Commits

Reviewing files that changed from the base of the PR and between 8bd9367 and bf0a7b3.

📒 Files selected for processing (2)
  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java
  • oshi-core/src/test/java/oshi/SystemInfoTest.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2026-04-12T19:22:09.716Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3149
File: oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacCentralProcessor.java:159-163
Timestamp: 2026-04-12T19:22:09.716Z
Learning: When reviewing OSHI hardware platform code that uses or implements `CentralProcessor`/`PhysicalProcessor.getEfficiency()`, remember the API’s counterintuitive semantics: a *higher* efficiency-class value indicates *greater performance* (lower efficiency). P-cores/“performance cores” should therefore have higher values (e.g., 1) than E-cores/“efficiency cores” (e.g., 0), as documented in the `CentralProcessor` Javadoc. Do not flag code as incorrect solely because ARM_P_CORES or Intel P-cores are assigned higher efficiency values.

Applied to files:

  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java
🔇 Additional comments (4)
oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java (3)

33-48: Nice work on the constants and memoization strategy.

The split between permanent memoization (version/path/containerized) and TTL-based memoization (limits) is exactly right — limits like CPU quota and memory cap can be retuned at runtime via cgroup controls (e.g., docker update --cpus, kubelet pod resize), while the version and cgroup path are effectively immutable for the lifetime of the process. The V1_NO_LIMIT_THRESHOLD guard band for page-rounded "no limit" values is a thoughtful touch too.


61-85: Container detection looks solid.

Good coverage of the common indicators: /.dockerenv, /run/.containerenv, plus marker scans across both the v2 cgroup path and v1 cgroup entries. This handles Docker, Podman, Kubernetes, LXC, containerd, CRI-O, and BuildKit reliably.


298-315: Critical fix from earlier review verified — readCpuUsageV2 now reads all lines and parses usage_usec correctly.

The previous getStringFromFile pre-check that made the parsing block dead code is gone. Multiplication by NANOSECONDS_PER_MICROSECOND (correctly named now) gives the right unit conversion µs → ns.

oshi-core/src/test/java/oshi/SystemInfoTest.java (1)

183-196: Clean integration of the new CgroupInfo API in the demo output.

The block is gated on isContainerized() so it stays silent on bare-metal hosts, sentinel values are checked against the public constants (great that they're now named rather than magic numbers), and Locale.ROOT is used for the float formatting. The == comparison against UNLIMITED_CPUS is safe here since -1.0 has an exact double representation and is returned by the API as that exact constant.

@dbwiddis
dbwiddis force-pushed the feature/cgroup-info-api branch from bf0a7b3 to b312934 Compare May 5, 2026 22:47

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java (1)

147-183: 💤 Low value

Optional: consolidate /proc/self/cgroup reads behind one memoized supplier.

/proc/self/cgroup ends up being read at least three times on cold start: once in detectVersion() (Line 151), once in parseCgroupPath() (Line 166), and again in detectContainerized() (Line 78). Hoisting the file contents into a single Supplier<List<String>> (memoized like the others) and reusing it in all three places would tidy this up and give you one obvious place to inject test data later. Not at all required — just a nice-to-have since you already have the Memoizer pattern in use.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java`
around lines 147 - 183, Consolidate repeated reads of /proc/self/cgroup by
creating a memoized Supplier<List<String>> (following the existing Memoizer
pattern) that reads ProcPath.SELF_CGROUP once, then replace direct
FileUtil.readFile(ProcPath.SELF_CGROUP) calls in detectVersion(),
parseCgroupPath(), and detectContainerized() to call that supplier.get(); ensure
the supplier is initialized once (static or instance field as appropriate) and
used wherever selfCgroup was previously read so tests can inject data via the
single supplier point.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In
`@oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java`:
- Around line 147-183: Consolidate repeated reads of /proc/self/cgroup by
creating a memoized Supplier<List<String>> (following the existing Memoizer
pattern) that reads ProcPath.SELF_CGROUP once, then replace direct
FileUtil.readFile(ProcPath.SELF_CGROUP) calls in detectVersion(),
parseCgroupPath(), and detectContainerized() to call that supplier.get(); ensure
the supplier is initialized once (static or instance field as appropriate) and
used wherever selfCgroup was previously read so tests can inject data via the
single supplier point.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 4fd6472d-013d-4434-9622-ec6785233fda

📥 Commits

Reviewing files that changed from the base of the PR and between bf0a7b3 and b312934.

📒 Files selected for processing (2)
  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java
  • oshi-core/src/test/java/oshi/SystemInfoTest.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • oshi-core/src/test/java/oshi/SystemInfoTest.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Analyze (java)
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: JMH Benchmarks, ubuntu-latest
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2026-04-12T19:22:09.716Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3149
File: oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacCentralProcessor.java:159-163
Timestamp: 2026-04-12T19:22:09.716Z
Learning: When reviewing OSHI hardware platform code that uses or implements `CentralProcessor`/`PhysicalProcessor.getEfficiency()`, remember the API’s counterintuitive semantics: a *higher* efficiency-class value indicates *greater performance* (lower efficiency). P-cores/“performance cores” should therefore have higher values (e.g., 1) than E-cores/“efficiency cores” (e.g., 0), as documented in the `CentralProcessor` Javadoc. Do not flag code as incorrect solely because ARM_P_CORES or Intel P-cores are assigned higher efficiency values.

Applied to files:

  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java
🔇 Additional comments (1)
oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java (1)

33-444: Welcome to OSHI, and very nice work overall! 🎉

First-time CgroupInfo contribution looks great — the v1/v2 split, memoized limits with TTL, package-private overloads for testability, broadened container markers, and the MICROSECONDS_PER_NANOSECOND → NANOSECONDS_PER_MICROSECOND rename all match the prior review feedback nicely. The thread-safety annotation, ConcurrentHashMap for the per-controller path cache, and V1_NO_LIMIT_THRESHOLD guard band for the quirky v1 "unlimited" sentinel are all thoughtful touches. Couple of small notes below for your consideration; nothing blocking from my side.

@dbwiddis
dbwiddis force-pushed the feature/cgroup-info-api branch 2 times, most recently from c5ea739 to 2101d10 Compare May 5, 2026 23:13
When running inside a container, prints cgroup version, CPU quota,
effective CPUs, memory limit/usage, and PID limit/current.
@dbwiddis
dbwiddis force-pushed the feature/cgroup-info-api branch 2 times, most recently from 163bab5 to a013602 Compare May 5, 2026 23:24

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (5)
oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java (2)

196-228: 💤 Low value

Minor: field declared mid-class.

v1ControllerPathCache at line 198 is declared between methods rather than alongside the other fields at lines 41-51. Moving it up keeps all instance state grouped together for readability. Purely cosmetic — feel free to take or leave.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java`
around lines 196 - 228, The instance field v1ControllerPathCache is declared
mid-class; move its declaration (private final Map<String, String>
v1ControllerPathCache = new ConcurrentHashMap<>();) up with the other instance
fields to keep state grouped for readability; ensure the field remains private
final and referenced by getV1ControllerPath and resolveV1ControllerPath with no
other changes.

240-258: 💤 Low value

Nit: cpu.max parsing accepts a stray "MAX" / "Max".

equalsIgnoreCase("max") is defensive but the kernel always writes lowercase max. Not a problem — just noting that exact "max".equals(parts[0]) would match the kernel's actual contract more strictly. Either is fine.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java`
around lines 240 - 258, The cpu.max parsing in readCpuQuotaV2(String basePath)
is currently using "max".equalsIgnoreCase(parts[0])—change this to the stricter
kernel-accurate check "max".equals(parts[0]) so only the exact lowercase token
is treated as UNLIMITED; update the condition in readCpuQuotaV2 to use equals on
parts[0] (preserving the existing parts length check and ParseUtil fallback).
.github/workflows/linux.yaml (1)

79-90: ⚡ Quick win

Optional: make this job runnable on pull requests.

The top-level on: block (lines 4-12) only triggers on push to master and workflow_dispatch, with paths-ignore covering **.yaml. That means the new container-cgroup job won't run automatically against PRs that introduce or change cgroup behavior — defeating part of the value of having an integration test. If you want this to gate PRs, consider either adding a pull_request: trigger to this workflow or moving the job into a workflow that runs on PRs. Not a blocker for this PR, just something to consider as a follow-up.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.github/workflows/linux.yaml around lines 79 - 90, The workflow currently
only triggers on push/workflow_dispatch so the new container-cgroup job won't
run for PRs; update the top-level on: block to include a pull_request: trigger
(or move the container-cgroup job into a workflow that already runs on
pull_request) so the container-cgroup job (named container-cgroup) executes on
PRs as well; ensure any paths/paths-ignore settings are adjusted so **/*.yaml
isn't preventing the job from running on PR changes.
oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoContainerTest.java (1)

54-57: 💤 Low value

Optional: use a delta for the double assertion.

assertEquals(1.5d, getEffectiveCpus(), "msg") does exact equality. It will pass today (1.5 is representable exactly and 150000.0/100000.0 is exact), but if anyone later rounds the kernel value or changes the computation, this becomes brittle. Adding a small delta makes the intent clearer:

-        assertEquals(1.5d, cgroup.getEffectiveCpus(), "Effective CPUs should be 1.5");
+        assertEquals(1.5d, cgroup.getEffectiveCpus(), 1e-9, "Effective CPUs should be 1.5");
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoContainerTest.java`
around lines 54 - 57, The test effectiveCpus in LinuxCgroupInfoContainerTest
uses assertEquals(1.5d, cgroup.getEffectiveCpus(), ...) which does exact double
equality; change it to use an assertion with a small delta (e.g., 1e-6) so
cgroup.getEffectiveCpus() comparisons tolerate tiny floating-point variations
and future rounding changes.
oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoTest.java (1)

284-290: 💤 Low value

Nice edge case for the v1 "near-max == unlimited" guard band.

Long.MAX_VALUE - 4095 is well within the V1_NO_LIMIT_THRESHOLD (Long.MAX_VALUE - 0x1_0000), so this exercises the page-rounded "no limit" sentinel correctly. Could also add a value just below the threshold (e.g., a real multi-TB limit) to lock in the boundary if you want to be extra thorough — optional.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoTest.java`
around lines 284 - 290, Add a complementary unit test to assert the boundary
just below the "no limit" sentinel: create a new test (e.g.,
readMemoryLimitV1BelowThreshold) that writes a value equal to
(V1_NO_LIMIT_THRESHOLD - 1) or another concrete multi-TB value into
memory.limit_in_bytes and assert that
cgroup.readMemoryLimitV1(tempDir.toString() + "/") returns that numeric limit
(not UNLIMITED_MEMORY); reuse the same tempDir/Files.write pattern from
readMemoryLimitV1Unlimited and reference the V1_NO_LIMIT_THRESHOLD constant to
lock in the boundary behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.github/workflows/linux.yaml:
- Around line 91-104: The build steps for "Build oshi-common" and the
in-container test run currently invoke ./mvnw install -pl oshi-common and ./mvnw
test -pl oshi-common which only build the single module and will fail to resolve
reactor dependencies; update both invocations to include the -am flag (e.g.,
./mvnw install -pl oshi-common -am ...) so Maven also builds dependent modules
(like oshi-annotation/parent POM) before testing; ensure both the install and
the dockerized mvn test commands include -am and keep the existing flags
(-DskipTests, -q, -B) intact.

---

Nitpick comments:
In @.github/workflows/linux.yaml:
- Around line 79-90: The workflow currently only triggers on
push/workflow_dispatch so the new container-cgroup job won't run for PRs; update
the top-level on: block to include a pull_request: trigger (or move the
container-cgroup job into a workflow that already runs on pull_request) so the
container-cgroup job (named container-cgroup) executes on PRs as well; ensure
any paths/paths-ignore settings are adjusted so **/*.yaml isn't preventing the
job from running on PR changes.

In
`@oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java`:
- Around line 196-228: The instance field v1ControllerPathCache is declared
mid-class; move its declaration (private final Map<String, String>
v1ControllerPathCache = new ConcurrentHashMap<>();) up with the other instance
fields to keep state grouped for readability; ensure the field remains private
final and referenced by getV1ControllerPath and resolveV1ControllerPath with no
other changes.
- Around line 240-258: The cpu.max parsing in readCpuQuotaV2(String basePath) is
currently using "max".equalsIgnoreCase(parts[0])—change this to the stricter
kernel-accurate check "max".equals(parts[0]) so only the exact lowercase token
is treated as UNLIMITED; update the condition in readCpuQuotaV2 to use equals on
parts[0] (preserving the existing parts length check and ParseUtil fallback).

In
`@oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoContainerTest.java`:
- Around line 54-57: The test effectiveCpus in LinuxCgroupInfoContainerTest uses
assertEquals(1.5d, cgroup.getEffectiveCpus(), ...) which does exact double
equality; change it to use an assertion with a small delta (e.g., 1e-6) so
cgroup.getEffectiveCpus() comparisons tolerate tiny floating-point variations
and future rounding changes.

In
`@oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoTest.java`:
- Around line 284-290: Add a complementary unit test to assert the boundary just
below the "no limit" sentinel: create a new test (e.g.,
readMemoryLimitV1BelowThreshold) that writes a value equal to
(V1_NO_LIMIT_THRESHOLD - 1) or another concrete multi-TB value into
memory.limit_in_bytes and assert that
cgroup.readMemoryLimitV1(tempDir.toString() + "/") returns that numeric limit
(not UNLIMITED_MEMORY); reuse the same tempDir/Files.write pattern from
readMemoryLimitV1Unlimited and reference the V1_NO_LIMIT_THRESHOLD constant to
lock in the boundary behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 458583f7-baaa-4996-a93e-ae84721a2618

📥 Commits

Reviewing files that changed from the base of the PR and between b312934 and a013602.

📒 Files selected for processing (5)
  • .github/workflows/linux.yaml
  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java
  • oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoContainerTest.java
  • oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoTest.java
  • oshi-core/src/test/java/oshi/SystemInfoTest.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Codacy Static Code Analysis
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2026-04-12T19:22:09.716Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3149
File: oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacCentralProcessor.java:159-163
Timestamp: 2026-04-12T19:22:09.716Z
Learning: When reviewing OSHI hardware platform code that uses or implements `CentralProcessor`/`PhysicalProcessor.getEfficiency()`, remember the API’s counterintuitive semantics: a *higher* efficiency-class value indicates *greater performance* (lower efficiency). P-cores/“performance cores” should therefore have higher values (e.g., 1) than E-cores/“efficiency cores” (e.g., 0), as documented in the `CentralProcessor` Javadoc. Do not flag code as incorrect solely because ARM_P_CORES or Intel P-cores are assigned higher efficiency values.

Applied to files:

  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java
🔇 Additional comments (5)
oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java (1)

33-58: Looks good — clean implementation overall!

The constants, memoization strategy, and supplier wiring address all the prior reviewer concerns (sentinel values, expirable limits, container detection markers). Nice work integrating the feedback from the earlier rounds.

oshi-core/src/test/java/oshi/SystemInfoTest.java (1)

183-196: LGTM — clean conditional container output.

The block uses the sentinel constants from CgroupInfo for the unlimited checks and Locale.ROOT for number formatting, and only prints when actually containerized so non-container runs stay quiet. Reads well alongside the existing OS info.

oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoContainerTest.java (1)

30-88: Nice integration test coverage!

Gating on OSHI_CGROUP_TEST and pinning the expected container parameters (cpus=1.5, memory=512m, pids=256) keeps this test deterministic and skippable on regular dev machines. The version == 1 || version == 2 check is a thoughtful touch given the runner kernel could be either.

oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoTest.java (2)

27-178: Solid test coverage — great job!

The mix of @TempDir-based unit tests for the _V2/_V1 package-private methods, missing-file fallbacks, line-order parsing, fractional getEffectiveCpus, and the explicit interfaceDefaults test gives this a really nice safety net. The pattern matches what the maintainer pointed at earlier in the review thread.


182-240: 💤 Low value

Heads-up: integration tests run against the host's real cgroup state.

These @EnabledOnOs(OS.LINUX) tests instantiate new LinuxCgroupInfo() and read real /proc and /sys/fs/cgroup files on the CI runner. They're written defensively (only assert non-negative or sentinel-or-positive), so they should be stable, but be aware that any future stricter assertions here could become flaky depending on the runner's cgroup configuration. Just something to keep in mind for future additions to this section.

Comment thread .github/workflows/linux.yaml Resolved
@dbwiddis
dbwiddis force-pushed the feature/cgroup-info-api branch from a013602 to 467c630 Compare May 5, 2026 23:42

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (1)
oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java (1)

41-42: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Cover systemd-style cgroup names in the container marker set.

This still misses common cgroup v2 paths like /system.slice/docker-<id>.scope and /kubepods.slice/.../cri-containerd-<id>.scope, because the matcher only looks for slash-delimited forms such as /docker/, /kubepods/, and /containerd/. In those environments isContainerized() can return false unless an indicator file happens to exist, and the Docker-only integration test won’t catch it because /.dockerenv makes that path pass.

Suggested patch
-    private static final String[] CONTAINER_MARKERS = { "/docker/", "/kubepods/", "/lxc/", "/containerd/", "/crio-",
-            "/buildkit/", "/libpod-", "/podman-" };
+    private static final String[] CONTAINER_MARKERS = { "/docker/", "/docker-", "/kubepods/", "/kubepods.slice/",
+            "/lxc/", "/containerd/", "/cri-containerd-", "/crio-", "/buildkit/", "/libpod-", "/podman-" };

Also applies to: 65-87

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java`
around lines 41 - 42, The container marker array CONTAINER_MARKERS and the
isContainerized() checks miss systemd/cgroup v2 slice-style names; update
CONTAINER_MARKERS to include patterns that match systemd slices and hyphenated
names (e.g., ".slice", "docker-", "kubepods.slice", "cri-containerd-",
"containerd-", "crio-") and adjust any matching logic in isContainerized() (or
the code that scans cgroup paths) to check for these substrings (not only
slash-delimited tokens) so paths like "system.slice/docker-<id>.scope" and
"kubepods.slice/.../cri-containerd-<id>.scope" are detected as containerized.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Duplicate comments:
In
`@oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java`:
- Around line 41-42: The container marker array CONTAINER_MARKERS and the
isContainerized() checks miss systemd/cgroup v2 slice-style names; update
CONTAINER_MARKERS to include patterns that match systemd slices and hyphenated
names (e.g., ".slice", "docker-", "kubepods.slice", "cri-containerd-",
"containerd-", "crio-") and adjust any matching logic in isContainerized() (or
the code that scans cgroup paths) to check for these substrings (not only
slash-delimited tokens) so paths like "system.slice/docker-<id>.scope" and
"kubepods.slice/.../cri-containerd-<id>.scope" are detected as containerized.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: efad2def-3dc6-4a6e-b583-eb4c4ce1e7be

📥 Commits

Reviewing files that changed from the base of the PR and between a013602 and 467c630.

📒 Files selected for processing (4)
  • .github/workflows/linux.yaml
  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java
  • oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoContainerTest.java
  • oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoTest.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoTest.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2026-04-12T19:22:09.716Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3149
File: oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacCentralProcessor.java:159-163
Timestamp: 2026-04-12T19:22:09.716Z
Learning: When reviewing OSHI hardware platform code that uses or implements `CentralProcessor`/`PhysicalProcessor.getEfficiency()`, remember the API’s counterintuitive semantics: a *higher* efficiency-class value indicates *greater performance* (lower efficiency). P-cores/“performance cores” should therefore have higher values (e.g., 1) than E-cores/“efficiency cores” (e.g., 0), as documented in the `CentralProcessor` Javadoc. Do not flag code as incorrect solely because ARM_P_CORES or Intel P-cores are assigned higher efficiency values.

Applied to files:

  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java
🔇 Additional comments (2)
oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoContainerTest.java (1)

27-88: Nice integration coverage for the constrained-container path.

This is a solid complement to the unit tests: it exercises the live cgroup files and matches the exact limits configured in .github/workflows/linux.yaml.

.github/workflows/linux.yaml (1)

79-104: Good addition of a dedicated constrained-container CI job.

This gives the new cgroup API a realistic end-to-end check, and the -am flags make the Maven invocations safe on a fresh runner.

@dbwiddis
dbwiddis force-pushed the feature/cgroup-info-api branch from 467c630 to 5b86bfb Compare May 5, 2026 23:49
Runs oshi-common tests inside a Docker container with:
  --cpus=1.5 --memory=512m --pids-limit=256

Tests assert exact cgroup values (quota, period, memory limit, PID limit)
and verify isContainerized(), CPU/memory usage, and effective CPUs.

Gated by OSHI_CGROUP_TEST=true env var; skipped in normal test runs.
@dbwiddis
dbwiddis force-pushed the feature/cgroup-info-api branch from 5b86bfb to cdc26a0 Compare May 5, 2026 23:51
@dbwiddis
dbwiddis merged commit f292bad into oshi:master May 6, 2026
18 of 19 checks passed
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