Skip to content

Add oshi-metrics module with Micrometer integration - #3227

Merged
dbwiddis merged 11 commits into
oshi:masterfrom
dbwiddis:feature/oshi-metrics
May 6, 2026
Merged

dbwiddis merged 11 commits into
oshi:masterfrom
dbwiddis:feature/oshi-metrics

Conversation

@dbwiddis

@dbwiddis dbwiddis commented May 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Add the oshi-metrics module — first-party Micrometer metrics for OSHI system information, following OpenTelemetry semantic conventions. This PR establishes the module structure, build configuration, and initial metrics.

Fun fact: I came to OSHI in 2015 as my first start in Open Source contributions to optimize my bang-for-the-buck usage of cloud servers and was interested in using all the CPU and memory I was paying for. So of course these are the metrics I would want. Kind of fun to go full circle a decade later back to these basics....

Metric names and attributes strictly follow OpenTelemetry semantic conventions per feedback from @jaydeluca in #3223.

Also bumps version to 7.1.0-SNAPSHOT (new public API).

Metrics implemented

General metrics

Metric Type Unit Attributes
system.uptime Gauge s —

Processor metrics

Metric Type Unit Attributes
system.cpu.physical.count Gauge {cpu} —
system.cpu.logical.count Gauge {cpu} —
system.cpu.time Counter s cpu.mode (user, nice, system, idle, iowait, interrupt, softirq, steal)
system.cpu.frequency Gauge Hz cpu.logical_number

Memory metrics

Metric Type Unit Attributes
system.memory.usage Gauge By system.memory.state (used, free)
system.memory.limit Gauge By —
system.memory.utilization Gauge 1 system.memory.state (used, free)

Paging/Swap metrics

Metric Type Unit Attributes
system.paging.usage Gauge By system.paging.state (used, free)
system.paging.utilization Gauge 1 system.paging.state (used, free)
system.paging.operations Counter {operation} system.paging.direction (in, out)

Disk controller metrics

Metric Type Unit Attributes
system.disk.io Counter By system.device, disk.io.direction (read, write)
system.disk.operations Counter {operation} system.device, disk.io.direction (read, write)
system.disk.io_time Counter s system.device
system.disk.limit Gauge By system.device

Filesystem metrics

Metric Type Unit Attributes
system.filesystem.usage Gauge By system.device, system.filesystem.mountpoint, system.filesystem.type, system.filesystem.mode, system.filesystem.state (used, free)
system.filesystem.utilization Gauge 1 (same as above)
system.filesystem.limit Gauge By system.device, system.filesystem.mountpoint, system.filesystem.type, system.filesystem.mode

Network metrics

Metric Type Unit Attributes
system.network.io Counter By system.device, network.io.direction (receive, transmit)
system.network.packet.count Counter {packet} system.device, network.io.direction (receive, transmit)
system.network.packet.dropped Counter {packet} system.device, network.io.direction (receive)
system.network.errors Counter {error} system.device, network.io.direction (receive, transmit)
system.network.connection.count Gauge {connection} network.transport, network.connection.state

Aggregate system process metrics

Metric Type Unit Attributes
system.process.count Gauge {process} —

Container metrics (when containerized)

Metric Type Unit Description
container.uptime Gauge s Time since PID 1 started
container.cpu.time Counter s Total CPU time consumed
container.memory.usage Gauge By Container memory usage
container.memory.available Gauge By Memory limit - usage (when limit set)

Selective registration (Builder API)

OshiMetrics.builder(hal, os)
    .enableCpu(true)
    .enableMemory(true)
    .enableDisk(false)
    .enableNetwork(false)
    .build()
    .bindTo(registry);

All categories enabled by default. Categories: general, cpu, memory, paging, disk, fileSystem, network.

Module design

  • JDK 17 target (aligns with Spring Boot 3.x / Micrometer 1.13+)
  • Micrometer 1.14.x as provided scope — user brings their own version
  • Depends on oshi-common interfaces only — works identically with both JNA (oshi-core) and FFM (oshi-core-ffm)
  • OshiMetrics entry point accepts HardwareAbstractionLayer + OperatingSystem directly (no reflection)
  • Implements MeterBinder for Spring Boot auto-discovery
  • Gated behind JDK 17+ Maven profile (like oshi-core-ffm on JDK 25+)

Demo

./mvnw clean install -DskipTests
./mvnw exec:java -pl oshi-metrics \
  -Dexec.mainClass="oshi.metrics.PrometheusDemoTest" \
  -Dexec.classpathScope="test"

Then open http://localhost:8080/metrics or curl localhost:8080/metrics.

Resolves #3223

Summary by CodeRabbit

  • New Features

    • Added oshi-metrics module with Micrometer binders exposing CPU, memory, disk, filesystem, network, paging, process, container and general system metrics; per-item tagging, units, Builder API and convenience bind method (OpenTelemetry conventions)
  • Tests

    • Comprehensive JUnit 5 suite and a Prometheus demo validating metric registration and basic values
  • Documentation

    • Module README, package javadoc, and CHANGELOG entry
  • Chores

    • Java 17 profile, POM and import-control updates to enable the new module

@coderabbitai

coderabbitai Bot commented May 4, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds a new Java 17 Maven module oshi-metrics that provides Micrometer MeterBinder implementations and an OshiMetrics orchestrator exposing OSHI-derived system, CPU, memory, paging, disk, filesystem, network, process, and container metrics. Build, import-control, tests, README, and changelog updates included. (36 words)

Changes

oshi-metrics Module & Micrometer Integration

Layer / File(s) Summary
Build Configuration
oshi-metrics/pom.xml, pom.xml
New module oshi-metrics (Java 17) with micrometer.version and dependencies; parent POM adds java17 profile including the module and excludes oshi.metrics.** from RestrictImports.
Import Control
config/import-control.xml, config/import-control-test.xml
Adds metrics subpackage allows for Micrometer packages and test/demo HTTP/IO packages.
Package Docs & README
oshi-metrics/src/main/java/oshi/metrics/package-info.java, oshi-metrics/README.md
Adds package Javadoc and README documenting Micrometer binders, usage, Builder API, Spring bean example, implemented/not-implemented metric lists.
Core Orchestrator / API
oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java
Introduces OshiMetrics (implements MeterBinder), constructors, static bindTo convenience, and Builder for selective per-category enablement; defaults to enabling all categories.
Per-Category Binders (Data/Implementation)
oshi-metrics/src/main/java/oshi/metrics/*.java
New MeterBinder implementations added: GeneralMetrics, CpuMetrics, MemoryMetrics, PagingMetrics, DiskMetrics, FileSystemMetrics, NetworkMetrics, ProcessMetrics, ContainerMetrics — each registers named gauges/counters with tags, units, and descriptions based on OSHI APIs.
Metrics Wiring
oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java, *Metrics.java
OshiMetrics.bindTo conditionally instantiates and registers each category binder (general, cpu, memory, paging, disk, fileSystem, network, process, container) using HAL/OperatingSystem and suppliers where applicable.
Tests & Demo
oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java, .../PrometheusDemoTest.java
Adds JUnit 5 tests asserting metric registration and basic value constraints; demo binds metrics to an in-memory Prometheus registry and serves /metrics.
Module POM & Packaging
oshi-metrics/pom.xml
Module POM declares parent, release=17, dependencies (micrometer-core provided), test deps, forbidden-apis config, Automatic-Module-Name manifest, and surefire config.
Changelog
CHANGELOG.md
Adds oshi-metrics entry under 7.1.0 (in progress).

Sequence Diagram

sequenceDiagram
    participant App as Application
    participant Registry as MeterRegistry
    participant Oshi as OshiMetrics
    participant Binder as MetricBinder<br/>(e.g., CpuMetrics)
    participant OSHI as OSHI API<br/>(CentralProcessor, GlobalMemory,...)

    App->>Oshi: new OshiMetrics(hal, os)
    App->>Oshi: OshiMetrics.bindTo(Registry)
    Oshi->>Binder: instantiate & Binder.bindTo(Registry)
    Binder->>Registry: register gauge/counter (with supplier)
    Note over Registry,Binder: On scrape, Registry invokes suppliers
    Registry->>OSHI: supplier samples OSHI API
    OSHI-->>Registry: current value
Loading

Estimated Code Review Effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Possibly related PRs

  • oshi/oshi#3225 — Introduces the CgroupInfo API used by ContainerMetrics; strong code-level relation.
  • oshi/oshi#3132 — Reorganizes/moves types into oshi-common that oshi-metrics depends on; relevant to module dependency layout.

Poem

⚙️ New meters hum where snapshots flow,
From cores and caches metrics grow,
A builder picks which binders glow,
Prometheus listens, dashboards show,
Welcome—let observability flow!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.56% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Add oshi-metrics module with Micrometer integration' clearly and concisely describes the main change—introduction of a new oshi-metrics module with Micrometer integration.
Linked Issues check ✅ Passed All primary objectives from issue #3223 are met: new oshi-metrics module created with Micrometer integration, depends on oshi-common for compatibility with both JNA and FFM, comprehensive metric implementations across CPU/memory/disk/filesystem/network/process/container, selective registration via Builder API, aligned with OpenTelemetry conventions, and Spring Boot MeterBinder support.
Out of Scope Changes check ✅ Passed All changes are directly related to creating the oshi-metrics module and its integration: new module structure, metric implementations, build configuration, import control rules, documentation, and a Java 17 Maven profile for JDK 17+ activation.

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

📋 Issue Planner

Built with CodeRabbit's Coding Plans for faster development and fewer bugs.

View plan used: #3223

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

Tip

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

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

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

Built for teams:

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

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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

❤️ Share

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

@codecov

codecov Bot commented May 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.38992% with 40 lines in your changes missing coverage. Please review.
✅ Project coverage is 63.80%. Comparing base (f292bad) to head (3710a89).

Files with missing lines Patch % Lines
...s/src/main/java/oshi/metrics/ContainerMetrics.java 22.72% 16 Missing and 1 partial ⚠️
...ics/src/main/java/oshi/metrics/NetworkMetrics.java 87.34% 8 Missing and 2 partials ⚠️
...etrics/src/main/java/oshi/metrics/DiskMetrics.java 88.88% 4 Missing ⚠️
.../src/main/java/oshi/metrics/FileSystemMetrics.java 92.50% 0 Missing and 3 partials ⚠️
...rics/src/main/java/oshi/metrics/MemoryMetrics.java 90.00% 0 Missing and 2 partials ⚠️
...rics/src/main/java/oshi/metrics/PagingMetrics.java 90.00% 0 Missing and 2 partials ⚠️
...metrics/src/main/java/oshi/metrics/CpuMetrics.java 96.96% 0 Missing and 1 partial ⚠️
...etrics/src/main/java/oshi/metrics/OshiMetrics.java 98.75% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3227      +/-   ##
============================================
+ Coverage     63.11%   63.80%   +0.68%     
- Complexity        0       73      +73     
============================================
  Files           410      420      +10     
  Lines         18910    19287     +377     
  Branches       3333     3355      +22     
============================================
+ Hits          11935    12306     +371     
+ Misses         5294     5278      -16     
- Partials       1681     1703      +22     
Flag Coverage Δ
linux 30.05% <89.38%> (+1.35%) ⬆️
macos 33.00% <89.38%> (+1.15%) ⬆️
windows 40.88% <89.38%> (+0.95%) ⬆️

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

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

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

@dbwiddis
dbwiddis force-pushed the feature/oshi-metrics branch 7 times, most recently from 7b3ce8c to 3ed1323 Compare May 4, 2026 04:41

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (4)
oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java (1)

52-53: 💤 Low value

value() called twice in the same assertion — gauge is re-evaluated between checks.

used.value() > 0 && used.value() < 1 invokes the backing GlobalMemory lambda twice. On a live system this is innocuous, but it's cleaner to capture the value once.

🔧 Suggested fix
-        assertTrue(used.value() > 0 && used.value() < 1, "Used utilization should be between 0 and 1");
-        assertTrue(free.value() > 0 && free.value() < 1, "Free utilization should be between 0 and 1");
+        double usedVal = used.value();
+        double freeVal = free.value();
+        assertTrue(usedVal > 0 && usedVal < 1, "Used utilization should be between 0 and 1");
+        assertTrue(freeVal > 0 && freeVal < 1, "Free utilization should be between 0 and 1");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java` around lines 52
- 53, The assertions call used.value() and free.value() twice causing the gauge
lambdas to be re-evaluated; capture each gauge value once into local variables
(e.g., double usedVal = used.value(); double freeVal = free.value();) in
OshiMetricsTest and then assert on those variables (assertTrue(usedVal > 0 &&
usedVal < 1, ...), assertTrue(freeVal > 0 && freeVal < 1, ...)) so the checks
use the same sampled value.
oshi-metrics/pom.xml (1)

70-76: ⚡ Quick win

Blanket forbiddenapis skip hides violations in production code.

Skipping the entire plugin disables checks on CpuMetrics, MemoryMetrics, and OshiMetrics too, not just the demo. The skip is almost certainly needed only for PrometheusDemoTest.main()'s System.out.println calls (caught by jdk-system-out). A more targeted approach: keep forbiddenapis enabled for main sources and apply @SuppressForbidden (already supported by the parent config) to just that method.

🔧 Suggested targeted suppression instead of module-wide skip

In oshi-metrics/pom.xml, keep forbiddenapis for main and skip only test:

 <plugin>
     <groupId>de.thetaphi</groupId>
     <artifactId>forbiddenapis</artifactId>
     <configuration>
-        <skip>true</skip>
+        <skipTestClasses>true</skipTestClasses>
     </configuration>
 </plugin>

Then annotate PrometheusDemoTest.main:

+@oshi.annotation.SuppressForbidden(reason = "Demo uses System.out intentionally")
 public static void main(String[] args) throws IOException {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-metrics/pom.xml` around lines 70 - 76, Remove the blanket
<skip>true</skip> for the forbiddenapis plugin so it runs against main sources
(so classes like CpuMetrics, MemoryMetrics, OshiMetrics remain checked); instead
configure the plugin to skip tests only (or leave plugin enabled and set its
test execution to skip). Then add a targeted `@SuppressForbidden` annotation to
the PrometheusDemoTest.main method (the single test that uses
System.out.println) to silence jdk-system-out for that method; the parent POM
already supports `@SuppressForbidden` so no extra setup is needed.
oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java (1)

47-55: 💤 Low value

Memory gauges are missing .description() — inconsistent with CpuMetrics.

CpuMetrics calls .description(...) on each FunctionCounter; none of the four Gauge builders here do. Micrometer surfaces descriptions in many backends (Prometheus # HELP, Grafana tooltips, etc.).

✨ Proposed addition
         Gauge.builder(MEMORY_USAGE, memory, mem -> mem.getTotal() - mem.getAvailable()).tags(Tags.of(STATE_USED))
-                .baseUnit("By").register(registry);
+                .description("Amount of memory used").baseUnit("By").register(registry);
         Gauge.builder(MEMORY_USAGE, memory, GlobalMemory::getAvailable).tags(Tags.of(STATE_FREE)).baseUnit("By")
-                .register(registry);
+                .description("Amount of memory free").register(registry);
         Gauge.builder(MEMORY_UTILIZATION, memory,
                 mem -> (double) (mem.getTotal() - mem.getAvailable()) / mem.getTotal()).tags(Tags.of(STATE_USED))
-                .register(registry);
+                .description("Fraction of memory used").register(registry);
         Gauge.builder(MEMORY_UTILIZATION, memory, mem -> (double) mem.getAvailable() / mem.getTotal())
-                .tags(Tags.of(STATE_FREE)).register(registry);
+                .tags(Tags.of(STATE_FREE)).description("Fraction of memory free").register(registry);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java` around lines 47 -
55, In MemoryMetrics, the four Gauge.builder(...) calls for MEMORY_USAGE and
MEMORY_UTILIZATION (using GlobalMemory) are missing .description(...) entries;
update each Gauge builder in class MemoryMetrics to add a clear description
(matching style used in CpuMetrics) for the used and free variants — e.g.,
describe MEMORY_USAGE as "Memory used in bytes" for STATE_USED and "Memory
available in bytes" for STATE_FREE, and describe MEMORY_UTILIZATION as "Fraction
of memory used" and "Fraction of memory free" respectively; ensure you call
.description(...) before .register(registry) on the Gauge builders for
MEMORY_USAGE and MEMORY_UTILIZATION.
oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java (1)

35-36: ⚡ Quick win

TICK_TO_MODE array is implicitly coupled to TickType.getIndex() ordinals.

Adding a new TickType or re-ordering indices in a future OSHI release would either throw a silent ArrayIndexOutOfBoundsException or produce wrong mode labels at runtime. An EnumMap is the idiomatic, safe alternative.

♻️ Proposed refactor using EnumMap
-    private static final String[] TICK_TO_MODE = { "user", "nice", "system", "idle", "iowait", "interrupt", "softirq",
-            "steal" };
+    private static final java.util.Map<TickType, String> TICK_TO_MODE =
+            new java.util.EnumMap<>(java.util.Map.of(
+                TickType.USER,    "user",
+                TickType.NICE,    "nice",
+                TickType.SYSTEM,  "system",
+                TickType.IDLE,    "idle",
+                TickType.IOWAIT,  "iowait",
+                TickType.IRQ,     "interrupt",
+                TickType.SOFTIRQ, "softirq",
+                TickType.STEAL,   "steal"));

     ...

     `@Override`
     public void bindTo(MeterRegistry registry) {
         for (TickType type : TickType.values()) {
-            int index = type.getIndex();
-            String mode = TICK_TO_MODE[index];
-            FunctionCounter.builder(CPU_TIME, processor, p -> p.getSystemCpuLoadTicks()[index] / MS_PER_SECOND)
+            String mode = TICK_TO_MODE.get(type);
+            if (mode == null) continue; // gracefully skip unknown future TickTypes
+            FunctionCounter.builder(CPU_TIME, processor, p -> p.getSystemCpuLoadTicks()[type.getIndex()] / MS_PER_SECOND)
                     .tag(CPU_MODE_KEY, mode).description("System CPU time spent in " + mode + " mode").baseUnit("s")
                     .register(registry);
         }
     }

Also applies to: 51-57

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java` around lines 35 -
36, The TICK_TO_MODE string array is coupled to TickType.getIndex() ordinals and
can break if TickType changes; replace the array with an
EnumMap<TickType,String> keyed by TickType constants (populate entries for user,
nice, system, idle, iowait, interrupt, softirq, steal) and update any code that
uses TICK_TO_MODE[TickType.getIndex()] to use map.get(TickType.<VALUE>) or
map.get(tickType) instead; do the same refactor for the other mode arrays
referenced around lines 51-57 so all lookups use an EnumMap rather than ordinal
indexing.
🤖 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-metrics/src/main/java/oshi/metrics/MemoryMetrics.java`:
- Line 1: Add a new package-info.java for the oshi.metrics package to satisfy
Checkstyle's JavadocPackage rule: create package-info.java containing the
license header and the package-level Javadoc describing that this package
contains Micrometer MeterBinder implementations for OSHI system metrics and
declare "package oshi.metrics;". Ensure the header includes the project
copyright and SPDX license line and that the Javadoc references
io.micrometer.core.instrument.binder.MeterBinder as in the suggested content.
- Around line 51-55: In MemoryMetrics update the two Gauge.builder lambdas that
compute utilization (the ones using MEMORY_UTILIZATION with tags STATE_USED and
STATE_FREE) to guard against mem.getTotal() == 0: if total is zero return 0.0
(or a safe finite value) instead of performing the division; apply this check to
both uses of mem.getTotal() (the used calculation (mem.getTotal() -
mem.getAvailable())/mem.getTotal() and the free calculation
mem.getAvailable()/mem.getTotal()) so the gauges never emit NaN/Infinity.

In `@oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java`:
- Around line 35-47: The OshiMetrics class currently stores an OperatingSystem
in the private field "os" (set in the OshiMetrics(HardwareAbstractionLayer hal,
OperatingSystem os) constructor) but never reads it; either document it as
reserved for future OS/process metrics or remove it to keep the API minimal:
update the constructor signature and remove the private "os" field and any
assignments/usages if you choose removal, or add a single-line comment above the
"os" field like "// reserved for future OS-level metrics (e.g., process)" to
make intent explicit and avoid dead-code confusion; adjust any callers
accordingly (constructor invocations) to match the chosen approach.

In `@oshi-metrics/src/test/java/oshi/metrics/PrometheusDemoTest.java`:
- Around line 57-63: The HTTP handler in PrometheusDemoTest is using
response.length() and response.getBytes() without a charset and missing
Content-Type; compute the response bytes with a fixed charset (e.g.
StandardCharsets.UTF_8), set the response Content-Type header to the Prometheus
text format including version and charset (e.g. "text/plain; version=0.0.4;
charset=utf-8") on exchange.getResponseHeaders(), then call
exchange.sendResponseHeaders(200, bytes.length) using the byte[] length and
write that byte[] to exchange.getResponseBody(); update the code around
registry.scrape(), exchange.sendResponseHeaders, and response.getBytes() to use
these changes.

---

Nitpick comments:
In `@oshi-metrics/pom.xml`:
- Around line 70-76: Remove the blanket <skip>true</skip> for the forbiddenapis
plugin so it runs against main sources (so classes like CpuMetrics,
MemoryMetrics, OshiMetrics remain checked); instead configure the plugin to skip
tests only (or leave plugin enabled and set its test execution to skip). Then
add a targeted `@SuppressForbidden` annotation to the PrometheusDemoTest.main
method (the single test that uses System.out.println) to silence jdk-system-out
for that method; the parent POM already supports `@SuppressForbidden` so no extra
setup is needed.

In `@oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java`:
- Around line 35-36: The TICK_TO_MODE string array is coupled to
TickType.getIndex() ordinals and can break if TickType changes; replace the
array with an EnumMap<TickType,String> keyed by TickType constants (populate
entries for user, nice, system, idle, iowait, interrupt, softirq, steal) and
update any code that uses TICK_TO_MODE[TickType.getIndex()] to use
map.get(TickType.<VALUE>) or map.get(tickType) instead; do the same refactor for
the other mode arrays referenced around lines 51-57 so all lookups use an
EnumMap rather than ordinal indexing.

In `@oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java`:
- Around line 47-55: In MemoryMetrics, the four Gauge.builder(...) calls for
MEMORY_USAGE and MEMORY_UTILIZATION (using GlobalMemory) are missing
.description(...) entries; update each Gauge builder in class MemoryMetrics to
add a clear description (matching style used in CpuMetrics) for the used and
free variants — e.g., describe MEMORY_USAGE as "Memory used in bytes" for
STATE_USED and "Memory available in bytes" for STATE_FREE, and describe
MEMORY_UTILIZATION as "Fraction of memory used" and "Fraction of memory free"
respectively; ensure you call .description(...) before .register(registry) on
the Gauge builders for MEMORY_USAGE and MEMORY_UTILIZATION.

In `@oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java`:
- Around line 52-53: The assertions call used.value() and free.value() twice
causing the gauge lambdas to be re-evaluated; capture each gauge value once into
local variables (e.g., double usedVal = used.value(); double freeVal =
free.value();) in OshiMetricsTest and then assert on those variables
(assertTrue(usedVal > 0 && usedVal < 1, ...), assertTrue(freeVal > 0 && freeVal
< 1, ...)) so the checks use the same sampled value.
🪄 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: cb1a0047-1e6e-4552-aa3e-acd033d3e067

📥 Commits

Reviewing files that changed from the base of the PR and between 27528a4 and 7b3ce8c.

📒 Files selected for processing (7)
  • oshi-metrics/pom.xml
  • oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java
  • oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java
  • oshi-metrics/src/test/java/oshi/metrics/PrometheusDemoTest.java
  • pom.xml
📜 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
🪛 GitHub Actions: Pull Request CI
oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java

[error] 10-10: Checkstyle (ImportControlCheck#ImportControlMain): Disallowed import - io.micrometer.core.instrument.FunctionCounter.


[error] 11-11: Checkstyle (ImportControlCheck#ImportControlMain): Disallowed import - io.micrometer.core.instrument.MeterRegistry.


[error] 12-12: Checkstyle (ImportControlCheck#ImportControlMain): Disallowed import - io.micrometer.core.instrument.binder.MeterBinder.

oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java

[error] 17-17: Checkstyle (ImportControlCheck#ImportControlTest): Disallowed import - io.micrometer.core.instrument.Gauge.


[error] 18-18: Checkstyle (ImportControlCheck#ImportControlTest): Disallowed import - io.micrometer.core.instrument.MeterRegistry.


[error] 19-19: Checkstyle (ImportControlCheck#ImportControlTest): Disallowed import - io.micrometer.core.instrument.simple.SimpleMeterRegistry.

oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java

[error] 1-1: Checkstyle (JavadocPackage): Missing package-info.java file.


[error] 9-9: Checkstyle (ImportControlCheck#ImportControlMain): Disallowed import - io.micrometer.core.instrument.Gauge.


[error] 10-10: Checkstyle (ImportControlCheck#ImportControlMain): Disallowed import - io.micrometer.core.instrument.MeterRegistry.


[error] 11-11: Checkstyle (ImportControlCheck#ImportControlMain): Disallowed import - io.micrometer.core.instrument.Tag.


[error] 12-12: Checkstyle (ImportControlCheck#ImportControlMain): Disallowed import - io.micrometer.core.instrument.Tags.


[error] 13-13: Checkstyle (ImportControlCheck#ImportControlMain): Disallowed import - io.micrometer.core.instrument.binder.MeterBinder.

oshi-metrics/pom.xml

[error] maven-checkstyle-plugin:check failed. You have 18 Checkstyle violations.

pom.xml

[error] maven-checkstyle-plugin:check failed. You have 18 Checkstyle violations.

oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java

[error] 10-10: Checkstyle (ImportControlCheck#ImportControlMain): Disallowed import - io.micrometer.core.instrument.MeterRegistry.


[error] 11-11: Checkstyle (ImportControlCheck#ImportControlMain): Disallowed import - io.micrometer.core.instrument.binder.MeterBinder.

oshi-metrics/src/test/java/oshi/metrics/PrometheusDemoTest.java

[error] 9-9: Checkstyle (ImportControlCheck#ImportControlTest): Disallowed import - java.net.InetSocketAddress.


[error] 12-12: Checkstyle (ImportControlCheck#ImportControlTest): Disallowed import - com.sun.net.httpserver.HttpServer.


[error] 16-16: Checkstyle (ImportControlCheck#ImportControlTest): Disallowed import - io.micrometer.prometheusmetrics.PrometheusConfig.


[error] 17-17: Checkstyle (ImportControlCheck#ImportControlTest): Disallowed import - io.micrometer.prometheusmetrics.PrometheusMeterRegistry.

🔇 Additional comments (2)
pom.xml (2)

1024-1033: New java17 profile looks correct.

The [17,) JDK activation range and the oshi-metrics module inclusion are consistent with the design intent. Both java17 and java25 profiles activate simultaneously on JDK 25+, which is intentional and desirable.


743-748: The Checkstyle ImportControl config already includes the necessary allowances for the oshi.metrics subpackage. Both config/import-control.xml (main source) and config/import-control-test.xml (tests) contain:

<subpackage name="metrics">
  <allow pkg="io.micrometer.core.instrument" />
  <allow pkg="io.micrometer.core.instrument.binder" />
  <allow pkg="io.micrometer.core.instrument.simple" />
  <allow pkg="io.micrometer.prometheusmetrics" />
  <allow pkg="com.sun.net.httpserver" />
</subpackage>

No changes needed here—the configuration is correct and complete for supporting the new metrics module.

			> Likely an incorrect or invalid review comment.

@dbwiddis
dbwiddis force-pushed the feature/oshi-metrics branch 2 times, most recently from 83b8b2f to 2a6bc8b Compare May 4, 2026 05:33
@dbwiddis
dbwiddis marked this pull request as ready for review May 4, 2026 05:33

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@CHANGELOG.md`:
- Line 3: Replace the incorrect level-5 heading "##### New Features" with a
level-2 heading "## New Features" (or adjust surrounding headings so the heading
hierarchy is consistent) in the CHANGELOG.md file so it no longer jumps from a
top-level release title (#) to a level-5 heading and satisfies markdownlint rule
MD001; specifically locate the "New Features" heading and change its leading
hashes to "##".

In `@config/import-control.xml`:
- Around line 115-117: The import-control for main sources currently allows
test-only packages — remove the <allow> entries for
io.micrometer.core.instrument.simple, io.micrometer.prometheusmetrics, and
com.sun.net.httpserver from the main import-control (the file shown) so those
packages are only permitted in import-control-test.xml; locate the allow tags
referencing those exact package strings and delete them to prevent production
code from silently importing test-only or internal APIs.

In `@oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java`:
- Line 24: The Javadoc for system.memory.utilization is misleading: it calls the
value a "percentage" but the gauges produced by MemoryMetrics return a ratio in
[0,1]; update the Javadoc in MemoryMetrics.java to describe
system.memory.utilization as a fraction/ratio in the range 0..1 (e.g., "fraction
of memory in use (0.0–1.0)") and optionally note that 1.0 corresponds to 100%
per OTel conventions so callers understand the scale; locate the doc string near
the system.memory.utilization entry in the MemoryMetrics class and replace
"percentage" with the clarified wording.

In `@oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java`:
- Around line 66-68: The test does a second
registry.find("system.cpu.time").tag("cpu.mode","idle").functionCounter() call
and chains .count() without null-checking, risking an NPE; change the test to
reuse the earlier lookup result (store the FunctionCounter from
registry.find(...).functionCounter() into a local variable used for
assertNotNull and for computing idle) or add an assertNotNull on that second
functionCounter before calling .count(), referencing registry.find,
functionCounter(), and the idle/assertTrue assertions to locate the code to
update.
🪄 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: a437a3ce-853d-4d3a-a629-bf848a279ddb

📥 Commits

Reviewing files that changed from the base of the PR and between 7b3ce8c and 2a6bc8b.

📒 Files selected for processing (17)
  • CHANGELOG.md
  • config/import-control-test.xml
  • config/import-control.xml
  • oshi-benchmark/pom.xml
  • oshi-common/pom.xml
  • oshi-core-ffm/pom.xml
  • oshi-core/pom.xml
  • oshi-demo/pom.xml
  • oshi-dist/pom.xml
  • oshi-metrics/pom.xml
  • oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/package-info.java
  • oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java
  • oshi-metrics/src/test/java/oshi/metrics/PrometheusDemoTest.java
  • pom.xml
✅ Files skipped from review due to trivial changes (9)
  • oshi-core/pom.xml
  • oshi-common/pom.xml
  • oshi-demo/pom.xml
  • oshi-dist/pom.xml
  • oshi-core-ffm/pom.xml
  • oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/package-info.java
  • oshi-benchmark/pom.xml
  • oshi-metrics/src/test/java/oshi/metrics/PrometheusDemoTest.java
🚧 Files skipped from review as they are similar to previous changes (2)
  • oshi-metrics/pom.xml
  • pom.xml
📜 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). (15)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 11, ubuntu-latest
  • GitHub Check: Test JDK 21, ubuntu-latest
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
  • GitHub Check: JMH Benchmarks, ubuntu-latest
🧰 Additional context used
🪛 markdownlint-cli2 (0.22.1)
CHANGELOG.md

[warning] 3-3: Heading levels should only increment by one level at a time
Expected: h2; Actual: h5

(MD001, heading-increment)

🔇 Additional comments (4)
config/import-control-test.xml (1)

50-58: LGTM!

The test import allowlist correctly covers all Micrometer, Prometheus, and JDK HTTP server packages used by the new test sources. The addition of java.net to cover PrometheusDemoTest is appropriate here (test-only).

oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java (1)

45-57: Division-by-zero guard and overall implementation look solid.

The 0d sentinel for getTotal() == 0 is in place, method reference for getAvailable() is clean, and both usage and utilization gauges are correctly wired with tags and descriptions. The omission of .baseUnit() on the utilization gauges is intentional and correct (dimensionless ratio per OTel conventions).

oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java (1)

33-65: Clean entry-point design.

The final class, the os placeholder comment, the static convenience overload, and the delegation pattern all look well-considered. The API surface is lean and the Javadoc usage example is a nice touch for Spring Boot auto-wiring consumers.

oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java (1)

27-34: Solid test setup.

@BeforeAll with a single SimpleMeterRegistry shared across all test methods is the right call here — meters are registered once and the read-only assertions are independent of each other. The eight cpu.mode values match CpuMetrics's TICK_TO_MODE map exactly, so no gaps in coverage.

Comment thread CHANGELOG.md Resolved
Comment thread config/import-control.xml Resolved
@dbwiddis
dbwiddis force-pushed the feature/oshi-metrics branch from 2a6bc8b to 0dfe9a6 Compare May 4, 2026 05:45

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
config/import-control.xml (1)

111-115: 💤 Low value

Previous concern resolved — looks great! 🎉

Welcome to the project, and thanks for a clean addition here! The three test-only packages (io.micrometer.core.instrument.simple, io.micrometer.prometheusmetrics, and com.sun.net.httpserver) that were flagged in the prior round are no longer present. The two remaining <allow> entries map precisely to what the production sources (CpuMetrics, MemoryMetrics, OshiMetrics) actually import.

One tiny nitpick for awareness: Checkstyle's import-control pkg attribute uses prefix matching, so io.micrometer.core.instrument already covers io.micrometer.core.instrument.binder.* by default. The second line is technically redundant — but keeping it is perfectly fine for readability and consistency with the style used elsewhere in this file (e.g., com.sun.jna alongside its many sub-package entries).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@config/import-control.xml` around lines 111 - 115, The import-control has a
redundant allow entry: within the <subpackage name="metrics"> the line <allow
pkg="io.micrometer.core.instrument.binder" /> is unnecessary because <allow
pkg="io.micrometer.core.instrument" /> already permits that subpackage via
prefix matching; remove the redundant <allow
pkg="io.micrometer.core.instrument.binder" /> (or optionally leave it for
explicitness) so only the broad io.micrometer.core.instrument allow remains in
the metrics subpackage.
oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java (1)

60-67: ⚖️ Poor tradeoff

Each FunctionCounter independently calls getSystemCpuLoadTicks() — consider caching the snapshot

With the current setup, Micrometer invokes each of the 8 lambdas separately at every scrape interval. Since getSystemCpuLoadTicks() makes a fresh OS-level query each time, this results in 8 separate native calls per scrape with values from 8 slightly different time points.

In practice the drift between calls is negligible, but it does mean the 8 mode values in any given scrape are not from an atomic snapshot. A common pattern to address both the syscall overhead and the consistency gap is to bind all counters against a shared, lazily-refreshed long[] supplier:

♻️ Sketch of a cached-snapshot approach
-    private final CentralProcessor processor;
+    private final CentralProcessor processor;
+    // Holds the most-recently fetched tick array; updated once per bindTo call cycle.
+    // Each FunctionCounter reads from the same array instance.
+    private volatile long[] cachedTicks;

     `@Override`
     public void bindTo(MeterRegistry registry) {
+        // Seed the cache so the first scrape has a valid baseline.
+        this.cachedTicks = processor.getSystemCpuLoadTicks();
         for (TickType type : TickType.values()) {
             int index = type.getIndex();
             String mode = TICK_TO_MODE.get(type);
-            FunctionCounter.builder(CPU_TIME, processor, p -> p.getSystemCpuLoadTicks()[index] / MS_PER_SECOND)
+            FunctionCounter.builder(CPU_TIME, this, self -> self.cachedTicks[index] / MS_PER_SECOND)
                     .tag(CPU_MODE_KEY, mode).description("System CPU time spent in " + mode + " mode").baseUnit("s")
                     .register(registry);
         }
     }
+
+    /** Call this on a periodic basis (e.g. from a scheduled task) to refresh all counters atomically. */
+    public void refresh() {
+        this.cachedTicks = processor.getSystemCpuLoadTicks();
+    }

