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

[ISSUE #2310]🚀Implement MappedFile isLoaded method #2311

Merged
merged 2 commits into from
Jan 17, 2025

Conversation

mxsm
Copy link
Owner

@mxsm mxsm commented Jan 17, 2025

Which Issue(s) This PR Fixes(Closes)

Fixes #2310

Brief Description

How Did You Test This Change?

Summary by CodeRabbit

  • New Features

    • Added platform-specific memory management capabilities for Linux and Windows.
    • Implemented method to check if memory regions are loaded into RAM.
  • Chores

    • Updated project dependencies for cross-platform support, including new target-specific dependencies for Linux and Windows.

Copy link
Contributor

coderabbitai bot commented Jan 17, 2025

Walkthrough

The pull request introduces platform-specific memory loading checks for the DefaultMappedFile struct in the RocketMQ store module. It adds target-specific dependencies in the Cargo.toml file for Linux and Windows platforms, including the libc and windows crates. The primary addition is an is_loaded method that uses platform-specific system calls (mincore for Linux) to determine if a specific memory region is resident in RAM, with a placeholder for Windows implementation.

Changes

File Change Summary
rocketmq-store/Cargo.toml Added target-specific dependencies:
- Linux: libc = "0.2.169"
- Windows: windows = {version = "0.59.0", features = ["Win32_Security","Win32_System_Memory_NonVolatile"]}
rocketmq-store/src/log_file/mapped_file/default_mapped_file_impl.rs Added is_loaded method with platform-specific implementations for checking memory residency

Assessment against linked issues

Objective Addressed Explanation
Implement MappedFile isLoaded method [#2310]

Possibly related PRs

Suggested labels

enhancement⚡️, rocketmq-store crate

Suggested reviewers

  • TeslaRustor
  • SpaceXCN
  • rocketmq-rust-bot

Poem

🐰 In bytes of memory, a tale unfolds,
Linux and Windows, their secrets now told.
is_loaded checks with a magical might,
Mapping files, keeping data tight!
A rabbit's code, crossing platform's gate 🚀


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7af7f2e and 37438f0.

📒 Files selected for processing (1)
  • rocketmq-store/src/log_file/mapped_file/default_mapped_file_impl.rs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: build (windows-latest, nightly)
  • GitHub Check: build (windows-latest, stable)
  • GitHub Check: build (macos-latest, nightly)
  • GitHub Check: build (macos-latest, stable)
  • GitHub Check: build
  • GitHub Check: build (ubuntu-latest, nightly)
  • GitHub Check: build (ubuntu-latest, stable)
  • GitHub Check: test
  • GitHub Check: auto-approve

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

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.

@rocketmq-rust-robot rocketmq-rust-robot added this to the v0.4.0 milestone Jan 17, 2025
@rocketmq-rust-bot
Copy link
Collaborator

🔊@mxsm 🚀Thanks for your contribution🎉!

💡CodeRabbit(AI) will review your code first🔥!

Note

🚨The code review suggestions from CodeRabbit are to be used as a reference only, and the PR submitter can decide whether to make changes based on their own judgment. Ultimately, the project management personnel will conduct the final code review💥.

Copy link
Contributor

@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: 3

🧹 Nitpick comments (1)
rocketmq-store/src/log_file/mapped_file/default_mapped_file_impl.rs (1)

726-774: Improve error handling and add logging.

Both implementations should log errors to help with debugging memory-related issues.

Add error logging:

 #[cfg(target_os = "linux")]
 fn is_loaded(&self, position: i64, size: usize) -> bool {
     use libc::c_void;
     use libc::mincore;
     use libc::EINVAL;
     let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize };
     let page_count = (size + page_size - 1) / page_size;
 
     let mut vec = vec![0u8; page_count];
     let address = self.mmapped_file.as_ptr().wrapping_add(position as usize);
     let ret = unsafe { mincore(address as *mut c_void, size, vec.as_mut_ptr()) };
 
     if ret == -1 {
+        error!("mincore failed with errno: {}", unsafe { *libc::__errno_location() });
         return false;
     }
 #[cfg(target_os = "windows")]
 fn is_loaded(&self, position: i64, size: usize) -> bool {
     // ... previous code ...
     if result == 0 {
+        error!("VirtualQuery failed with error: {}", std::io::Error::last_os_error());
         return false;
     }
🧰 Tools
🪛 GitHub Actions: CI

[error] 728-730: Missing dependency: The 'libc' crate is not included in dependencies but is being used in imports


[error] 732-732: Undefined variable: Cannot find value 'length' in scope


[error] 735-735: Undefined variables: Cannot find values 'address' and 'length' in scope


[error] 731-731: Unresolved module: Failed to resolve 'libc' crate in sysconf call

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3049e47 and 7af7f2e.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (2)
  • rocketmq-store/Cargo.toml (1 hunks)
  • rocketmq-store/src/log_file/mapped_file/default_mapped_file_impl.rs (1 hunks)
🧰 Additional context used
🪛 GitHub Actions: CI
rocketmq-store/src/log_file/mapped_file/default_mapped_file_impl.rs

[error] 728-730: Missing dependency: The 'libc' crate is not included in dependencies but is being used in imports


[error] 732-732: Undefined variable: Cannot find value 'length' in scope


[error] 735-735: Undefined variables: Cannot find values 'address' and 'length' in scope


[error] 731-731: Unresolved module: Failed to resolve 'libc' crate in sysconf call

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test
  • GitHub Check: auto-approve
🔇 Additional comments (1)
rocketmq-store/Cargo.toml (1)

52-56: LGTM! Dependencies are correctly configured.

The target-specific dependencies are properly defined with appropriate versions:

  • Linux: libc crate for memory management
  • Windows: windows crate with necessary memory management features

Comment on lines 726 to 774
#[cfg(target_os = "linux")]
fn is_loaded(&self, position: i64, size: usize) -> bool {
use libc::c_void;
use libc::mincore;
use libc::EINVAL;
let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize };
let page_count = (length + page_size - 1) / page_size;

let mut vec = vec![0u8; page_count];
let ret = unsafe { mincore(address as *mut c_void, length, vec.as_mut_ptr()) };

if ret == -1 {
return false;
}

!vec.iter().any(|&byte| byte & 1 == 0)
}

#[inline]
#[cfg(target_os = "windows")]
fn is_loaded(&self, position: i64, size: usize) -> bool {
/*use windows::Win32::Foundation::{BOOL, HANDLE};
use windows::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT};

let address = self.mmapped_file.as_ptr().wrapping_add(position as usize);
let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
let mut offset = 0;

while offset < length {
let result = unsafe {
VirtualQuery(
address.add(offset) as *const _,
&mut info,
std::mem::size_of::<MEMORY_BASIC_INFORMATION>(),
)
};

if result == 0 {
return Err(std::io::Error::last_os_error());
}

if info.State != MEM_COMMIT {
return Ok(false);
}

offset += info.RegionSize;
}*/

true
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add bounds checking for memory safety.

The implementations need bounds checking to prevent buffer overflows and ensure memory safety.

Add bounds checking at the start of both implementations:

 #[cfg(target_os = "linux")]
 fn is_loaded(&self, position: i64, size: usize) -> bool {
+    if position < 0 || position as usize + size > self.file_size as usize {
+        error!("Invalid position or size: position={}, size={}, file_size={}", 
+               position, size, self.file_size);
+        return false;
+    }
     // ... rest of the implementation
 }

 #[cfg(target_os = "windows")]
 fn is_loaded(&self, position: i64, size: usize) -> bool {
+    if position < 0 || position as usize + size > self.file_size as usize {
+        error!("Invalid position or size: position={}, size={}, file_size={}", 
+               position, size, self.file_size);
+        return false;
+    }
     // ... rest of the implementation
 }

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 GitHub Actions: CI

[error] 728-730: Missing dependency: The 'libc' crate is not included in dependencies but is being used in imports


[error] 732-732: Undefined variable: Cannot find value 'length' in scope


[error] 735-735: Undefined variables: Cannot find values 'address' and 'length' in scope


[error] 731-731: Unresolved module: Failed to resolve 'libc' crate in sysconf call

Comment on lines 726 to 742
#[cfg(target_os = "linux")]
fn is_loaded(&self, position: i64, size: usize) -> bool {
use libc::c_void;
use libc::mincore;
use libc::EINVAL;
let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize };
let page_count = (length + page_size - 1) / page_size;

let mut vec = vec![0u8; page_count];
let ret = unsafe { mincore(address as *mut c_void, length, vec.as_mut_ptr()) };

if ret == -1 {
return false;
}

!vec.iter().any(|&byte| byte & 1 == 0)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix critical issues in Linux implementation of is_loaded.

The implementation has several issues:

  1. Unused parameters: position and size
  2. Undefined variables: length and address
  3. Incorrect memory page calculation

Apply this diff to fix the implementation:

 #[cfg(target_os = "linux")]
 fn is_loaded(&self, position: i64, size: usize) -> bool {
     use libc::c_void;
     use libc::mincore;
     use libc::EINVAL;
     let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize };
-    let page_count = (length + page_size - 1) / page_size;
+    let page_count = (size + page_size - 1) / page_size;
 
     let mut vec = vec![0u8; page_count];
-    let ret = unsafe { mincore(address as *mut c_void, length, vec.as_mut_ptr()) };
+    let address = self.mmapped_file.as_ptr().wrapping_add(position as usize);
+    let ret = unsafe { mincore(address as *mut c_void, size, vec.as_mut_ptr()) };
 
     if ret == -1 {
         return false;
     }
 
     !vec.iter().any(|&byte| byte & 1 == 0)
 }
📝 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
#[cfg(target_os = "linux")]
fn is_loaded(&self, position: i64, size: usize) -> bool {
use libc::c_void;
use libc::mincore;
use libc::EINVAL;
let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize };
let page_count = (length + page_size - 1) / page_size;
let mut vec = vec![0u8; page_count];
let ret = unsafe { mincore(address as *mut c_void, length, vec.as_mut_ptr()) };
if ret == -1 {
return false;
}
!vec.iter().any(|&byte| byte & 1 == 0)
}
#[cfg(target_os = "linux")]
fn is_loaded(&self, position: i64, size: usize) -> bool {
use libc::c_void;
use libc::mincore;
use libc::EINVAL;
let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize };
let page_count = (size + page_size - 1) / page_size;
let mut vec = vec![0u8; page_count];
let address = self.mmapped_file.as_ptr().wrapping_add(position as usize);
let ret = unsafe { mincore(address as *mut c_void, size, vec.as_mut_ptr()) };
if ret == -1 {
return false;
}
!vec.iter().any(|&byte| byte & 1 == 0)
}
🧰 Tools
🪛 GitHub Actions: CI

