Repository navigation
Extract testable parse methods from Linux /proc and command readers - #3494
Conversation
Separate acquisition from parsing so the parse logic can be unit-tested with
synthetic fixtures instead of only running against the live host. Behavior is
unchanged; each reader now delegates to a package-private static parser taking
the already-read List<String>.
- LinuxCentralProcessor.queryProcessorId -> parseProcessorIdFromCpuinfo (into an
immutable CpuInfoIdentity holder) + parseLscpuIdentity
- LinuxLogicalVolumeGroup.queryPhysicalVolumes -> parsePhysicalVolumes
- LinuxGlobalMemory.readMemInfo -> parseMemInfo
- LinuxVirtualMemory.queryMemInfo/queryVmStat -> parseMemInfo/parseVmStat
- CpuStat: parse{System,Processor}CpuLoadTicks, parse{ContextSwitches,
Interrupts,BootTime}
- DiskStats.getDiskStats -> parseDiskStats
New fixture tests (grounded in real /proc/cpuinfo, /proc/stat, /proc/meminfo,
/proc/diskstats, lscpu, and pvs output) run on every platform, covering the ARM
MIDR, empty-input, fallback, and malformed-line branches that a single-CPU Linux
CI host cannot exercise. Existing live-host smoke tests are retained but gated
per-method to @EnabledOnOs(LINUX).
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (3)
📜 Recent review details⏰ Context from checks skipped due to timeout. (13)
📝 WalkthroughWalkthroughLinux parsing code now separates file or command input acquisition from parsing logic. CPU identity parsing uses structured helpers, and new tests cover CPU, memory, volume, CPU-stat, and disk-stat parsing behavior. ChangesLinux parser refactor
Estimated code review effort: 4 (Complex) | ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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 #3494 +/- ##
=============================================
+ Coverage 56.86% 70.99% +14.13%
Complexity 76 76
=============================================
Files 591 591
Lines 21586 21617 +31
Branches 3616 3613 -3
=============================================
+ Hits 12274 15347 +3073
+ Misses 7876 4415 -3461
- Partials 1436 1855 +419
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
oshi-common/src/main/java/oshi/util/driver/linux/proc/CpuStat.java (1)
57-59: 🩺 Stability & Availability | 🔴 Critical | ⚡ Quick winMissing array bounds checks can cause
ArrayIndexOutOfBoundsException.The split arrays are accessed without ensuring they have sufficient length. While valid
/proc/statfiles generally have enough columns, missing columns on older kernels (e.g., kernels prior to 2.6.11 missingstealticks) or malformed lines (e.g., just"btime") will cause a runtime crash instead of safely defaulting to zero.
oshi-common/src/main/java/oshi/util/driver/linux/proc/CpuStat.java#L57-L59: add an array bounds check to the loop condition:for (int i = 0; i < TickType.values().length && i < tickArr.length - 1; i++) {.oshi-common/src/main/java/oshi/util/driver/linux/proc/CpuStat.java#L100-L102: add the same array bounds check to the processor ticks loop:for (int i = 0; i < TickType.values().length && i < tickArr.length - 1; i++) {.oshi-common/src/main/java/oshi/util/driver/linux/proc/CpuStat.java#L186-L188: ensurebTimehas at least two elements before accessing index 1:return bTime.length >= 2 ? ParseUtil.parseLongOrDefault(bTime[1], 0L) : 0L;.🤖 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/util/driver/linux/proc/CpuStat.java` around lines 57 - 59, Prevent malformed or truncated /proc/stat data from causing index errors in CpuStat: update both tick-parsing loops at oshi-common/src/main/java/oshi/util/driver/linux/proc/CpuStat.java lines 57-59 and 100-102 to stop when tickArr lacks the requested element, and update the bTime parsing at lines 186-188 to return 0L unless bTime has at least two elements. Preserve zero defaults for missing values.
🧹 Nitpick comments (1)
oshi-common/src/test/java/oshi/util/driver/linux/proc/CpuStatTest.java (1)
84-85: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRename test method for consistency.
Consider renaming this method to
testGetSystemCpuLoadTicksto match the naming convention of the other smoke tests in this class (e.g.,testGetProcessorCpuLoadTicks,testGetBootTime).💡 Proposed refactor
`@Test` `@EnabledOnOs`(OS.LINUX) - void testSystemCpuLoadTicks() { + void testGetSystemCpuLoadTicks() { long[] systemCpuLoadTicks = CpuStat.getSystemCpuLoadTicks();🤖 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/util/driver/linux/proc/CpuStatTest.java` around lines 84 - 85, Rename the test method testSystemCpuLoadTicks to testGetSystemCpuLoadTicks in CpuStatTest, matching the naming convention used by the other smoke tests while leaving its annotation and test behavior unchanged.
🤖 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.
Outside diff comments:
In `@oshi-common/src/main/java/oshi/util/driver/linux/proc/CpuStat.java`:
- Around line 57-59: Prevent malformed or truncated /proc/stat data from causing
index errors in CpuStat: update both tick-parsing loops at
oshi-common/src/main/java/oshi/util/driver/linux/proc/CpuStat.java lines 57-59
and 100-102 to stop when tickArr lacks the requested element, and update the
bTime parsing at lines 186-188 to return 0L unless bTime has at least two
elements. Preserve zero defaults for missing values.
---
Nitpick comments:
In `@oshi-common/src/test/java/oshi/util/driver/linux/proc/CpuStatTest.java`:
- Around line 84-85: Rename the test method testSystemCpuLoadTicks to
testGetSystemCpuLoadTicks in CpuStatTest, matching the naming convention used by
the other smoke tests while leaving its annotation and test behavior unchanged.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: f72ed6f8-345e-4464-a8d3-4323654f98c1
📒 Files selected for processing (12)
oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.javaoshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxGlobalMemory.javaoshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxLogicalVolumeGroup.javaoshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxVirtualMemory.javaoshi-common/src/main/java/oshi/util/driver/linux/proc/CpuStat.javaoshi-common/src/main/java/oshi/util/driver/linux/proc/DiskStats.javaoshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxCentralProcessorTest.javaoshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxGlobalMemoryTest.javaoshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxLogicalVolumeGroupTest.javaoshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxVirtualMemoryTest.javaoshi-common/src/test/java/oshi/util/driver/linux/proc/CpuStatTest.javaoshi-common/src/test/java/oshi/util/driver/linux/proc/DiskStatsTest.java
📜 Review details
⏰ Context from checks skipped due to timeout. (9)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: Analyze (java)
- GitHub Check: Test JDK 21, macos-latest
- GitHub Check: Test JDK 26, macos-latest
- GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
- GitHub Check: Test JDK 25, OpenBSD (+ JNA==FFM)
- GitHub Check: Test JDK 25, OpenIndiana (+ JNA==FFM)
- GitHub Check: Test JDK 25, FreeBSD (+ JNA==FFM)
- GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
🧰 Additional context used
🧠 Learnings (3)
📚 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/hardware/common/platform/linux/LinuxLogicalVolumeGroup.javaoshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxVirtualMemory.javaoshi-common/src/main/java/oshi/util/driver/linux/proc/DiskStats.javaoshi-common/src/main/java/oshi/util/driver/linux/proc/CpuStat.javaoshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxGlobalMemory.javaoshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java
📚 Learning: 2026-07-06T19:25:59.225Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3432
File: oshi-common/src/main/java/oshi/util/ExceptionUtil.java:26-56
Timestamp: 2026-07-06T19:25:59.225Z
Learning: In this repo’s SLF4J 1.x-compatible logging code, do not flag cases where a logger call uses SLF4J 1.6+ implicit-cause handling—e.g., `log.error("...{}", value, t)` (or similar with a single `{}` placeholder) where `t` is passed as the final/trailing argument. SLF4J will attach `t` as the log event’s cause with the full stack trace; this is equivalent to SLF4J 2.x’s fluent `atLevel(...).setCause(t).log(...)` and is intentionally used to preserve SLF4J 1.x runtime compatibility.
Applied to files:
oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxLogicalVolumeGroup.javaoshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxVirtualMemory.javaoshi-common/src/main/java/oshi/util/driver/linux/proc/DiskStats.javaoshi-common/src/main/java/oshi/util/driver/linux/proc/CpuStat.javaoshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxGlobalMemory.javaoshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java
📚 Learning: 2026-04-12T19:34:56.879Z
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:34:56.879Z
Learning: In OSHI’s Java platform implementations, `PhysicalProcessor.getEfficiency()` / `EfficiencyClass` follow the same convention as Windows `PROCESSOR_RELATIONSHIP.EfficiencyClass`: a *higher* numeric efficiency class value represents *greater performance* and *less efficiency* (typically P-cores higher than E-cores). When reviewing, do not treat cases where P-cores are assigned higher efficiency/class values as a bug—this is intentional cross-platform consistency.
Applied to files:
oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java
🔇 Additional comments (17)
oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java (5)
46-46: LGTM!
69-98: LGTM!
100-154: LGTM!
156-235: LGTM!
247-261: LGTM!oshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxCentralProcessorTest.java (2)
33-33: LGTM!
504-591: LGTM!oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxGlobalMemory.java (1)
74-126: LGTM!oshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxGlobalMemoryTest.java (1)
1-53: LGTM!oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxVirtualMemory.java (2)
73-109: LGTM!
111-141: LGTM!oshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxVirtualMemoryTest.java (1)
1-55: LGTM!oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxLogicalVolumeGroup.java (2)
9-9: LGTM!
43-69: LGTM!oshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxLogicalVolumeGroupTest.java (1)
1-46: LGTM!oshi-common/src/main/java/oshi/util/driver/linux/proc/DiskStats.java (1)
121-133: LGTM!oshi-common/src/test/java/oshi/util/driver/linux/proc/DiskStatsTest.java (1)
28-54: LGTM!
…on Windows Address CodeRabbit review and fix Windows CI on the parse-coverage branch: - CpuStat: bound both tick-parsing loops by the actual field count so a truncated /proc/stat line that clears the user/nice/system/idle guard but stops short of steal no longer overruns tickArr; missing fields keep their zero defaults. Guard parseBootTime against a bare "btime" line. These harden a latent index bug that predates the parse-method extraction. - LinuxLogicalVolumeGroupTest: disable on Windows. parsePhysicalVolumes dereferences DevPath.DEV, whose static initializer validates that the configured /dev path exists; that holds on Linux, macOS, and the BSD/illumos CI hosts but throws on Windows. - CpuStatTest: rename testSystemCpuLoadTicks to testGetSystemCpuLoadTicks for consistency with the other smoke tests, and cover the mid-length truncation case in the parse test.
…3496) * NetBSD/OpenBSD: extract testable parse methods from command readers Extract inline command-output parsing into package-private static methods that accept List<String>, mirroring the pattern from #3494 (Linux) and #3495 (FreeBSD). This allows fixture-based tests to exercise the parse logic on every CI platform without requiring the target OS. Extractions: - BsdCentralProcessor: parseTopology, parseDmesgModelsAndCaches, parseCacheStr (shared by NetBSD + OpenBSD) - BsdGraphicsCard: parsePciDump (pcidump -v) - BsdSoundCard: parseDmesg (dmesg audio/pci) - BsdUsbDevice: parseUsbDevices (usbdevs -v) - NetBsdCentralProcessor: parseVmStats, parseFamilyModelStepping, parseCpTime - NetBsdFirmware: parseDmesg (bios0 vendor line) - OpenBsdCentralProcessor: parseVmStats, cpuidToFamilyModelStepping - OpenBsdFirmware: parseDmesg (bios0 vendor line) * Fix firmware vendor extraction to preserve multi-word BIOS vendor names Both NetBsd and OpenBsd parsers now extract the vendor substring between the "vendor" keyword and the " version " delimiter, correctly handling multi-word vendors like "American Megatrends Inc." or "Phoenix Technologies LTD". Falls back to first-token extraction if no " version " delimiter is present.
* Solaris: extract testable parse methods from command readers Extract inline command-output parsing into package-private static methods that accept List<String> (or String), mirroring the pattern from #3494 (Linux), #3495 (FreeBSD), and #3496 (NetBSD/OpenBSD). This allows fixture-based tests to exercise the parse logic on every CI platform without requiring Solaris/OpenIndiana. Extractions: - SolarisCentralProcessor: parseDmesgCpuInfo (dmesg), parseNumaNodes (lgrpinfo -c leaves), parseIsainfoFlags (isainfo -v), sumKstatLong (kstat -p cpu_stat) - SolarisComputerSystem: parseSmbios (smbios), parseSerialFromPrtconf (prtconf -pv chassis-sn) - SolarisGraphicsCard: parsePrtconf (prtconf -pv display class) - SolarisSoundCard: parseLshal (lshal audio810 driver) - SolarisVirtualMemory: parseSwapInfo (swap -lk), sumKstatLong (kstat -p cpu_stat:::pgswapin/pgswapout) - SolarisInternetProtocolStats: parseTcpStats and parseUdpStats (netstat -s -P tcp/udp/ip), splitOnPrefix made package-private * Use split("=", 2) in netstat parsers for mixed-prefix lines When tcpInErr is paired with a non-tcp stat on the same line (e.g. udpNoPorts), splitOnPrefix finds only one "tcp" occurrence, leaving the full remainder including a second "=" sign. Limiting split to 2 parts ensures the length check passes and getFirstIntValue extracts the correct value from the leading portion.
Summary
Improves test coverage of the Linux hardware/driver layer by separating acquisition (reading
/procfiles or running commands) from parsing. Each reader now delegates to a package-privatestaticparser that takes the already-readList<String>, so the parse logic can be unit-tested with synthetic fixtures rather than only executing against the live host. Behavior is unchanged — the parse loops were relocated verbatim.This is the first of an OS-by-OS series (Linux first; FreeBSD next).
Refactors
LinuxCentralProcessor.queryProcessorIdparseProcessorIdFromCpuinfo(into an immutableCpuInfoIdentityholder) +parseLscpuIdentityLinuxLogicalVolumeGroup.queryPhysicalVolumesparsePhysicalVolumesLinuxGlobalMemory.readMemInfoparseMemInfoLinuxVirtualMemory.queryMemInfo/queryVmStatparseMemInfo/parseVmStatCpuStat(5 methods)parseSystemCpuLoadTicks,parseProcessorCpuLoadTicks,parseContextSwitches,parseInterrupts,parseBootTimeDiskStats.getDiskStatsparseDiskStatsTests
New/expanded fixture tests are grounded in real
/proc/cpuinfo(Intel x86 and Raspberry Pi ARM),/proc/stat,/proc/meminfo,/proc/vmstat,/proc/diskstats,lscpu, andpvsoutput. They carry no@EnabledOnOs, so they run on every CI host — including NetBSD/AIX, where these Linux paths never execute — and cover the ARM MIDR, empty-input, fallback-estimate, and malformed-line branches a single-CPU Linux runner cannot reach. The existing live-host smoke tests are retained, gated per-method to@EnabledOnOs(LINUX).Locally (macOS) the extracted parse methods measure ~100% line coverage despite the Linux runtime paths never executing here — which is exactly the point.
Testing
./mvnw clean install(full reactor); spotless, checkstyle, forbiddenapis, and javadoc all pass; all new and existing tests pass.🤖 Generated with Claude Code
Summary by CodeRabbit
/proc/cpuinfoandlscpu, including better handling for ARM stepping and frequency-based names./proc/statparsing, including empty and malformed inputs.