Note: full atomic consistency would also require using an AtomicReference<long[]> for the cached array and a single refresh that all 8 counters read within the same Micrometer polling cycle. This is a follow-up concern for the next iteration of the module.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java` around lines 60 -
67, The FunctionCounter lambdas in bindTo currently call
processor.getSystemCpuLoadTicks() separately for each TickType, causing multiple
native queries per scrape; change to capture a shared, lazily-refreshed snapshot
(long[]), e.g. add a supplier/cachedTicks (backed by an AtomicReference<long[]>
or similar) that refreshes once per Micrometer polling cycle and have each
FunctionCounter.builder(CPU_TIME, processor, p -> ...) read the corresponding
index from that cached snapshot (divide by MS_PER_SECOND as before) so all
TickType counters use the same atomic snapshot and avoid repeated OS calls.
🤖 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-metrics/src/main/java/oshi/metrics/CpuMetrics.java`:
- Around line 61-67: The loop in CpuMetrics that iterates over TickType.values()
uses TICK_TO_MODE.get(type) which can be null for new TickType entries and cause
an NPE when calling FunctionCounter.builder(...).tag(CPU_MODE_KEY, mode); change
the code in the for-loop (inside class CpuMetrics where the FunctionCounter
builders are registered) to compute mode = TICK_TO_MODE.get(type); and if that
returns null fall back to type.name().toLowerCase() (or similar deterministic
string) before calling .tag(...), so the register loop never passes a null tag
value.

---

Nitpick comments:
In `@config/import-control.xml`:
- Around line 111-115: The import-control has a redundant allow entry: within
the <subpackage name="metrics"> the line <allow
pkg="io.micrometer.core.instrument.binder" /> is unnecessary because <allow
pkg="io.micrometer.core.instrument" /> already permits that subpackage via
prefix matching; remove the redundant <allow
pkg="io.micrometer.core.instrument.binder" /> (or optionally leave it for
explicitness) so only the broad io.micrometer.core.instrument allow remains in
the metrics subpackage.

In `@oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java`:
- Around line 60-67: The FunctionCounter lambdas in bindTo currently call
processor.getSystemCpuLoadTicks() separately for each TickType, causing multiple
native queries per scrape; change to capture a shared, lazily-refreshed snapshot
(long[]), e.g. add a supplier/cachedTicks (backed by an AtomicReference<long[]>
or similar) that refreshes once per Micrometer polling cycle and have each
FunctionCounter.builder(CPU_TIME, processor, p -> ...) read the corresponding
index from that cached snapshot (divide by MS_PER_SECOND as before) so all
TickType counters use the same atomic snapshot and avoid repeated OS calls.
🪄 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: 76c2b233-0f61-43d8-add9-79b63e7d9ca5

📥 Commits

Reviewing files that changed from the base of the PR and between 2a6bc8b and 0dfe9a6.

📒 Files selected for processing (17)
  • CHANGELOG.md
  • config/import-control-test.xml
  • config/import-control.xml
  • oshi-benchmark/pom.xml
  • oshi-common/pom.xml
  • oshi-core-ffm/pom.xml
  • oshi-core/pom.xml
  • oshi-demo/pom.xml
  • oshi-dist/pom.xml
  • oshi-metrics/pom.xml
  • oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/package-info.java
  • oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java
  • oshi-metrics/src/test/java/oshi/metrics/PrometheusDemoTest.java
  • pom.xml
✅ Files skipped from review due to trivial changes (9)
  • oshi-dist/pom.xml
  • oshi-common/pom.xml
  • oshi-core-ffm/pom.xml
  • oshi-core/pom.xml
  • oshi-demo/pom.xml
  • oshi-metrics/src/main/java/oshi/metrics/package-info.java
  • oshi-benchmark/pom.xml
  • config/import-control-test.xml
  • oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java
🚧 Files skipped from review as they are similar to previous changes (5)
  • oshi-metrics/pom.xml
  • oshi-metrics/src/test/java/oshi/metrics/PrometheusDemoTest.java
  • pom.xml
  • oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java
  • oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.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 21, windows-latest
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • 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, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
🧰 Additional context used
🪛 markdownlint-cli2 (0.22.1)
CHANGELOG.md

[warning] 3-3: Heading levels should only increment by one level at a time
Expected: h2; Actual: h5

(MD001, heading-increment)

🔇 Additional comments (2)
CHANGELOG.md (1)

1-6: LGTM! Changelog entries are well-formatted and accurate.

The new 7.1.0 release section properly documents the oshi-metrics module with Micrometer integration and the CgroupInfo API. The entries follow the established format with proper issue links, backticks for code elements, and contributor attribution. The metric names (system.cpu.time, system.memory.usage, system.memory.utilization) and feature descriptions align perfectly with the PR objectives.

oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java (1)

29-57: Solid overall structure — good use of FunctionCounter and EnumMap

FunctionCounter is the right choice here as it tracks a monotonically increasing function, and getSystemCpuLoadTicks() returns cumulative milliseconds per mode since boot, which is exactly that contract. The ÷ 1000.0 conversion and baseUnit("s") correctly align with the OpenTelemetry system.cpu.time (seconds) convention. Using EnumMap for TICK_TO_MODE is idiomatic and efficient for an enum-keyed lookup.

@dbwiddis
dbwiddis force-pushed the feature/oshi-metrics branch from 0dfe9a6 to 605257e Compare May 4, 2026 05:54

@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)
pom.xml (1)

747-747: Consider replacing the package-wide exclusion with explicit Micrometer and Sun HTTP Server imports.

Great idea enabling the module! Rather than excluding oshi.metrics.** (which disables import guardrails for the entire package), we can be more precise. Verification found the module needs io.micrometer.* classes plus com.sun.net.httpserver.HttpServer, so let's add just those to the allowlist:

Suggested config
                                 <allowedImports>
                                     <!-- Allow oshi itself :-) -->
                                     <allowedImport>oshi.**</allowedImport>
                                     <!-- Allow core Java usage -->
                                     <allowedImport>java.**</allowedImport>
+                                    <!-- Allow Micrometer APIs used by oshi-metrics -->
+                                    <allowedImport>io.micrometer.**</allowedImport>
+                                    <!-- Allow Sun HTTP server for oshi-metrics demo -->
+                                    <allowedImport>com.sun.net.httpserver.**</allowedImport>
                                     <!-- Allow known dependencies -->
                                     <allowedImport>com.sun.jna.**</allowedImport>
                                     <allowedImport>io.github.pandalxb.jlibrehardwaremonitor.**</allowedImport>
                                     <allowedImport>org.slf4j.**</allowedImport>
                                     <allowedImport>org.junit.jupiter.api.**</allowedImport>
                                     <allowedImport>static org.hamcrest.**</allowedImport>
                                 </allowedImports>
@@
                                     <exclusions>
                                         <exclusion>oshi.demo.**</exclusion>
                                         <exclusion>oshi.benchmark.**</exclusion>
                                         <exclusion>oshi.comparison.**</exclusion>
-                                        <exclusion>oshi.metrics.**</exclusion>
                                     </exclusions>
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pom.xml` at line 747, Remove the broad package exclusion "oshi.metrics.**"
and replace it with explicit allowlist entries for the Micrometer and Sun HTTP
Server packages; specifically, stop excluding oshi.metrics.** and instead add
explicit imports/permissions for io.micrometer.* (all required Micrometer
classes) and com.sun.net.httpserver.HttpServer so the module guardrails permit
only those classes; update the POM section that contains the
<exclusion>oshi.metrics.**</exclusion> to remove that line and add allowlist
entries referencing io.micrometer.* and com.sun.net.httpserver.HttpServer.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@pom.xml`:
- Line 747: Remove the broad package exclusion "oshi.metrics.**" and replace it
with explicit allowlist entries for the Micrometer and Sun HTTP Server packages;
specifically, stop excluding oshi.metrics.** and instead add explicit
imports/permissions for io.micrometer.* (all required Micrometer classes) and
com.sun.net.httpserver.HttpServer so the module guardrails permit only those
classes; update the POM section that contains the
<exclusion>oshi.metrics.**</exclusion> to remove that line and add allowlist
entries referencing io.micrometer.* and com.sun.net.httpserver.HttpServer.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 24bdd86d-85c9-447e-b26a-af18352da129

📥 Commits

Reviewing files that changed from the base of the PR and between 0dfe9a6 and 605257e.

📒 Files selected for processing (17)
  • CHANGELOG.md
  • config/import-control-test.xml
  • config/import-control.xml
  • oshi-benchmark/pom.xml
  • oshi-common/pom.xml
  • oshi-core-ffm/pom.xml
  • oshi-core/pom.xml
  • oshi-demo/pom.xml
  • oshi-dist/pom.xml
  • oshi-metrics/pom.xml
  • oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/package-info.java
  • oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java
  • oshi-metrics/src/test/java/oshi/metrics/PrometheusDemoTest.java
  • pom.xml
✅ Files skipped from review due to trivial changes (7)
  • oshi-dist/pom.xml
  • oshi-common/pom.xml
  • oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java
  • oshi-benchmark/pom.xml
  • oshi-demo/pom.xml
  • oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java
  • config/import-control-test.xml
🚧 Files skipped from review as they are similar to previous changes (7)
  • oshi-core/pom.xml
  • config/import-control.xml
  • oshi-core-ffm/pom.xml
  • oshi-metrics/src/main/java/oshi/metrics/package-info.java
  • oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java
  • oshi-metrics/pom.xml
  • oshi-metrics/src/test/java/oshi/metrics/PrometheusDemoTest.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). (12)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: Analyze (java)
🧰 Additional context used
🪛 markdownlint-cli2 (0.22.1)
CHANGELOG.md

[warning] 3-3: Heading levels should only increment by one level at a time
Expected: h2; Actual: h5

(MD001, heading-increment)

🔇 Additional comments (4)
CHANGELOG.md (1)

1-6: Changelog update looks good.

The new 7.1.0 in-progress entries are clear, scoped, and consistent with the project’s existing changelog format.

oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java (1)

61-67: CPU metric binding is solid.

Good use of per-TickType counters with stable cpu.mode tags, and the fallback mode mapping prevents null tag values during registration.

pom.xml (2)

7-7: Version bump is consistent with the new module rollout.

Nice update—this keeps the parent version aligned with the new oshi-metrics module lineage.


1024-1033: JDK-gated module inclusion looks correct.

This profile cleanly introduces oshi-metrics only on Java 17+, which keeps older JDK builds stable while enabling the new module where supported.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

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

Inline comments:
In `@oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java`:
- Around line 74-75: The description for the meter registered on system.cpu.time
incorrectly claims per-logical-CPU granularity; update the .description(...)
call (the builder that uses CPU_MODE_KEY and registers to registry) to a
concise, accurate string such as "Seconds spent in each CPU mode" or "Seconds
spent in each CPU mode (aggregated)", so the meter (system.cpu.time) no longer
implies per-CPU tagging.
🪄 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: 6a609996-f99d-4241-92de-72e026808237

📥 Commits

Reviewing files that changed from the base of the PR and between 605257e and 0c7d6d2.

📒 Files selected for processing (5)
  • oshi-metrics/README.md
  • oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/GeneralMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java
  • oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java
✅ Files skipped from review due to trivial changes (2)
  • oshi-metrics/README.md
  • oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.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: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Analyze (java)
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (3)
oshi-metrics/src/main/java/oshi/metrics/GeneralMetrics.java (1)

39-43: Clean and focused binder implementation.

Nice addition—this keeps system.uptime registration simple and readable.

oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java (1)

70-73: Great defensive handling for future TickType additions.

Using a stable fallback mode value here is a solid robustness improvement.

oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java (1)

61-66: Nice binder composition in the entry point.

This keeps the module integration easy to follow and easy to extend as new metric groups land.

@dbwiddis
dbwiddis force-pushed the feature/oshi-metrics branch from 0c7d6d2 to 355a5b3 Compare May 5, 2026 16:48

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

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

Inline comments:
In `@oshi-metrics/src/main/java/oshi/metrics/PagingMetrics.java`:
- Around line 57-59: The meter description string incorrectly lowercases
"Windows"; update the two Gauge.builder description calls that build the
system.paging.usage gauges (the lines using Gauge.builder(PAGING_USAGE, vm, v ->
v.getSwapTotal() - v.getSwapUsed()) and the similar free-usage builder using
v.getSwapTotal() - v.getSwapUsed()) to use "Unix swap or Windows pagefile usage"
(capitalize "Windows") so the exported /metrics text is correct.

