Skip to content

Add FAQ entries for container usage and CPU usage polling - #3197

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:doc/faq-containers-and-cpu-usage
Apr 26, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:doc/faq-containers-and-cpu-usage

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Apr 26, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds two new FAQ entries to src/site/markdown/FAQ.md, placed before the existing Windows Task Manager questions for better flow.

1. Does OSHI work in containers (Docker, Kubernetes)?

Summarizes common issues from container-tagged issues:

Provides cgroup v1 and v2 command-line workarounds for obtaining container-scoped CPU and memory limits.

2. How do I get CPU usage?

Answers the recurring question with working code examples for:

  • System-level CPU polling using getSystemCpuLoadTicks() / getSystemCpuLoadBetweenTicks()
  • Process-level CPU polling using getProcessCpuLoadBetweenTicks() with a prior snapshot map
  • Comparison table explaining the key difference: system ticks include idle time, process ticks do not
  • Windows Task Manager scaling (divide by logical processor count)
  • Links to ProcessorPanel and ProcessPanel in oshi-demo for GUI examples

Summary by CodeRabbit

  • Documentation
    • Added FAQ section clarifying how OSHI reports metrics inside containers and guidance on accessing cgroup limits for container-scoped values.
    • Added FAQ section with guidance on computing CPU usage using delta-based snapshots, including system vs process CPU differences and Java polling examples.

@coderabbitai

coderabbitai Bot commented Apr 26, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f452fa85-4a18-4a14-afeb-fe8eac2e27c4

📥 Commits

Reviewing files that changed from the base of the PR and between 5eb3629 and 49e413c.

📒 Files selected for processing (1)
  • src/site/markdown/FAQ.md
📜 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). (1)
  • GitHub Check: Codacy Static Code Analysis
🧰 Additional context used
🧠 Learnings (3)
📚 Learning: 2026-04-20T03:07:05.660Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3176
File: oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsVirtualMemoryFFM.java:53-60
Timestamp: 2026-04-20T03:07:05.660Z
Learning: In OSHI's Windows FFM paging file implementation (`oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsVirtualMemoryFFM.java`), the `querySwapUsed()` method uses the Windows PDH raw counter for "% Usage" on the paging file. Despite its name, this raw counter returns page counts: `FirstValue` is the number of pages currently used and `SecondValue` is the total number of pages in the swap file. The formatted counter performs the division and multiplies by 100% to yield a true percentage. Therefore, computing swap used bytes as `pageSize * used.get()` (pages × page size) is correct — do not treat the return value as a percentage.

Applied to files:

  • src/site/markdown/FAQ.md
📚 Learning: 2026-04-12T19:34:59.050Z
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:59.050Z
Learning: The counterintuitive naming of `PhysicalProcessor.getEfficiency()` / `EfficiencyClass` in OSHI (where a higher value means MORE performance and LESS efficiency, so P-cores get higher values than E-cores) is intentionally inherited from Microsoft's `PROCESSOR_RELATIONSHIP.EfficiencyClass` Win32 API: "A core with a higher value for the efficiency class has intrinsically greater performance and less efficiency." OSHI follows this same convention for cross-platform consistency. Do not flag P-cores being assigned higher efficiency values as a bug.

Applied to files:

  • src/site/markdown/FAQ.md
📚 Learning: 2026-04-18T03:18:06.205Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3170
File: oshi-benchmark/src/test/java/oshi/comparison/PerfmonComparisonTest.java:177-183
Timestamp: 2026-04-18T03:18:06.205Z
Learning: In `oshi-benchmark/src/test/java/oshi/comparison/PerfmonComparisonTest.java`, GPU engine PDH instance counts (from `GpuInformationJNA.queryGpuEngineCounters()` / `GpuInformationFFM.queryGpuEngineCounters()`) are highly volatile — counts can differ dramatically (e.g., 53 vs 40) even between queries taken milliseconds apart. Do not assert instance count equality or exact instance list matching between JNA and FFM results. The only reliable assertion is that both are empty or both are non-empty (`assertThat(ffm.getA().isEmpty()).isEqualTo(jna.getA().isEmpty())`).

Applied to files:

  • src/site/markdown/FAQ.md
🪛 LanguageTool
src/site/markdown/FAQ.md

[style] ~180-~180: This phrase is redundant. Consider writing “points” or “times”.
Context: ...puted by comparing tick counters at two points in time. A single snapshot is meaningless on it...

(MOMENT_IN_TIME)

🔇 Additional comments (4)
src/site/markdown/FAQ.md (4)

13-14: LGTM! TOC entries are well-placed.

The new FAQ entries are logically positioned before the Windows Task Manager questions, making the progression from general container/CPU usage to platform-specific details intuitive.


144-177: Excellent container guidance!

