Skip to content

Split Linux Who driver into common/JNA/FFM, add FFM utmpx and systemd - #3137

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:linux-who-split
Apr 11, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:linux-who-split

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Apr 11, 2026 •

Copy link
Copy Markdown
Member

Split the Linux Who session-query driver across all three modules and create FFM equivalents for the JNA utmpx and systemd native bindings.

oshi-common

  • oshi.util.driver.unix.Who — Removed Linux-specific date parsing and PlatformEnum dependency; now Unix-only. Made matchUnix public for cross-package use.
  • oshi.util.driver.linux.Who — New. Parses who command output trying Linux date format first, falling back to matchUnix per line. Serves as command-line fallback for all Linux native implementations.

oshi-core

  • oshi.driver.linux.Who → oshi.driver.linux.WhoJNA — Renamed. Fallback references updated to oshi.util.driver.linux.Who.queryWho().
  • LinuxOperatingSystem.getSessions() — Uses WhoJNA.queryUtxent() and oshi.util.driver.linux.Who.queryWho() (no longer delegates to super.getSessions()).

oshi-core-java25

  • LinuxLibcFunctions — Added Linux utmpx struct layout (384 bytes, verified against glibc header), LOGIN_PROCESS/USER_PROCESS constants, setutxent/getutxent/endutxent FFM bindings, and field accessor methods.
  • SystemdFunctions — New. FFM bindings for sd_get_sessions, sd_session_get_username, sd_session_get_start_time, sd_session_get_tty, sd_session_get_remote_host, with lazy loading and availability check.
  • oshi.driver.linux.WhoFFM — New. FFM port of the Linux Who driver: systemd native (gated by oshi.os.linux.allowsystemd), utmpx via FFM, systemd file fallback, who command fallback.
  • LinuxOperatingSystemFFM — Added getSessions() override using WhoFFM.

Summary by CodeRabbit

  • Refactor

    • Enhanced session query mechanism with multiple fallback implementations for improved reliability across different Linux configurations. Added support for systemd-based session queries with fallback to utmpx and native command-based approaches.
  • Tests

    • Updated test references to reflect refactored implementation structure.

…emd bindings

Split the Linux Who session-query driver across all three modules and create FFM equivalents for the JNA utmpx and systemd native bindings.

### oshi-common
- oshi.util.driver.unix.Who — Removed Linux-specific date parsing and PlatformEnum dependency; now Unix-only. Made matchUnix public for cross-package use.
- oshi.util.driver.linux.Who — New. Parses who command output trying Linux date format first, falling back to matchUnix per line. Serves as command-line fallback for all Linux native implementations.

### oshi-core
- oshi.driver.linux.Who → oshi.driver.linux.WhoJNA — Renamed. Fallback references updated to oshi.util.driver.linux.Who.queryWho().
- LinuxOperatingSystem.getSessions() — Uses WhoJNA.queryUtxent() and oshi.util.driver.linux.Who.queryWho() (no longer delegates to super.getSessions()).

### oshi-core-java25
- LinuxLibcFunctions — Added Linux utmpx struct layout (384 bytes, verified against glibc header), LOGIN_PROCESS/USER_PROCESS constants, setutxent/getutxent/endutxent FFM bindings, and field accessor methods.
- SystemdFunctions — New. FFM bindings for sd_get_sessions, sd_session_get_username, sd_session_get_start_time, sd_session_get_tty, sd_session_get_remote_host, with lazy loading and availability check.
- oshi.driver.linux.WhoFFM — New. FFM port of the Linux Who driver: systemd native (gated by oshi.os.linux.allowsystemd), utmpx via FFM, systemd file fallback, who command fallback.
- LinuxOperatingSystemFFM — Added getSessions() override using WhoFFM.
@coderabbitai

coderabbitai Bot commented Apr 11, 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: 5185aef2-1c1f-41d9-b143-d88d3513c79d

📥 Commits

Reviewing files that changed from the base of the PR and between b912e25 and 4fe411d.

📒 Files selected for processing (9)
  • oshi-common/src/main/java/oshi/util/driver/linux/Who.java
  • oshi-common/src/main/java/oshi/util/driver/unix/Who.java
  • oshi-core-java25/src/main/java/oshi/driver/linux/WhoFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/linux/LinuxLibcFunctions.java
  • oshi-core-java25/src/main/java/oshi/ffm/linux/SystemdFunctions.java
  • oshi-core-java25/src/main/java/oshi/software/os/linux/LinuxOperatingSystemFFM.java
  • oshi-core/src/main/java/oshi/driver/linux/WhoJNA.java
  • oshi-core/src/main/java/oshi/software/os/linux/LinuxOperatingSystem.java
  • oshi-core/src/test/java/oshi/driver/linux/WhoTest.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). (9)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 25, windows-latest
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 25, macos-latest
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (7)
📚 Learning: 2026-04-06T04:45:51.516Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3121
File: oshi-core/src/main/java/oshi/software/os/linux/LinuxOperatingSystem.java:53-53
Timestamp: 2026-04-06T04:45:51.516Z
Learning: In the oshi/oshi project, the public API is strictly limited to interfaces and classes in the `oshi`, `oshi.hardware`, and `oshi.software.os` packages. All platform-specific code under subpackages like `oshi.software.os.linux`, `oshi.hardware.platform.linux`, etc., is considered implementation detail — not public API. Do not flag changes to platform-specific classes (e.g., making `LinuxOperatingSystem` abstract, narrowing constructor visibility, adding abstract methods) as public API breaks.