In `@oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java`:
- Around line 69-70: The assertions in OshiMetricsTest.java that check usedVal
and freeVal currently use strict bounds (usedVal > 0 && usedVal < 1) which can
be flaky on CI; update the checks in the test method to use inclusive bounds
(usedVal >= 0 && usedVal <= 1 and freeVal >= 0 && freeVal <= 1) so they match
the paging utilization assertions and avoid false failures when values round to
exactly 0 or 1.
🪄 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: a84fed98-92d6-4a6a-9a0c-56b355b4c566

📥 Commits

Reviewing files that changed from the base of the PR and between 605257e and 355a5b3.

📒 Files selected for processing (7)
  • oshi-metrics/README.md
  • oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/GeneralMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/PagingMetrics.java
  • oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java
✅ Files skipped from review due to trivial changes (2)
  • oshi-metrics/README.md
  • oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java
🚧 Files skipped from review as they are similar to previous changes (2)
  • oshi-metrics/src/main/java/oshi/metrics/GeneralMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.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 comments (3)
oshi-metrics/src/main/java/oshi/metrics/PagingMetrics.java (1)

54-73: Overall bindTo implementation looks solid — nice work!

The zero-guard on getSwapTotal() in both utilization gauges is the right call (consistent with MemoryMetrics), and using FunctionCounter for the cumulative getSwapPagesIn/getSwapPagesOut values is exactly the right Micrometer primitive.

oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java (1)

47-61: All previously flagged issues have been addressed — bindTo looks great!

The zero-guard on getTotal() for both utilization gauges and the corrected Javadoc ("fraction" instead of "percentage") are exactly right.

oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java (1)

28-35: The overall test structure and coverage are excellent — great job!

The @BeforeAll shared-registry setup is clean, the previously flagged NPE on the idle counter (now stored as idleCounter with its own assertNotNull) is handled properly, and the paging tests correctly use inclusive >= 0 && <= 1 bounds and allow zero swap counts for systems with no swap configured.

Also applies to: 73-83, 111-142

@dbwiddis
dbwiddis force-pushed the feature/oshi-metrics branch 2 times, most recently from 753027e to 9539f34 Compare May 5, 2026 17:40
@dbwiddis

dbwiddis commented May 5, 2026

Copy link
Copy Markdown
Member Author

@CodeRabbit full review

@coderabbitai

coderabbitai Bot commented May 5, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Full review triggered.

1 similar comment
@coderabbitai

coderabbitai Bot commented May 5, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Full review triggered.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (4)
oshi-metrics/src/main/java/oshi/metrics/FileSystemMetrics.java (1)

51-53: 💤 Low value

bindTo registers a fixed snapshot — consider documenting the limitation.

fileStoreSupplier.get() is called exactly once when bindTo runs. Filesystems mounted after that point won't gain meters, and (with strongReference(true)) meters for filesystems unmounted later will keep reporting stale values. This is a common pattern for MeterBinder implementations (analogous to how JVM disk metrics work), but it's worth a short Javadoc note so users aren't surprised.