This section provides practical, actionable workarounds for the most common container-related user issues. The cgroup v1/v2 examples are technically accurate and use the appropriate FileUtil methods. The issue references give users a path to more detailed discussions.


178-237: Outstanding CPU usage guide with practical examples!

This section fills a critical gap in the FAQ by providing working code for both system and process CPU polling. The examples are clear, the comparison table is helpful, and the tips are practical.


215-215: The code example is safe as-is; getProcessCpuLoadBetweenTicks() explicitly handles null parameters.

The method documentation clearly states the parameter "May be null," and the implementation gracefully falls back to getProcessCpuLoadCumulative() when no prior snapshot exists. The suggested defensive null check isn't necessary and would make the example less clean. Welcome to the project!


📝 Walkthrough

Walkthrough

Adds two FAQ sections to documentation: one explaining OSHI's container behavior and how to read cgroup v1/v2 limits, and another explaining CPU usage computation via tick deltas with example code and system-vs-process comparisons.

Changes

Cohort / File(s) Summary
Container & CPU FAQ
src/site/markdown/FAQ.md
Added two FAQ sections: (1) how OSHI typically reports host-level metrics inside containers and how to read cgroup v1/v2 CPU and memory limits/usage via the cgroup filesystem using FileUtil; (2) CPU usage calculation as deltas between tick snapshots, CentralProcessor.getSystemCpuLoadBetweenTicks(...) and OSProcess.getProcessCpuLoadBetweenTicks(...), scaling notes, example Java polling code, and a system-vs-process comparison table.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~2 minutes

Poem

Docs bloom with answers, clear and bright,
Containers and ticks step into the light,
Examples to copy, comparisons to see,
Thanks for the update—welcome aboard! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Add FAQ entries for container usage and CPU usage polling' directly summarizes the main change: adding two FAQ sections to address container-related issues and CPU usage computation guidance.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

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

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

❤️ Share

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

@dbwiddis dbwiddis linked an issue Apr 26, 2026 that may be closed by this pull request
19 of 21 tasks

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/site/markdown/FAQ.md (1)

203-224: Guard against processes that appear between snapshots.

Line 217 calls priorSnapshot.get(p.getProcessID()), which returns null if the process wasn't in the first snapshot (e.g., it started between the two polls). While this is example code, adding a null-check would make it more robust for users copying the pattern.

