Repository navigation
Add CgroupInfo API for container resource monitoring - #3225
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (4)
📜 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)
🧰 Additional context used🧠 Learnings (1)📚 Learning: 2026-04-12T19:22:09.716ZApplied to files:
🔇 Additional comments (4)
📝 WalkthroughWalkthroughAdds 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. ChangesCgroupInfo API & Linux Implementation
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related issues
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches✨ Simplify 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.
Built for teams:
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. Comment |
Codecov Report❌ Patch coverage is 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (2)
oshi-common/src/main/java/oshi/software/common/NoOpCgroupInfo.java (1)
36-40: ⚡ Quick winMake the singleton constructor
privateThe class uses a singleton pattern (
INSTANCE), but the no-arg constructor is package-private. Any class inoshi.software.commoncan callnew NoOpCgroupInfo()and bypass the singleton, potentially leading to unnecessary object creation or unexpected usage. The standard singleton idiom uses aprivateconstructor.📝 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 valueDead / unreachable code in
detectVersion()After the
if (selfCgroup.isEmpty()) { return 0; }guard on lines 120–122,selfCgroupis guaranteed non-empty for the rest of the method. Theif (!selfCgroup.isEmpty())condition on line 130 is therefore alwaystrue, and the finalreturn 0on 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
📒 Files selected for processing (7)
oshi-common/src/main/java/oshi/software/common/NoOpCgroupInfo.javaoshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.javaoshi-common/src/main/java/oshi/software/common/os/linux/LinuxOperatingSystem.javaoshi-common/src/main/java/oshi/software/os/CgroupInfo.javaoshi-common/src/main/java/oshi/software/os/OperatingSystem.javaoshi-common/src/main/java/oshi/util/linux/ProcPath.javaoshi-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.javaoshi-common/src/main/java/oshi/software/common/os/linux/LinuxOperatingSystem.javaoshi-common/src/main/java/oshi/software/common/NoOpCgroupInfo.javaoshi-common/src/main/java/oshi/software/os/OperatingSystem.javaoshi-common/src/main/java/oshi/util/linux/SysPath.javaoshi-common/src/main/java/oshi/software/os/CgroupInfo.javaoshi-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
CGROUPconstant is a perfect fit here — it follows the exact same naming and path-composition pattern as all existingSysPathconstants,/sys/fs/cgroup/is the correct canonical mount point for both cgroup v1 (under systemd) and v2, and itspublic static finalnature keeps the@ThreadSafeguarantee 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_CGROUPandFILESYSTEMScorrectly mirror the existing pattern in this file and map to real/procpaths 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 correctThe
cgroupInfoSupplierfollows the exact same pattern asinstalledAppsSupplieralready in this class.LinuxCgroupInfoitself 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 integrationThe
default getCgroupInfo()follows the same pattern asgetServices(),getSessions(), andgetInstalledApplications(), 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
|
The lint failure is because we added to the API which requires a minor version bump to 7.1.0 :) |
|
Implementation looks good. We need some tests! |
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
There was a problem hiding this comment.
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
📒 Files selected for processing (12)
CHANGELOG.mdoshi-benchmark/pom.xmloshi-common/pom.xmloshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.javaoshi-common/src/main/java/oshi/software/os/CgroupInfo.javaoshi-common/src/main/java/oshi/software/os/OperatingSystem.javaoshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoTest.javaoshi-core-ffm/pom.xmloshi-core/pom.xmloshi-demo/pom.xmloshi-dist/pom.xmlpom.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
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.
fee3061 to
6e26605
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (6)
oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoTest.java (3)
7-22: 💤 Low valueTiny readability nit: import
StandardCharsets.The fully-qualified
java.nio.charset.StandardCharsets.UTF_8repeats 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 valueOptional: parameterize for less repetition.
Each test is "write one file, call one reader, assert one value" — a textbook fit for
@ParameterizedTestwith@MethodSourceproviding(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 winGreat test foundation — a few easy additions would round it out.
The v2 coverage is solid and the
@TempDirapproach is exactly right. Some high-value, low-effort additions you could fold in:
- Missing-file parity:
readCpuQuotaV2MissingFileis a nice edge case; analogous one-liner tests forreadCpuPeriodV2,readMemoryLimitV2,readMemoryUsageV2,readPidLimitV2,readPidCurrentV2, andreadCpuUsageV2(with no file present) would lock in the documented "return sentinel/zero" behavior.getEffectiveCpus()default-method math: a quick test against theCgroupInfointerface (e.g., quota=200000, period=100000 → 2.0; quota=-1 →UNLIMITED_CPUS) would protect that calculation from regressions.cpu.statordering: consider a variant whereusage_usecisn'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 valueConsider naming the v1 "no limit" threshold (and noting page-size assumption).
The
UNLIMITED_MEMORY - 4096check is the well-known "kernel reportsLONG_MAXrounded down to PAGE_SIZE" sentinel for cgroup v1'smemory.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
4096assumes 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 fromLong.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 winExcellent testable refactor.
The
private noArg() → packagePrivate(String basePath)split for every v2 reader matches the establishedLinuxCentralProcessorpattern 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 throughgetV1ControllerPath(...)which reads/proc/self/cgroupdirectly. 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 valueContainer detection logic looks great now.
Combining
/.dockerenv+ cgroup-path markers + raw/proc/self/cgroupline 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/cgroupeven though that file's contents are immutable for the process lifetime. IfisContainerized()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
📒 Files selected for processing (2)
oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.javaoshi-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-backeddefaultExpiration()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
d5f3125 to
8bd9367
Compare
There was a problem hiding this comment.
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
📒 Files selected for processing (2)
oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.javaoshi-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
There was a problem hiding this comment.
♻️ Duplicate comments (1)
oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java (1)
39-40:⚠️ Potential issue | 🟠 Major | ⚡ Quick winHandle libpod-style containers here too.
Nice addition overall, but
isContainerized()still misses common Podman/Buildah cases because it only checks/.dockerenvand 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 winThese 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/cgroupparsing inLinuxCgroupInfonever runs. That leaves the combined-controller case on Lines 195-219 inoshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.javaunguarded, 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 forcpu,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
📒 Files selected for processing (2)
oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.javaoshi-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
There was a problem hiding this comment.
🧹 Nitpick comments (1)
oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java (1)
195-219: ⚡ Quick winConsider memoizing v1 controller paths to avoid re-reading
/proc/self/cgroupon every usage call.The getV1ControllerPath method is invoked from the usage readers (
readCpuUsageV1,readMemoryUsageV1,readPidCurrentV1), which are deliberately called fresh every timegetCpuUsage()/getMemoryUsage()/getPidCurrent()are queried (no supplier memoization on usage). On a v1 system, each of those calls re-parses/proc/self/cgroupend-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
📒 Files selected for processing (2)
oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.javaoshi-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. TheV1_NO_LIMIT_THRESHOLDguard 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 —readCpuUsageV2now reads all lines and parsesusage_useccorrectly.The previous
getStringFromFilepre-check that made the parsing block dead code is gone. Multiplication byNANOSECONDS_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), andLocale.ROOTis used for the float formatting. The==comparison againstUNLIMITED_CPUSis safe here since-1.0has an exact double representation and is returned by the API as that exact constant.
bf0a7b3 to
b312934
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (1)
oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java (1)
147-183: 💤 Low valueOptional: consolidate
/proc/self/cgroupreads behind one memoized supplier.
/proc/self/cgroupends up being read at least three times on cold start: once indetectVersion()(Line 151), once inparseCgroupPath()(Line 166), and again indetectContainerized()(Line 78). Hoisting the file contents into a singleSupplier<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 theMemoizerpattern 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
📒 Files selected for processing (2)
oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.javaoshi-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_MICROSECONDrename all match the prior review feedback nicely. The thread-safety annotation,ConcurrentHashMapfor the per-controller path cache, andV1_NO_LIMIT_THRESHOLDguard band for the quirky v1 "unlimited" sentinel are all thoughtful touches. Couple of small notes below for your consideration; nothing blocking from my side.
c5ea739 to
2101d10
Compare
When running inside a container, prints cgroup version, CPU quota, effective CPUs, memory limit/usage, and PID limit/current.
163bab5 to
a013602
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (5)
oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java (2)
196-228: 💤 Low valueMinor: field declared mid-class.
v1ControllerPathCacheat 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 valueNit:
cpu.maxparsing accepts a stray "MAX" / "Max".
equalsIgnoreCase("max")is defensive but the kernel always writes lowercasemax. 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 winOptional: make this job runnable on pull requests.
The top-level
on:block (lines 4-12) only triggers onpushtomasterandworkflow_dispatch, withpaths-ignorecovering**.yaml. That means the newcontainer-cgroupjob 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 apull_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 valueOptional: use a delta for the
doubleassertion.
assertEquals(1.5d, getEffectiveCpus(), "msg")does exact equality. It will pass today (1.5 is representable exactly and150000.0/100000.0is 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 valueNice edge case for the v1 "near-max == unlimited" guard band.
Long.MAX_VALUE - 4095is well within theV1_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
📒 Files selected for processing (5)
.github/workflows/linux.yamloshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.javaoshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoContainerTest.javaoshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoTest.javaoshi-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
CgroupInfofor the unlimited checks andLocale.ROOTfor 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_TESTand pinning the expected container parameters (cpus=1.5, memory=512m, pids=256) keeps this test deterministic and skippable on regular dev machines. Theversion == 1 || version == 2check 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/_V1package-private methods, missing-file fallbacks, line-order parsing, fractionalgetEffectiveCpus, and the explicitinterfaceDefaultstest gives this a really nice safety net. The pattern matches what the maintainer pointed at earlier in the review thread.
182-240: 💤 Low valueHeads-up: integration tests run against the host's real cgroup state.
These
@EnabledOnOs(OS.LINUX)tests instantiatenew LinuxCgroupInfo()and read real/procand/sys/fs/cgroupfiles 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.
a013602 to
467c630
Compare
There was a problem hiding this comment.
♻️ Duplicate comments (1)
oshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.java (1)
41-42:⚠️ Potential issue | 🟠 Major | ⚡ Quick winCover systemd-style cgroup names in the container marker set.
This still misses common cgroup v2 paths like
/system.slice/docker-<id>.scopeand/kubepods.slice/.../cri-containerd-<id>.scope, because the matcher only looks for slash-delimited forms such as/docker/,/kubepods/, and/containerd/. In those environmentsisContainerized()can returnfalseunless an indicator file happens to exist, and the Docker-only integration test won’t catch it because/.dockerenvmakes 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
📒 Files selected for processing (4)
.github/workflows/linux.yamloshi-common/src/main/java/oshi/software/common/os/linux/LinuxCgroupInfo.javaoshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoContainerTest.javaoshi-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
-amflags make the Maven invocations safe on a fresh runner.
467c630 to
5b86bfb
Compare
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.
5b86bfb to
cdc26a0
Compare
Summary
Implements a new
CgroupInfointerface to expose cgroup resource limits and usage metrics, enabling OSHI users to detect containerized environments and retrieve resource constraints.Relates to #3224
Usage Examples
Design
CgroupInfointerfacedefaultimplementations returning sentinel values, so non-Linux platforms get correct no-op behavior without a separate classUNLIMITED(-1),DEFAULT_CPU_PERIOD(100000),UNLIMITED_MEMORY(Long.MAX_VALUE),UNLIMITED_CPUS(-1.0d)getEffectiveCpus()is a default method computed fromgetCpuQuota() / getCpuPeriod()OperatingSystem.getCgroupInfo()returns an anonymous instance using the defaultsLinuxCgroupInfoimplementation/proc/filesystemsfor cgroup2 supportcpu.max,cpu.stat,memory.max,memory.current,pids.max,pids.currentcpu.cfs_quota_us,cpuacct.usage, etc.)defaultExpiration()TTL since they can be reconfigured at runtime@TempDirOther changes
ProcPath.java— addedSELF_CGROUPandFILESYSTEMSconstantsSysPath.java— addedCGROUPconstantLinuxOperatingSystem.java— overridesgetCgroupInfo()with memoized instanceSummary by CodeRabbit
New Features
Tests
Chores