Applied to files:

  • oshi-core/src/test/java/oshi/driver/linux/WhoTest.java
  • oshi-common/src/main/java/oshi/util/driver/unix/Who.java
  • oshi-core-java25/src/main/java/oshi/ffm/linux/SystemdFunctions.java
📚 Learning: 2026-03-29T20:01:06.452Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3014
File: oshi-core-java11/src/main/java/module-info.java:10-17
Timestamp: 2026-03-29T20:01:06.452Z
Learning: In the oshi project, `oshi-core-java25/src/main/java/module-info.java` intentionally does NOT export `oshi.util.platform.unix.freebsd`, `oshi.util.platform.unix.openbsd`, or `oshi.util.platform.unix.solaris`, because the FFM (Foreign Function & Memory) implementation only supports Windows, macOS, and Linux. This differs from `oshi-core-java11/src/main/java/module-info.java` which exports all Unix platform packages. The asymmetry is by design.

Applied to files:

  • oshi-core/src/test/java/oshi/driver/linux/WhoTest.java
  • oshi-core-java25/src/main/java/oshi/software/os/linux/LinuxOperatingSystemFFM.java
  • oshi-common/src/main/java/oshi/util/driver/unix/Who.java
  • oshi-core-java25/src/main/java/oshi/ffm/linux/LinuxLibcFunctions.java
  • oshi-core-java25/src/main/java/oshi/ffm/linux/SystemdFunctions.java
📚 Learning: 2026-04-06T04:45:47.644Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3121
File: oshi-core/src/main/java/oshi/software/os/linux/LinuxOperatingSystem.java:53-53
Timestamp: 2026-04-06T04:45:47.644Z
Learning: In the oshi/oshi project, only interfaces and classes in the root packages `oshi`, `oshi.hardware`, and `oshi.software.os` are considered the public API. Code in subpackages that represent specific implementations/platforms (e.g., `oshi.software.os.linux`, `oshi.hardware.platform.linux`, and similar subpackages) is implementation detail. When reviewing, do not treat changes to classes in these platform-specific subpackages as public API breaks (for example: making `LinuxOperatingSystem` abstract, narrowing constructor visibility, or adding/removing abstract methods should not be flagged as breaking public API).

Applied to files:

  • oshi-core/src/main/java/oshi/software/os/linux/LinuxOperatingSystem.java
📚 Learning: 2026-04-10T22:44:32.055Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3136
File: oshi-core-java25/src/main/java/oshi/software/os/linux/LinuxOperatingSystemFFM.java:46-53
Timestamp: 2026-04-10T22:44:32.055Z
Learning: In OSHI's `AuxvFFM.queryAuxv()` (oshi-core-java25/src/main/java/oshi/driver/linux/proc/AuxvFFM.java), the do-while loop is safe even when `/proc/self/auxv` cannot be read: `FileUtil.readAllBytesAsBuffer` returns an empty ByteBuffer on failure, and `FileUtil.readLongFromBuffer`/`readIntFromBuffer` return 0L when reading past the buffer limit. This 0L equals AT_NULL, causing the loop to exit immediately with an empty map, which triggers the `getconf`/hardcoded-default fallback in callers like `LinuxOperatingSystemFFM`. Do not flag this do-while loop or the static initializer that calls `AuxvFFM.queryAuxv()` as unsafe.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/software/os/linux/LinuxOperatingSystemFFM.java
📚 Learning: 2026-04-05T05:40:45.797Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3117
File: oshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.java:62-65
Timestamp: 2026-04-05T05:40:45.797Z
Learning: In OSHI's Linux FFM and JNA udev code, a null guard on `udev_enumerate_new()` is intentionally absent and should not be flagged. This is consistent across all four FFM classes (LinuxPowerSourceFFM, LinuxHWDiskStoreFFM, LinuxLogicalVolumeGroupFFM, LinuxUsbDeviceFFM) and the JNA implementation (which also does not guard `enumerateNew()` for null). Per libudev semantics, `udev_enumerate_new()` only returns NULL when udev itself is broken (e.g. OOM), so a successful `udev_new()` (which is guarded) implies `udev_enumerate_new()` will succeed. Adding a null guard would be both redundant and inconsistent with the established pattern.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/software/os/linux/LinuxOperatingSystemFFM.java
  • oshi-core-java25/src/main/java/oshi/driver/linux/WhoFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/linux/SystemdFunctions.java