📝 Suggested Javadoc addition on the class
 /**
  * {`@link` MeterBinder} for system filesystem metrics following
  * ...
  *
  * <p>
+ * Note: filesystems are enumerated once at {`@link` `#bindTo`(MeterRegistry)} time.
+ * Filesystems mounted after that call will not be tracked automatically;
+ * create and bind a new instance to capture them.
+ * </p>
  * Registers per filesystem:
🤖 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-metrics/src/main/java/oshi/metrics/FileSystemMetrics.java` around lines
51 - 53, Add a short Javadoc on FileSystemMetrics explaining that bindTo calls
fileStoreSupplier.get() exactly once (in bindTo) producing a fixed snapshot of
filesystems: files mounted after bind won't get meters and files unmounted later
may leave stale meters if strongReference(true) is used; mention this is
intentional/common, and suggest alternatives (provide a dynamic supplier,
rebind, or use weak references) and reference the bindTo method,
fileStoreSupplier.get(), and strongReference(true) so callers understand the
limitation and workarounds.
oshi-metrics/src/main/java/oshi/metrics/NetworkMetrics.java (1)

106-127: 🏗️ Heavy lift

getConnections() is called once per TCP state per scrape — consider batching.

countConnections calls ip.getConnections() on every invocation. With 11 non-NONE TcpState values plus 1 UDP gauge, each metrics scrape triggers 12 independent OS-level queries (reading /proc/net/tcp* on Linux, calling GetExtendedTcpTable/GetExtendedUdpTable on Windows). For systems with thousands of open connections, this is also O(N × M) on the stream filters.

A lightweight fix is to compute all state counts in a single pass from one getConnections() call at scrape time. One idiomatic approach uses MultiGauge refreshed periodically, or a simple volatile-cached map:

// Sketch — capture once per scrape with a short-lived cache
private volatile long cacheTs = 0;
private volatile Map<String, Long> cachedCounts = Map.of();

private long cachedCount(String transport, TcpState state) {
    long now = System.currentTimeMillis();
    if (now - cacheTs > 1_000) {
        Map<String, Long> fresh = computeAllCounts(ipStats.getConnections());
        cachedCounts = fresh;
        cacheTs = now;
    }
    return cachedCounts.getOrDefault(key(transport, state), 0L);
}

The simplest alternative is a MultiGauge that's refreshed externally on each collection. Either way, reducing 12 syscalls per scrape to 1 is worthwhile.

🤖 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-metrics/src/main/java/oshi/metrics/NetworkMetrics.java` around lines 106
- 127, The current implementation calls InternetProtocolStats.getConnections()
inside countConnections() for every Gauge (via registerConnectionCountGauges),
causing N syscalls per scrape; fix by batching a single getConnections() per
scrape and computing all transport/state counts once. Add a scrape-cache (e.g.,
volatile cacheTs and cachedCounts) and a helper
computeAllCounts(List<IPConnection>) or
computeAllCountsFromIp(InternetProtocolStats) that builds a Map keyed by
transport+state; then change the Gauge callbacks in
registerConnectionCountGauges to read from the cachedCounts (via a
cachedCount(key) accessor) instead of calling countConnections() which should be
replaced to use the cache or removed. Ensure cache validity is short-lived
(e.g., milliseconds/seconds) so each scrape uses one getConnections() call.
oshi-metrics/pom.xml (1)

74-75: ⚡ Quick win

Prefer keeping forbidden-apis checks enabled for the new module.

Lines 74-75 fully disable forbiddenapis, which reduces static guardrails for a newly introduced public module. A better tradeoff is to keep checks on and add targeted suppressions only where needed.

🤖 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-metrics/pom.xml` around lines 74 - 75, The POM currently disables the
forbidden-apis check by setting <skip>true</skip>; revert this by removing or
changing that element to keep the forbidden-apis plugin active (look for the
forbidden-apis / forbiddenapis-maven-plugin plugin configuration and its <skip>
flag) and instead add targeted suppressions via the plugin's suppression file or
<excludes>/<suppressions> entries for the specific false positives; ensure the
plugin runs in validate/verify phases so the new public module retains static
API checks.
oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java (1)

73-75: ⚡ Quick win

Add fail-fast null guards for hal/os in public API entry points.

Failing early with clear messages makes integration errors much easier to diagnose than deferred NPEs during bindTo().

Suggested change
+import java.util.Objects;
+
 import oshi.hardware.HardwareAbstractionLayer;
 import oshi.software.os.OperatingSystem;
@@
     public OshiMetrics(HardwareAbstractionLayer hal, OperatingSystem os) {
-        this.hal = hal;
-        this.os = os;
+        this.hal = Objects.requireNonNull(hal, "hal must not be null");
+        this.os = Objects.requireNonNull(os, "os must not be null");
         this.general = true;
@@
         private Builder(HardwareAbstractionLayer hal, OperatingSystem os) {
-            this.hal = hal;
-            this.os = os;
+            this.hal = Objects.requireNonNull(hal, "hal must not be null");
+            this.os = Objects.requireNonNull(os, "os must not be null");
         }

Also applies to: 155-157

🤖 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-metrics/src/main/java/oshi/metrics/OshiMetrics.java` around lines 73 -
75, Add fail-fast null guards for the public API by validating constructor
parameters in OshiMetrics: in the OshiMetrics(HardwareAbstractionLayer hal,
OperatingSystem os) constructor use Objects.requireNonNull (or explicit checks)
to throw a clear NPE/IllegalArgumentException with messages like "hal must not
be null" and "os must not be null"; do the same for the other public entry that
accepts hal/os (the public method/constructor around lines 155-157) and for the
public bindTo(...) entry that uses these fields so callers get immediate,
descriptive errors instead of deferred NPEs.
🤖 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-metrics/pom.xml`:
- Around line 30-34: The pom currently declares io.micrometer:micrometer-core
with <scope>provided</scope>, which will break any consumer compiling against
this module because public API types (e.g., classes implementing MeterBinder
such as OshiMetrics, CpuMetrics, MemoryMetrics, GeneralMetrics,
FileSystemMetrics, NetworkMetrics, DiskMetrics, PagingMetrics, ProcessMetrics)
reference Micrometer types; change the dependency scope to a compile-time
dependency (remove or replace <scope>provided</scope> with the default compile
scope) or mark it as <optional>true</optional> depending on your intended
contract, and update module documentation/README to state whether downstream
projects must declare micrometer-core themselves if you choose optional.

In `@oshi-metrics/src/main/java/oshi/metrics/DiskMetrics.java`:
- Around line 61-87: The HWDiskStore getters used by FunctionCounter.builder
(e.g., HWDiskStore::getReadBytes, HWDiskStore::getWriteBytes, and the lambda for
getTransferTime) return snapshot values and must be refreshed; call
HWDiskStore.updateAttributes() for each disk from diskStoreSupplier.get() before
registering or sampling metrics (or wrap the counters' value suppliers to call
updateAttributes() then return the desired getter), so that DISK_IO,
DISK_OPERATIONS, DISK_IO_TIME and the Gauge for DISK_LIMIT use up-to-date values
from each HWDiskStore.

In `@oshi-metrics/src/main/java/oshi/metrics/GeneralMetrics.java`:
- Around line 45-46: The Gauge for PROCESS_COUNT (Gauge.builder(PROCESS_COUNT,
os, OperatingSystem::getProcessCount) in GeneralMetrics.java) has a misleading
description "Total number of processes in each state"; update the description to
accurately reflect the metric's granularity (e.g., "Total number of processes"
or similar) so it does not imply per-state counts. Ensure the updated
description string replaces the existing one in the Gauge.builder call.

In `@oshi-metrics/src/main/java/oshi/metrics/NetworkMetrics.java`:
- Around line 53-54: The FunctionCounter uses weak refs so you must keep a
strong reference to the collected NetworkIF instances in the NetworkMetrics
class: add a field like List<NetworkIF> networkIFs (or similar) and when you
call networkIFSupplier.get() (the place where you build per-interface counters
using FunctionCounter.builder(...)) assign the returned list to this.networkIFs
before binding the counters; continue to use that stored list as the state
object passed into FunctionCounter.builder so the monitored NetworkIFs are not
garbage-collected (note Gauge already used .strongReference(true) but
FunctionCounter requires the caller to hold the strong reference).

---

Nitpick comments:
In `@oshi-metrics/pom.xml`:
- Around line 74-75: The POM currently disables the forbidden-apis check by
setting <skip>true</skip>; revert this by removing or changing that element to
keep the forbidden-apis plugin active (look for the forbidden-apis /
forbiddenapis-maven-plugin plugin configuration and its <skip> flag) and instead
add targeted suppressions via the plugin's suppression file or
<excludes>/<suppressions> entries for the specific false positives; ensure the
plugin runs in validate/verify phases so the new public module retains static
API checks.

In `@oshi-metrics/src/main/java/oshi/metrics/FileSystemMetrics.java`:
- Around line 51-53: Add a short Javadoc on FileSystemMetrics explaining that
bindTo calls fileStoreSupplier.get() exactly once (in bindTo) producing a fixed
snapshot of filesystems: files mounted after bind won't get meters and files
unmounted later may leave stale meters if strongReference(true) is used; mention
this is intentional/common, and suggest alternatives (provide a dynamic
supplier, rebind, or use weak references) and reference the bindTo method,
fileStoreSupplier.get(), and strongReference(true) so callers understand the
limitation and workarounds.

In `@oshi-metrics/src/main/java/oshi/metrics/NetworkMetrics.java`:
- Around line 106-127: The current implementation calls
InternetProtocolStats.getConnections() inside countConnections() for every Gauge
(via registerConnectionCountGauges), causing N syscalls per scrape; fix by
batching a single getConnections() per scrape and computing all transport/state
counts once. Add a scrape-cache (e.g., volatile cacheTs and cachedCounts) and a
helper computeAllCounts(List<IPConnection>) or
computeAllCountsFromIp(InternetProtocolStats) that builds a Map keyed by
transport+state; then change the Gauge callbacks in
registerConnectionCountGauges to read from the cachedCounts (via a
cachedCount(key) accessor) instead of calling countConnections() which should be
replaced to use the cache or removed. Ensure cache validity is short-lived
(e.g., milliseconds/seconds) so each scrape uses one getConnections() call.

In `@oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java`:
- Around line 73-75: Add fail-fast null guards for the public API by validating
constructor parameters in OshiMetrics: in the
OshiMetrics(HardwareAbstractionLayer hal, OperatingSystem os) constructor use
Objects.requireNonNull (or explicit checks) to throw a clear
NPE/IllegalArgumentException with messages like "hal must not be null" and "os
must not be null"; do the same for the other public entry that accepts hal/os
(the public method/constructor around lines 155-157) and for the public
bindTo(...) entry that uses these fields so callers get immediate, descriptive
errors instead of deferred NPEs.
🪄 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: d03458aa-8661-41d2-8446-7f898d49271f

📥 Commits

Reviewing files that changed from the base of the PR and between 27528a4 and d7c5a8f.

📒 Files selected for processing (24)
  • CHANGELOG.md
  • config/import-control-test.xml
  • config/import-control.xml
  • oshi-benchmark/pom.xml
  • oshi-common/pom.xml
  • oshi-core-ffm/pom.xml
  • oshi-core/pom.xml
  • oshi-demo/pom.xml
  • oshi-dist/pom.xml
  • oshi-metrics/README.md
  • oshi-metrics/pom.xml
  • oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/DiskMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/FileSystemMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/GeneralMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/NetworkMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/PagingMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/package-info.java
  • oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java
  • oshi-metrics/src/test/java/oshi/metrics/PrometheusDemoTest.java
  • pom.xml
📜 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
🪛 markdownlint-cli2 (0.22.1)
CHANGELOG.md

[warning] 3-3: Heading levels should only increment by one level at a time
Expected: h2; Actual: h5

(MD001, heading-increment)

🔇 Additional comments (17)
oshi-metrics/src/main/java/oshi/metrics/package-info.java (1)

1-9: Welcome aboard, and great start with the package docs! 🎉

The license header, Javadoc, and package declaration all look correct and complete.

config/import-control.xml (1)

111-115: Import allowances look clean.

Only io.micrometer.core.instrument and io.micrometer.core.instrument.binder are permitted for production sources — the test-only packages that were flagged earlier are correctly absent.

CHANGELOG.md (1)

1-6: Changelog entry looks good.

The new 7.1.0 (in progress) entries accurately describe the oshi-metrics module and the CgroupInfo API addition.

oshi-metrics/src/main/java/oshi/metrics/PagingMetrics.java (1)

53-74: Implementation looks correct.

The "Windows" capitalization fix is in place, divide-by-zero guard matches MemoryMetrics style, and vm being a class field ensures the FunctionCounter's weak reference has a backing strong reference.

oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java (1)

47-61: All previous feedback addressed, implementation looks solid.

Divide-by-zero guard is in place, Javadoc accurately describes the fraction range, and the used+free utilization fractions correctly sum to 1.0.

oshi-benchmark/pom.xml (1)

8-8: Simple version bump — looks correct.

Aligns oshi-benchmark's parent version with the project-wide 7.1.0-SNAPSHOT bump.

oshi-core/pom.xml (1)

8-8: Version bump is consistent and clean.

Line 8 correctly aligns this module with the 7.1.0-SNAPSHOT parent version used in the PR.

oshi-dist/pom.xml (1)

8-8: Looks good — parent version alignment only.

Line 8 updates the parent version consistently with the rest of the multi-module bump.

oshi-demo/pom.xml (1)

8-8: Nice, this is a safe version sync.

Line 8 cleanly updates oshi-demo to the new parent version without changing module behavior.

oshi-core-ffm/pom.xml (1)

8-8: Good update for module consistency.

Line 8 keeps oshi-core-ffm aligned with the repository-wide 7.1.0-SNAPSHOT version bump.

oshi-common/pom.xml (1)

8-8: LGTM on the parent version bump.

Line 8 is consistent with the global 7.1.0-SNAPSHOT transition.

config/import-control-test.xml (1)

50-58: Good scoped import-control update for metrics tests.

The new metrics subpackage block keeps additional Micrometer/HTTP imports localized to test scope instead of broadening global allowances.

pom.xml (3)

7-7: Root version bump is correct.

Line 7 cleanly advances the parent project to 7.1.0-SNAPSHOT.


747-747: Import restriction exclusion is appropriately targeted.

Line 747 excludes oshi.metrics.**, which is reasonable given the new module’s dependency surface and separate import-control rules.


1024-1033: Java 17 profile wiring for oshi-metrics looks solid.

The new profile at Lines 1024-1033 correctly gates module inclusion by JDK level and keeps older JDK builds unaffected.

oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java (1)

70-97: Nice defensive CPU metric registration.

Great call using getOrDefault(...) for TickType mapping and guarding frequency array access with a bounds check; this keeps registration robust across platform/API variance.

oshi-metrics/src/test/java/oshi/metrics/PrometheusDemoTest.java (1)

58-63: Prometheus scrape response handling looks solid now.

Using UTF-8 bytes, explicit Prometheus Content-Type, and byte-accurate Content-Length is the right shape for scrapers.

Comment thread oshi-metrics/pom.xml
Comment on lines +30 to +34
<groupId>io.micrometer</groupId>
<artifactId>micrometer-core</artifactId>
<version>${micrometer.version}</version>
<scope>provided</scope>
</dependency>

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify whether public API in oshi-metrics exposes Micrometer types
rg -n --type=java -C2 'public (class|interface|record)|implements\s+MeterBinder|import io\.micrometer' oshi-metrics/src/main/java
rg -n -C2 '<artifactId>micrometer-core</artifactId>|<scope>provided</scope>' oshi-metrics/pom.xml

Repository: oshi/oshi

Length of output: 10950


micrometer-core with provided scope will break downstream consumers depending on this module's public API.

This module's public API extensively exposes Micrometer types through 9 public classes implementing MeterBinder (OshiMetrics, CpuMetrics, MemoryMetrics, GeneralMetrics, FileSystemMetrics, NetworkMetrics, DiskMetrics, PagingMetrics, and ProcessMetrics). When a dependency is declared with provided scope, it is not transitively available to consumers. This means anyone trying to use these public classes will encounter compile errors unless they explicitly add micrometer-core to their own dependencies.

For a module exposing a rich public API that depends on a framework library, consider using compile scope or optional (depending on your intended contract) and documenting the dependency expectations. This prevents downstream surprises and friction.

🤖 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-metrics/pom.xml` around lines 30 - 34, The pom currently declares
io.micrometer:micrometer-core with <scope>provided</scope>, which will break any
consumer compiling against this module because public API types (e.g., classes
implementing MeterBinder such as OshiMetrics, CpuMetrics, MemoryMetrics,
GeneralMetrics, FileSystemMetrics, NetworkMetrics, DiskMetrics, PagingMetrics,
ProcessMetrics) reference Micrometer types; change the dependency scope to a
compile-time dependency (remove or replace <scope>provided</scope> with the
default compile scope) or mark it as <optional>true</optional> depending on your
intended contract, and update module documentation/README to state whether
downstream projects must declare micrometer-core themselves if you choose
optional.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

♻️ Duplicate comments (3)
oshi-metrics/src/main/java/oshi/metrics/GeneralMetrics.java (1)

45-46: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Misleading description on system.process.count gauge still present.

This was flagged in a previous review — the description "Total number of processes in each state" implies per-state granularity, but the gauge has no state tag and reports a single total. The fix is straightforward.

✏️ Proposed fix
-        Gauge.builder(PROCESS_COUNT, os, OperatingSystem::getProcessCount)
-                .description("Total number of processes in each state").baseUnit("{process}").register(registry);
+        Gauge.builder(PROCESS_COUNT, os, OperatingSystem::getProcessCount)
+                .description("Total number of processes").baseUnit("{process}").register(registry);
🤖 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-metrics/src/main/java/oshi/metrics/GeneralMetrics.java` around lines 45
- 46, The gauge built with Gauge.builder(PROCESS_COUNT, os,
OperatingSystem::getProcessCount) has a misleading description "Total number of
processes in each state" even though it reports a single total without any state
tag; update the description to accurately reflect the metric (for example "Total
number of processes" or "Total number of processes on the system") in the
Gauge.builder(...) call (leave baseUnit and registry as-is), or alternatively
add appropriate state tagging if you intend per-state counts.
oshi-metrics/pom.xml (1)

29-34: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

micrometer-core with provided scope exposes a public-API dependency gap.

Since all 9 public classes in oshi-metrics implement MeterBinder (a Micrometer type), consumers cannot compile against this module without explicitly declaring micrometer-core themselves — Maven provided is non-transitive. Depending on the intended contract, compile scope or <optional>true</optional> should be considered, with the README updated to clarify the expectation.

🤖 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-metrics/pom.xml` around lines 29 - 34, The pom currently declares the
micrometer dependency with scope "provided", causing a public API leak because
oshi-metrics' public classes implement
io.micrometer.core.instrument.binder.MeterBinder; change the dependency
declaration for artifactId "micrometer-core" (in the oshi-metrics module) to a
compile-scoped dependency (or set <optional>true</optional> if you intend
consumers to opt-in) so consumers can compile without adding Micrometer
themselves, and update the README to document the chosen contract (that
Micrometer is required at compile/runtime or is optional).
oshi-metrics/src/main/java/oshi/metrics/DiskMetrics.java (1)

61-87: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

HWDiskStore getters return stale snapshot data without updateAttributes() — still unresolved.

The FunctionCounter lambdas (getReadBytes, getWriteBytes, getReads, getWrites, getTransferTime) read cached values; they won't reflect current disk activity until updateAttributes() is called on each HWDiskStore. As currently written, metrics will report the values captured at bind time on every subsequent poll.

Embedding updateAttributes() inside each lambda would refresh per-metric, but since there are 4–5 counters per disk, that's 4–5 system calls per poll per disk instead of one. A shared-refresh wrapper (calling updateAttributes() once then returning the desired value) would be more efficient.

🤖 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-metrics/src/main/java/oshi/metrics/DiskMetrics.java` around lines 61 -
87, The lambdas passed to FunctionCounter.builder and Gauge.builder are reading
stale HWDiskStore snapshots because updateAttributes() is never called; to fix,
create a small shared-refresh wrapper for each HWDiskStore in the loop that
calls disk.updateAttributes() once and then returns the requested value (e.g., a
helper method or Supplier that accepts HWDiskStore and a value-extractor like
HWDiskStore::getReadBytes/getWriteBytes/getReads/getWrites/getTransferTime/getSize),
and use that wrapper in place of the direct getters when constructing the
counters (refer to the loop over diskStoreSupplier.get(), the HWDiskStore
variable disk, and the
FunctionCounter.builder(DISK_IO/DISK_OPERATIONS/DISK_IO_TIME) and
Gauge.builder(DISK_LIMIT) invocations).
🧹 Nitpick comments (5)
oshi-dist/pom.xml (1)

17-39: oshi-metrics is not included in the oshi-dist assembly ordering dependencies.

Since oshi-metrics is a separately released artifact with a provided-scope Micrometer dependency, this is likely intentional — consumers bring their own Micrometer. If the intention is to ship the oshi-metrics jar as part of the distribution archive in future, a dependency entry would need to be added here.

🤖 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-dist/pom.xml` around lines 17 - 39, The pom dependency list for the
oshi-dist assembly is missing the oshi-metrics artifact so it won't be sorted
into the multimodule assembly; add a dependency entry for artifactId
"oshi-metrics" (with groupId ${project.groupId} and version ${project.version})
to the <dependencies> block in the oshi-dist pom.xml so the metrics JAR is
included in the distribution ordering if you intend to ship it.
oshi-metrics/pom.xml (1)

70-76: ⚡ Quick win

Blanket forbiddenapis skip removes all API-safety enforcement from this module.

Other OSHI modules (e.g., oshi-common) apply granular bundledSignatures such as jdk-unsafe, jdk-deprecated, and jdk-system-out. oshi-metrics has no reason to exempt itself from those checks — it doesn't use JNA or FFM. If the plugin was skipped to avoid a missing config/forbidden-apis.txt reference, consider configuring the plugin from scratch (without the JNA/native signatures file) rather than disabling it entirely.

♻️ Proposed fix — minimal forbidden-api config appropriate for a pure-Java integration module
         <plugin>
             <groupId>de.thetaphi</groupId>
             <artifactId>forbiddenapis</artifactId>
             <configuration>
-                <skip>true</skip>
+                <failOnUnsupportedJava>false</failOnUnsupportedJava>
+                <bundledSignatures>
+                    <bundledSignature>jdk-unsafe</bundledSignature>
+                    <bundledSignature>jdk-deprecated</bundledSignature>
+                    <bundledSignature>jdk-non-portable</bundledSignature>
+                    <bundledSignature>jdk-system-out</bundledSignature>
+                </bundledSignatures>
             </configuration>
         </plugin>
🤖 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-metrics/pom.xml` around lines 70 - 76, The POM currently disables the
forbiddenapis plugin entirely; update the <artifactId>forbiddenapis</artifactId>
plugin configuration in the oshi-metrics module to remove the blanket
<skip>true</skip> and instead configure bundledSignatures appropriate for a
pure-Java module (e.g., include "jdk-unsafe", "jdk-deprecated",
"jdk-system-out") while omitting any JNA/native signatures; ensure the plugin
block (forbiddenapis) is defined with these bundledSignatures so API-safety
checks run without referencing native/JNA signature files.
oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java (1)

67-97: ⚖️ Poor tradeoff

Past issues resolved; implementation looks solid.

Both previously-flagged issues (getOrDefault fallback for unknown TickType, corrected description) are in place. The cpuIndex < freqs.length guard on line 94 is good defensive coding.

One minor efficiency note: each frequency Gauge independently calls processor.getCurrentFreq() at poll time, meaning N full-array fetches per poll cycle for N logical CPUs. If profiling ever shows this as a hot path on large-core-count machines, a shared invalidating cache or a single MultiGauge keyed by cpu.logical_number would be worth exploring.

🤖 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-metrics/src/main/java/oshi/metrics/CpuMetrics.java` around lines 67 -
97, The current per-CPU Gauge.builder for CPU_FREQUENCY calls
processor.getCurrentFreq() independently for each logical CPU causing N
full-array fetches per poll; change to a single fetch per poll by either (a)
switching to a MultiGauge keyed by CPU_LOGICAL_NUMBER_KEY and populate
measurements from one processor.getCurrentFreq() call, or (b) cache the latest
long[] from processor.getCurrentFreq() in a shared volatile/AtomicReference and
have each Gauge (created in the loop) read its value from that shared array
(using cpuIndex) so only one full-array fetch occurs per poll; update code
around Gauge.builder(CPU_FREQUENCY, ...) and references to
processor.getCurrentFreq() accordingly.
oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java (1)

185-201: ⚡ Quick win

No test for system.filesystem.utilization

FileSystemMetrics.bindTo() registers system.filesystem.utilization gauges (both used and free states), but OshiMetricsTest only tests system.filesystem.usage and system.filesystem.limit. Consider adding a filesystemUtilizationRegistered() test alongside the existing filesystem tests for completeness.

🤖 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-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java` around lines
185 - 201, Add a new test method (e.g., filesystemUtilizationRegistered) in
OshiMetricsTest that locates the "system.filesystem.utilization" gauges via
registry.find(...).tag("system.filesystem.state", "used").gauge() and
.tag("system.filesystem.state", "free").gauge(), assert both are not null, and
assert their values are non-negative (>= 0); this corresponds to the gauges
registered by FileSystemMetrics.bindTo() and mirrors the existing
filesystemUsageRegistered/filesystemLimitRegistered tests.
oshi-metrics/src/main/java/oshi/metrics/NetworkMetrics.java (1)

106-127: ⚡ Quick win

Consider caching getConnections() to reduce redundant OS-level reads on each Prometheus scrape

Each gauge in registerConnectionCountGauges calls countConnections(), which fetches and streams the full connection list independently. With ~12 TCP-state gauges plus one UDP gauge, a single scrape triggers ≈13 separate calls to ip.getConnections(). Since the OSHI implementations don't cache internally, each call performs a fresh OS-level read (e.g., /proc/net/tcp on Linux, WMI on Windows).

A simple time-based cache in NetworkMetrics would reduce this to one read per scrape:

Example cache implementation
private volatile long cacheTime = 0L;
private volatile List<IPConnection> connectionCache = List.of();

private List<IPConnection> getCachedConnections() {
    long now = System.currentTimeMillis();
    if (now - cacheTime > 1_000L) {
        connectionCache = ipStats.getConnections();
        cacheTime = now;
    }
    return connectionCache;
}

Then change countConnections to a non-static method using the cache instead of calling ip.getConnections() directly.

🤖 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-metrics/src/main/java/oshi/metrics/NetworkMetrics.java` around lines 106
- 127, registerConnectionCountGauges currently causes ~13 separate OS reads
because countConnections calls ip.getConnections() for each gauge; implement a
simple time-based cache in NetworkMetrics (add volatile fields like
connectionCache and cacheTime) and change countConnections to a non-static
instance method that uses a new getCachedConnections() helper which refreshes
connectionCache from ipStats.getConnections() only if now - cacheTime > 1_000
ms; update all Gauge.builder calls in registerConnectionCountGauges to call the
instance countConnections (or reference the instance method) so gauges share the
cached list for a single scrape.
🤖 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-metrics/src/main/java/oshi/metrics/ProcessMetrics.java`:
- Around line 79-118: The Gauge builders in ProcessMetrics (e.g., Gauge.builder
for MEMORY_USAGE, MEMORY_VIRTUAL, THREAD_COUNT, OPEN_FD, and UPTIME) currently
create weakly-referenced gauges so processSupplier can be GC'd; update each
Gauge.builder(...) call to include .strongReference(true) so the registry holds
a strong reference to processSupplier (this preserves the os::getCurrentProcess
state used by all FunctionCounter.builders that lack strongReference).

In `@oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java`:
- Around line 106-107: The test OshiMetricsTest calls
registry.find("system.cpu.physical.count").gauge() and then uses
physical.value() without null-check, which can NPE if the meter is missing;
update the test to first assert the gauge is present (e.g., assertNotNull or
assertTrue(registry.find(...).gauge() != null) with a clear message) before
calling physical.value(), or fail with a descriptive assertion that
"system.cpu.physical.count" must be registered, then compare count.value() >=
physical.value(); reference registry.find(...).gauge(), the local variable
physical, and the existing assertion using count.value().

---

Duplicate comments:
In `@oshi-metrics/pom.xml`:
- Around line 29-34: The pom currently declares the micrometer dependency with
scope "provided", causing a public API leak because oshi-metrics' public classes
implement io.micrometer.core.instrument.binder.MeterBinder; change the
dependency declaration for artifactId "micrometer-core" (in the oshi-metrics
module) to a compile-scoped dependency (or set <optional>true</optional> if you
intend consumers to opt-in) so consumers can compile without adding Micrometer
themselves, and update the README to document the chosen contract (that
Micrometer is required at compile/runtime or is optional).

In `@oshi-metrics/src/main/java/oshi/metrics/DiskMetrics.java`:
- Around line 61-87: The lambdas passed to FunctionCounter.builder and
Gauge.builder are reading stale HWDiskStore snapshots because updateAttributes()
is never called; to fix, create a small shared-refresh wrapper for each
HWDiskStore in the loop that calls disk.updateAttributes() once and then returns
the requested value (e.g., a helper method or Supplier that accepts HWDiskStore
and a value-extractor like
HWDiskStore::getReadBytes/getWriteBytes/getReads/getWrites/getTransferTime/getSize),
and use that wrapper in place of the direct getters when constructing the
counters (refer to the loop over diskStoreSupplier.get(), the HWDiskStore
variable disk, and the
FunctionCounter.builder(DISK_IO/DISK_OPERATIONS/DISK_IO_TIME) and
Gauge.builder(DISK_LIMIT) invocations).

In `@oshi-metrics/src/main/java/oshi/metrics/GeneralMetrics.java`:
- Around line 45-46: The gauge built with Gauge.builder(PROCESS_COUNT, os,
OperatingSystem::getProcessCount) has a misleading description "Total number of
processes in each state" even though it reports a single total without any state
tag; update the description to accurately reflect the metric (for example "Total
number of processes" or "Total number of processes on the system") in the
Gauge.builder(...) call (leave baseUnit and registry as-is), or alternatively
add appropriate state tagging if you intend per-state counts.

---

Nitpick comments:
In `@oshi-dist/pom.xml`:
- Around line 17-39: The pom dependency list for the oshi-dist assembly is
missing the oshi-metrics artifact so it won't be sorted into the multimodule
assembly; add a dependency entry for artifactId "oshi-metrics" (with groupId
${project.groupId} and version ${project.version}) to the <dependencies> block
in the oshi-dist pom.xml so the metrics JAR is included in the distribution
ordering if you intend to ship it.

In `@oshi-metrics/pom.xml`:
- Around line 70-76: The POM currently disables the forbiddenapis plugin
entirely; update the <artifactId>forbiddenapis</artifactId> plugin configuration
in the oshi-metrics module to remove the blanket <skip>true</skip> and instead
configure bundledSignatures appropriate for a pure-Java module (e.g., include
"jdk-unsafe", "jdk-deprecated", "jdk-system-out") while omitting any JNA/native
signatures; ensure the plugin block (forbiddenapis) is defined with these
bundledSignatures so API-safety checks run without referencing native/JNA
signature files.

In `@oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java`:
- Around line 67-97: The current per-CPU Gauge.builder for CPU_FREQUENCY calls
processor.getCurrentFreq() independently for each logical CPU causing N
full-array fetches per poll; change to a single fetch per poll by either (a)
switching to a MultiGauge keyed by CPU_LOGICAL_NUMBER_KEY and populate
measurements from one processor.getCurrentFreq() call, or (b) cache the latest
long[] from processor.getCurrentFreq() in a shared volatile/AtomicReference and
have each Gauge (created in the loop) read its value from that shared array
(using cpuIndex) so only one full-array fetch occurs per poll; update code
around Gauge.builder(CPU_FREQUENCY, ...) and references to
processor.getCurrentFreq() accordingly.

In `@oshi-metrics/src/main/java/oshi/metrics/NetworkMetrics.java`:
- Around line 106-127: registerConnectionCountGauges currently causes ~13
separate OS reads because countConnections calls ip.getConnections() for each
gauge; implement a simple time-based cache in NetworkMetrics (add volatile
fields like connectionCache and cacheTime) and change countConnections to a
non-static instance method that uses a new getCachedConnections() helper which
refreshes connectionCache from ipStats.getConnections() only if now - cacheTime
> 1_000 ms; update all Gauge.builder calls in registerConnectionCountGauges to
call the instance countConnections (or reference the instance method) so gauges
share the cached list for a single scrape.

In `@oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java`:
- Around line 185-201: Add a new test method (e.g.,
filesystemUtilizationRegistered) in OshiMetricsTest that locates the
"system.filesystem.utilization" gauges via
registry.find(...).tag("system.filesystem.state", "used").gauge() and
.tag("system.filesystem.state", "free").gauge(), assert both are not null, and
assert their values are non-negative (>= 0); this corresponds to the gauges
registered by FileSystemMetrics.bindTo() and mirrors the existing
filesystemUsageRegistered/filesystemLimitRegistered tests.
🪄 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: 8ba330a2-ff94-411f-9017-0f5c26ff1f3e

📥 Commits

Reviewing files that changed from the base of the PR and between 27528a4 and d7c5a8f.

📒 Files selected for processing (24)
  • CHANGELOG.md
  • config/import-control-test.xml
  • config/import-control.xml
  • oshi-benchmark/pom.xml
  • oshi-common/pom.xml
  • oshi-core-ffm/pom.xml
  • oshi-core/pom.xml
  • oshi-demo/pom.xml
  • oshi-dist/pom.xml
  • oshi-metrics/README.md
  • oshi-metrics/pom.xml
  • oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/DiskMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/FileSystemMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/GeneralMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/NetworkMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/PagingMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/package-info.java
  • oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java
  • oshi-metrics/src/test/java/oshi/metrics/PrometheusDemoTest.java
  • pom.xml
📜 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
🪛 markdownlint-cli2 (0.22.1)
CHANGELOG.md

[warning] 3-3: Heading levels should only increment by one level at a time
Expected: h2; Actual: h5

(MD001, heading-increment)

🔇 Additional comments (19)
CHANGELOG.md (1)

1-6: Looks good — changelog entries match the PR scope and project style.

The new 7.1.0 in-progress section clearly documents the oshi-metrics addition and related CgroupInfo API work, and formatting is consistent with this file’s established convention.

oshi-metrics/src/main/java/oshi/metrics/package-info.java (1)

1-9: LGTM!

Clean package-level Javadoc, accurate description, and correctly placed copyright header.

config/import-control.xml (1)

111-115: LGTM!

The past issue has been addressed — test-only packages (simple, prometheusmetrics, com.sun.net.httpserver) are correctly excluded here and kept in import-control-test.xml. The two production-necessary allows are correctly scoped.

config/import-control-test.xml (1)

50-58: LGTM!

All test-exclusive packages (simple, prometheusmetrics, com.sun.net.httpserver, java.net) correctly live here and are properly scoped to the metrics subpackage.

pom.xml (2)

1024-1033: LGTM — java17 profile is correctly structured.

Using [17,) means the oshi-metrics module builds on JDK 17–24 (as the only addition) and also on 25+ alongside the java25 modules, which is the right behavior.


744-748: LGTM — oshi.metrics.** exclusion is consistent with the existing pattern.

Mirrors the treatment of oshi.demo.** and oshi.benchmark.**.

oshi-benchmark/pom.xml (1)

8-8: LGTM — routine parent version sync.

oshi-core/pom.xml (1)

8-8: LGTM — routine parent version sync.

oshi-dist/pom.xml (1)

8-8: LGTM — routine parent version sync.

oshi-demo/pom.xml (1)

8-8: Version bump looks good!

Routine parent version bump to 7.1.0-SNAPSHOT to align with the new oshi-metrics module and the project-wide version increment.

oshi-core-ffm/pom.xml (1)

8-8: LGTM!

Standard parent version bump in sync with the rest of the project.

oshi-common/pom.xml (1)

8-8: LGTM!

Standard parent version bump in sync with the rest of the project.

oshi-metrics/src/main/java/oshi/metrics/PagingMetrics.java (1)

53-73: Past issues resolved; clean implementation.

The "Windows" capitalization fix is in place, the swapTotal == 0 guard prevents division-by-zero, and FunctionCounter is correctly used for the monotonically-increasing page-in/page-out counters.

oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java (1)

47-61: All past issues resolved; clean and correct implementation.

Division-by-zero guards on getTotal() == 0 are in place, Javadoc correctly describes a fraction (0.0–1.0), and the five gauges cover the full OTel memory metric surface accurately.

oshi-metrics/pom.xml (1)

20-20: ⚡ Quick win

Consider updating micrometer.version to 1.15.10 (current stable).

1.14.11 is on the maintenance branch. Since your module has Micrometer as provided scope and there's no Spring Boot version constraint in this project, updating to 1.15.10 is straightforward and keeps development aligned with the latest stable release.

oshi-metrics/src/main/java/oshi/metrics/FileSystemMetrics.java (1)

51-84: LGTM — strong references and defensive arithmetic correctly applied

The per-store Gauge registrations correctly use .strongReference(true), keeping the OSFileStore objects alive via the registry. The division-by-zero guard (totalSpace == 0 ? 0d) and Math.max(0, ...) clamps are both well-placed.

oshi-metrics/src/test/java/oshi/metrics/PrometheusDemoTest.java (1)

55-68: LGTM — previous Content-Length / Content-Type issues are fully addressed

The UTF-8 byte array length is correctly used for Content-Length and the Content-Type header matches the Prometheus text exposition format. The oshiMetrics field being held for the lifetime of the demo also correctly prevents the OSHI-backed meters from being GC'd.

oshi-metrics/README.md (1)

1-181: LGTM — well-structured and accurate documentation

The metric tables, "Not implemented" sections, and usage examples are all consistent with the implementations. Good call explicitly documenting why system.cpu.utilization and system.paging.faults are omitted — that transparency is very helpful for adopters.

oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java (1)

97-123: LGTM — clean conditional wiring and solid builder pattern

The selective registration logic is straightforward and correct. The static bindTo convenience method is a nice ergonomic touch, and the dual constructor (all-on public + builder-driven private) keeps the API clean without duplication.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

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

Inline comments:
In `@oshi-metrics/src/main/java/oshi/metrics/NetworkMetrics.java`:
- Around line 134-151: The refreshCache() method has a TOCTOU race: make the
method atomic by adding synchronization (e.g., declare refreshCache()
synchronized or guard its body with a synchronized block) so the check now -
cacheTimestamp > CACHE_TTL_MS, the call to ipStats.getConnections(), and the
writes to tcpCounts, udpCount, and cacheTimestamp happen without interleaving;
reference refreshCache(), the volatile fields tcpCounts/udpCount/cacheTimestamp,
and the ipStats.getConnections() call when applying 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: 2f0708ee-21d0-4f92-90a8-b521bf0d1583

📥 Commits

Reviewing files that changed from the base of the PR and between d7c5a8f and 4d2cd93.

📒 Files selected for processing (7)
  • oshi-metrics/pom.xml
  • oshi-metrics/src/main/java/oshi/metrics/DiskMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/FileSystemMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/GeneralMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/NetworkMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.java
✅ Files skipped from review due to trivial changes (1)
  • oshi-metrics/src/main/java/oshi/metrics/GeneralMetrics.java
🚧 Files skipped from review as they are similar to previous changes (3)
  • oshi-metrics/pom.xml
  • oshi-metrics/src/main/java/oshi/metrics/DiskMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/FileSystemMetrics.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). (4)
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (2)
oshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.java (1)

68-122: strongReference(true) properly applied — GC concern fully resolved. 👍

All five Gauge builders carry .strongReference(true), keeping processSupplier reachable. The FunctionCounter weak references to the same object therefore stay valid for the lifetime of the registry. The process.context_switch.type = "total" deviation from the OTel well-known values (voluntary/involuntary) is correctly acknowledged in the Javadoc since OSHI can't provide the split, and the spec permits a custom value in that case.

oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java (1)

41-123: Clean entry-point design — LGTM! 🎉

Welcome to the project, and great first module! The builder pattern is well-structured, the null-guard placement in both the public constructor and Builder constructor is consistent, the static convenience shortcut composes correctly on top of the instance bindTo, and the per-category conditional dispatch is easy to follow. The os field intentionally reserved for future metrics is noted.

@dbwiddis
dbwiddis force-pushed the feature/oshi-metrics branch from 4d2cd93 to 6192e81 Compare May 5, 2026 19:06
dbwiddis added 10 commits May 6, 2026 00:08
Initial setup for first-party Micrometer metrics following OpenTelemetry
semantic conventions. Establishes module structure for incremental additions.

Metrics implemented:
- system.cpu.time (FunctionCounter, seconds, per cpu.mode)
- system.memory.usage (Gauge, bytes, per system.memory.state)
- system.memory.utilization (Gauge, ratio, per system.memory.state)

Module design:
- JDK 17 target, Micrometer 1.14.x (provided scope)
- Depends on oshi-common interfaces only (works with JNA or FFM)
- OshiMetrics entry point accepts HAL + OS (no reflection)
- Gated behind JDK 17+ Maven profile
- Includes Prometheus HTTP demo

Also bumps version to 7.1.0-SNAPSHOT (new public API) and adds
changelog entries for oshi-metrics and CgroupInfo API.

Relates to #3223
- system.uptime (Gauge, seconds)
- system.cpu.physical.count (Gauge, {cpu})
- system.cpu.logical.count (Gauge, {cpu})
- system.cpu.frequency (Gauge, Hz, per logical CPU)
- Module README documenting all implemented metrics
- system.memory.limit (Gauge, bytes)
- system.paging.usage (Gauge, bytes, state used/free)
- system.paging.utilization (Gauge, 0-1, state used/free)
- system.paging.operations (FunctionCounter, direction in/out)
- system.paging.faults not implemented (OSHI lacks system-level fault counters)
- system.disk.io (FunctionCounter, bytes, direction read/write per device)
- system.disk.operations (FunctionCounter, per device and direction)
- system.disk.io_time (FunctionCounter, seconds per device)
- system.disk.limit (Gauge, bytes per device)
- system.filesystem.usage (Gauge, bytes, state used/free per mount)
- system.filesystem.utilization (Gauge, 0-1, state used/free per mount)
- system.filesystem.limit (Gauge, bytes per mount)

Not implemented (OSHI lacks the data):
- system.disk.operation_time (needs per-direction time)
- system.disk.merged (needs merged operation counts)
- system.network.io (FunctionCounter, bytes, direction receive/transmit per device)
- system.network.packet.count (FunctionCounter, per device and direction)
- system.network.packet.dropped (FunctionCounter, receive only per device)
- system.network.errors (FunctionCounter, per device and direction)
- system.network.connection.count (Gauge, per transport and state)
- system.process.count (Gauge, total processes on the system)
- system.process.created not implemented (OSHI lacks the data)
OshiMetrics.builder(hal, os)
    .enableCpu(true)
    .enableMemory(true)
    .enableDisk(false)
    .build()
    .bindTo(registry);

All categories enabled by default. Existing bindTo() API unchanged.
Process metrics (current JVM process, per OTel process-metrics spec):
- process.cpu.time (FunctionCounter, seconds, mode user/system)
- process.memory.usage (Gauge, RSS bytes)
- process.memory.virtual (Gauge, virtual bytes)
- process.disk.io (FunctionCounter, bytes, direction read/write)
- process.thread.count (Gauge)
- process.open_file_descriptor.count (Gauge)
- process.paging.faults (FunctionCounter, type major/minor)
- process.context_switches (FunctionCounter, type total)
- process.uptime (Gauge, seconds)

Builder: added enableProcess() option.
README: full setup/usage docs with Maven coordinates, Spring Boot example.
- DiskMetrics: call updateAttributes() before reading counters; hold strong refs
- NetworkMetrics: hold strong ref to NetworkIF list; cache getConnections() with 1s TTL
- GeneralMetrics: fix misleading process count description
- OshiMetrics: add Objects.requireNonNull guards on constructors
- FileSystemMetrics: document snapshot-at-bind behavior in javadoc
- Re-enable forbiddenapis plugin with proper bundled signatures
- Automatic-Module-Name: com.github.oshi.metrics (via manifest)
- ProcessMetrics: add strongReference(true) to Gauges to prevent GC
- Remove unused micrometer-test dependency
- Re-enable forbiddenapis with proper bundled signatures
- Clean up pom.xml plugin configuration
@dbwiddis
dbwiddis force-pushed the feature/oshi-metrics branch from 6192e81 to 3b5a3b4 Compare May 6, 2026 00:14

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🧹 Nitpick comments (6)
oshi-metrics/src/main/java/oshi/metrics/ContainerMetrics.java (1)

78-78: 💤 Low value

Nit: inline comment says "Counter (Gauge)" but this is a Gauge.

Gauge.builder(...) is a pure gauge, not a counter. The comment format "Counter (Gauge)" is used elsewhere in the codebase (e.g., DiskMetrics) to signal a semantically-updown-counter implemented as a Gauge, but container.memory.usage is monotonically non-decreasing and doesn't need the "Counter" qualifier.

✏️ Suggested fix
-        // container.memory.usage — Counter (Gauge), unit "By"
+        // container.memory.usage — Gauge, unit "By"
🤖 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-metrics/src/main/java/oshi/metrics/ContainerMetrics.java` at line 78,
The inline comment for the metric "container.memory.usage" in ContainerMetrics
is incorrect: it's labeled "Counter (Gauge)" but this metric is implemented with
Gauge.builder(...) and should be described as a Gauge only; update the comment
in the ContainerMetrics class (near the container.memory.usage metric
definition) to remove the "Counter" qualifier and mark it as a Gauge with unit
"By" so the comment accurately reflects the implementation and intent.
oshi-metrics/src/main/java/oshi/metrics/DiskMetrics.java (1)

66-97: ⚖️ Poor tradeoff

Each FunctionCounter triggers a separate updateAttributes() call per scrape.

For a single disk, Micrometer invokes each lambda independently during a scrape, leading to 5 consecutive updateAttributes() system calls. Related pairs (e.g., read-bytes vs. write-bytes for the same disk) may therefore capture slightly different OS snapshots. While the delta is typically negligible, the approach becomes noticeably wasteful on systems with many disks.

A possible improvement is to call updateAttributes() once at scrape time via a shared, time-stamped cache (e.g., a volatile snapshot refreshed at most once per scrape interval) and have all lambdas for the same disk read from that snapshot.

🤖 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-metrics/src/main/java/oshi/metrics/DiskMetrics.java` around lines 66 -
97, The current DiskMetrics implementation calls HWDiskStore.updateAttributes()
inside each FunctionCounter lambda (for DISK_IO, DISK_OPERATIONS, DISK_IO_TIME),
causing multiple updates per scrape; change this by introducing a per-disk
cached snapshot (e.g., a small immutable holder object stored in a volatile
field or ConcurrentHashMap keyed by disk.getName()) that stores the latest
attributes plus a lastUpdated timestamp, refresh that snapshot at most once per
scrape interval by calling updateAttributes() once when the cached timestamp is
stale, and have all FunctionCounter lambdas (the read/write bytes and
reads/writes and transfer time calculators) read from that cached snapshot
instead of calling updateAttributes() directly; keep existing symbols
(DiskMetrics, HWDiskStore, updateAttributes(), DISK_IO, DISK_OPERATIONS,
DISK_IO_TIME, MS_PER_SECOND, device) to locate and replace the inline update
calls.
oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java (2)

100-129: 💤 Low value

Consider documenting that bindTo(registry) is intended to be called once per registry.

OshiMetrics is itself a MeterBinder, so Spring Boot will auto-call bindTo exactly once when it discovers the bean — that path is fine. But the public bindTo(MeterRegistry) API can also be invoked manually, and the static helper bindTo(registry, hal, os) plus the Builder make repeat invocations easy. Re-binding to the same registry will throw or quietly drop meters depending on Meter.Id collisions (Micrometer rejects type-conflicting duplicates outright). A one-line Javadoc note ("call once per registry") would set expectations without code changes.

🤖 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-metrics/src/main/java/oshi/metrics/OshiMetrics.java` around lines 100 -
129, Add a one-line Javadoc to the public bindTo(MeterRegistry) method on
OshiMetrics to document that it is intended to be called once per MeterRegistry;
mention that Spring Boot auto-calls the MeterBinder once, but manual calls
(including the static bindTo(registry, hal, os) helper and usage via the
Builder) may cause Meter.Id collisions or rejected duplicates if invoked
multiple times on the same registry. Reference the
OshiMetrics.bindTo(MeterRegistry) method, the static bindTo(registry, hal, os)
helper, and the Builder in the comment so callers know the limitation.

75-87: 💤 Low value

Public no-flag constructor duplicates the Builder defaults — small DRY opportunity.

Both OshiMetrics(HardwareAbstractionLayer, OperatingSystem) and the Builder initialize all nine flags to true independently. If you ever add a tenth category (e.g., sensors, battery), you'll need to remember to flip the default in two places. Easy to consolidate by routing the public constructor through the builder:

♻️ Suggested change
-    public OshiMetrics(HardwareAbstractionLayer hal, OperatingSystem os) {
-        this.hal = java.util.Objects.requireNonNull(hal, "hal must not be null");
-        this.os = java.util.Objects.requireNonNull(os, "os must not be null");
-        this.general = true;
-        this.cpu = true;
-        this.memory = true;
-        this.paging = true;
-        this.disk = true;
-        this.fileSystem = true;
-        this.network = true;
-        this.process = true;
-        this.container = true;
-    }
+    public OshiMetrics(HardwareAbstractionLayer hal, OperatingSystem os) {
+        this(new Builder(hal, os));
+    }
🤖 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-metrics/src/main/java/oshi/metrics/OshiMetrics.java` around lines 75 -
87, Refactor the public constructor OshiMetrics(HardwareAbstractionLayer hal,
OperatingSystem os) to delegate to the existing Builder so the default boolean
flags (general, cpu, memory, paging, disk, fileSystem, network, process,
container) are defined in one place; i.e., remove the duplicated flag
assignments and construct via the Builder (ensuring hal and os are still
null-checked via java.util.Objects.requireNonNull either before delegation or by
using Builder methods that validate them) so adding new categories only requires
changing the Builder.
oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java (1)

90-97: 💤 Low value

getCurrentFreq() is called once per logical CPU per scrape.

Each per-CPU gauge re-fetches the entire long[] of frequencies and then indexes into it, so a single scrape on an N-core box performs N reads of the same OS frequency table (and discards N-1 of the values each time). It's not wrong, just a bit wasteful. If you'd like to keep things simple you can leave it as-is; otherwise a tiny TTL'd cache (similar to NetworkMetrics) on the long[] would amortize this to one read per scrape.

🤖 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-metrics/src/main/java/oshi/metrics/CpuMetrics.java` around lines 90 -
97, The per-CPU gauges built in CpuMetrics call processor.getCurrentFreq()
inside each gauge function, causing N full reads per scrape; introduce a small
TTL'd cache (like NetworkMetrics) to store the long[] frequencies and a
timestamp, expose a cached accessor used by the Gauge lambdas so
processor.getCurrentFreq() is invoked at most once per TTL/scrape; update the
code around Gauge.builder(CPU_FREQUENCY, processor, p -> ...) to read the cached
long[] (fallback to calling getCurrentFreq() to populate the cache) and use
cpuIndex to index that cached array, and ensure the cache key/expiry is based on
a short TTL to amortize cost.
oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java (1)

49-60: ⚡ Quick win

Consider .strongReference(true) on these gauges for consistency with the other binders.

FileSystemMetrics, ProcessMetrics, and (the gauges in) NetworkMetrics all set .strongReference(true) to keep their state objects alive once the binder instance becomes GC-eligible. MemoryMetrics is constructed anonymously in OshiMetrics.bindTo and discarded immediately, so the weak references in these gauges rely entirely on the caller retaining hal (which transitively retains GlobalMemory). If a caller does OshiMetrics.bindTo(registry, si.getHardware(), si.getOperatingSystem()) and lets si/hal go out of scope, all four memory gauges silently flip to NaN after the next GC. Per the Micrometer docs, "All of the different forms of creating a gauge maintain only a weak reference to the object being observed, so as not to prevent garbage collection of the object."

♻️ Suggested change
         Gauge.builder(MEMORY_USAGE, memory, mem -> mem.getTotal() - mem.getAvailable()).tags(Tags.of(STATE_USED))
-                .description("Memory used in bytes").baseUnit("By").register(registry);
+                .description("Memory used in bytes").baseUnit("By").strongReference(true).register(registry);
         Gauge.builder(MEMORY_USAGE, memory, GlobalMemory::getAvailable).tags(Tags.of(STATE_FREE))
-                .description("Memory available in bytes").baseUnit("By").register(registry);
+                .description("Memory available in bytes").baseUnit("By").strongReference(true).register(registry);
         Gauge.builder(MEMORY_LIMIT, memory, GlobalMemory::getTotal).description("Total memory available in the system")
-                .baseUnit("By").register(registry);
+                .baseUnit("By").strongReference(true).register(registry);
         Gauge.builder(MEMORY_UTILIZATION, memory,
                 mem -> mem.getTotal() == 0 ? 0d : (double) (mem.getTotal() - mem.getAvailable()) / mem.getTotal())
-                .tags(Tags.of(STATE_USED)).description("Fraction of memory used").register(registry);
+                .tags(Tags.of(STATE_USED)).description("Fraction of memory used").strongReference(true)
+                .register(registry);
         Gauge.builder(MEMORY_UTILIZATION, memory,
                 mem -> mem.getTotal() == 0 ? 0d : (double) mem.getAvailable() / mem.getTotal())
-                .tags(Tags.of(STATE_FREE)).description("Fraction of memory free").register(registry);
+                .tags(Tags.of(STATE_FREE)).description("Fraction of memory free").strongReference(true)
+                .register(registry);

Could you confirm whether OshiMetrics/the user is expected to retain hal for the lifetime of the registry? If so a sentence in the OshiMetrics Javadoc would suffice and we can leave these gauges as-is.

🤖 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-metrics/src/main/java/oshi/metrics/MemoryMetrics.java` around lines 49 -
60, Memory gauges in MemoryMetrics are created with weak references and can
become NaN if the anonymous MemoryMetrics instance or its GlobalMemory (hal) is
GC'd; update the Gauge.builder calls in MemoryMetrics (the four builders for
MEMORY_USAGE with STATE_USED/STATE_FREE, MEMORY_LIMIT, and the two
MEMORY_UTILIZATION gauges) to call .strongReference(true) before
.register(registry) so the observed GlobalMemory is held strongly like
FileSystemMetrics/ProcessMetrics/NetworkMetrics; alternatively, if you prefer
not to change behavior, add a clear note to OshiMetrics.bindTo Javadoc stating
callers must retain the HardwareAbstractionLayer (hal) / SystemInfo for the
lifetime of the registry, but default to adding .strongReference(true) for
consistency.
🤖 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-metrics/src/main/java/oshi/metrics/ContainerMetrics.java`:
- Around line 70-72: The current Gauge for CONTAINER_UPTIME uses
os.getSystemUptime() (via Gauge.builder(CONTAINER_UPTIME, os, o -> (double)
o.getSystemUptime())), which yields host/kernel uptime inside containers; change
the metric to approximate container uptime from PID 1's start time instead:
fetch OSProcess init = os.getProcess(1), if non-null use init.getStartTime()
(epoch ms) as the instrumented value and compute (System.currentTimeMillis() -
startMs)/1000.0 in the Gauge callback, register with the same
description/baseUnit/registry; if init is null (or you decide not to change
behavior), document in the Javadoc/README that CONTAINER_UPTIME reflects
host/kernel uptime and not container start time.
- Around line 70-72: The CONTAINER_UPTIME gauge currently uses
os.getSystemUptime() which yields host uptime; change it to compute
container-specific uptime instead by using the init process start time or JVM
uptime: obtain the PID 1 process via os.getProcess(1) and compute (nowSeconds -
os.getProcess(1).getStartTime()) for the gauge value (fall back to
ManagementFactory.getRuntimeMXBean().getUptime()/1000.0 if PID 1 is
unavailable), updating the Gauge.builder(CONTAINER_UPTIME, os, ...) callback to
return that computed double and keep the same description/baseUnit/register
call.

In `@oshi-metrics/src/main/java/oshi/metrics/DiskMetrics.java`:
- Around line 48-64: OshiMetrics currently creates binders with the throw-away
pattern (e.g. new GeneralMetrics(...).bindTo(registry)) which lets the binder
objects be garbage-collected and causes their FunctionCounters to silently
return 0; fix by adding instance fields to OshiMetrics to hold each binder
(GeneralMetrics, MemoryMetrics, PagingMetrics, CpuMetrics, DiskMetrics,
FileSystemMetrics, NetworkMetrics, ProcessMetrics, ContainerMetrics),
instantiate each binder once and assign it to its field in
OshiMetrics.bindTo(registry) before calling binder.bindTo(registry), and remove
the ephemeral new ... .bindTo(...) usage so binders (and their internal strong
references such as DiskMetrics.diskStores) remain reachable for the application
lifetime.

In `@oshi-metrics/src/main/java/oshi/metrics/FileSystemMetrics.java`:
- Line 62: The current logic in FileSystemMetrics (in the code that sets
variable mode from fs.getOptions()) uses fs.getOptions().contains("rw") which
can mis-classify options; change it to parse the comma-separated options string
and check tokens for an exact "rw" match—e.g., split fs.getOptions() by ',' (or
use a simple regex like "(^|,)rw(,|$)") and test for equality on each token—so
the assignment of mode (rw vs ro) is based on an exact token match rather than
substring containment.

In `@oshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.java`:
- Around line 64-122: ProcessMetrics currently calls processSupplier.get()
repeatedly during bindTo which causes redundant /proc reads and inconsistent
snapshots; add a 1s TTL cache (like NetworkMetrics' CACHE_TTL_MS = 1000L) inside
ProcessMetrics and use a single cached snapshot accessor instead of direct
processSupplier.get() in all meters. Implement a private method (e.g.,
getCachedProcess() or makeCachedSupplier()) that keeps a cached OSProcess and
lastFetch timestamp, refreshes by calling processSupplier.get() only when now -
lastFetch > CACHE_TTL_MS, and update all Gauge/FunctionCounter builders in
bindTo to call that accessor (replace s -> s.get().getX() usage with s ->
getCachedProcess().getX() or wrap the supplier so the meter builders use the
cached supplier). Ensure thread-safety for the cache refresh (simple volatile +
synchronized refresh or AtomicReference) and define CACHE_TTL_MS = 1000L as a
private static final.

In `@oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java`:
- Around line 205-211: The test filesystemUtilizationRegistered in
OshiMetricsTest currently asserts only non-negativity for the
"system.filesystem.utilization" gauges; add upper-bound assertions to also
verify semantic correctness by asserting used.value() <= 1.0 and free.value() <=
1.0 (or <= 1) for the Gauge instances retrieved via
registry.find(...).tag(...).gauge() so both used and free are in the [0,1]
range.

---

Nitpick comments:
In `@oshi-metrics/src/main/java/oshi/metrics/ContainerMetrics.java`:
- Line 78: The inline comment for the metric "container.memory.usage" in
ContainerMetrics is incorrect: it's labeled "Counter (Gauge)" but this metric is
implemented with Gauge.builder(...) and should be described as a Gauge only;
update the comment in the ContainerMetrics class (near the
container.memory.usage metric definition) to remove the "Counter" qualifier and
mark it as a Gauge with unit "By" so the comment accurately reflects the
implementation and intent.

In `@oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java`:
- Around line 90-97: The per-CPU gauges built in CpuMetrics call
processor.getCurrentFreq() inside each gauge function, causing N full reads per
scrape; introduce a small TTL'd cache (like NetworkMetrics) to store the long[]
frequencies and a timestamp, expose a cached accessor used by the Gauge lambdas
so processor.getCurrentFreq() is invoked at most once per TTL/scrape; update the
code around Gauge.builder(CPU_FREQUENCY, processor, p -> ...) to read the cached
long[] (fallback to calling getCurrentFreq() to populate the cache) and use
cpuIndex to index that cached array, and ensure the cache key/expiry is based on
a short TTL to amortize cost.

In `@oshi-metrics/src/main/java/oshi/metrics/DiskMetrics.java`:
- Around line 66-97: The current DiskMetrics implementation calls
HWDiskStore.updateAttributes() inside each FunctionCounter lambda (for DISK_IO,
DISK_OPERATIONS, DISK_IO_TIME), causing multiple updates per scrape; change this
by introducing a per-disk cached snapshot (e.g., a small immutable holder object
stored in a volatile field or ConcurrentHashMap keyed by disk.getName()) that
stores the latest attributes plus a lastUpdated timestamp, refresh that snapshot
at most once per scrape interval by calling updateAttributes() once when the
cached timestamp is stale, and have all FunctionCounter lambdas (the read/write
bytes and reads/writes and transfer time calculators) read from that cached
snapshot instead of calling updateAttributes() directly; keep existing symbols
(DiskMetrics, HWDiskStore, updateAttributes(), DISK_IO, DISK_OPERATIONS,
DISK_IO_TIME, MS_PER_SECOND, device) to locate and replace the inline update
calls.

In `@oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java`:
- Around line 49-60: Memory gauges in MemoryMetrics are created with weak
references and can become NaN if the anonymous MemoryMetrics instance or its
GlobalMemory (hal) is GC'd; update the Gauge.builder calls in MemoryMetrics (the
four builders for MEMORY_USAGE with STATE_USED/STATE_FREE, MEMORY_LIMIT, and the
two MEMORY_UTILIZATION gauges) to call .strongReference(true) before
.register(registry) so the observed GlobalMemory is held strongly like
FileSystemMetrics/ProcessMetrics/NetworkMetrics; alternatively, if you prefer
not to change behavior, add a clear note to OshiMetrics.bindTo Javadoc stating
callers must retain the HardwareAbstractionLayer (hal) / SystemInfo for the
lifetime of the registry, but default to adding .strongReference(true) for
consistency.

In `@oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java`:
- Around line 100-129: Add a one-line Javadoc to the public
bindTo(MeterRegistry) method on OshiMetrics to document that it is intended to
be called once per MeterRegistry; mention that Spring Boot auto-calls the
MeterBinder once, but manual calls (including the static bindTo(registry, hal,
os) helper and usage via the Builder) may cause Meter.Id collisions or rejected
duplicates if invoked multiple times on the same registry. Reference the
OshiMetrics.bindTo(MeterRegistry) method, the static bindTo(registry, hal, os)
helper, and the Builder in the comment so callers know the limitation.
- Around line 75-87: Refactor the public constructor
OshiMetrics(HardwareAbstractionLayer hal, OperatingSystem os) to delegate to the
existing Builder so the default boolean flags (general, cpu, memory, paging,
disk, fileSystem, network, process, container) are defined in one place; i.e.,
remove the duplicated flag assignments and construct via the Builder (ensuring
hal and os are still null-checked via java.util.Objects.requireNonNull either
before delegation or by using Builder methods that validate them) so adding new
categories only requires changing the Builder.
🪄 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: 5ee9ddf5-1348-4344-a990-f95b3e826361

📥 Commits

Reviewing files that changed from the base of the PR and between 6192e81 and 3b5a3b4.

📒 Files selected for processing (19)
  • CHANGELOG.md
  • config/import-control-test.xml
  • config/import-control.xml
  • oshi-metrics/README.md
  • oshi-metrics/pom.xml
  • oshi-metrics/src/main/java/oshi/metrics/ContainerMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/DiskMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/FileSystemMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/GeneralMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/NetworkMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/PagingMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/package-info.java
  • oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java
  • oshi-metrics/src/test/java/oshi/metrics/PrometheusDemoTest.java
  • pom.xml
✅ Files skipped from review due to trivial changes (1)
  • CHANGELOG.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). (9)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
🔇 Additional comments (13)
oshi-metrics/src/main/java/oshi/metrics/package-info.java (1)

1-9: Welcome, and LGTM!

Clean package-info with proper copyright header and accurate Javadoc. Great start!

config/import-control.xml (1)

111-115: LGTM — test-only packages correctly removed.

The past review concern (test-only SimpleMeterRegistry, io.micrometer.prometheusmetrics, com.sun.net.httpserver leaking into the main-source allow-list) has been fully resolved. The two entries remaining here are exactly what production code needs.

pom.xml (2)

747-748: LGTM.

Excluding oshi.metrics.** from the RestrictImports rule is consistent with the existing exclusions for oshi.demo, oshi.benchmark, and oshi.comparison.


1024-1033: LGTM — profile placement and activation look correct.

The java17 profile activates for [17,∞) and is additive to java25, so oshi-metrics will also be compiled on Java 25+. That's the intended behaviour for a library that targets JDK 17+.

oshi-metrics/src/main/java/oshi/metrics/GeneralMetrics.java (1)

41-47: LGTM — clean and correct.

Both gauges use appropriate base units (s and {process}), the description for system.process.count accurately reflects single-value granularity (past concern addressed), and the long→double widening is safe.

config/import-control-test.xml (1)

50-58: LGTM.

Test-only packages (simple, prometheusmetrics, com.sun.net.httpserver) are correctly in the test import-control only, as the past review requested.

oshi-metrics/README.md (1)

1-181: LGTM — comprehensive and accurate documentation.

The metric tables, Spring Boot wiring example, and "not implemented" callouts all look correct. The system.process.count placement under "Aggregate system process metrics" (rather than "General") correctly follows the OTel spec categorisation, even though GeneralMetrics implements both in a single class.

oshi-metrics/src/main/java/oshi/metrics/PagingMetrics.java (1)

56-67: ⚡ Quick win

Same .strongReference(true) consistency note as MemoryMetrics.

PagingMetrics is created and discarded inside OshiMetrics.bindTo, so vm (the VirtualMemory state object) is only kept reachable through whatever holds hal outside the registry. The FunctionCounter builders below (lines 70–73) have no strongReference knob, but the four Gauges here can be aligned with FileSystemMetrics/NetworkMetrics/ProcessMetrics. This is the same pattern Micrometer recommends to avoid silent NaN after GC.

♻️ Suggested change
         Gauge.builder(PAGING_USAGE, vm, VirtualMemory::getSwapUsed).tags(Tags.of(STATE_USED))
-                .description("Unix swap or Windows pagefile usage").baseUnit("By").register(registry);
+                .description("Unix swap or Windows pagefile usage").baseUnit("By").strongReference(true)
+                .register(registry);
         Gauge.builder(PAGING_USAGE, vm, v -> v.getSwapTotal() - v.getSwapUsed()).tags(Tags.of(STATE_FREE))
-                .description("Unix swap or Windows pagefile usage").baseUnit("By").register(registry);
+                .description("Unix swap or Windows pagefile usage").baseUnit("By").strongReference(true)
+                .register(registry);

         // system.paging.utilization — Gauge, unit "1", attr system.paging.state
         Gauge.builder(PAGING_UTILIZATION, vm,
                 v -> v.getSwapTotal() == 0 ? 0d : (double) v.getSwapUsed() / v.getSwapTotal()).tags(Tags.of(STATE_USED))
-                .description("Fraction of swap/pagefile used").register(registry);
+                .description("Fraction of swap/pagefile used").strongReference(true).register(registry);
         Gauge.builder(PAGING_UTILIZATION, vm,
                 v -> v.getSwapTotal() == 0 ? 0d : (double) (v.getSwapTotal() - v.getSwapUsed()) / v.getSwapTotal())
-                .tags(Tags.of(STATE_FREE)).description("Fraction of swap/pagefile free").register(registry);
+                .tags(Tags.of(STATE_FREE)).description("Fraction of swap/pagefile free").strongReference(true)
+                .register(registry);
oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java (1)

79-97: ⚡ Quick win

Same .strongReference(true) consistency note for the gauges.

CentralProcessor is held only via hal outside the registry; once CpuMetrics is GC'd (it's anonymous in OshiMetrics.bindTo), the gauges below rely on the user's grip on hal. Aligning with FileSystemMetrics/ProcessMetrics/NetworkMetrics keeps the binders' GC behavior uniform. Per the Micrometer docs, "It is your responsibility to hold a strong reference to the state object that you are measuring with a Gauge."

♻️ Suggested change
         Gauge.builder(CPU_PHYSICAL_COUNT, processor, CentralProcessor::getPhysicalProcessorCount)
                 .description("Reports the number of actual physical processor cores on the hardware").baseUnit("{cpu}")
-                .register(registry);
+                .strongReference(true).register(registry);

         // system.cpu.logical.count — UpDownCounter (Gauge), unit "{cpu}"
         Gauge.builder(CPU_LOGICAL_COUNT, processor, CentralProcessor::getLogicalProcessorCount).description(
                 "Reports the number of logical (virtual) processor cores created by the operating system to manage multitasking")
-                .baseUnit("{cpu}").register(registry);
+                .baseUnit("{cpu}").strongReference(true).register(registry);

         // system.cpu.frequency — Gauge, unit "Hz", attr cpu.logical_number
         int logicalCount = processor.getLogicalProcessorCount();
         for (int i = 0; i < logicalCount; i++) {
             final int cpuIndex = i;
             Gauge.builder(CPU_FREQUENCY, processor, p -> {
                 long[] freqs = p.getCurrentFreq();
                 return cpuIndex < freqs.length ? (double) freqs[cpuIndex] : 0d;
             }).tag(CPU_LOGICAL_NUMBER_KEY, String.valueOf(i))
-                    .description("Operating frequency of the logical CPU in Hertz").baseUnit("Hz").register(registry);
+                    .description("Operating frequency of the logical CPU in Hertz").baseUnit("Hz")
+                    .strongReference(true).register(registry);
         }
oshi-metrics/pom.xml (1)

1-104: POM looks consistent with the other OSHI modules.

The provided-scope choice for micrometer-core was raised on a prior commit and aligns with the PR objectives ("declares Micrometer 1.14.x as provided scope"), so leaving it. Module name, JDK 17 enforcement, forbiddenapis config, Automatic-Module-Name, and useModulePath=false for surefire all look reasonable for a non-modularized add-on.

oshi-metrics/src/main/java/oshi/metrics/NetworkMetrics.java (1)

80-151: Past GC-safety and TOCTOU concerns look fully addressed.

Holding networkIFs as a strong field plus .strongReference(true) on the connection-count gauges (which use this as the state object) cascades reachability to both networkIFs and ipStats, so the FunctionCounters' weak refs to per-NetworkIF state remain valid for the life of the registry. synchronized refreshCache() closes the TOCTOU window cleanly. Nice cleanup.

oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java (1)

126-128: ⚡ Quick win

No issue found — getCgroupInfo() is properly declared on the OperatingSystem interface in oshi-common.

Great to see you being thorough about cross-module compatibility! The verification confirms that getCgroupInfo() is declared as a default method on the OperatingSystem interface at line 400 of oshi-common/src/main/java/oshi/software/os/OperatingSystem.java, with a safe fallback implementation that returns an empty CgroupInfo object. The Linux-specific implementation overrides it appropriately. Downstream consumers using only oshi-common will compile and link without issues.

oshi-metrics/src/test/java/oshi/metrics/PrometheusDemoTest.java (1)

49-53: Nice fix on scrape response encoding and headers.

Great improvement here—using UTF-8 bytes plus byte-accurate Content-Length and explicit Prometheus Content-Type makes this endpoint much safer for real scrapers.

Comment on lines +48 to +64
private final Supplier<List<HWDiskStore>> diskStoreSupplier;
private List<HWDiskStore> diskStores;

/**
* Creates a new {@code DiskMetrics} binder.
*
* @param diskStoreSupplier supplier that returns the current list of {@link HWDiskStore} instances
*/
public DiskMetrics(Supplier<List<HWDiskStore>> diskStoreSupplier) {
this.diskStoreSupplier = diskStoreSupplier;
}

