Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add OpenBSD support #59

Merged
merged 5 commits into from
Oct 11, 2024
Merged

Add OpenBSD support #59

merged 5 commits into from
Oct 11, 2024

Conversation

AMDmi3
Copy link
Contributor

@AMDmi3 AMDmi3 commented Oct 10, 2024

I was curious about supporting other platforms with the help of cross-platform-actions, and it turned out not too hard to add OpenBSD. It still lacks part of the metrics, hopefully OpenBSD uses will improve it (I myself don't have OpenBSD installed).

This PR also makes cross-platform testing more flexible and allows add support for more platforms in the future.

Summary by CodeRabbit

  • New Features

    • Introduced support for OpenBSD, enhancing cross-platform compatibility.
    • Added new metrics collection functionality specific to OpenBSD.
    • Updated testing capabilities to include OpenBSD in the cross-platform test suite.
  • Bug Fixes

    • Adjusted compilation conditions to ensure compatibility with OpenBSD.
  • Documentation

    • Updated README to reflect OpenBSD as a supported platform and its corresponding metrics.
    • Revised dependency management to include OpenBSD requirements in project configuration.

This allows spoting data problems on foreign platforms
Note that this doesn't use latest OpenBSD version because
cross-platform-actions/action doesn't yet have a tag with its support.

Also disable fail-fast for cross-platform tests, as it allows to
see whether just a specific system failed, or all cross-platform,
or all BSD systems.
This is based on FreeBSD code, but lacks some fields
Copy link

coderabbitai bot commented Oct 10, 2024

Walkthrough

The pull request introduces updates to enhance cross-platform testing, specifically for OpenBSD and FreeBSD. The workflow file .github/workflows/test.yml has been modified to implement a matrix strategy for dynamic OS testing. The Cargo.toml file now includes a new dependency for OpenBSD, while the src/collector.rs file has been updated to support OpenBSD-specific implementations. A new file, src/collector/openbsd.rs, has been created to handle system resource interactions on OpenBSD.

Changes

File Change Summary
.github/workflows/test.yml Renamed job to test-cross-platform, added matrix strategy for OS testing (FreeBSD, OpenBSD), updated caching key, and modified steps to use matrix variables.
Cargo.toml Added new target dependency for OpenBSD: libc = "0.2.159" under [target.'cfg(target_os = "openbsd")'.dependencies].
src/collector.rs Added conditional compilation for OpenBSD, updated compile error conditions, and added a new test function for OpenBSD.
src/collector/openbsd.rs Introduced functions for system resource interactions on OpenBSD, including collect, getrusage, getrlimit, and kinfo_getproc.

Possibly related PRs

  • Add FreeBSD support #53: This PR adds FreeBSD support, which is directly related to the changes in the main PR that enhance cross-platform testing capabilities, including FreeBSD.
  • Make CI cache specific to actual build system #56: This PR modifies the CI caching mechanism and introduces a job for FreeBSD testing, aligning with the main PR's updates to the workflow for cross-platform testing.

Suggested reviewers

  • lambdalisue

Poem

🐇 In the meadow where bunnies hop,
Cross-platform tests now never stop!
With OpenBSD joining the race,
Our metrics gather at a faster pace.
So let’s cheer with a joyful thump,
For every OS, we’ll take the jump! 🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

codecov bot commented Oct 10, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 55.68%. Comparing base (f199808) to head (da32542).
Report is 6 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main      #59   +/-   ##
=======================================
  Coverage   55.68%   55.68%           
=======================================
  Files           5        5           
  Lines         264      264           
=======================================
  Hits          147      147           
  Misses        117      117           

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

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (9)
Cargo.toml (1)

48-50: LGTM! Consider using a version range for libc.

The addition of the OpenBSD-specific dependency aligns well with the PR objective of adding OpenBSD support. The structure and version of the libc dependency are consistent with the FreeBSD configuration.

To allow for minor updates and reduce the need for frequent version bumps, consider using a version range for libc. For example:

 [target.'cfg(target_os = "openbsd")'.dependencies]
-libc = "0.2.159"
+libc = "0.2.159" # Alternatively, use a range like "0.2"

This change would allow for minor updates within the 0.2.x range, potentially reducing maintenance overhead while still maintaining compatibility.

src/collector.rs (2)

86-102: LGTM: OpenBSD-specific test function added correctly.

The new test function test_collect_internal_ok_openbsd is well-implemented and correctly verifies the expected behavior of collect() on OpenBSD. It's appropriate to have a separate test at this stage, given the differences in available metrics.

The TODO comment about potentially merging this test with test_collect_internal_ok in the future is a good reminder for maintainability.

Consider adding a brief comment explaining why certain metrics return None for OpenBSD. This would provide context for future developers and align with the PR author's note about lacking certain metrics.


Line range hint 1-124: Overall: Excellent implementation of OpenBSD support.

The changes in this file consistently and correctly implement OpenBSD support across conditional compilation, error handling, and testing. The modifications align well with the PR objective and acknowledge current limitations.

To improve maintainability and clarity, consider the following suggestions:

  1. Add a comment in the Metrics struct documenting which fields are currently unsupported on OpenBSD.
  2. Create a tracking issue for implementing the missing metrics on OpenBSD, as mentioned in the PR description.

These changes would help future contributors understand the current state of OpenBSD support and provide a clear path for further improvements.

.github/workflows/test.yml (3)

107-115: LGTM! Well-structured matrix strategy for cross-platform testing.

The matrix strategy is well-defined, allowing for efficient testing across multiple operating systems. The inclusion of specific preparation commands for each OS is a good practice.

Consider adding a TODO comment or creating an issue to track the addition of OpenBSD 7.6 support when it becomes available in the action.


135-136: LGTM! Correct test execution with OS-specific preparation.

The use of the matrix variable for the preparation command ensures the correct setup for each OS. Running the test command with --nocapture is helpful for debugging.

Consider adding error handling to the preparation command, such as:

run: |
  set -e
  ${{matrix.prepare_cmd}}
  cargo test -- --nocapture

This will ensure that the workflow fails if the preparation command encounters any errors.


Line range hint 107-136: Overall, excellent implementation of cross-platform testing.

The changes to this workflow file successfully introduce OpenBSD support and enhance the flexibility of cross-platform testing. The use of a matrix strategy, dynamic job naming, and OS-specific preparation commands are all well-implemented. This setup will make it easier to add support for more platforms in the future.

To further improve the workflow:

  1. Consider adding a job that runs on the latest stable versions of all supported platforms to catch any breaking changes quickly.
  2. Implement a strategy to periodically update the OS versions in the matrix to ensure testing on the most recent stable releases.
src/collector/openbsd.rs (3)

37-38: Use size_of instead of size_of_val for clarity

In line 37, using std::mem::size_of::<libc::kinfo_proc>() is clearer and directly conveys the intention to obtain the size of libc::kinfo_proc, rather than using size_of_val on a MaybeUninit instance.

Apply this diff for improved clarity:

- let kinfo_proc_size = std::mem::size_of_val(&kinfo_proc) as libc::size_t;
+ let kinfo_proc_size = std::mem::size_of::<libc::kinfo_proc>() as libc::size_t;

76-81: Offer assistance with implementing missing metrics

The TODO comments indicate missing metrics such as virtual_memory_bytes, virtual_memory_max_bytes, threads, and open_fds. If needed, I can help research alternative methods to obtain these metrics on OpenBSD.

Would you like me to explore possible ways to retrieve these metrics on OpenBSD or open a GitHub issue to track this enhancement?


79-79: Fix unclosed parenthesis in comment

The comment on line 79 has an unclosed parenthesis:

// - threads (no corresponding field in kinfo_proc(

Apply this diff to correct the typo:

- // - threads (no corresponding field in kinfo_proc(
+ // - threads (no corresponding field in kinfo_proc)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f199808 and 3512bc3.

📒 Files selected for processing (4)
  • .github/workflows/test.yml (2 hunks)
  • Cargo.toml (1 hunks)
  • src/collector.rs (3 hunks)
  • src/collector/openbsd.rs (1 hunks)
🧰 Additional context used
🔇 Additional comments (10)
src/collector.rs (3)

5-5: LGTM: OpenBSD-specific implementation path added correctly.

The new conditional compilation attribute for OpenBSD is correctly implemented, following the established pattern for other operating systems. This change aligns well with the PR objective of adding OpenBSD support.


16-17: LGTM: OpenBSD correctly added to the list of supported platforms.

The compile error condition has been appropriately updated to include OpenBSD. This ensures that the "dummy" feature is only required for truly unsupported platforms, which now excludes OpenBSD. This change is consistent with the PR objective.


108-108: LGTM: OpenBSD correctly excluded from the dummy test.

The addition of #[cfg(not(target_os = "openbsd"))] to the dummy test function is correct. This ensures that the dummy test only runs on truly unsupported platforms, now excluding OpenBSD. This change is consistent with the overall goal of adding OpenBSD support.

.github/workflows/test.yml (3)

116-117: LGTM! Appropriate runner and clear job naming.

The use of ubuntu-latest as the runner is correct for cross-platform testing with cross-platform-actions/action. The dynamic job name clearly identifies which OS and version is being tested in each matrix combination.


128-128: LGTM! Improved caching strategy.

The updated caching key now includes the OS and version from the matrix. This ensures that each OS and version combination has its own cache, preventing potential issues with incompatible caches between different environments.


132-133: LGTM! Correct use of matrix variables in cross-platform action.

The operating_system and version are correctly set using matrix variables, allowing the workflow to dynamically configure the environment for each matrix combination. This is consistent with the matrix strategy defined earlier.

src/collector/openbsd.rs (4)

5-14: getrusage function is correctly implemented

The getrusage function correctly wraps the libc::getrusage system call with appropriate handling of unsafe code and safety comments.


16-25: getrlimit function is properly implemented

The getrlimit function accurately wraps the libc::getrlimit system call, with correct usage of unsafe blocks and safety explanations.


82-87: Calculation of cpu_seconds_total is accurate

The computation of cpu_seconds_total correctly sums user and system CPU times, converting microseconds to seconds.


102-104: Verify the correctness of start_time_seconds

Assigning kinfo_proc.p_ustart_sec to metrics.start_time_seconds assumes this field represents the process start time in seconds since the epoch. Please verify that p_ustart_sec is in the expected format and units.

Run the following script to confirm the correctness:

Comment on lines +46 to +51
// this is required because MIB is array of ints, and is safe
// as long size of kinfo_proc structure doesn't exceed 2GB
kinfo_proc_size.try_into().unwrap(),
1,
];

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle potential failure in try_into conversion