[error] 728-730: Missing dependency: The 'libc' crate is not included in dependencies but is being used in imports


[error] 732-732: Undefined variable: Cannot find value 'length' in scope


[error] 735-735: Undefined variables: Cannot find values 'address' and 'length' in scope


[error] 731-731: Unresolved module: Failed to resolve 'libc' crate in sysconf call

Comment on lines +745 to 774
#[cfg(target_os = "windows")]
fn is_loaded(&self, position: i64, size: usize) -> bool {
/*use windows::Win32::Foundation::{BOOL, HANDLE};
use windows::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT};

let address = self.mmapped_file.as_ptr().wrapping_add(position as usize);
let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
let mut offset = 0;

while offset < length {
let result = unsafe {
VirtualQuery(
address.add(offset) as *const _,
&mut info,
std::mem::size_of::<MEMORY_BASIC_INFORMATION>(),
)
};

if result == 0 {
return Err(std::io::Error::last_os_error());
}

if info.State != MEM_COMMIT {
return Ok(false);
}

offset += info.RegionSize;
}*/

true
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix Windows implementation returning incorrect result.

The current implementation always returns true without performing any memory checks, which could lead to incorrect behavior.

Uncomment and fix the Windows implementation:

 #[cfg(target_os = "windows")]
 fn is_loaded(&self, position: i64, size: usize) -> bool {
-    /*use windows::Win32::Foundation::{BOOL, HANDLE};
-    use windows::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT};
-
-    let address = self.mmapped_file.as_ptr().wrapping_add(position as usize);
-    let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
-    let mut offset = 0;
-
-    while offset < length {
-        let result = unsafe {
-            VirtualQuery(
-                address.add(offset) as *const _,
-                &mut info,
-                std::mem::size_of::<MEMORY_BASIC_INFORMATION>(),
-            )
-        };
-
-        if result == 0 {
-            return Err(std::io::Error::last_os_error());
-        }
-
-        if info.State != MEM_COMMIT {
-            return Ok(false);
-        }
-
-        offset += info.RegionSize;
-    }*/
-
-    true
+    use windows::Win32::Foundation::BOOL;
+    use windows::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT};
+
+    let address = self.mmapped_file.as_ptr().wrapping_add(position as usize);
+    let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
+    let mut offset = 0;
+
+    while offset < size {
+        let result = unsafe {
+            VirtualQuery(
+                address.wrapping_add(offset) as *const _,
+                &mut info,
+                std::mem::size_of::<MEMORY_BASIC_INFORMATION>(),
+            )
+        };
+
+        if result == 0 {
+            return false;
+        }
+
+        if info.State != MEM_COMMIT {
+            return false;
+        }
+
+        offset += info.RegionSize;
+    }
+
+    true
 }