🛡️ Optional null-safety enhancement
 for (OSProcess p : os.getProcesses(null, null, 0)) {
-    double cpu = p.getProcessCpuLoadBetweenTicks(priorSnapshot.get(p.getProcessID()));
-    // Unix-style (can exceed 100%):
-    System.out.printf("PID %d: %.1f%% (Unix-style)%n", p.getProcessID(), cpu * 100);
-    // Windows Task Manager-style (capped per system):
-    System.out.printf("PID %d: %.1f%% (Windows-style)%n", p.getProcessID(), cpu * 100 / cpuCount);
+    OSProcess prior = priorSnapshot.get(p.getProcessID());
+    if (prior != null) {
+        double cpu = p.getProcessCpuLoadBetweenTicks(prior);
+        // Unix-style (can exceed 100%):
+        System.out.printf("PID %d: %.1f%% (Unix-style)%n", p.getProcessID(), cpu * 100);
+        // Windows Task Manager-style (capped per system):
+        System.out.printf("PID %d: %.1f%% (Windows-style)%n", p.getProcessID(), cpu * 100 / cpuCount);
+    }
     priorSnapshot.put(p.getProcessID(), p);
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/site/markdown/FAQ.md` around lines 203 - 224, The example uses
priorSnapshot.get(p.getProcessID()) directly when calling
p.getProcessCpuLoadBetweenTicks, which can be null for processes that started
between snapshots; update the loop (referring to priorSnapshot,
p.getProcessID(), and getProcessCpuLoadBetweenTicks/OSProcess) to check whether
priorSnapshot contains an entry for that PID before calling
getProcessCpuLoadBetweenTicks, and if it’s null either skip CPU calculation (and
optionally print a message indicating the process is new) or treat the prior
snapshot as zeroed/initial so the code won’t throw a NullPointerException.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/site/markdown/FAQ.md`:
- Around line 203-224: The example uses priorSnapshot.get(p.getProcessID())
directly when calling p.getProcessCpuLoadBetweenTicks, which can be null for
processes that started between snapshots; update the loop (referring to
priorSnapshot, p.getProcessID(), and getProcessCpuLoadBetweenTicks/OSProcess) to
check whether priorSnapshot contains an entry for that PID before calling
getProcessCpuLoadBetweenTicks, and if it’s null either skip CPU calculation (and
optionally print a message indicating the process is new) or treat the prior
snapshot as zeroed/initial so the code won’t throw a NullPointerException.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 1b2b94dd-8131-40b2-972b-422a90a260fe

📥 Commits

Reviewing files that changed from the base of the PR and between ef3e4bc and 5eb3629.

📒 Files selected for processing (1)
  • src/site/markdown/FAQ.md
📜 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 (3)
📚 Learning: 2026-04-20T03:07:05.660Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3176
File: oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsVirtualMemoryFFM.java:53-60
Timestamp: 2026-04-20T03:07:05.660Z
Learning: In OSHI's Windows FFM paging file implementation (`oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsVirtualMemoryFFM.java`), the `querySwapUsed()` method uses the Windows PDH raw counter for "% Usage" on the paging file. Despite its name, this raw counter returns page counts: `FirstValue` is the number of pages currently used and `SecondValue` is the total number of pages in the swap file. The formatted counter performs the division and multiplies by 100% to yield a true percentage. Therefore, computing swap used bytes as `pageSize * used.get()` (pages × page size) is correct — do not treat the return value as a percentage.

Applied to files:

  • src/site/markdown/FAQ.md
📚 Learning: 2026-04-12T19:34:59.050Z
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:59.050Z
Learning: The counterintuitive naming of `PhysicalProcessor.getEfficiency()` / `EfficiencyClass` in OSHI (where a higher value means MORE performance and LESS efficiency, so P-cores get higher values than E-cores) is intentionally inherited from Microsoft's `PROCESSOR_RELATIONSHIP.EfficiencyClass` Win32 API: "A core with a higher value for the efficiency class has intrinsically greater performance and less efficiency." OSHI follows this same convention for cross-platform consistency. Do not flag P-cores being assigned higher efficiency values as a bug.

Applied to files:

  • src/site/markdown/FAQ.md
📚 Learning: 2026-04-18T03:18:06.205Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3170
File: oshi-benchmark/src/test/java/oshi/comparison/PerfmonComparisonTest.java:177-183
Timestamp: 2026-04-18T03:18:06.205Z
Learning: In `oshi-benchmark/src/test/java/oshi/comparison/PerfmonComparisonTest.java`, GPU engine PDH instance counts (from `GpuInformationJNA.queryGpuEngineCounters()` / `GpuInformationFFM.queryGpuEngineCounters()`) are highly volatile — counts can differ dramatically (e.g., 53 vs 40) even between queries taken milliseconds apart. Do not assert instance count equality or exact instance list matching between JNA and FFM results. The only reliable assertion is that both are empty or both are non-empty (`assertThat(ffm.getA().isEmpty()).isEqualTo(jna.getA().isEmpty())`).

Applied to files:

  • src/site/markdown/FAQ.md
🪛 LanguageTool
src/site/markdown/FAQ.md

[style] ~182-~182: This phrase is redundant. Consider writing “points” or “times”.
Context: ...puted by comparing tick counters at two points in time. A single snapshot is meaningless on it...

(MOMENT_IN_TIME)

🔇 Additional comments (4)
src/site/markdown/FAQ.md (4)

13-14: LGTM!

The TOC entries are properly formatted and logically positioned before the Windows-specific questions.


144-178: Excellent coverage of container behavior!

This section comprehensively addresses the container-specific issues users encounter. The cgroup v1/v2 examples provide practical workarounds, and the issue references give users additional context. The explanation clearly sets expectations that OSHI reports host-level metrics by design.


186-199: Clean system CPU polling example!

The code correctly demonstrates the snapshot-based approach and saves the current ticks for the next interval. Good illustration of OSHI's delta-based CPU measurement.


226-238: Excellent comparison table and practical tips!

The side-by-side comparison clearly highlights the key differences between system and process CPU calculations. The tips section provides valuable operational guidance, and the demo references give users working examples to explore.

Add two new entries to the FAQ:

1. Does OSHI work in containers (Docker, Kubernetes)?
   Summarizes common issues from container-tagged GitHub issues
   (host-level CPU/memory, missing libudev, unavailable hardware
   IDs, file store duplication, Windows perf counter gaps) and
   provides cgroup v1/v2 command-line workarounds.

2. How do I get CPU usage?
   Covers system-level tick polling, process-level snapshot maps,
   the no-idle-ticks difference for processes, Windows Task Manager
   scaling, and links to the oshi-demo GUI panels.

Signed-off-by: Dan Widdis <[email protected]>
@dbwiddis
dbwiddis force-pushed the doc/faq-containers-and-cpu-usage branch from 5eb3629 to 49e413c Compare April 26, 2026 21:36
@dbwiddis
dbwiddis merged commit b54bb8b into oshi:master Apr 26, 2026
2 checks passed
@dbwiddis
dbwiddis deleted the doc/faq-containers-and-cpu-usage branch May 26, 2026 16:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Improve API documentation for @PublicApi interfaces

1 participant