At line 48, kinfo_proc_size.try_into().unwrap() could panic if the conversion fails. Although the comment mentions safety due to the size constraint, it's safer to handle the Result explicitly to prevent possible panics.

Apply this diff to gracefully handle conversion errors:

let mib = [
    libc::CTL_KERN,
    libc::KERN_PROC,
    libc::KERN_PROC_PID,
    pid,
-   kinfo_proc_size.try_into().unwrap(),
+   match kinfo_proc_size.try_into() {
+       Ok(size) => size,
+       Err(_) => return None, // Handle the error appropriately
+   },
    1,
];

Alternatively, if you're confident the size will always fit, consider using expect with a descriptive message:

kinfo_proc_size.try_into().expect("kinfo_proc_size exceeds libc::c_int range"),

Committable suggestion was skipped due to low confidence.

Comment on lines +27 to +33
fn translate_rlim(rlim: libc::rlim_t) -> u64 {
if rlim == libc::RLIM_INFINITY {
0
} else {
rlim as u64
}
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Review handling of RLIM_INFINITY in translate_rlim function

In the translate_rlim function, mapping RLIM_INFINITY to 0 might be misleading, as 0 could be interpreted as no resource limit rather than an infinite limit. Consider using u64::MAX or a sentinel value that more clearly represents an infinite limit.

Apply this diff to adjust the handling:

fn translate_rlim(rlim: libc::rlim_t) -> u64 {
    if rlim == libc::RLIM_INFINITY {
-       0
+       u64::MAX
    } else {
        rlim as u64
    }
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
fn translate_rlim(rlim: libc::rlim_t) -> u64 {
if rlim == libc::RLIM_INFINITY {
0
} else {
rlim as u64
}
}
fn translate_rlim(rlim: libc::rlim_t) -> u64 {
if rlim == libc::RLIM_INFINITY {
u64::MAX
} else {
rlim as u64
}
}

@lambdalisue
Copy link
Owner

Could you update README as well?

@AMDmi3
Copy link
Contributor Author

AMDmi3 commented Oct 10, 2024

Oops, forgot to push

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (3)
README.md (3)

45-55: LGTM: Updated metrics table with OpenBSD support.

The metrics table has been accurately updated to include OpenBSD support, clearly showing which metrics are available on this platform. This is consistent with the PR objectives and provides valuable information to users.

Consider adding a note or legend explaining what the 'x' marks represent in the table, for improved clarity.


Line range hint 137-143: Consider updating the Features section.

While the Features section remains unchanged, it might be worth considering if any updates are needed to reflect the addition of OpenBSD support. For example, you could mention if any specific features are related to or affect OpenBSD support.


Line range hint 1-148: Overall LGTM: README.md updated to reflect OpenBSD support.

The changes to the README.md file accurately reflect the addition of OpenBSD support, which is the main objective of this PR. The updates to the supported platforms list and the metrics table provide clear and valuable information to users about the crate's capabilities on OpenBSD.

Consider adding a brief note in the Usage section mentioning that the usage remains the same across all supported platforms, including OpenBSD. This would reassure users that no platform-specific code is needed when using the crate on OpenBSD.

🧰 Tools
🪛 LanguageTool

[style] ~42-~42: ‘Prior to’ might be wordy. Consider a shorter alternative.
Context: ...lient_golang]) provides. > [!NOTE] > > Prior to version 2.0.0, the `process_cpu_seconds...

(EN_WORDINESS_PREMIUM_PRIOR_TO)


[style] ~57-~57: Using many exclamation marks might seem excessive (in this case: 7 exclamation marks for a text that’s 4851 characters long)
Context: ... | | x | | > [!NOTE] > > If you only need to compile th...

(EN_EXCESSIVE_EXCLAMATION)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 3512bc3 and da32542.

📒 Files selected for processing (1)
  • README.md (2 hunks)
🧰 Additional context used
🔇 Additional comments (1)
README.md (1)

11-14: *LGTM: Updated supported platforms and acknowledgment of BSD support.

The changes accurately reflect the addition of OpenBSD support and acknowledge the broader *BSD support. This aligns well with the PR objectives and provides clear information to users about the crate's capabilities.

@lambdalisue lambdalisue merged commit 4868bc2 into lambdalisue:main Oct 11, 2024
13 checks passed
@lambdalisue
Copy link
Owner

Thanks a lot 🎉

@AMDmi3 AMDmi3 deleted the openbsd branch October 11, 2024 14:17
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.

2 participants