📚 Learning: 2026-04-03T02:07:47.621Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3110
File: oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java:119-121
Timestamp: 2026-04-03T02:07:47.621Z
Learning: In OSHI’s Java FFM/API implementation classes (e.g., *FFM.java) that implement/override `updateAttributes()`, preserve the intentional failure-handling pattern: catch `Throwable` and return `false` without logging. `updateAttributes()` is a public API whose contract is to signal failure via the boolean return value, and callers rely on that return value (so emitting logs from this path is not desired and should not be introduced during review unless the method contract changes).

Applied to files:

  • oshi-core-java25/src/main/java/oshi/software/os/linux/LinuxOperatingSystemFFM.java
  • oshi-core-java25/src/main/java/oshi/driver/linux/WhoFFM.java
📚 Learning: 2026-03-29T20:03:00.830Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3014
File: oshi-core-java25/src/main/java/oshi/util/platform/windows/PdhUtilFFM.java:87-89
Timestamp: 2026-03-29T20:03:00.830Z
Learning: In the OSHI FFM codebase (oshi-core-java25), all PDH/Kernel32/COM wrapper methods in classes like PdhFFM, Kernel32FFM, etc. declare `throws Throwable` solely as a compiler artifact of `MethodHandle.invokeExact`. They are native calls and do not throw Java checked exceptions in practice. The enclosing `getOpenFileDescriptors()` method in PdhUtilFFM already has an outer `catch (Throwable t)` that covers the entire method body including any `finally` blocks, so no exception-masking concern exists for cleanup calls like `PdhCloseQuery` in `finally`.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/ffm/linux/SystemdFunctions.java
🔇 Additional comments (5)
oshi-core-java25/src/main/java/oshi/ffm/linux/LinuxLibcFunctions.java (2)

228-230: The utmpx symbols are available on all supported Linux libc implementations.

The symbols setutxent, getutxent, and endutxent are exported and callable on both glibc and musl-based systems (including Alpine). On glibc, they are standard POSIX functions with full implementations. On musl, they are implemented as stubs but are still exported from libc.so and callable. The findOrThrow() calls will succeed on all supported targets, so no risk of breaking unrelated FFM paths during class initialization.


315-328: Fix getString(0) for fixed-size utmpx char arrays without guaranteed null terminators.

The ut_user and ut_line fields are fixed-size char arrays (32 bytes each) that may legally contain no trailing \0. Calling MemorySegment.getString(0) throws IndexOutOfBoundsException, causing WhoFFM.queryUtxent() to fall back to the command-based path for otherwise valid sessions. Since Java 25 is the target (JDK 27+ getString(long, Charset, long) is unavailable), implement a helper to read up to the first null byte or field length.

♻️ Proposed fix
+import java.nio.charset.Charset;
@@
     public static String utmpxUser(MemorySegment ut) {
-        return ut.asSlice(UTMPX_LAYOUT.byteOffset(MemoryLayout.PathElement.groupElement("ut_user")), UT_NAMESIZE)
-                .getString(0);
+        return readFixedCString(ut, "ut_user", UT_NAMESIZE);
     }
@@
     public static String utmpxLine(MemorySegment ut) {
-        return ut.asSlice(UTMPX_LAYOUT.byteOffset(MemoryLayout.PathElement.groupElement("ut_line")), UT_LINESIZE)
-                .getString(0);
+        return readFixedCString(ut, "ut_line", UT_LINESIZE);
     }
+
+    private static String readFixedCString(MemorySegment ut, String fieldName, long fieldSize) {
+        long offset = UTMPX_LAYOUT.byteOffset(MemoryLayout.PathElement.groupElement(fieldName));
+        byte[] bytes = ut.asSlice(offset, fieldSize).toArray(JAVA_BYTE);
+        int len = 0;
+        while (len < bytes.length && bytes[len] != 0) {
+            len++;
+        }
+        return new String(bytes, 0, len, Charset.defaultCharset());
+    }
oshi-core-java25/src/main/java/oshi/ffm/linux/SystemdFunctions.java (3)

40-80: Static symbol binding and availability state are implemented cleanly.

The all-or-nothing binding pattern with AVAILABLE is clear and safe for feature gating.


98-158: FFM wrapper methods are consistent and correctly minimal.

Thin invokeExact wrappers with native return-code propagation look good for this layer.


168-176: readAndFreeString handles lifetime correctly.

Null guard plus finally-based free(ptr) ensures deterministic cleanup.