@Override
public void bindTo(MeterRegistry registry) {
List<HWDiskStore> disks = diskStoreSupplier.get();
// Hold strong references to prevent GC (FunctionCounter uses WeakReference)
this.diskStores = disks;

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check whether OshiMetrics.java stores sub-binders (like DiskMetrics) as instance fields
ast-grep --pattern '
class OshiMetrics {
  $$$
  DiskMetrics $_
  $$$
}'

# Also check if DiskMetrics is created inline without being assigned to a field
rg -n -A2 'new DiskMetrics' --type=java

Repository: oshi/oshi

Length of output: 338


🏁 Script executed:

# Get full context around line 115 in OshiMetrics.java
sed -n '100,130p' oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java

# Check all metric binder creations to see if they follow the same pattern
rg -n 'new \w+Metrics.*bindTo' --type=java

# Look at OshiMetrics class structure to understand field declarations
rg -n 'private.*Metrics|public.*Metrics' oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java

Repository: oshi/oshi

Length of output: 2634


🏁 Script executed:

# Check if MemoryMetrics holds references
sed -n '1,100p' oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java | head -80

# Check FileSystemMetrics as another example
rg -n 'private.*Memory|this\.' oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java | head -10

# Look for any field assignments in metric binders
rg -n 'this\.\w+\s*=.*(?:supplier|hal|os)' --type=java oshi-metrics/src/main/java/oshi/metrics/ | head -20

Repository: oshi/oshi

Length of output: 3827


🏁 Script executed:

# Get the full bindTo() method from DiskMetrics
cat -n oshi-metrics/src/main/java/oshi/metrics/DiskMetrics.java | sed -n '60,150p'

# Check if FunctionCounter is used in DiskMetrics
rg -n 'FunctionCounter' oshi-metrics/src/main/java/oshi/metrics/DiskMetrics.java -A3 -B1

Repository: oshi/oshi

Length of output: 5029


Store all metric binders as fields in OshiMetrics to prevent silent metric failures.

Every metric binder created in OshiMetrics.bindTo() follows the throw-away pattern — new XXXMetrics(...).bindTo(registry) — which makes each binder immediately eligible for garbage collection. DiskMetrics attempts to work around this by storing strong references to HWDiskStore objects in its diskStores field. However, if DiskMetrics itself is garbage collected, the diskStores field disappears, the HWDiskStore objects lose their only strong root, and every FunctionCounter using them silently returns 0 — a particularly hard failure to debug.

This vulnerability affects all 9 metric binders (GeneralMetrics, MemoryMetrics, PagingMetrics, CpuMetrics, DiskMetrics, FileSystemMetrics, NetworkMetrics, ProcessMetrics, ContainerMetrics). The fix is to store each binder as an instance field in OshiMetrics for the lifetime of the application.

🤖 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-metrics/src/main/java/oshi/metrics/DiskMetrics.java` around lines 48 -
64, OshiMetrics currently creates binders with the throw-away pattern (e.g. new
GeneralMetrics(...).bindTo(registry)) which lets the binder objects be
garbage-collected and causes their FunctionCounters to silently return 0; fix by
adding instance fields to OshiMetrics to hold each binder (GeneralMetrics,
MemoryMetrics, PagingMetrics, CpuMetrics, DiskMetrics, FileSystemMetrics,
NetworkMetrics, ProcessMetrics, ContainerMetrics), instantiate each binder once
and assign it to its field in OshiMetrics.bindTo(registry) before calling
binder.bindTo(registry), and remove the ephemeral new ... .bindTo(...) usage so
binders (and their internal strong references such as DiskMetrics.diskStores)
remain reachable for the application lifetime.

Comment on lines +64 to +122
public ProcessMetrics(Supplier<OSProcess> processSupplier) {
this.processSupplier = processSupplier;
}

@Override
public void bindTo(MeterRegistry registry) {
// process.cpu.time — Counter, unit "s", attr cpu.mode (Required)
FunctionCounter.builder(CPU_TIME, processSupplier, s -> s.get().getUserTime() / MS_PER_SECOND)
.tag("cpu.mode", "user").description("Total CPU seconds broken down by different CPU modes")
.baseUnit("s").register(registry);
FunctionCounter.builder(CPU_TIME, processSupplier, s -> s.get().getKernelTime() / MS_PER_SECOND)
.tag("cpu.mode", "system").description("Total CPU seconds broken down by different CPU modes")
.baseUnit("s").register(registry);

// process.memory.usage — UpDownCounter (Gauge), unit "By"
Gauge.builder(MEMORY_USAGE, processSupplier, s -> s.get().getResidentMemory())
.description("The amount of physical memory in use").baseUnit("By").strongReference(true)
.register(registry);

// process.memory.virtual — UpDownCounter (Gauge), unit "By"
Gauge.builder(MEMORY_VIRTUAL, processSupplier, s -> s.get().getVirtualSize())
.description("The amount of committed virtual memory").baseUnit("By").strongReference(true)
.register(registry);

// process.disk.io — Counter, unit "By", attr disk.io.direction (Required)
FunctionCounter.builder(DISK_IO, processSupplier, s -> s.get().getBytesRead()).tag("disk.io.direction", "read")
.description("Disk bytes transferred").baseUnit("By").register(registry);
FunctionCounter.builder(DISK_IO, processSupplier, s -> s.get().getBytesWritten())
.tag("disk.io.direction", "write").description("Disk bytes transferred").baseUnit("By")
.register(registry);

// process.thread.count — UpDownCounter (Gauge), unit "{thread}"
Gauge.builder(THREAD_COUNT, processSupplier, s -> s.get().getThreadCount()).description("Process threads count")
.baseUnit("{thread}").strongReference(true).register(registry);

// process.open_file_descriptor.count — UpDownCounter (Gauge), unit "{file_descriptor}"
Gauge.builder(OPEN_FD, processSupplier, s -> s.get().getOpenFiles())
.description("Number of file descriptors in use by the process").baseUnit("{file_descriptor}")
.strongReference(true).register(registry);

// process.paging.faults — Counter, unit "{fault}", attr system.paging.fault.type (Recommended)
FunctionCounter.builder(PAGING_FAULTS, processSupplier, s -> s.get().getMinorFaults())
.tag("system.paging.fault.type", "minor").description("Number of page faults the process has made")
.baseUnit("{fault}").register(registry);
FunctionCounter.builder(PAGING_FAULTS, processSupplier, s -> s.get().getMajorFaults())
.tag("system.paging.fault.type", "major").description("Number of page faults the process has made")
.baseUnit("{fault}").register(registry);

// process.context_switches — Counter, unit "{context_switch}", attr process.context_switch.type (Required)
FunctionCounter.builder(CONTEXT_SWITCHES, processSupplier, s -> s.get().getContextSwitches())
.tag("process.context_switch.type", "total")
.description("Number of times the process has been context switched").baseUnit("{context_switch}")
.register(registry);

// process.uptime — Gauge, unit "s"
Gauge.builder(UPTIME, processSupplier, s -> s.get().getUpTime() / MS_PER_SECOND)
.description("The time the process has been running").baseUnit("s").strongReference(true)
.register(registry);
}

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.

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🌐 Web query:

oshi OperatingSystem getCurrentProcess cost /proc/pid/stat refresh per call

💡 Result:

OSHI is a Java library (https://github.com/oshi/oshi/) for operating system and hardware information. Its OperatingSystem interface includes a getCurrentProcess method, implemented as getProcess(getProcessId), which fetches the current process details.[1][2] On Linux, process details like those from /proc/[pid]/stat are read via oshi.driver.linux.proc.ProcessStat utility.[3][4] Each call to getCurrentProcess triggers a fresh read from /proc/[pid]/stat (and potentially other /proc files like statm for memory), as there's no evidence of caching in the method; OSProcess fields are populated on-demand.[5][6] Reading /proc/[pid]/stat is cheap and provides real-time kernel data generated on open/read, not periodically refreshed.[7][8] No fixed refresh period exists; content updates with process state changes (e.g., scheduling).[7] Cost per call is low (simple file read/parsing), suitable for frequent calls, though high-frequency polling (e.g., >1/sec) is unnecessary for monitoring.[8] No prominent Rust crate named "oshi" with this exact API exists; similar functionality appears in crates like sysinfo (reads /proc on refresh, recommends single instance/reuse to avoid redundant work[9][10][11]), procfs-core[12], or psutil[13], where per-call cost is also a fast /proc read.[14][15] If referring to a specific Rust "oshi", evidence is lacking; likely the Java OSHI.

Citations:


🏁 Script executed:

# Count the number of FunctionCounter.builder and Gauge.builder calls in ProcessMetrics
cd oshi-metrics && grep -E "(FunctionCounter\.builder|Gauge\.builder)" src/main/java/oshi/metrics/ProcessMetrics.java | wc -l

Repository: oshi/oshi

Length of output: 56


🏁 Script executed:

# Look at NetworkMetrics to verify the caching claim
find . -name "NetworkMetrics.java" -type f | head -1 | xargs cat

Repository: oshi/oshi

Length of output: 7642


🏁 Script executed:

# Check if there's a TTL cache or memoization utility used elsewhere in the metrics module
grep -r "TTL\|memoize\|Cache" oshi-metrics/src/main/java/oshi/metrics/ --include="*.java" | head -20

Repository: oshi/oshi

Length of output: 1106


Add a short-TTL cache to avoid redundant process reads per scrape.

Each processSupplier.get() call triggers a fresh read from /proc/<pid>/stat and related files on Linux. Since this binder registers 12 meters, each scrape invokes the supplier ~12 times independently — for example, user and system CPU times come from different OSProcess instances. This creates two issues:

  1. Redundant I/O: Over a 30-second Prometheus scrape cycle, you're reading /proc/<pid> ~12 times per scrape (~24 reads/minute), and with shorter scrape intervals (10s), the cost compounds.
  2. Stale snapshots: Within a single scrape, process.cpu.time (user) and process.cpu.time (system) reflect different process state because they call processSupplier.get() independently.

The solution is straightforward — NetworkMetrics already uses this pattern: add a 1-second TTL cache (like CACHE_TTL_MS = 1000L in NetworkMetrics) so one scrape resolves to one OSProcess instance. That keeps memory metrics and CPU metrics consistent within the same collection window and eliminates redundant reads.

Alternatively, document in the constructor's Javadoc that users wrapping with a caching supplier (e.g., Suppliers.memoizeWithExpiration(...) or oshi.util.Memoizer) when scrape frequency is high is recommended, but the internal cache is cleaner and consistent with the existing NetworkMetrics approach.

🤖 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-metrics/src/main/java/oshi/metrics/ProcessMetrics.java` around lines 64
- 122, ProcessMetrics currently calls processSupplier.get() repeatedly during
bindTo which causes redundant /proc reads and inconsistent snapshots; add a 1s
TTL cache (like NetworkMetrics' CACHE_TTL_MS = 1000L) inside ProcessMetrics and
use a single cached snapshot accessor instead of direct processSupplier.get() in
all meters. Implement a private method (e.g., getCachedProcess() or
makeCachedSupplier()) that keeps a cached OSProcess and lastFetch timestamp,
refreshes by calling processSupplier.get() only when now - lastFetch >
CACHE_TTL_MS, and update all Gauge/FunctionCounter builders in bindTo to call
that accessor (replace s -> s.get().getX() usage with s ->
getCachedProcess().getX() or wrap the supplier so the meter builders use the
cached supplier). Ensure thread-safety for the cache refresh (simple volatile +
synchronized refresh or AtomicReference) and define CACHE_TTL_MS = 1000L as a
private static final.

@dbwiddis
dbwiddis force-pushed the feature/oshi-metrics branch from 3b5a3b4 to 10cad6a Compare May 6, 2026 00:36

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

♻️ Duplicate comments (1)
oshi-metrics/src/main/java/oshi/metrics/FileSystemMetrics.java (1)

62-62: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Guard against null options to avoid an NPE during binding.

OSFileStore#getOptions() can return null on some platforms or for stores where the OSHI implementation hasn't populated mount options (e.g., certain pseudo filesystems). Calling .split(",") on null throws NPE inside bindTo, which would abort registration of every subsequent filesystem in the snapshot. A small defensive check (and importing Arrays) keeps this robust.

🛡️ Suggested change
-            String mode = java.util.Arrays.asList(fs.getOptions().split(",")).contains("rw") ? "rw" : "ro";
+            String options = fs.getOptions();
+            String mode = options != null && Arrays.asList(options.split(",")).contains("rw") ? "rw" : "ro";

Add import java.util.Arrays; to the imports.

🤖 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-metrics/src/main/java/oshi/metrics/FileSystemMetrics.java` at line 62,
Guard against null returned by OSFileStore#getOptions() in FileSystemMetrics:
update the mode computation that currently uses fs.getOptions().split(",") to
first check for null (e.g., getOptions into a local variable opts and only call
split when opts != null), then use Arrays.asList(opts.split(",")) to test for
"rw"; also add import java.util.Arrays; reference fs.getOptions() and the line
computing mode in FileSystemMetrics.java so bindTo won't NPE and filesystem
registration continues.
🧹 Nitpick comments (1)
oshi-metrics/src/main/java/oshi/metrics/ContainerMetrics.java (1)

70-77: ⚡ Quick win

Cache PID 1's start time at bind time to avoid per-scrape process enumeration.

The lambda invokes os.getProcess(1) on every Micrometer scrape, which on Linux walks /proc/1/... (and on other platforms triggers the equivalent process lookup) just to read a value that is constant for the container's lifetime. Resolving init.getStartTime() once during bindTo and capturing it in the gauge closure keeps the polled work to a single subtraction, and lets the host-uptime fallback be decided at registration time too.

♻️ Proposed refactor
-        // container.uptime — Gauge, unit "s" (time since PID 1 started)
-        Gauge.builder(CONTAINER_UPTIME, os, o -> {
-            oshi.software.os.OSProcess init = o.getProcess(1);
-            if (init != null && init.getStartTime() > 0) {
-                return (System.currentTimeMillis() - init.getStartTime()) / 1000.0;
-            }
-            return (double) o.getSystemUptime();
-        }).description("The time the container has been running").baseUnit("s").register(registry);
+        // container.uptime — Gauge, unit "s" (time since PID 1 started, captured once)
+        OSProcess init = os.getProcess(1);
+        if (init != null && init.getStartTime() > 0) {
+            long startMs = init.getStartTime();
+            Gauge.builder(CONTAINER_UPTIME, startMs, s -> (System.currentTimeMillis() - s) / 1000.0)
+                    .description("The time the container has been running").baseUnit("s").register(registry);
+        } else {
+            Gauge.builder(CONTAINER_UPTIME, os, o -> (double) o.getSystemUptime())
+                    .description("The time the container has been running").baseUnit("s").register(registry);
+        }

You'll also want import oshi.software.os.OSProcess; added rather than the fully-qualified name on line 72.

🤖 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-metrics/src/main/java/oshi/metrics/ContainerMetrics.java` around lines
70 - 77, Cache PID 1's start time during bind/registration instead of calling
os.getProcess(1) on every scrape: in the method that registers CONTAINER_UPTIME,
call os.getProcess(1) once, compute a long initStartTime (e.g. -1 if not found
or startTime <= 0), and capture that final variable in the Gauge closure; then
have the closure return (System.currentTimeMillis() - initStartTime) / 1000.0
when initStartTime > 0, otherwise fall back to (double) o.getSystemUptime();
also add an import for oshi.software.os.OSProcess and remove the inline
fully-qualified type usage.
🤖 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-metrics/src/main/java/oshi/metrics/FileSystemMetrics.java`:
- Line 62: Guard against null returned by OSFileStore#getOptions() in
FileSystemMetrics: update the mode computation that currently uses
fs.getOptions().split(",") to first check for null (e.g., getOptions into a
local variable opts and only call split when opts != null), then use
Arrays.asList(opts.split(",")) to test for "rw"; also add import
java.util.Arrays; reference fs.getOptions() and the line computing mode in
FileSystemMetrics.java so bindTo won't NPE and filesystem registration
continues.

---

Nitpick comments:
In `@oshi-metrics/src/main/java/oshi/metrics/ContainerMetrics.java`:
- Around line 70-77: Cache PID 1's start time during bind/registration instead
of calling os.getProcess(1) on every scrape: in the method that registers
CONTAINER_UPTIME, call os.getProcess(1) once, compute a long initStartTime (e.g.
-1 if not found or startTime <= 0), and capture that final variable in the Gauge
closure; then have the closure return (System.currentTimeMillis() -
initStartTime) / 1000.0 when initStartTime > 0, otherwise fall back to (double)
o.getSystemUptime(); also add an import for oshi.software.os.OSProcess and
remove the inline fully-qualified type usage.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 5964de92-9e1b-4334-81ce-d3963e901b85

📥 Commits

Reviewing files that changed from the base of the PR and between 3b5a3b4 and 10cad6a.

📒 Files selected for processing (5)
  • oshi-metrics/src/main/java/oshi/metrics/ContainerMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/FileSystemMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java
  • oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.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: Analyze (java)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: JMH Benchmarks, windows-latest
🔇 Additional comments (2)
oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java (1)

41-141: Clean orchestrator: builder + convenience static + MeterBinder all line up.

The category-flag plumbing through both the public constructor and the Builder is straightforward, the convenience bindTo(registry, hal, os) matches what the README and Javadoc document, and the per-category dispatch in bindTo(MeterRegistry) cleanly composes each binder with the right OSHI handle (notably ContainerMetrics(os, os.getCgroupInfo()) matches that class's constructor). Welcome addition — looks good.

oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java (1)

23-297: Comprehensive test coverage across all metric categories.

Nice spread — registration, value bounds, and inter-metric relationships (logical ≥ physical CPU count, utilization in [0,1]) are all covered, and builderSelectiveRegistration validates that the per-category toggles actually gate registration. Past feedback on inclusive bounds and null-guards before .value()/.count() calls has been incorporated.

@dbwiddis
dbwiddis force-pushed the feature/oshi-metrics branch from 10cad6a to 224d7c4 Compare May 6, 2026 00:43

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 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-metrics/src/main/java/oshi/metrics/ContainerMetrics.java`:
- Around line 74-77: The CONTAINER_UPTIME gauge built in ContainerMetrics uses
Gauge.builder(CONTAINER_UPTIME, os, ...) but does not call
.strongReference(true); to match other gauges (e.g., the memory gauges) and
prevent the OperatingSystem backing object from being held weakly, add
.strongReference(true) to the builder chain before .register(registry) so the
uptime gauge retains a strong reference to the os object.

In `@oshi-metrics/src/main/java/oshi/metrics/FileSystemMetrics.java`:
- Around line 58-88: The gauges in FileSystemMetrics are using snapshot values
from OSFileStore and must call fs.updateAttributes() before reading live stats;
update each Gauge.builder lambda (the ones using f -> ... and
OSFileStore::getUsableSpace / OSFileStore::getTotalSpace) to first invoke
f.updateAttributes() (or fs.updateAttributes() in closures) and then return the
computed value so filesystem usage/utilization/limit reflect current values at
each metric read.

In `@oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java`:
- Around line 254-256: The CPU-only test is still enabling container metrics
because the builder defaults container to true; update the builder invocation in
OshiMetricsTest by calling OshiMetrics.builder(hal,
os)...enableProcess(false).enableContainer(false).build().bindTo(selective) so
the test explicitly disables container meters (use the enableContainer(false)
method on the same builder chain to keep intent and ensure selective
registration for container metrics is tested).
🪄 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: fd52eebf-92d8-440a-9a02-5ae65580a394

📥 Commits

Reviewing files that changed from the base of the PR and between 10cad6a and 224d7c4.

📒 Files selected for processing (5)
  • oshi-metrics/src/main/java/oshi/metrics/ContainerMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/FileSystemMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java
  • oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.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). (11)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Analyze (java)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: JMH Benchmarks, macos-latest

@dbwiddis
dbwiddis force-pushed the feature/oshi-metrics branch from 224d7c4 to 2d9cd81 Compare May 6, 2026 00:54
@dbwiddis

dbwiddis commented May 6, 2026

Copy link
Copy Markdown
Member Author

@CodeRabbit full review

@coderabbitai

coderabbitai Bot commented May 6, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Full review triggered.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (7)
oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java (1)

70-97: ⚡ Quick win

Each scrape triggers N+8 native CPU reads — cache the arrays once per sample window.

Both system.cpu.time and system.cpu.frequency invoke the underlying native query repeatedly per scrape:

  • getSystemCpuLoadTicks() is called once per registered TickType → 8 reads per scrape returning the same array.
  • getCurrentFreq() is called once per logical CPU → e.g., 16 reads on a 16‑core box, again returning the same array.

A 1‑second TTL cache (matching the NetworkMetrics pattern) reduces this to one native call per metric family per scrape and keeps tick values internally consistent across the 8 modes within a single scrape.

♻️ Sketch
+    private static final long CACHE_TTL_MS = 1000L;
+    private volatile long ticksTimestamp;
+    private volatile long[] cachedTicks = new long[TickType.values().length];
+    private volatile long freqTimestamp;
+    private volatile long[] cachedFreq = new long[0];
+
+    private synchronized long[] ticks() {
+        long now = System.currentTimeMillis();
+        if (now - ticksTimestamp > CACHE_TTL_MS) {
+            cachedTicks = processor.getSystemCpuLoadTicks();
+            ticksTimestamp = now;
+        }
+        return cachedTicks;
+    }
+    // ... similar for freq()
🤖 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-metrics/src/main/java/oshi/metrics/CpuMetrics.java` around lines 70 -
97, The metric builders call the native getters repeatedly per scrape
(getSystemCpuLoadTicks() inside the TickType loop and getCurrentFreq() inside
the logical CPU loop) causing N+8 native reads; implement a 1‑second sample
cache (like NetworkMetrics) that captures and reuses the arrays for the duration
of the sample window and expose accessor methods used by the builders.
Concretely, add a small cached-sample helper (timestamp + cached long[] for
ticks and long[] for freqs) referenced by the TickType loop that returns the
same getSystemCpuLoadTicks() array for all modes within a second and by the
CPU_FREQUENCY builders that returns a single getCurrentFreq() array per second,
then update the FunctionCounter/Gauge lambdas to call those cached accessors
instead of directly calling CentralProcessor.getSystemCpuLoadTicks() or
getCurrentFreq().
oshi-metrics/src/main/java/oshi/metrics/NetworkMetrics.java (1)

134-151: 💤 Low value

refreshCache() synchronized + volatile fields look correct; nice fix.

Atomicity is now intact and the volatile fields ensure visibility for the gauge readers. One small thought: since both tcpCounts and udpCount are read on every gauge sample, you may want to call refreshCache() only once per scrape rather than once per gauge. With ~10 TCP states, you currently take the synchronized lock 11× per scrape, even though only the first call actually refreshes — not a correctness issue, just lock-contention noise that disappears if the cache is keyed on a single timestamp check outside the synchronized block (double-checked TTL).

🤖 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-metrics/src/main/java/oshi/metrics/NetworkMetrics.java` around lines 134
- 151, refreshCache() currently acquires the synchronized lock on every gauge
call even when the cache is fresh; implement a double-checked TTL to reduce lock
contention by first checking cacheTimestamp vs CACHE_TTL_MS outside
synchronization and only entering synchronized block if expired, then recheck
cacheTimestamp inside before performing the refresh (update tcpCounts, udpCount,
cacheTimestamp using ipStats.getConnections()). Keep tcpCounts and udpCount
volatile as-is so readers see updates.
oshi-metrics/src/main/java/oshi/metrics/FileSystemMetrics.java (1)

66-99: ⚡ Quick win

Same updateAttributes() redundancy as DiskMetrics — 5 native refreshes per filesystem per scrape.

Each of the 5 gauge lambdas (used, free, util-used, util-free, limit) calls f.updateAttributes(), so a single scrape triggers 5 refreshes per OSFileStore. On Linux hosts that easily exposes dozens of mounts (overlay, tmpfs, cgroup, autofs…), this becomes a noticeable hot path.

A short-TTL cache (or memoizing the four numeric values once and reading them in subsequent gauges within the same window) keeps the four numeric values internally consistent within a scrape too — right now used+free can momentarily diverge from total because each lambda re-reads independently.

See the equivalent comment on DiskMetrics for a sketch; the same approach applies here.

🤖 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-metrics/src/main/java/oshi/metrics/FileSystemMetrics.java` around lines
66 - 99, The five Gauge lambdas in FileSystemMetrics each call
f.updateAttributes(), causing 5 native refreshes per OSFileStore per scrape;
change to update attributes once per scrape and reuse the cached numeric values
for all gauges. Implement per-OSFileStore memoization: call f.updateAttributes()
once (e.g., in a small helper or closure near where Gauge.builder(...) is
invoked), read f.getTotalSpace() and f.getUsableSpace() into local variables
(total, usable), compute used, free, and utilization from those cached values,
and have each Gauge.builder supplier return those precomputed numbers instead of
calling updateAttributes() again (reference FileSystemMetrics and the
OSFileStore fs used in the Gauge.builder blocks). Ensure cached values are
refreshed for each scrape window (short TTL / per-invocation cache) so metrics
remain synchronized.
oshi-metrics/src/test/java/oshi/metrics/PrometheusDemoTest.java (2)

22-22: 💤 Low value

Class-name convention: this is a runnable demo, not a test.

PrometheusDemoTest has no @Test methods — only main(String[] args) — yet the *Test suffix matches Surefire/Failsafe's default include patterns, which means the build will try to load and inspect it during the test phase even though it has nothing to assert. Consider renaming to PrometheusDemo (and/or relocating under a demo/examples source set) so the build doesn't waste cycles on it and so contributors aren't surprised that "the test" never actually runs.

🤖 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-metrics/src/test/java/oshi/metrics/PrometheusDemoTest.java` at line 22,
The class PrometheusDemoTest is a runnable demo containing only a main(String[]
args) entry and no `@Test` methods, which triggers test runners due to the *Test
suffix; rename the class to something like PrometheusDemo (or move it into a
demo/examples source set) and update any references to the class name so it no
longer matches Surefire/Failsafe include patterns, ensuring the runnable demo
main method remains intact and the build's test phase no longer attempts to load
it.

47-59: 💤 Low value

Hardcoded port 8080 and no shutdown hook — acceptable for a demo, worth a one-line caveat.

Port 8080 is a heavily contested local port (Tomcat, Spring Boot defaults, etc.); a contributor running this on a dev box with anything else listening will get a BindException with no actionable message. Also, start() returns immediately and the main exits the call frame; the demo only stays alive because HttpServer spins non-daemon threads. Both behaviors are reasonable for a quick demo, but a brief comment ("port can be overridden via env/system property in real use; HttpServer keeps the JVM alive via non-daemon threads") would save the next reader some head-scratching. Not blocking.

🤖 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-metrics/src/test/java/oshi/metrics/PrometheusDemoTest.java` around lines
47 - 59, In PrometheusDemoTest where the HttpServer is created with
HttpServer.create(new InetSocketAddress(8080), 0) and started via
server.start(), add a brief one-line caveat comment noting that the port 8080 is
hardcoded and may collide with local services and can be overridden in real use
via an env var or system property, and also add a shutdown hook
(Runtime.getRuntime().addShutdownHook) that calls server.stop(0) to ensure clean
shutdown; reference the local variable server and the HttpServer.create/start
calls when locating where to add the comment and the hook.
oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java (2)

96-98: 💤 Low value

Optional: consider documenting bindTo re-invocation semantics.

OshiMetrics.bindTo(...) and the instance bindTo(MeterRegistry) will happily register the same gauges/counters twice if invoked more than once against the same registry, which Micrometer treats as a duplicate-meter situation depending on the registry's filter config. A short Javadoc note ("call once per registry") would steer Spring Boot users away from accidental double-binding when both manual wiring and MeterBinder auto-discovery are in play. Not blocking.

🤖 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-metrics/src/main/java/oshi/metrics/OshiMetrics.java` around lines 96 -
98, Add a short Javadoc comment to the static method
OshiMetrics.bindTo(MeterRegistry, HardwareAbstractionLayer, OperatingSystem)
(and mirror note on the instance method bindTo(MeterRegistry)) stating that
calling bindTo more than once against the same MeterRegistry will register
duplicate meters and therefore callers should only bind once per registry (e.g.,
"Call once per registry — repeated invocations will attempt to register the same
gauges/counters and may be treated as duplicates by the MeterRegistry"). This
should be added directly above the method signatures for OshiMetrics.bindTo to
make the re-invocation semantics clear to users.

100-129: 💤 Low value

Minor: hal.getMemory() evaluated twice.

Lines 105–110 call hal.getMemory() twice when both memory and paging are enabled. Caching the GlobalMemory reference in a local would avoid the redundant lookup and guarantee both binders see the same instance.

The concern about VirtualMemory, InternetProtocolStats, and cgroup objects being snapshots is not an issue—the metric binders store live references and invoke their methods during each metric scrape (via Gauge/FunctionCounter builders with lambdas), not at bind time.

♻️ Optional cleanup for the duplicate `getMemory()` call
     `@Override`
     public void bindTo(MeterRegistry registry) {
         if (general) {
             new GeneralMetrics(os).bindTo(registry);
         }
+        GlobalMemory mem = (memory || paging) ? hal.getMemory() : null;
         if (memory) {
-            new MemoryMetrics(hal.getMemory()).bindTo(registry);
+            new MemoryMetrics(mem).bindTo(registry);
         }
         if (paging) {
-            new PagingMetrics(hal.getMemory().getVirtualMemory()).bindTo(registry);
+            new PagingMetrics(mem.getVirtualMemory()).bindTo(registry);
         }

(would also need import oshi.hardware.GlobalMemory;)

🤖 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-metrics/src/main/java/oshi/metrics/OshiMetrics.java` around lines 100 -
129, Cache the GlobalMemory from hal.getMemory() into a local variable before
creating binders so MemoryMetrics and PagingMetrics use the same instance (e.g.,
call hal.getMemory() once and pass that local to new MemoryMetrics(...) and new
PagingMetrics(...)); update bindTo usage in the bindTo method (references:
bindTo, hal.getMemory(), MemoryMetrics, PagingMetrics, VirtualMemory) and add
the necessary import for oshi.hardware.GlobalMemory.
🤖 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-metrics/src/main/java/oshi/metrics/DiskMetrics.java`:
- Around line 70-97: The code currently calls disk.updateAttributes() inside
each FunctionCounter lambda (in the FunctionCounter.builder blocks for DISK_IO,
DISK_OPERATIONS, and DISK_IO_TIME), causing redundant platform calls per scrape;
modify bindTo so you refresh attributes once per disk per scrape (e.g., call a
single maybeRefresh(disk) or disk.updateAttributes() guarded by a short-lived
timestamp/cache prior to creating/registering the five counters) or extract a
shared helper that returns cached disk values so the five lambdas read the
cached snapshot instead of invoking updateAttributes() themselves; ensure the
helper uses a per-disk, per-scrape freshness check to keep metrics consistent.

In `@oshi-metrics/src/main/java/oshi/metrics/NetworkMetrics.java`:
- Around line 80-112: The FunctionCounter builders in NetworkMetrics currently
use raw NetworkIF method references (e.g., NetworkIF::getBytesRecv,
getBytesSent, getPacketsRecv, getPacketsSent, getInDrops, getInErrors,
getOutErrors) which read stale snapshot values because updateAttributes() is
never called; modify NetworkMetrics so each interface's counters call
net.updateAttributes() once per scrape before returning values (e.g., wrap the
suppliers passed to FunctionCounter.builder with a lightweight per-interface
refresh/TTL that calls net.updateAttributes() and then returns the requested
NetworkIF getter), ensuring all six counters per NetworkIF observe the same
refreshed snapshot while avoiding redundant system calls.

---

Nitpick comments:
In `@oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java`:
- Around line 70-97: The metric builders call the native getters repeatedly per
scrape (getSystemCpuLoadTicks() inside the TickType loop and getCurrentFreq()
inside the logical CPU loop) causing N+8 native reads; implement a 1‑second
sample cache (like NetworkMetrics) that captures and reuses the arrays for the
duration of the sample window and expose accessor methods used by the builders.
Concretely, add a small cached-sample helper (timestamp + cached long[] for
ticks and long[] for freqs) referenced by the TickType loop that returns the
same getSystemCpuLoadTicks() array for all modes within a second and by the
CPU_FREQUENCY builders that returns a single getCurrentFreq() array per second,
then update the FunctionCounter/Gauge lambdas to call those cached accessors
instead of directly calling CentralProcessor.getSystemCpuLoadTicks() or
getCurrentFreq().

In `@oshi-metrics/src/main/java/oshi/metrics/FileSystemMetrics.java`:
- Around line 66-99: The five Gauge lambdas in FileSystemMetrics each call
f.updateAttributes(), causing 5 native refreshes per OSFileStore per scrape;
change to update attributes once per scrape and reuse the cached numeric values
for all gauges. Implement per-OSFileStore memoization: call f.updateAttributes()
once (e.g., in a small helper or closure near where Gauge.builder(...) is
invoked), read f.getTotalSpace() and f.getUsableSpace() into local variables
(total, usable), compute used, free, and utilization from those cached values,
and have each Gauge.builder supplier return those precomputed numbers instead of
calling updateAttributes() again (reference FileSystemMetrics and the
OSFileStore fs used in the Gauge.builder blocks). Ensure cached values are
refreshed for each scrape window (short TTL / per-invocation cache) so metrics
remain synchronized.

In `@oshi-metrics/src/main/java/oshi/metrics/NetworkMetrics.java`:
- Around line 134-151: refreshCache() currently acquires the synchronized lock
on every gauge call even when the cache is fresh; implement a double-checked TTL
to reduce lock contention by first checking cacheTimestamp vs CACHE_TTL_MS
outside synchronization and only entering synchronized block if expired, then
recheck cacheTimestamp inside before performing the refresh (update tcpCounts,
udpCount, cacheTimestamp using ipStats.getConnections()). Keep tcpCounts and
udpCount volatile as-is so readers see updates.

In `@oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java`:
- Around line 96-98: Add a short Javadoc comment to the static method
OshiMetrics.bindTo(MeterRegistry, HardwareAbstractionLayer, OperatingSystem)
(and mirror note on the instance method bindTo(MeterRegistry)) stating that
calling bindTo more than once against the same MeterRegistry will register
duplicate meters and therefore callers should only bind once per registry (e.g.,
"Call once per registry — repeated invocations will attempt to register the same
gauges/counters and may be treated as duplicates by the MeterRegistry"). This
should be added directly above the method signatures for OshiMetrics.bindTo to
make the re-invocation semantics clear to users.
- Around line 100-129: Cache the GlobalMemory from hal.getMemory() into a local
variable before creating binders so MemoryMetrics and PagingMetrics use the same
instance (e.g., call hal.getMemory() once and pass that local to new
MemoryMetrics(...) and new PagingMetrics(...)); update bindTo usage in the
bindTo method (references: bindTo, hal.getMemory(), MemoryMetrics,
PagingMetrics, VirtualMemory) and add the necessary import for
oshi.hardware.GlobalMemory.

In `@oshi-metrics/src/test/java/oshi/metrics/PrometheusDemoTest.java`:
- Line 22: The class PrometheusDemoTest is a runnable demo containing only a
main(String[] args) entry and no `@Test` methods, which triggers test runners due
to the *Test suffix; rename the class to something like PrometheusDemo (or move
it into a demo/examples source set) and update any references to the class name
so it no longer matches Surefire/Failsafe include patterns, ensuring the
runnable demo main method remains intact and the build's test phase no longer
attempts to load it.
- Around line 47-59: In PrometheusDemoTest where the HttpServer is created with
HttpServer.create(new InetSocketAddress(8080), 0) and started via
server.start(), add a brief one-line caveat comment noting that the port 8080 is
hardcoded and may collide with local services and can be overridden in real use
via an env var or system property, and also add a shutdown hook
(Runtime.getRuntime().addShutdownHook) that calls server.stop(0) to ensure clean
shutdown; reference the local variable server and the HttpServer.create/start
calls when locating where to add the comment and the hook.
🪄 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: 44c6702c-86e3-42c6-9afb-6857b4b852b6

📥 Commits

Reviewing files that changed from the base of the PR and between f292bad and 2d9cd81.

📒 Files selected for processing (19)
  • CHANGELOG.md
  • config/import-control-test.xml
  • config/import-control.xml
  • oshi-metrics/README.md
  • oshi-metrics/pom.xml
  • oshi-metrics/src/main/java/oshi/metrics/ContainerMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/CpuMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/DiskMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/FileSystemMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/GeneralMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/NetworkMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/PagingMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/package-info.java
  • oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java
  • oshi-metrics/src/test/java/oshi/metrics/PrometheusDemoTest.java
  • pom.xml
📜 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). (6)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
🔇 Additional comments (16)
config/import-control.xml (1)

111-115: Scoped import-control update looks correct.

The new metrics subpackage rules are focused and align with the production Micrometer usage in this module.

oshi-metrics/src/main/java/oshi/metrics/package-info.java (1)

5-8: Package-level Javadoc is clear and aligned with module intent.

Nice, concise package documentation for the new metrics surface.

CHANGELOG.md (1)

4-4: Changelog entry is clear and release-appropriate.

Good addition for discoverability of the new module in 7.1.0.

pom.xml (1)

747-747: Build/profile wiring for oshi-metrics looks good.

The Java 17 profile activation and module inclusion are consistent with the new module’s target runtime.

Also applies to: 1024-1033

oshi-metrics/pom.xml (1)

17-21: Module dependency setup matches the intended contract.

Java level, dependency scopes, and test dependencies are coherent with the lightweight oshi-metrics design.

Also applies to: 23-60

oshi-metrics/src/main/java/oshi/metrics/GeneralMetrics.java (1)

41-47: General metrics binder implementation looks solid.

The gauges, units, and descriptions are straightforward and correctly registered.

config/import-control-test.xml (1)

50-58: Test import-control updates are appropriately scoped.

The new allowances fit the Prometheus/demo test use cases without broadening global test imports excessively.

oshi-metrics/README.md (1)

6-77: README coverage is thorough and practical.

Great job documenting setup, selective registration, Spring Boot usage, and implemented/not-implemented metric scope.

Also applies to: 79-197

oshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.java (1)

71-122: ⚡ Quick win

Per-scrape processSupplier.get() fan-out remains unaddressed.

A quick re-check: the 12 meters here each call processSupplier.get() independently, so a single scrape still triggers ~12 reads of /proc/<pid>/* (or platform equivalent), and CPU/memory/IO numbers within one scrape are not from the same snapshot. The previous suggestion to add a 1‑second TTL cache (matching NetworkMetrics) has not landed yet — flagging again so it isn't lost.

oshi-metrics/src/main/java/oshi/metrics/DiskMetrics.java (1)

99-103: Disk size is effectively static — Gauge here is fine, no updateAttributes() needed.

Skipping updateAttributes() for system.disk.limit is correct since getSize() doesn't change at runtime. Just calling this out so it doesn't regress later.

oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java (2)

41-87: Class structure looks clean and well-documented.

The dual-constructor pattern (full registration + builder-based selective) reads nicely, the Javadoc is comprehensive with concrete usage examples, and the oshi-common-only dependency posture is correctly called out for JNA/FFM compatibility. Per the prior thread, the unused os field is intentional as a placeholder for upcoming OS-level metric expansion.


148-274: Builder API is clear and consistent.

Default-on with explicit enableX(false) opt-out is a sensible choice for a "first-party" integration where users typically want the full set; the symmetry with the public constructor's defaults keeps the two construction paths predictable. No concerns.

oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java (3)

23-263: Solid coverage for a v1 of this module.

Test breadth is impressive — every category exposed by OshiMetrics.bindTo has at least one registration assertion plus a basic value-range sanity check, and builderSelectiveRegistration exercises both positive (CPU registered) and negative (memory/network not registered) paths through the builder. Past-review nits about NPE-prone .gauge()/.functionCounter() chains and inclusive [0,1] utilization bounds have all been addressed. Nice work.


274-282: Metric names are correctly registered in ProcessMetrics.

The process.memory.usage and process.memory.virtual metrics are properly registered as Gauges in the ProcessMetrics.bindTo() method with the exact names expected by this test. No typos or renames here—your assertions are safe.


81-91: All eight CPU modes are always registered across platforms — this test is correctly written.

The CpuMetrics.bindTo() method iterates over TickType.values() (all 8 enum members), mapping each to a mode string and registering a counter for every one, regardless of platform. On Windows and macOS where some modes have no underlying tick counter, the value is 0, but the counter exists and is tagged correctly. Your test expectation is spot-on, and this will pass consistently on all platforms. Nice work!

oshi-metrics/src/test/java/oshi/metrics/PrometheusDemoTest.java (1)

18-19: No issues found with the Prometheus dependency setup.

The imports io.micrometer.prometheusmetrics.PrometheusConfig and PrometheusMeterRegistry are correctly sourced from micrometer-registry-prometheus (v1.14.11), which is properly declared in test scope. No additional micrometer-prometheusmetrics artifact is required.

Comment on lines +70 to +97
FunctionCounter.builder(DISK_IO, disk, d -> {
d.updateAttributes();
return d.getReadBytes();
}).tag(DEVICE_KEY, device).tag(DIRECTION_KEY, "read").description("Disk bytes transferred").baseUnit("By")
.register(registry);
FunctionCounter.builder(DISK_IO, disk, d -> {
d.updateAttributes();
return d.getWriteBytes();
}).tag(DEVICE_KEY, device).tag(DIRECTION_KEY, "write").description("Disk bytes transferred").baseUnit("By")
.register(registry);

// system.disk.operations — Counter, unit "{operation}", attrs: disk.io.direction, system.device
FunctionCounter.builder(DISK_OPERATIONS, disk, d -> {
d.updateAttributes();
return d.getReads();
}).tag(DEVICE_KEY, device).tag(DIRECTION_KEY, "read").description("Disk operations count")
.baseUnit("{operation}").register(registry);
FunctionCounter.builder(DISK_OPERATIONS, disk, d -> {
d.updateAttributes();
return d.getWrites();
}).tag(DEVICE_KEY, device).tag(DIRECTION_KEY, "write").description("Disk operations count")
.baseUnit("{operation}").register(registry);

// system.disk.io_time — Counter, unit "s", attr: system.device
FunctionCounter.builder(DISK_IO_TIME, disk, d -> {
d.updateAttributes();
return d.getTransferTime() / MS_PER_SECOND;
}).tag(DEVICE_KEY, device).description("Time disk spent activated").baseUnit("s").register(registry);

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

Micrometer FunctionCounter sampling order single registry scrape thread safety

💡 Result:

Micrometer's FunctionCounter is thread-safe for concurrent sampling. It works like a gauge, sampling a user-provided monotonically increasing function (ToDoubleFunction) on each access, such as during registry scrape [1][2][3][4]. The Meter.measure method, called during scrape, must return consistent measurements in the same order regardless of activity [1][5]. Examples use thread-safe state like AtomicInteger [6]. The user's function must be thread-safe and monotonic; Micrometer does not enforce monotonicity [7][3]. For a single MeterRegistry (e.g., PrometheusMeterRegistry), scrape (e.g., /metrics endpoint) is safe even under concurrent meter updates or sampling, as registry uses locks/synchronization for mutations (e.g., meterMapLock) while getMeters returns safe views [8][9][10]. Concurrent registration has race conditions fixed over time [11], but sampling/measure is designed safe. Prometheus scrape iterates all meters safely [12][13][14]. No evidence of required single-threaded scrape; designed for concurrent app threads [15][10].

Citations:


🏁 Script executed:

# First, locate and examine DiskMetrics.java to confirm the updateAttributes() calls
find . -name "DiskMetrics.java" -type f

Repository: oshi/oshi

Length of output: 112


🏁 Script executed:

# Also check for NetworkMetrics to verify the TTL cache pattern mentioned
find . -name "NetworkMetrics.java" -type f

Repository: oshi/oshi

Length of output: 115


🏁 Script executed:

# Look for HWDiskStore in the OSHI dependency to understand the synchronization requirements
find . -name "HWDiskStore.java" -type f

Repository: oshi/oshi

Length of output: 112


🏁 Script executed:

# Check the length of DiskMetrics.java first
wc -l ./oshi-metrics/src/main/java/oshi/metrics/DiskMetrics.java

Repository: oshi/oshi

Length of output: 116


🏁 Script executed:

# Read DiskMetrics.java to see the full context around lines 70-97
cat -n ./oshi-metrics/src/main/java/oshi/metrics/DiskMetrics.java

Repository: oshi/oshi

Length of output: 5428


🏁 Script executed:

# Check NetworkMetrics to verify if it uses a TTL cache pattern
wc -l ./oshi-metrics/src/main/java/oshi/metrics/NetworkMetrics.java

Repository: oshi/oshi

Length of output: 119


🏁 Script executed:

# Read NetworkMetrics to see the pattern mentioned in the review
cat -n ./oshi-metrics/src/main/java/oshi/metrics/NetworkMetrics.java

Repository: oshi/oshi

Length of output: 8776


🏁 Script executed:

# Check HWDiskStore to understand updateAttributes() and thread-safety requirements
wc -l ./oshi-common/src/main/java/oshi/hardware/HWDiskStore.java

Repository: oshi/oshi

Length of output: 116


🏁 Script executed:

# Read relevant parts of HWDiskStore
head -100 ./oshi-common/src/main/java/oshi/hardware/HWDiskStore.java

Repository: oshi/oshi

Length of output: 2730


🏁 Script executed:

# Read the rest of HWDiskStore to see the updateAttributes() method documentation
tail -80 ./oshi-common/src/main/java/oshi/hardware/HWDiskStore.java

Repository: oshi/oshi

Length of output: 2075


Cache updateAttributes() to avoid redundant system calls—5× overhead per disk per scrape.

Each Micrometer scrape invokes d.updateAttributes() five times per disk (read bytes, write bytes, reads, writes, transfer time). On systems with many disk devices or partitions, this multiplies unnecessary platform I/O; a single system call per disk per scrape is sufficient. Consider a short-lived timestamp cache to guard the update:

Suggested pattern
+    private static final long REFRESH_TTL_MS = 1000L;
+    private final Map<HWDiskStore, Long> lastRefresh = new ConcurrentHashMap<>();
+    
+    private void maybeRefresh(HWDiskStore d) {
+        long now = System.currentTimeMillis();
+        Long prev = lastRefresh.get(d);
+        if (prev == null || now - prev > REFRESH_TTL_MS) {
+            synchronized (d) {
+                Long again = lastRefresh.get(d);
+                if (again == null || now - again > REFRESH_TTL_MS) {
+                    d.updateAttributes();
+                    lastRefresh.put(d, now);
+                }
+            }
+        }
+    }

Then call maybeRefresh(disk) once per disk at the start of the bindTo loop, or embed a similar check in a shared helper method all five counters call.

This also keeps metrics within a single scrape consistent against the same disk snapshot.

🤖 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-metrics/src/main/java/oshi/metrics/DiskMetrics.java` around lines 70 -
97, The code currently calls disk.updateAttributes() inside each FunctionCounter
lambda (in the FunctionCounter.builder blocks for DISK_IO, DISK_OPERATIONS, and
DISK_IO_TIME), causing redundant platform calls per scrape; modify bindTo so you
refresh attributes once per disk per scrape (e.g., call a single
maybeRefresh(disk) or disk.updateAttributes() guarded by a short-lived
timestamp/cache prior to creating/registering the five counters) or extract a
shared helper that returns cached disk values so the five lambdas read the
cached snapshot instead of invoking updateAttributes() themselves; ensure the
helper uses a per-disk, per-scrape freshness check to keep metrics consistent.

@dbwiddis
dbwiddis force-pushed the feature/oshi-metrics branch from 2d9cd81 to 2e0bf37 Compare May 6, 2026 01:10

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (1)
oshi-metrics/src/main/java/oshi/metrics/FileSystemMetrics.java (1)

66-98: ⚡ Quick win

Each scrape triggers 5 updateAttributes() system calls per filesystem.

Every gauge lambda independently calls f.updateAttributes(), so a single Micrometer publish cycle invokes it five times per OSFileStore (used/free usage, used/free utilization, limit). Beyond being wasteful, this also means usage(used) + usage(free) and limit may not be perfectly consistent within one scrape because each underlying system call can return slightly different totals — and OSHI's OSFileStore.updateAttributes() Javadoc explicitly recommends not invoking it more than ~once per second.

NetworkMetrics already addressed the analogous problem with a per-object TTL refresh (≈1 s) in commit 2e0bf37. Applying the same pattern here would keep the four/five gauges per filesystem internally consistent and avoid redundant I/O.

♻️ Sketch of the refactor
+    private static final long FS_REFRESH_TTL_MS = 1000L;
+    private final java.util.Map<OSFileStore, Long> fsLastRefresh = new java.util.concurrent.ConcurrentHashMap<>();
+
+    private OSFileStore refreshed(OSFileStore fs) {
+        long now = System.currentTimeMillis();
+        Long prev = fsLastRefresh.get(fs);
+        if (prev == null || now - prev > FS_REFRESH_TTL_MS) {
+            synchronized (fs) {
+                Long again = fsLastRefresh.get(fs);
+                if (again == null || now - again > FS_REFRESH_TTL_MS) {
+                    fs.updateAttributes();
+                    fsLastRefresh.put(fs, now);
+                }
+            }
+        }
+        return fs;
+    }

…and replace each f.updateAttributes(); return …; body with refreshed(f).….

🤖 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-metrics/src/main/java/oshi/metrics/FileSystemMetrics.java` around lines
66 - 98, The lambdas used for Gauge builders FS_USAGE, FS_UTILIZATION and
FS_LIMIT call f.updateAttributes() independently, causing multiple system calls
per scrape and inconsistent values; add a per-OSFileStore TTL-based refresh
helper (e.g., refreshed(OSFileStore f)) that only calls f.updateAttributes()
when the last refresh is older than ~1s, using a thread-safe cache keyed by the
OSFileStore (Weak/Concurrent map or ConcurrentHashMap<OSFileStore, AtomicLong>
for timestamps) to avoid memory leaks, and replace each f.updateAttributes()
call in the Gauge lambdas with refreshed(f) so all gauges for a file store share
the same recent attributes within a scrape.
🤖 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-metrics/README.md`:
- Around line 53-65: The README’s builder example omits the container category:
add an .enableContainer(true) call into the fluent builder chain (alongside
.enableGeneral(true), .enableCpu(true), etc.) before .build().bindTo(registry)
so the example matches the documented categories and shows how to enable
container metrics using the enableContainer() method.

In `@oshi-metrics/src/main/java/oshi/metrics/ContainerMetrics.java`:
- Around line 90-93: The Gauge for CONTAINER_MEMORY_AVAILABLE in
ContainerMetrics currently computes cgroup.getMemoryLimit() - c.getMemoryUsage()
which can become negative if usage transiently exceeds the limit; change the
value supplier used in Gauge.builder (the lambda passed to
Gauge.builder(CONTAINER_MEMORY_AVAILABLE, cgroup, c -> ...)) to clamp the result
with Math.max(0L, c.getMemoryLimit() - c.getMemoryUsage()) so the gauge never
reports negative available bytes and then register it as before with registry.

In `@oshi-metrics/src/main/java/oshi/metrics/NetworkMetrics.java`:
- Around line 140-146: The UDP Gauge registration for metric name
NET_CONNECTIONS (system.network.connection.count) is missing the STATE_KEY tag
which makes tag keys inconsistent with the TCP gauges; update the UDP
registration in NetworkMetrics (the Gauge.builder call that uses
getCachedUdpCount) to include the same STATE_KEY tag as the TCP gauges (e.g.,
.tag(STATE_KEY, "connectionless") or another explicit placeholder) so all meters
with NET_CONNECTIONS share identical tag keys (alternatively, if UDP semantics
differ, create a distinct metric name instead).

---

Nitpick comments:
In `@oshi-metrics/src/main/java/oshi/metrics/FileSystemMetrics.java`:
- Around line 66-98: The lambdas used for Gauge builders FS_USAGE,
FS_UTILIZATION and FS_LIMIT call f.updateAttributes() independently, causing
multiple system calls per scrape and inconsistent values; add a per-OSFileStore
TTL-based refresh helper (e.g., refreshed(OSFileStore f)) that only calls
f.updateAttributes() when the last refresh is older than ~1s, using a
thread-safe cache keyed by the OSFileStore (Weak/Concurrent map or
ConcurrentHashMap<OSFileStore, AtomicLong> for timestamps) to avoid memory
leaks, and replace each f.updateAttributes() call in the Gauge lambdas with
refreshed(f) so all gauges for a file store share the same recent attributes
within a scrape.
🪄 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: d71e1f93-ba28-4510-8d59-e525e6bbf371

📥 Commits

Reviewing files that changed from the base of the PR and between 2d9cd81 and 2e0bf37.

📒 Files selected for processing (7)
  • oshi-metrics/README.md
  • oshi-metrics/src/main/java/oshi/metrics/ContainerMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/FileSystemMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/NetworkMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java
  • oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.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 comments (3)
oshi-metrics/README.md (2)

27-27: Update the JDK version requirement for oshi-core-ffm to reflect actual FFM stabilization.

Line 27 states "JDK 25+" but the Foreign Function & Memory API became stable in JDK 22. Change this to "JDK 22+" to accurately reflect the minimum version users need.


150-150: Verify dropped packet direction support.

The documentation states dropped packets are "(receive only)", which suggests transmit-direction drops aren't available. Please confirm this is a limitation of OSHI's NetworkIF API rather than an implementation choice, as networks can drop packets in both directions.

#!/bin/bash
# Description: Check what packet drop metrics OSHI's NetworkIF interface exposes

# Search for NetworkIF interface methods related to dropped packets
ast-grep --pattern 'interface NetworkIF {
  $$$
  $_ getPackets$_($$$);
  $$$
}'

# Look for dropped packet getters
rg -n "getOut.*Drop|getPacketsSent.*Drop|InDrops|OutDrops" --type=java -C2
oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java (1)

23-297: Comprehensive test coverage across all metric domains.

The test suite covers every category exposed by OshiMetrics (uptime, process count, memory, CPU, paging, disk, filesystem, network, process), validates both presence and reasonable value bounds, and exercises the builder's selective-registration path with assertNull checks confirming disabled categories are absent. The earlier round of review feedback (NPE guards, inclusive utilization bounds, explicit enableContainer(false) in the selective test) is all incorporated. Nice work.

Comment thread oshi-metrics/README.md Resolved
Comment on lines +140 to +146
Gauge.builder(NET_CONNECTIONS, this, self -> self.getCachedTcpCount(state)).tag(TRANSPORT_KEY, "tcp")
.tag(STATE_KEY, stateValue).description("Total number of connections in each state")
.baseUnit("{connection}").strongReference(true).register(registry);
}
Gauge.builder(NET_CONNECTIONS, this, self -> self.getCachedUdpCount()).tag(TRANSPORT_KEY, "udp")
.description("Total number of UDP connections").baseUnit("{connection}").strongReference(true)
.register(registry);

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Inconsistent tag keys for system.network.connection.count between TCP and UDP gauges.

The TCP gauges (line 140) register with tags {network.transport, network.connection.state}, while the UDP gauge (line 144) registers only {network.transport} — missing network.connection.state. Micrometer's convention is that all meters sharing a metric name should declare the same tag keys; mixing tag sets can lead to dropped meters, empty-string label values, or registry warnings depending on the backend (e.g., Prometheus, OTel, Datadog).

Two reasonable options:

  • Add a placeholder state to the UDP gauge (e.g., state="open" or state="connectionless"), or
  • Use a separate metric name for UDP if the semantics genuinely differ.
🛠️ Suggested patch (option A)
-        Gauge.builder(NET_CONNECTIONS, this, self -> self.getCachedUdpCount()).tag(TRANSPORT_KEY, "udp")
+        Gauge.builder(NET_CONNECTIONS, this, self -> self.getCachedUdpCount()).tag(TRANSPORT_KEY, "udp")
+                .tag(STATE_KEY, "open")
                 .description("Total number of UDP connections").baseUnit("{connection}").strongReference(true)
                 .register(registry);
Micrometer convention: must all meters with the same name have the same tag keys? What happens in Prometheus and OpenTelemetry exporters when tag sets differ?
🤖 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-metrics/src/main/java/oshi/metrics/NetworkMetrics.java` around lines 140
- 146, The UDP Gauge registration for metric name NET_CONNECTIONS
(system.network.connection.count) is missing the STATE_KEY tag which makes tag
keys inconsistent with the TCP gauges; update the UDP registration in
NetworkMetrics (the Gauge.builder call that uses getCachedUdpCount) to include
the same STATE_KEY tag as the TCP gauges (e.g., .tag(STATE_KEY,
"connectionless") or another explicit placeholder) so all meters with
NET_CONNECTIONS share identical tag keys (alternatively, if UDP semantics
differ, create a distinct metric name instead).

- container.uptime (Gauge, seconds)
- container.cpu.time (FunctionCounter, seconds, from cgroup CPU usage)
- container.memory.usage (Gauge, bytes)
- container.memory.available (Gauge, bytes, limit - usage when limit is set)

Only registers when CgroupInfo.isContainerized() returns true.
Builder: added enableContainer() option.
@dbwiddis
dbwiddis force-pushed the feature/oshi-metrics branch from 2e0bf37 to 3710a89 Compare May 6, 2026 02:51

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

♻️ Duplicate comments (1)
oshi-metrics/src/main/java/oshi/metrics/NetworkMetrics.java (1)

144-146: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

UDP gauge still missing the network.connection.state tag — tag-key set diverges from the TCP gauges.

The TCP gauges register system.network.connection.count with {network.transport, network.connection.state}, but the UDP gauge below it registers only {network.transport}. Micrometer expects all meters sharing a name to declare the same tag keys; mixed tag sets can lead to dropped meters or empty-string label values in Prometheus / OTel exporters.

🛡️ Suggested fix
-        Gauge.builder(NET_CONNECTIONS, this, self -> self.getCachedUdpCount()).tag(TRANSPORT_KEY, "udp")
-                .description("Total number of UDP connections").baseUnit("{connection}").strongReference(true)
-                .register(registry);
+        Gauge.builder(NET_CONNECTIONS, this, self -> self.getCachedUdpCount()).tag(TRANSPORT_KEY, "udp")
+                .tag(STATE_KEY, "open")
+                .description("Total number of UDP connections").baseUnit("{connection}").strongReference(true)
+                .register(registry);
🤖 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-metrics/src/main/java/oshi/metrics/NetworkMetrics.java` around lines 144
- 146, The UDP Gauge (NET_CONNECTIONS using getCachedUdpCount) is missing the
network.connection.state tag key that the TCP gauges include, causing
inconsistent tag sets; update the UDP registration to include the same state tag
key (the same constant used by the TCP gauges, e.g., CONNECTION_STATE_KEY or
equivalent) and supply a suitable value (e.g., "unknown" or the appropriate UDP
state) so the Meter has the same tag keys as the TCP meters.
🧹 Nitpick comments (2)
oshi-metrics/src/main/java/oshi/metrics/NetworkMetrics.java (1)

78-127: ⚡ Quick win

Consider implementing a TTL cache for NetworkIF.updateAttributes() to avoid redundant system calls.

Currently, each of the six per-interface counters (rx/tx bytes, rx/tx packets, rx drops, rx/tx errors) calls n.updateAttributes() within its own lambda, resulting in 6 successive system calls per interface per scrape. Per OSHI's documentation, updateAttributes() should not be called more frequently than approximately once per second, and invoking it 6× means the counters may observe slightly different snapshots—making per-scrape totals (e.g., rx bytes vs rx packets) inconsistent.

This module already uses the TTL pattern in refreshCache() for ipStats; applying it here would refresh once per scrape and keep all counters consistent.

♻️ Sketch — `refreshed(net)` helper with 1 s TTL
+    private static final long IF_REFRESH_TTL_MS = 1000L;
+    private final java.util.Map<NetworkIF, Long> ifLastRefresh = new java.util.concurrent.ConcurrentHashMap<>();
+
+    private NetworkIF refreshed(NetworkIF n) {
+        long now = System.currentTimeMillis();
+        Long prev = ifLastRefresh.get(n);
+        if (prev == null || now - prev > IF_REFRESH_TTL_MS) {
+            synchronized (n) {
+                Long again = ifLastRefresh.get(n);
+                if (again == null || now - again > IF_REFRESH_TTL_MS) {
+                    n.updateAttributes();
+                    ifLastRefresh.put(n, now);
+                }
+            }
+        }
+        return n;
+    }
@@
-            FunctionCounter.builder(NET_IO, net, n -> {
-                n.updateAttributes();
-                return n.getBytesRecv();
-            })...
+            FunctionCounter.builder(NET_IO, net, n -> refreshed(n).getBytesRecv())...

(Apply analogously to the remaining five lambdas.)

🤖 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-metrics/src/main/java/oshi/metrics/NetworkMetrics.java` around lines 78
- 127, The per-interface counters in NetworkMetrics.bindTo call
NetworkIF.updateAttributes() six times per scrape; add a TTL refresh helper
(e.g., private boolean refreshed(NetworkIF net)) with a 1s TTL (store
lastRefresh timestamps keyed by net.getName() or NetworkIF) similar to the
existing refreshCache/ipStats pattern so updateAttributes() is invoked at most
once per scrape; call refreshed(net) from each lambda before reading
bytes/packets/errors so all FunctionCounter lambdas use the same snapshot, and
ensure thread-safety if metrics scrapes are concurrent.
oshi-metrics/src/main/java/oshi/metrics/FileSystemMetrics.java (1)

56-100: ⚡ Quick win

Consider a per-OSFileStore TTL cache to reduce redundant polling.

Each scrape currently invokes f.updateAttributes() five times per filesystem (once per gauge: used, free, used-util, free-util, limit). For a host with N filesystems, that's 5N syscalls per scrape. More importantly, the five independent reads can observe different snapshots — so within a single scrape, used + free may not equal limit.

NetworkMetrics already uses a similar pattern with refreshCache() and CACHE_TTL_MS = 1000L; mirroring it here would give each scrape one consistent snapshot per filesystem and reduce syscalls 5×.

♻️ Sketch — per-`OSFileStore` TTL refresh helper
+    private static final long FS_REFRESH_TTL_MS = 1000L;
+    private final java.util.Map<OSFileStore, Long> lastRefresh = new java.util.concurrent.ConcurrentHashMap<>();
+
+    private OSFileStore refreshed(OSFileStore fs) {
+        long now = System.currentTimeMillis();
+        Long prev = lastRefresh.get(fs);
+        if (prev == null || now - prev > FS_REFRESH_TTL_MS) {
+            synchronized (fs) {
+                Long again = lastRefresh.get(fs);
+                if (again == null || now - again > FS_REFRESH_TTL_MS) {
+                    fs.updateAttributes();
+                    lastRefresh.put(fs, now);
+                }
+            }
+        }
+        return fs;
+    }
@@
-            Gauge.builder(FS_USAGE, fs, f -> {
-                f.updateAttributes();
-                return Math.max(0L, f.getTotalSpace() - f.getUsableSpace());
-            }).tag(STATE_KEY, "used")...
+            Gauge.builder(FS_USAGE, fs, f -> {
+                refreshed(f);
+                return Math.max(0L, f.getTotalSpace() - f.getUsableSpace());
+            }).tag(STATE_KEY, "used")...

Apply refreshed(f) in place of bare f.updateAttributes() in the other four lambdas as well.

🤖 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-metrics/src/main/java/oshi/metrics/FileSystemMetrics.java` around lines
56 - 100, The code calls OSFileStore.updateAttributes() multiple times per
scrape causing extra syscalls and inconsistent snapshots; add a per-OSFileStore
TTL cache like in NetworkMetrics: introduce a helper method (e.g.,
refreshed(OSFileStore f)) and a CACHE_TTL_MS constant (e.g., 1000L) inside
FileSystemMetrics that stores the last-read snapshot and timestamp per
OSFileStore and only calls f.updateAttributes() when stale, then replace all
direct f.updateAttributes() calls in the Gauge lambdas (and any other places)
with refreshed(f) so each scrape uses one consistent snapshot and reduces
syscalls.
🤖 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-metrics/src/main/java/oshi/metrics/NetworkMetrics.java`:
- Around line 144-146: The UDP Gauge (NET_CONNECTIONS using getCachedUdpCount)
is missing the network.connection.state tag key that the TCP gauges include,
causing inconsistent tag sets; update the UDP registration to include the same
state tag key (the same constant used by the TCP gauges, e.g.,
CONNECTION_STATE_KEY or equivalent) and supply a suitable value (e.g., "unknown"
or the appropriate UDP state) so the Meter has the same tag keys as the TCP
meters.

---

Nitpick comments:
In `@oshi-metrics/src/main/java/oshi/metrics/FileSystemMetrics.java`:
- Around line 56-100: The code calls OSFileStore.updateAttributes() multiple
times per scrape causing extra syscalls and inconsistent snapshots; add a
per-OSFileStore TTL cache like in NetworkMetrics: introduce a helper method
(e.g., refreshed(OSFileStore f)) and a CACHE_TTL_MS constant (e.g., 1000L)
inside FileSystemMetrics that stores the last-read snapshot and timestamp per
OSFileStore and only calls f.updateAttributes() when stale, then replace all
direct f.updateAttributes() calls in the Gauge lambdas (and any other places)
with refreshed(f) so each scrape uses one consistent snapshot and reduces
syscalls.

In `@oshi-metrics/src/main/java/oshi/metrics/NetworkMetrics.java`:
- Around line 78-127: The per-interface counters in NetworkMetrics.bindTo call
NetworkIF.updateAttributes() six times per scrape; add a TTL refresh helper
(e.g., private boolean refreshed(NetworkIF net)) with a 1s TTL (store
lastRefresh timestamps keyed by net.getName() or NetworkIF) similar to the
existing refreshCache/ipStats pattern so updateAttributes() is invoked at most
once per scrape; call refreshed(net) from each lambda before reading
bytes/packets/errors so all FunctionCounter lambdas use the same snapshot, and
ensure thread-safety if metrics scrapes are concurrent.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e121ea10-19b8-452e-8736-e2045bb4e372

📥 Commits

Reviewing files that changed from the base of the PR and between 2e0bf37 and 3710a89.

📒 Files selected for processing (7)
  • oshi-metrics/README.md
  • oshi-metrics/src/main/java/oshi/metrics/ContainerMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/FileSystemMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/NetworkMetrics.java
  • oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java
  • oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.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, macos-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
🔇 Additional comments (5)
oshi-metrics/src/main/java/oshi/metrics/ContainerMetrics.java (1)

60-95: LGTM!

Past review feedback (PID 1 uptime, strongReference(true) on the uptime gauge, and the Math.max(0L, …) clamp on container.memory.available) has been incorporated cleanly. The isContainerized() short-circuit and the init != null guard around PID 1 lookup also look right.

oshi-metrics/README.md (1)

50-66: LGTM — documentation reads cleanly.

Builder example now lists .enableContainer(true) (matches the documented categories), and the metric tables faithfully reflect what's registered in each binder. Nice cross-references to the OTel semantic conventions for each section as well.

oshi-metrics/src/main/java/oshi/metrics/MemoryMetrics.java (1)

28-63: LGTM — past review concerns are all addressed.

Division-by-zero guard on utilization, the corrected "fraction (0.0–1.0)" Javadoc, strongReference(true) on every gauge, and the new package-info.java together resolve the prior feedback. Implementation is concise and matches the OTel convention.

oshi-metrics/src/main/java/oshi/metrics/OshiMetrics.java (1)

41-129: LGTM — clean orchestrator with consistent null-safety and a complete builder surface.

Constructors null-check hal/os on both the public and Builder paths, the convenience bindTo(registry, hal, os) static stays in lockstep with the all-enabled instance constructor, and each conditional binder line matches its target's constructor signature (e.g., hal::getDiskStores, os.getFileSystem()::getFileStores, os::getCurrentProcess). Builder defaults to all-enabled which mirrors the README docs.

oshi-metrics/src/test/java/oshi/metrics/OshiMetricsTest.java (1)

23-297: LGTM — broad coverage and prior nits all addressed.

The follow-ups from earlier rounds (NPE-safe idleCounter lookup, inclusive [0,1] bounds for utilization gauges, assertNotNull guard on physical, and .enableContainer(false) in the selective-registration test) are all in place. The selective test now exercises both presence (system.cpu.time) and absence (system.memory.usage, system.network.io), which should catch flag-wiring regressions in OshiMetrics.

@dbwiddis
dbwiddis merged commit 8805a1d into oshi:master May 6, 2026
18 of 19 checks passed
@dbwiddis
dbwiddis deleted the feature/oshi-metrics branch May 6, 2026 03:08
dbwiddis added a commit that referenced this pull request May 9, 2026
- Add native-free Linux SystemInfoProvider and Apple Silicon fix to 7.2.0
- Fix issue links to point to implementing PRs (#3230, #3232, #3227)
- Add macOS disk type (#3231) and OSFileStore fast path (#3195)
- Mention native-free Linux option in README Usage section
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.

First-party Micrometer metrics module (oshi-metrics)

1 participant