📝 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
#[cfg(target_os = "windows")]
fn is_loaded(&self, position: i64, size: usize) -> bool {
/*use windows::Win32::Foundation::{BOOL, HANDLE};
use windows::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT};
let address = self.mmapped_file.as_ptr().wrapping_add(position as usize);
let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
let mut offset = 0;
while offset < length {
let result = unsafe {
VirtualQuery(
address.add(offset) as *const _,
&mut info,
std::mem::size_of::<MEMORY_BASIC_INFORMATION>(),
)
};
if result == 0 {
return Err(std::io::Error::last_os_error());
}
if info.State != MEM_COMMIT {
return Ok(false);
}
offset += info.RegionSize;
}*/
true
#[cfg(target_os = "windows")]
fn is_loaded(&self, position: i64, size: usize) -> bool {
use windows::Win32::Foundation::BOOL;
use windows::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT};
let address = self.mmapped_file.as_ptr().wrapping_add(position as usize);
let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
let mut offset = 0;
while offset < size {
let result = unsafe {
VirtualQuery(
address.wrapping_add(offset) as *const _,
&mut info,
std::mem::size_of::<MEMORY_BASIC_INFORMATION>(),
)
};
if result == 0 {
return false;
}
if info.State != MEM_COMMIT {
return false;
}
offset += info.RegionSize;
}
true
}