📝 Walkthrough

Walkthrough

Introduces Linux-specific session query implementations for both FFM (Java 21+) and JNA backends, adds native systemd and utmpx bindings, creates a shared Linux "who" command utility class, and refactors existing Unix Who utility by extracting Linux-specific logic and exposing helper methods.

Changes

Cohort / File(s) Summary
New Linux Who Utility
oshi-common/src/main/java/oshi/util/driver/linux/Who.java
Added new Linux-specific WHO query class parsing Linux timestamp format (yyyy-MM-dd HH:mm) with fallback to Unix format parsing via matchUnix.
Unix Who Refactoring
oshi-common/src/main/java/oshi/util/driver/unix/Who.java
Removed Linux-specific logic and platform branching; changed matchUnix from private to public; simplified queryWho() to always use Unix-format parsing.
FFM Native Bindings
oshi-core-java25/src/main/java/oshi/ffm/linux/LinuxLibcFunctions.java, oshi-core-java25/src/main/java/oshi/ffm/linux/SystemdFunctions.java
Added utmpx structure layout and accessors for login time, user, device, and IPv6 address; introduced SystemdFunctions FFM bindings for session query APIs with proper error handling and memory cleanup.
FFM Linux Session Implementation
oshi-core-java25/src/main/java/oshi/driver/linux/WhoFFM.java
New FFM-based session query with three fallback paths: systemd API (if available), utmpx iteration, and /run/systemd/sessions file parsing, with delegation to Who.queryWho() on failure.
FFM OS Integration
oshi-core-java25/src/main/java/oshi/software/os/linux/LinuxOperatingSystemFFM.java
Added getSessions() override delegating to Who.queryWho() or WhoFFM.queryUtxent() based on USE_WHO_COMMAND flag.
JNA Updates
oshi-core/src/main/java/oshi/driver/linux/WhoJNA.java, oshi-core/src/main/java/oshi/software/os/linux/LinuxOperatingSystem.java, oshi-core/src/test/java/oshi/driver/linux/WhoTest.java
Renamed Who class to WhoJNA; updated imports and test references; modified fallback to use oshi.util.driver.linux.Who instead of Unix Who.

Sequence Diagram(s)

sequenceDiagram
    participant App as Application
    participant OS as LinuxOperatingSystem<br/>(FFM/JNA)
    participant Query as WhoFFM/Who
    participant Systemd as Systemd FFM
    participant Utmpx as utmpx (libc FFM)
    participant File as /run/systemd/<br/>sessions
    participant Fallback as Who Command

    App->>OS: getSessions()
    
    alt USE_WHO_COMMAND enabled
        OS->>Query: Who.queryWho()
        Query->>Query: Parse 'who' output
        Query-->>OS: List<OSSession>
    else FFM Backend
        OS->>Query: WhoFFM.queryUtxent()
        
        alt Systemd Available & Configured
            Query->>Systemd: sdGetSessions()
            Systemd-->>Query: session IDs
            loop Each Session
                Query->>Systemd: sdSessionGetUsername/Time/TTY
                Systemd-->>Query: session details
            end
        else No Systemd Results
            Query->>Utmpx: setutxent()
            loop Each utmpx Entry
                Query->>Utmpx: getutxent()
                Utmpx-->>Query: entry data
                Query->>Query: Filter & Validate
            end
            Utmpx->>Query: endutxent()
        end
        
        alt No Sessions Found
            Query->>File: Read /run/systemd/sessions
            File-->>Query: session files
            Query->>Query: Parse key/value
        end
        
        alt Still No Sessions
            Query->>Fallback: Who.queryWho()
            Fallback-->>Query: List<OSSession>
        end
        
        Query-->>OS: List<OSSession>
    end
    
    OS-->>App: List<OSSession>
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰 Hops with glee at sessions found,
FFM and JNA bound!
Systemd dance with utmpx grace,
Who commands join the race. ✨
Linux logged-in, now we see!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 63.89% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main architectural change: splitting the Linux Who driver implementation across three build artifacts (oshi-common, oshi-core/JNA, oshi-core-java25/FFM) and adding FFM bindings for utmpx and systemd.

✏️ 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.

@codecov

codecov Bot commented Apr 11, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 61.91%. Comparing base (b912e25) to head (4fe411d).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3137      +/-   ##
============================================
+ Coverage     61.14%   61.91%   +0.77%     
  Complexity       12       12              
============================================
  Files            39       39              
  Lines          2329     2329              
  Branches        407      407              
============================================
+ Hits           1424     1442      +18     
+ Misses          786      768      -18     
  Partials        119      119              

☔ 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 3ee332f into oshi:master Apr 11, 2026
14 of 15 checks passed
@dbwiddis
dbwiddis deleted the linux-who-split branch April 11, 2026 00:42
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.

1 participant