Skip to content

Fix resource leaks and flaky test in PrivilegedUtil - #3119

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:resource-leak
Apr 5, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:resource-leak

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Apr 5, 2026 •

Copy link
Copy Markdown
Member

Fixes three Coverity-reported resource leaks in PrivilegedUtil and a race-condition-driven flaky unit test.

Resource leaks (Coverity)

CID 1670515 & CID 1670513: readAllBytesPrivileged()

p.getInputStream() and p.getErrorStream() were not explicitly closed. Wrapped both in a single try-with-resources block so they are closed before destroyProcess() runs in the outer finally.

CID 1670514: isFileAllowed()

FileSystems.getDefault() was called on every loop iteration, producing a new FileSystem reference each time that Coverity false-positive flagged as unclosed. Pulled the call outside the loop into a local variable. The default FileSystem must never be closed (it is the JVM singleton), but this change also avoids the redundant repeated calls.

Flaky test

testGetPrefixConfigured intermittently failed with the memoized prefix supplier returning "" instead of "sudo -n". The @BeforeEach setup called clearCaches() before the config was set, leaving a window where another test class running in parallel could call getPrefix() and prime the new supplier with an empty config before GlobalConfig.set() ran in this test. Fixed by calling clearCaches() immediately after GlobalConfig.set(), ensuring the supplier is always evaluated against the updated config value.

Fixes #3118

Summary by CodeRabbit

  • Bug Fixes

    • Fixed resource leaks in file system pattern handling and subprocess stream handling to prevent resource exhaustion and flakiness.
  • Documentation

    • Added changelog entry documenting the fixes.
  • Tests

    • Improved test reliability by ensuring caches are cleared before assertions.

@coderabbitai

coderabbitai Bot commented Apr 5, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: cce5ee1b-d6ea-4103-a4ec-3871f6ff7e7b

📥 Commits

Reviewing files that changed from the base of the PR and between 499c362 and 225673b.

📒 Files selected for processing (3)
  • CHANGELOG.md
  • oshi-core/src/main/java/oshi/util/PrivilegedUtil.java
  • oshi-core/src/test/java/oshi/util/PrivilegedUtilTest.java
✅ Files skipped from review due to trivial changes (1)
  • CHANGELOG.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • oshi-core/src/test/java/oshi/util/PrivilegedUtilTest.java
📜 Recent review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 25, windows-latest
  • GitHub Check: Test JDK 25, macos-latest
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Analyze (java)
🔇 Additional comments (2)
oshi-core/src/main/java/oshi/util/PrivilegedUtil.java (2)

122-124: LGTM!

Good fix for Coverity CID 1670514. Hoisting FileSystems.getDefault() out of the loop avoids redundant calls and obtaining new references on each iteration. Since the default FileSystem is a singleton that must never be closed, caching this reference is both safe and efficient.


275-280: LGTM!

Good fix for Coverity CID 1670515 & CID 1670513. Wrapping both streams in a single try-with-resources ensures they are properly closed before destroyProcess() runs in the outer finally block.


📝 Walkthrough

Walkthrough

Updated changelog; optimized PrivilegedUtil.isFileAllowed to reuse a single FileSystem for glob matchers; ensured subprocess streams in readAllBytesPrivileged are closed via try-with-resources; test testGetPrefixConfigured now calls PrivilegedUtil.clearCaches() after setting the config.

Changes

Cohort / File(s) Summary
Changelog
CHANGELOG.md
Added a "Bug fixes / Improvements" bullet for version 6.11.1 (in progress) referencing PR #3119.
PrivilegedUtil implementation
oshi-core/src/main/java/oshi/util/PrivilegedUtil.java
Reused a single FileSystem when building PathMatcher instances for glob patterns; wrapped subprocess getInputStream() and getErrorStream() reads in a try-with-resources block to ensure streams are closed.
PrivilegedUtil tests
oshi-core/src/test/java/oshi/util/PrivilegedUtilTest.java
After setting GlobalConfig.OSHI_OS_LINUX_PRIVILEGED_PREFIX, the test now invokes PrivilegedUtil.clearCaches() to ensure the assertion uses a fresh cache state.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 I hopped through the code with a twitchy paw,
I closed the streams that once gnawed at law,
I pooled a FileSystem neat and small,
Cleared the cache so tests don't fall,
Hooray — no more flaky sprawl! 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% 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 'Fix resource leaks and flaky test in PrivilegedUtil' clearly and concisely summarizes the main changes: addressing resource leaks and a flaky test in the PrivilegedUtil class.
Linked Issues check ✅ Passed All coding requirements from linked issue #3118 are met: the test race condition is fixed by calling clearCaches() after GlobalConfig.set(), and resource leaks are addressed in readAllBytesPrivileged() and isFileAllowed().
Out of Scope Changes check ✅ Passed All changes directly address the linked issue objectives: resource leak fixes in PrivilegedUtil and the flaky test fix via cache clearing in the test file, with a supporting CHANGELOG entry.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
✨ Simplify code
  • Create PR with simplified code

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

❤️ Share

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

- Wrap process stdout/stderr streams in try-with-resources in
  readAllBytesPrivileged() to fix CID 1670515 and CID 1670513
- Hoist FileSystems.getDefault() outside the loop in isFileAllowed()
  to fix CID 1670514 (FileSystem obtained once, not per iteration)
- In testGetPrefixConfigured(), call clearCaches() after
GlobalConfig.set()
  so the memoized prefix supplier is always re-evaluated against the
  updated config, preventing a race where parallel test classes could
  prime the supplier before the config value is set
@codecov

codecov Bot commented Apr 5, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 40.00000% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 67.40%. Comparing base (32c5bfa) to head (225673b).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
...i-core/src/main/java/oshi/util/PrivilegedUtil.java 40.00% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #3119      +/-   ##
==========================================
+ Coverage   66.53%   67.40%   +0.87%     
==========================================
  Files          37       37              
  Lines        2023     2025       +2     
  Branches      336      336              
==========================================
+ Hits         1346     1365      +19     
+ Misses        562      545      -17     
  Partials      115      115              

☔ 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 merged commit 9a00acd into oshi:master Apr 5, 2026
14 checks passed
@dbwiddis
dbwiddis deleted the resource-leak branch April 5, 2026 16:45
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.

PrivilegedUtilTest is flaky

1 participant