@rocketmq-rust-bot
Copy link
Collaborator

🔊@mxsm 🚀Thanks for your contribution🎉!

💡CodeRabbit(AI) will review your code first🔥!

Note

🚨The code review suggestions from CodeRabbit are to be used as a reference only, and the PR submitter can decide whether to make changes based on their own judgment. Ultimately, the project management personnel will conduct the final code review💥.

Copy link
Collaborator

@rocketmq-rust-bot rocketmq-rust-bot left a comment

Choose a reason for hiding this comment

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

LGTM

@rocketmq-rust-bot rocketmq-rust-bot merged commit 94d1532 into main Jan 17, 2025
17 checks passed
@rocketmq-rust-bot rocketmq-rust-bot added approved PR has approved and removed ready to review waiting-review waiting review this PR labels Jan 17, 2025
Copy link

codecov bot commented Jan 17, 2025

Codecov Report

Attention: Patch coverage is 0% with 16 lines in your changes missing coverage. Please review.

Project coverage is 28.20%. Comparing base (3049e47) to head (37438f0).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...c/log_file/mapped_file/default_mapped_file_impl.rs 0.00% 16 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2311      +/-   ##
==========================================
- Coverage   28.21%   28.20%   -0.01%     
==========================================
  Files         504      504              
  Lines       72456    72470      +14     
==========================================
  Hits        20440    20440              
- Misses      52016    52030      +14     

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

@mxsm mxsm deleted the feature-2310 branch January 18, 2025 10:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
AI review first Ai review pr first approved PR has approved auto merge feature🚀 Suggest an idea for this project.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Feature🚀] Implement MappedFile isLoaded method
3 participants