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

Make sure to acquire the advisory file lock during open() #4

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
//! log.write(&mut b"log entry".to_vec()).unwrap();
//! log.write(&mut b"foobar".to_vec()).unwrap();
//! log.write(&mut b"123".to_vec()).unwrap();
//!
//!
//! // flush to disk
//! log.flush().unwrap();
//! }
Expand Down Expand Up @@ -194,6 +194,7 @@ impl LogFile {
/// This is O(n): we have to iterate to the end of the log in order to clean interrupted writes and determine the length of the log
pub fn open<P: AsRef<std::path::Path>>(path: P) -> Result<LogFile, LogError> {
let mut file = AdvisoryFileLock::new(&path, advisory_lock::FileLockMode::Exclusive)?;
file.try_lock()?;
let path = path.as_ref().to_owned();

let file_size = file.metadata()?.len();
Expand Down Expand Up @@ -623,4 +624,24 @@ mod tests {

std::fs::remove_file(path).unwrap();
}

#[cfg(target_os = "linux")]
#[test]
fn test_locking() {
let path = std::path::Path::new("./wal-log-test-locking");
let _ = std::fs::remove_file(path);
let log = LogFile::open(path).unwrap();

// use flock(1) to verify that we're actually holding the lock
let output = std::process::Command::new("flock")
.arg("-x")
.arg("--nonblock")
.arg(&path)
.arg("-c")
.arg("echo hello")
.status()
.unwrap();
assert_eq!(output.code().unwrap(), 1);
assert!(log.len == 0);
}
}